openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines (6 loc) • 33.9 kB
JavaScript
import{En as e,Kt as t,Yt as n,_ as r,cn as i,d as a,dt as o,in as s,kn as c,pn as l,rn as u,tn as d,xt as f}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import"./openclaw-state-read-cli-invocation-OtTkpH1g.mjs";import{n as p}from"./openclaw-state-read-node-runtime-env-BdqTfovi.mjs";import{Pt as m,Vt as h}from"./openclaw-state-read-src-RL5xtYG2.mjs";import{t as g}from"./openclaw-state-read-promise-like-3qqJObCs.mjs";import{t as _}from"./openclaw-state-read-deferred-B75K7ut7.mjs";import{r as v,t as ee}from"./openclaw-state-read-process-env-DgVwfN3Y.mjs";import{n as te,t as y}from"./openclaw-state-read-pid-alive-C5QrpWWk.mjs";import{a as ne}from"./openclaw-state-read-runtime-worker-url-C8NPtAdy.mjs";import{d as re,f as b,l as x,m as S,t as C,u as w}from"./openclaw-state-read-context-RUh9cSel.mjs";import{t as T}from"./openclaw-state-read-spawn-diagnostics-DIzymF4G.mjs";import{i as E,r as ie,t as ae}from"./openclaw-state-read-windows-install-roots-DY9gXOhm.mjs";import{n as oe,r as se}from"./openclaw-state-read-local-workspace-manifest-scan-oB9D3lW1.mjs";import"node:module";import D from"node:fs";import O from"node:path";import{fileURLToPath as k}from"node:url";import{constants as ce}from"node:os";import{AsyncLocalStorage as le}from"node:async_hooks";import{stripVTControlCharacters as ue}from"node:util";import A from"node:process";import{isUtf8 as j}from"node:buffer";import{once as M}from"node:events";import{StringDecoder as N}from"node:string_decoder";import{execa as P}from"execa";const F=Symbol.for(`openclaw.command-cleanup-uncertain`),I=`Command cleanup could not confirm that owned work stopped`;function isCanonicalCommandProcessCleanupError(e){try{return Object.getOwnPropertyDescriptor(e,F)?.value===!0}catch{return!1}}var CommandProcessCleanupError=class extends Error{constructor(t){let n=I;for(let r of e(t?.cause))if(isCanonicalCommandProcessCleanupError(r))try{let e=Object.getOwnPropertyDescriptor(r,`message`)?.value;if(typeof e==`string`&&e.trim()&&e!==I){n=e;break}}catch{}super(n,t),this.code=`ERR_COMMAND_PROCESS_CLEANUP_UNCERTAIN`,this.cleanup=`uncertain`,this.name=`CommandProcessCleanupError`,Object.defineProperty(this,F,{value:!0})}};function hasCommandProcessCleanupError(t){return e(t).some(isCanonicalCommandProcessCleanupError)}const L=Symbol.for(`openclaw.command-process-cleanup`);function recordCommandProcessCleanup(e,t){return t?Object.defineProperty(e,L,{value:t}):e}const R=Symbol.for(`openclaw.command-process-outcome`);function recordCommandProcessFailure(e,t){let n=c(e,`Command failed`),r=Object.isExtensible(n)?n:Error(n.message,{cause:n});return Object.defineProperty(r,R,{value:Object.freeze({...t}),configurable:!0})}function readCommandProcessFailure(t){for(let n of e(t))try{let e=f(n)?Object.getOwnPropertyDescriptor(n,R):void 0;if(e?.value)return e.value}catch{return}}function createSanitizedCommandError(e){let t=typeof e.code==`string`?e.code:void 0,n=typeof e.exitCode==`number`?e.exitCode:void 0,r=typeof e.signal==`string`?e.signal:void 0,i=e.timedOut?`Command timed out`:e.isMaxBuffer?`Command output exceeded its capture limit`:e.isCanceled?`Command was canceled`:e.isTerminated?`Command was terminated${r?` by ${r}`:``}`:n!==void 0&&n!==0?`Command exited with code ${n}`:`Command failed during launch or output capture${t?` (${t})`:``}`;return Object.assign(Error(i),{...t?{code:t}:{},...n===void 0?{}:{exitCode:n},...r?{signal:r}:{}})}function isPlainCommandExitFailure(e){return e.failed&&typeof e.exitCode==`number`&&e.exitCode!==0&&e.signal===void 0&&e.cause===void 0&&!e.timedOut&&!e.isCanceled&&!e.isMaxBuffer&&!e.isTerminated}function isPlainCommandSignalFailure(e){return e.failed&&e.exitCode===void 0&&typeof e.signal==`string`&&e.cause===void 0&&!e.timedOut&&!e.isCanceled&&!e.isMaxBuffer&&e.isTerminated===!0}function resolveProcessExitCode(e){return e.explicitCode??e.childExitCode??(e.usesWindowsExitCodeShim&&e.resolvedSignal==null&&!e.timedOut&&!e.noOutputTimedOut&&!e.killIssuedByTimeout&&!e.killIssuedByAbort?0:null)}function markOpenClawExecEnv(e){return{...e,OPENCLAW_CLI:`1`}}function resolveExecutablePathCandidate(e,t){let n=e.startsWith(`~`)?i(e,{env:t?.env}):e;if(process.platform===`win32`&&/^:[\\/]/.test(n))return;let r=n.includes(`/`)||n.includes(`\\`);if(t?.requirePathSeparator&&!r)return;if(!r)return n;if(O.isAbsolute(n))return O.resolve(n);let a=t?.cwd&&t.cwd.trim()?t.cwd:process.cwd();return O.resolve(a,n)}function resolveWindowsExecutableExtensions(e,t,n=!0){if(process.platform!==`win32`||O.extname(e).length>0)return[``];let r=[...resolveWindowsExecutableExtSet(t)];return n?[``,...r]:r}function resolveWindowsExecutableExtSet(e){return new Set((v(e,`PATHEXT`)??v(process.env,`PATHEXT`)??`.EXE;.CMD;.BAT;.COM`).split(`;`).map(e=>l(e)).filter(Boolean))}function isRegularFile(e){return h(e)?.isFile()??!1}const z=/* @__PURE__ */ new Set([`.com`,`.exe`,`.bat`,`.cmd`]);function isExecutableFile(e,t){if(!isRegularFile(e))return!1;try{if(process.platform===`win32`){let n=l(O.extname(e));return!n||z.has(n)?!0:resolveWindowsExecutableExtSet(t?.env).has(n)}return D.accessSync(e,D.constants.X_OK),!0}catch{return!1}}const B=6e4,V=/* @__PURE__ */ new Map;function cacheExecutablePath(e,t){V.set(e,{expiresAt:Date.now()+B,resolved:t??null}),a(V,128)}function resolveExecutableFromPathEnv(e,t,n,r){let i=r?.cwd?.trim()?O.resolve(r.cwd):void 0,a=r?.useCache!==!1,o=v(n,`PATHEXT`)??v(process.env,`PATHEXT`)??``,s=``;try{s=i??process.cwd()}catch{}let c=`${process.platform}\0${e}\0${JSON.stringify(t)}\0${o}\0${r?.includeExtensionless!==!1}\0${s}\0${i!==void 0}`,l=a?V.get(c):void 0,u=Date.now();if(l&&l.expiresAt>u)return l.expiresAt=u+B,V.delete(c),V.set(c,l),l.resolved??void 0;l&&V.delete(c);let d=process.platform===`win32`?`;`:O.delimiter,f=(typeof t==`string`?t.split(d):t).filter(e=>!!e||i!==void 0&&process.platform!==`win32`),p=resolveWindowsExecutableExtensions(e,n,r?.includeExtensionless);for(let t of f){let r=process.platform!==`win32`&&t.split(`/`).includes(`..`),o=i!==void 0&&!O.isAbsolute(t)?`${i}${O.sep}${t}`:t;for(let s of p){let l=r?`${o}${O.sep}${e}${s}`:O.join(i===void 0?t:O.resolve(i,t),e+s);if(isExecutableFile(l,{env:n}))return a&&cacheExecutablePath(c,l),l}}a&&cacheExecutablePath(c,void 0)}function encodeOwnedBuffer(e,t=`utf8`){let n=Buffer.allocUnsafeSlow(Buffer.byteLength(e,t));return n.write(e,t),n}function copyOwnedBuffer(e){let t=Buffer.allocUnsafeSlow(e.byteLength);return t.set(e),t}function hasChildProcessExited(e){return e.exitCode!=null||e.signalCode!=null}function releaseChildProcessOutputAfterExit(e){let t,n,r,cleanup=()=>{clearTimeout(t),clearTimeout(n),clearTimeout(r),e.removeListener(`exit`,onExit),e.stdout?.removeListener(`data`,onData),e.stderr?.removeListener(`data`,onData)},release=()=>{cleanup(),e.stdout?.destroy(),e.stderr?.destroy()},scheduleRelease=()=>{n??=setTimeout(release,0),n.unref()},armIdleTimer=()=>{clearTimeout(t),clearTimeout(n),n=void 0,t=setTimeout(scheduleRelease,100),t.unref()},onData=()=>{r&&armIdleTimer()},onExit=()=>{r=setTimeout(()=>{r=void 0,scheduleRelease()},1e3),r.unref(),armIdleTimer()};return e.stdout?.on(`data`,onData),e.stderr?.on(`data`,onData),hasChildProcessExited(e)?onExit():e.once(`exit`,onExit),cleanup}function createCapturedOutputBuffers(){return{chunks:[],bytes:0,truncatedBytes:0,preservedLines:[],decoder:new N(`utf8`),pendingLine:``}}function resolveMaxOutputBytes(e,n){return d(t(typeof e==`number`?e:e?.[n]),16777216,{min:1})}function resolveOutputCapture(e,t){return(typeof e==`string`?e:e?.[t])??`tail`}function shouldTerminateOnOutput(e,t){return typeof e==`boolean`?e:e?.[t]===!0}function appendCapturedOutput(e,t,n,r){if(r===`discard`){e.truncatedBytes+=Buffer.byteLength(t);return}let i=Buffer.isBuffer(t)?t:encodeOwnedBuffer(t);if(r===`head`){let t=Math.max(0,n-e.bytes);if(t>0){let n=i.subarray(0,t);e.chunks.push(n.byteLength<i.byteLength?copyOwnedBuffer(n):n),e.bytes+=n.byteLength}e.truncatedBytes+=Math.max(0,i.byteLength-t)}else if(i.byteLength>=n)e.chunks=[copyOwnedBuffer(i.subarray(i.byteLength-n))],e.truncatedBytes+=e.bytes+i.byteLength-n,e.bytes=n;else for(e.chunks.push(i),e.bytes+=i.byteLength;e.bytes>n&&e.chunks.length>0;){let t=o(e.chunks[0],`chunks entry at 0`),r=e.bytes-n;t.byteLength<=r?(e.chunks.shift(),e.bytes-=t.byteLength,e.truncatedBytes+=t.byteLength):(e.chunks[0]=copyOwnedBuffer(t.subarray(r)),e.bytes-=r,e.truncatedBytes+=r)}}function trimTruncatedUtf8Boundary(e,t,n,r){if(n===0||e.length===0||A.platform===`win32`&&!r)return e;if(t===`tail`){let t=0;for(;t<e.length&&(o(e[t],`buffer byte`)&192)==128;)t+=1;return e.subarray(t)}for(let t=0;t<=3&&t<=e.length;t+=1){let n=e.length-t;if(j(e.subarray(0,n)))return e.subarray(0,n)}return e}function finalizeCapturedOutput(e,t,n=!1){let r=Buffer.concat(e.chunks,e.bytes),i=trimTruncatedUtf8Boundary(r,t,e.truncatedBytes,n);return e.truncatedBytes+=r.byteLength-i.byteLength,i}function appendPreservedOutputLines(e){let{capture:t,maxPreservedOutputLines:n,preserveOutputLine:r}=e;if(!r||t.preservedLines.length>=n)return;let i=Buffer.isBuffer(e.chunk)?t.decoder.write(e.chunk):e.chunk;if(!i)return;let a=(t.pendingLine+i).split(/\r?\n/);t.pendingLine=S(a.pop()??``,e.maxPendingLineBytes);for(let i of a)t.preservedLines.length<n&&r(i,e.stream)&&t.preservedLines.push(i)}function flushPreservedOutputLine(e){let{capture:t,maxPreservedOutputLines:n,preserveOutputLine:r}=e;if(!r||n<=0)return;let i=S(t.pendingLine+t.decoder.end(),e.maxPendingLineBytes);t.pendingLine=``,i&&t.preservedLines.length<n&&r(i,e.stream)&&t.preservedLines.push(i)}const H=new TextDecoder,U=/* @__PURE__ */ new Map([[` `,` `],[`
`,`
`],[`\b`,`\\b`],[`\f`,`\\f`],[`\r`,`\\r`],[` `,`\\t`]]);function renderOutput(e){let t=typeof e==`string`?e:H.decode(e);return t.endsWith(`
`)&&(t=t.slice(0,t.endsWith(`\r
`)?-2:-1)),ue(t).replace(/[\p{Separator}\p{Other}]/gu,e=>{let t=U.get(e);if(t!==void 0)return t;let n=e.codePointAt(0),r=n.toString(16);return n<=65535?`\\u${r.padStart(4,`0`)}`:`\\U${r}`})}function decodeExecaMessage(e,t){return e.messageOutputs?[e.message,...e.messageOutputs.map(e=>renderOutput(t[e]))].join(`
`):e.message}function restoreError(e,t){let n=Error(decodeExecaMessage(e,t),{cause:e.cause?restoreError(e.cause,t):void 0});return Object.assign(n,{name:e.name,code:e.code})}function restoreExecaResult(e){let{error:t,...n}=e,r={...n,stdout:n.stdout,stderr:n.stderr,shortMessage:n.shortMessage,code:n.code};if(t){let e=restoreError(t,r);return Object.assign(e,r,{cause:e.cause})}return{...r,cause:void 0}}const W=/[&|<>%\r\n]/;function resolveNpmArgvForWindows(e){if(A.platform!==`win32`||e.length===0)return null;let t=l(O.basename(o(e[0],`argv entry at 0`))).replace(/\.(cmd|exe|bat)$/,``),n=t===`npx`?`npx`:t===`npm`?`npm`:null;if(!n)return null;let r=k(ne(n,O.join(O.dirname(A.execPath),`node_modules`,`npm`,`bin`)));if(D.existsSync(r))return[A.execPath,r,...e.slice(1)];let i=e[0]??``;return[l(O.extname(i))?i:`${i}.cmd`,...e.slice(1)]}function createWindowsCommandNotFoundError(e){let t=/* @__PURE__ */ Error(`spawn ${e} ENOENT`);return t.code=`ENOENT`,t.path=e,t.syscall=`spawn ${e}`,t}function resolveWindowsCommandFromCwdOrPath(e){if(e.command.includes(`/`)||e.command.includes(`\\`)){let t=resolveExecutablePathCandidate(e.command,{cwd:e.cwd,env:e.env});return t?O.extname(t)?isRegularFile(t)?t:void 0:resolveExecutableFromPathEnv(O.basename(t),O.dirname(t),e.env,{includeExtensionless:!1}):void 0}let t=e.cwd&&e.cwd.trim()?e.cwd:A.cwd(),n=(v(e.env,`PATH`)??v(A.env,`PATH`)??``).split(`;`).map(e=>e.replace(/^"(.*)"$/,`$1`).trim()).filter(Boolean).map(e=>O.isAbsolute(e)?e:O.resolve(t,e));return resolveExecutableFromPathEnv(e.command,n.join(`;`),e.env,{includeExtensionless:!1})}function resolveSupportedWindowsCommand(e){if(A.platform!==`win32`)return e.command;let t=resolveWindowsCommandFromCwdOrPath(e),n=resolveWindowsCommandShim({command:e.command,cmdCommands:[`corepack`,`pnpm`,`yarn`]});if(!t&&n!==e.command&&(t=resolveWindowsCommandFromCwdOrPath({...e,command:n})),!t)throw createWindowsCommandNotFoundError(e.command);let r=l(O.extname(t));if([`.exe`,`.com`,`.cmd`,`.bat`].includes(r))return t;throw Error(`Unsupported Windows command extension ${JSON.stringify(r||`<none>`)} for ${JSON.stringify(e.command)}; use an explicit executable or shell wrapper.`)}function resolveSafeChildProcessInvocation(e){let t=resolveNpmArgvForWindows(e.argv)??e.argv,n=e.cwd instanceof URL?k(e.cwd):e.cwd,r=resolveSupportedWindowsCommand({command:t[0]??``,cwd:n,env:e.env}),i=isWindowsBatchCommand(r);return{command:i?resolveSupportedWindowsCommand({command:resolveTrustedWindowsCmdExe(),cwd:n,env:e.env}):r,args:i?[`/d`,`/s`,`/c`,buildWindowsCmdExeCommandLine(r,t.slice(1))]:t.slice(1),usesWindowsExitCodeShim:A.platform===`win32`&&(i||t!==e.argv),windowsHide:!0,windowsVerbatimArguments:i?!0:e.windowsVerbatimArguments}}function isWindowsBatchCommand(e,t=A.platform){if(t!==`win32`)return!1;let n=l(O.extname(e));return n===`.cmd`||n===`.bat`}function buildWindowsCmdExeCommandLine(e,t){return`"${[e,...t].map(e=>{if(W.test(e))throw Error(`Unsafe Windows cmd.exe argument detected: ${JSON.stringify(e)}. Pass an explicit shell-wrapper argv at the call site instead.`);return`"${e.replace(/\\+/g,(t,n)=>{let r=e[n+t.length];return r===`"`||r===void 0?t.repeat(2):t}).replace(/"/g,`""`)}"`}).join(` `)}"`}function resolveTrustedWindowsCmdExe(e=A.platform){return e===`win32`?ae():`cmd.exe`}function resolveWindowsCommandShim(e){if(A.platform!==`win32`)return e.command;let t=l(O.basename(e.command));return O.extname(t)?e.command:e.cmdCommands.includes(t)?`${e.command}.cmd`:e.command}function isOutputOption(e){return e===void 0||e===`pipe`||e===`ignore`||e===`inherit`||typeof e==`object`&&!!e&&`file`in e&&typeof e.file==`string`&&Object.keys(e).length===1}function brokerExecaOptions(e){if(e.ipc||e.cleanup===!1||typeof e.stdin==`number`||e.stdout===`inherit`||e.stderr===`inherit`||e.stdio===`inherit`||typeof e.stdout==`number`||typeof e.stderr==`number`||e.stdio&&typeof e.stdio!=`string`&&e.stdio.some((e,t)=>typeof e==`number`||t>0&&e===`inherit`))return;if(e.cwd!==void 0&&typeof e.cwd!=`string`||e.input!==void 0&&typeof e.input!=`string`&&!(e.input instanceof Uint8Array)||e.stdin!==void 0&&e.stdin!==`pipe`&&e.stdin!==`ignore`&&e.stdin!==`inherit`||!isOutputOption(e.stdout)||!isOutputOption(e.stderr)||e.shell!==void 0&&e.shell!==!1)throw TypeError(`Unsupported spawn broker execa stream or invocation options`);if(Array.isArray(e.stdio)&&(e.stdio.length!==3||![`pipe`,`ignore`,`inherit`].includes(String(e.stdio[0]))||!isOutputOption(e.stdio[1])||!isOutputOption(e.stdio[2])))throw TypeError(`Unsupported spawn broker execa stdio`);let{cancelSignal:t,...n}=e;return n}function spawnBrokerCommand(e,t,n,r){let i=e.spawnExeca(t,r),a=i.child,o=a.waitForClose(),onAbort=()=>{a.killed=!0,i.cancel()};n.cancelSignal?.addEventListener(`abort`,onAbort,{once:!0}),n.cancelSignal?.aborted&&onAbort();let s=i.result.then(async e=>{e.timedOut&&(a.killed=!0),await o;let t=restoreExecaResult(e);if(t instanceof Error&&(n.reject!==!1||t.code===`ERR_SPAWN_BROKER_UNAVAILABLE`))throw t;return t}).finally(()=>n.cancelSignal?.removeEventListener(`abort`,onAbort));s.catch(()=>{}),M(a,`spawn`).then(()=>{setImmediate(()=>{for(let e of[a.stdout,a.stderr])e?.readableFlowing===null&&e.resume()})},()=>{});let c={nodeChildProcess:a,get pid(){return a.pid},get stdin(){return a.stdin},get stdout(){return a.stdout},get stderr(){return a.stderr},kill:e=>a.kill(e??n.killSignal)},l=Object.assign(s,c);return Object.defineProperties(l,Object.getOwnPropertyDescriptors(c))}const G=1e4;async function waitForCommandProcessGroupExit(e,t){let n=performance.now()+G;for(;x({pid:e});){if(!t())return`replaced`;let i=n-performance.now();if(i<=0)return x({pid:e})?`alive`:`exited`;await r(Math.min(25,i))}return`exited`}const K=/* @__PURE__ */ new WeakMap;async function waitForCommandSpawn(e){if(e.nodeChildProcess instanceof b)try{await e.nodeChildProcess.ready()}catch{await e}await K.get(e.nodeChildProcess)}const q=new le;function resolveCommandProcessSignal(e){let t=q.getStore()?.signal;return t&&e?AbortSignal.any([t,e]):t??e}function runOutsideCommandProcessScope(e){return q.exit(e)}function retainCommandProcessCleanup(e){let t=q.getStore();if(!t)return;let n=e.then(e=>{e===`uncertain`&&(t.failure??={error:new CommandProcessCleanupError})},e=>{t.failure??={error:e}});t.cleanups.add(n),n.then(()=>t.cleanups.delete(n))}function retainCommandProcess(e,t,n){let r,i=null,a=!1,o=!1,s=!1,l=!1,settleCustody=()=>{if(!(!n||s||l))try{n.settled(),l=!0}catch(e){throw s=!0,e}},u=t.nodeChildProcess,d=u.exitCode!=null||u.signalCode!=null,onExit=()=>{d=!0};u.once(`exit`,onExit);let f=u instanceof b?u.waitForClose():void 0,stop=()=>{if(!(a||r===void 0||A.platform===`win32`)){if(a=!0,u.exitCode!==null||u.signalCode!==null){if(!x({pid:r})){o=!0;return}let e=y(r);if(e!==null&&e!==i)throw new CommandProcessCleanupError}re(r,{detached:!0,force:!0}),w(u,!0)}},initialize=()=>{if(r=t.pid,r!==void 0)try{A.platform!==`win32`&&(i=y(r)),n?.spawned({pid:r,startedAt:te(r)}),e.signal.aborted&&stop()}catch(t){throw e.failure??={error:t},stop(),t}},p,m;if(u instanceof b&&t.pid===void 0)m=u.ready().then(initialize);else try{initialize(),m=Promise.resolve()}catch(e){p={error:e},m=Promise.reject(c(e,`Command process custody admission failed`))}K.set(u,m);let h=Promise.resolve(t).then(()=>void 0,()=>void 0).then(async()=>{await f,u.removeListener(`exit`,onExit)}),g=m.catch(t=>{u instanceof b&&u.notStarted||(e.failure??={error:t})}),_={stop,async settle(){if(await g,await h,o){settleCustody();return}if(r===void 0){if(u instanceof b&&!u.notStarted)throw new CommandProcessCleanupError;settleCustody();return}if(A.platform===`win32`){if(!d)throw new CommandProcessCleanupError;settleCustody();return}let e=r;if(await waitForCommandProcessGroupExit(e,()=>{let t=y(e);return t===null||t===i})!==`exited`)throw new CommandProcessCleanupError;settleCustody()}};if(e.children.add(_),h.then(()=>{if(r===void 0&&(!(u instanceof b)||u.notStarted)||r!==void 0&&A.platform!==`win32`&&!x({pid:r}))try{settleCustody(),e.children.delete(_)}catch(t){e.failure??={error:t}}}),p)throw p.error}function commandCreatesChildPipes(e){if((e.ipc??(e.node===!0||e.ipcInput!==void 0||e.gracefulCancel===!0))||e.input!==void 0||e.inputFile!==void 0)return!0;let t=typeof e.stdio==`string`||e.stdio===void 0?[e.stdio,e.stdio,e.stdio]:e.stdio;return[e.stdin??t[0],e.stdout??t[1],e.stderr??t[2],...t.slice(3).filter(e=>e!==void 0)].some(e=>e!==`ignore`&&e!==`inherit`&&!(typeof e==`number`&&e>=0))}function spawnCommandWithInvocation(e,t={}){A.platform===`win32`&&commandCreatesChildPipes(t)&&E();let n=q.getStore();if(n?.signal.aborted)throw Error(`Command process scope is closed`);let{baseEnv:r,env:i,windowsVerbatimArguments:a,cancelSignal:o,executionTimeoutMs:s,inheritScopeCancellation:c=!0,...l}=t,u=resolveCommandEnv({argv:e,baseEnv:r,env:i}),d=resolveSafeChildProcessInvocation({argv:e,cwd:l.cwd,env:u,windowsVerbatimArguments:a}),f={...l,cancelSignal:c?resolveCommandProcessSignal(o):o,...n?{killDescendants:!0}:{},env:u,extendEnv:!1,shell:!1,windowsHide:d.windowsHide,windowsVerbatimArguments:d.windowsVerbatimArguments},p=C(),m=p?brokerExecaOptions(f):void 0;m&&s!==void 0&&(m.executionDeadlineMs=s+1e3);let h=n?.custody?.reserve([d.command,...d.args]),g=p&&m?spawnBrokerCommand(p,[d.command,...d.args],f,m):P(d.command,d.args,f),_=e[0]===`nice`&&e[1]===`-n`&&e[2]===`10`&&e[3]===`git`;return T(_?`git`:d.command,g.nodeChildProcess,void 0,_?e.slice(4):d.args),n&&retainCommandProcess(n,g,h),{child:g,invocation:d}}function spawnCommand(e,t={}){return spawnCommandWithInvocation(e,t).child}function resolveCommandEnv(e){let t=e.baseEnv??A.env,n=e.platform??A.platform,r=O.basename(e.argv[0]??``),i=r===`npm`||r===`npm.cmd`||r===`npm.exe`||(r===`node`||r===`node.exe`)&&(e.argv[1]??``).includes(`npm-cli.js`),a=e.argv[0]??``,o=n===`win32`?O.win32:O.posix,s=o.isAbsolute(a)&&/^(?:node|node\.exe)$/iu.test(o.basename(a))&&/^(?:npm-cli\.js|npx-cli\.js|pnpm\.(?:cjs|js))$/iu.test(o.basename(e.argv[1]??``)),c=ee([t,e.env],n),l=s?p(c,a,n):c;return i&&(l.NPM_CONFIG_FUND??=`false`,l.npm_config_fund??=`false`),markOpenClawExecEnv(l)}function createCommandTerminationController(e){let t,n=`normal`,readOriginalStart=()=>e.processTree&&e.child.pid&&A.platform!==`win32`?y(e.child.pid):null,i=e.spawned!==void 0,a=!1,o=i?null:readOriginalStart(),s,isDirectChildAlive=()=>!e.isChildExited()&&e.child.exitCode==null&&e.child.signalCode==null,spawnTaskkill=async t=>{try{await runOutsideCommandProcessScope(()=>spawnCommand([ie(`taskkill.exe`),...t],{baseEnv:e.baseEnv,env:e.env,forceKillAfterDelay:300,reject:!1,stdio:`ignore`,timeout:5e3}))}catch{}},startWindowsTermination=(t,n)=>{let i=[];s=(async()=>{n?(i.push(spawnTaskkill([`/PID`,String(t),`/T`])),await r(e.killGraceMs),isDirectChildAlive()&&i.push(spawnTaskkill([`/PID`,String(t),`/T`,`/F`]))):i.push(spawnTaskkill([`/PID`,String(t),`/T`,`/F`])),await Promise.allSettled(i),e.isCommandSettled()||e.cancelController.abort()})()},terminate=()=>{if(i)return a=!0,!1;let r=e.child.pid,s=isDirectChildAlive();if(A.platform===`win32`&&!s)return!1;if(e.processTree&&typeof r==`number`){if(A.platform===`win32`)return startWindowsTermination(r,e.processTree.mode!==`force`),!0;let i=e.processTree.mode===`force`||e.killSignal===`SIGKILL`||e.killSignal===ce.signals.SIGKILL;if(t)return!i;let groupAlive=()=>x({pid:r}),forceAndObserve=async()=>{let t=y(r);t!==null&&t!==o?(n=`uncertain`,isDirectChildAlive()&&e.cancelController.abort()):(n=`forced`,re(r,{force:!0,detached:!0}),w(e.child,!0),n=await waitForCommandProcessGroupExit(r,()=>{let e=y(r);return e===null||e===o})===`exited`?`forced`:`uncertain`)};if(!s&&!groupAlive())return!1;if(i)return t=forceAndObserve(),!1;n=`cooperative`;try{A.kill(-r,e.killSignal??`SIGTERM`)}catch(e){e.code!==`ESRCH`&&(n=`uncertain`)}return w(e.child,!0,e.killGraceMs+G),t=new Promise(t=>{let r=performance.now()+e.killGraceMs,check=()=>{groupAlive()?performance.now()<r?setTimeout(check,Math.min(25,r-performance.now())):forceAndObserve().then(t):(n=`cooperative`,t())};check()}),!0}return s?A.platform===`win32`&&typeof r==`number`&&(startWindowsTermination(r,!1),!0):!1};return e.spawned&&e.spawned.then(()=>{o=readOriginalStart(),i=!1,a&&!terminate()&&e.cancelController.abort()},()=>{i=!1}),{terminate,settle:async()=>s?(await s,`forced`):(await t,n)}}function setProcessTimeout(e,t){let n,r=setTimeout(()=>{n=setTimeout(e,0)},t);return{clear(){clearTimeout(r),clearTimeout(n)},refresh(){clearTimeout(n),n=void 0,r.refresh()}}}async function runCommandWithTimeout(e,t){return await runCommandWithOutputEncoding(e,t,!1)}async function runCommandWithOutputEncoding(e,r,i,a=!1){let l=typeof r==`number`?{timeoutMs:r}:r,{timeoutMs:d,cwd:f,input:p,stdinFileDescriptor:h,baseEnv:v,env:ee,noOutputTimeoutMs:te,killProcessTree:y,killSignal:ne,killGraceMs:re}=l,x=resolveCommandProcessSignal(l.signal),S=typeof d==`number`?s(d,1):void 0;if(l.requireProcessTreeExtinction&&!y)throw Error(`Process-tree extinction requires process-tree ownership`);let C=p!==void 0;if(h!==void 0){if(!Number.isInteger(h)||h<0)throw Error(`stdinFileDescriptor must be a nonnegative integer`);if(C)throw Error(`Command accepts either input or stdinFileDescriptor, not both`)}if(l.beforeInput&&!C)throw Error(`Child input admission requires explicit input`);let w=s(re,300,0);if(x?.aborted){let e={code:null,signal:null,killed:!1,termination:`signal`,cleanup:`normal`,noOutputTimedOut:!1};return a?{...e,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0),windowsEncoding:null}:{...e,stdout:``,stderr:``}}let T=createCapturedOutputBuffers(),E=createCapturedOutputBuffers(),ie=resolveMaxOutputBytes(l.maxOutputBytes,`stdout`),ae=resolveMaxOutputBytes(l.maxOutputBytes,`stderr`),D=u(t(l.maxCombinedOutputBytes),{min:1}),O=resolveOutputCapture(l.outputCapture,`stdout`),k=resolveOutputCapture(l.outputCapture,`stderr`);if(D!==void 0&&O!==k)throw Error(`maxCombinedOutputBytes requires matching stdout and stderr capture modes`);let ce=D!==void 0&&O===`tail`&&k===`tail`,le=Math.min(Math.max(ie,ae),8192),ue=Math.max(0,Math.floor(l.maxPreservedOutputLines??16)),j=i?null:se(),M=new AbortController,N,P,F=!1,I=0,L=0,R={stdout:0,stderr:0},z={stdout:0,stderr:0},B=[],V,H,U,W,G,{child:K,invocation:q}=spawnCommandWithInvocation(e,{buffer:!1,cancelSignal:M.signal,inheritScopeCancellation:!1,cwd:f,detached:!!(y&&A.platform!==`win32`),encoding:`buffer`,executionTimeoutMs:S,baseEnv:v,env:ee,forceKillAfterDelay:w,killSignal:ne,...C&&!l.beforeInput?{input:p}:{},reject:!1,stdio:[l.stdinFileDescriptor??(C?`pipe`:`inherit`),`pipe`,`pipe`],stripFinalNewline:!1,windowsVerbatimArguments:l.windowsVerbatimArguments}),J=K.pid===void 0?waitForCommandSpawn(K):void 0,de=J!==void 0,fe=_(),Y=K.nodeChildProcess,pe=!l.beforeInput&&void 0,failedProcess=(e,t=`uncertain`)=>{let n=recordCommandProcessFailure(e,{pid:Y.pid,code:P?.code??Y.exitCode??null,cleanup:t,inputReleased:pe,termination:N===`output-limit`?`signal`:N??(Y.signalCode?`signal`:`exit`)});return Object.assign(n,{cleanup:t})},me=!!(y&&A.platform!==`win32`),he=n(te),ge=me&&(S!==void 0||he!==void 0),_e,ve=createCommandTerminationController({child:Y,spawned:J,cancelController:M,baseEnv:v,env:ee,processTree:y?{mode:`graceful`}:void 0,isChildExited:()=>P!==void 0,isCommandSettled:()=>F,killGraceMs:w,killSignal:ne}),X=(async()=>(await K.then(()=>void 0,()=>void 0),F=!0,await J?.catch(()=>{}),await ve.settle()))();retainCommandProcessCleanup(X),X.catch(()=>{}),Y.once(`exit`,(e,t)=>{P={code:e,signal:t},(!ge||e!==0||N)&&(_e=releaseChildProcessOutputAfterExit(Y)),y&&!N&&(e!==0||l.requireProcessTreeExtinction)&&ve.terminate()});let cancel=(e,t=!1)=>{if(!(N||F||P&&e!==`output-limit`&&(!me||P.code!==0))){if((e===`timeout`||e===`no-output-timeout`)&&(P||hasChildProcessExited(Y))){if(!ge||(P?.code??Y.exitCode)!==0||(!Y.stdout||Y.stdout.readableEnded)&&(!Y.stderr||Y.stderr.readableEnded))return;if(!t){H??=setProcessTimeout(()=>cancel(e,!0),100);return}}H?.clear(),N=e,de&&fe.resolve(e),P&&(_e??=releaseChildProcessOutputAfterExit(Y)),ve.terminate()||M.abort()}},armNoOutputTimer=()=>{he===void 0||F||N||P&&!me||(V?V.refresh():V=setProcessTimeout(()=>cancel(`no-output-timeout`),he))},ye=S===void 0?void 0:setProcessTimeout(()=>cancel(`timeout`),S),onAbort=()=>cancel(`signal`);x?.addEventListener(`abort`,onAbort,{once:!0}),armNoOutputTimer();let clearTimers=()=>{ye?.clear(),V?.clear(),H?.clear(),V=void 0,x?.removeEventListener(`abort`,onAbort)};if(J){let e;try{e=await Promise.race([J.then(()=>void 0),fe.promise])}catch(e){throw clearTimers(),failedProcess(e,Y instanceof b&&Y.notStarted?`normal`:`uncertain`)}if(e){clearTimers(),X.finally(()=>_e?.()).catch(()=>{});let t={pid:Y.pid,code:e===`timeout`||e===`no-output-timeout`?124:null,signal:null,killed:Y.killed,cleanup:`uncertain`,termination:e===`output-limit`?`signal`:e,noOutputTimedOut:e===`no-output-timeout`,outputLimitExceeded:e===`output-limit`||void 0};return recordCommandProcessCleanup(a?{...t,stdout:Buffer.alloc(0),stderr:Buffer.alloc(0),windowsEncoding:j}:{...t,stdout:``,stderr:``},X)}de=!1}let captureOutput=(e,t,n,r,i)=>{R[r]+=t.byteLength;let a=R[r]>n;if(D===void 0){appendCapturedOutput(e,t,n,i),a&&shouldTerminateOnOutput(l.terminateOnOutputLimit,r)&&cancel(`output-limit`);return}let s=I;I+=t.byteLength;let c=I>D;if(ce){B.push({stream:r,buffer:t}),L+=t.byteLength,z[r]+=t.byteLength;let removeCapturedBytes=(e,t)=>{let n=o(B[e],`combined tail chunk`),r=Math.min(t,n.buffer.byteLength);r===n.buffer.byteLength?B.splice(e,1):n.buffer=copyOwnedBuffer(n.buffer.subarray(r)),L-=r,z[n.stream]-=r,(n.stream===`stdout`?T:E).truncatedBytes+=r};for(;z[r]>n;){let e=B.findIndex(e=>e.stream===r);if(e<0)break;removeCapturedBytes(e,z[r]-n)}let e=L-D;for(;e>0;)removeCapturedBytes(0,e),e=L-D}else{let r=Math.max(0,D-s);appendCapturedOutput(e,t,Math.min(n,e.bytes+r),i)}(c&&shouldTerminateOnOutput(l.terminateOnOutputLimit,`combined`)||a&&shouldTerminateOnOutput(l.terminateOnOutputLimit,r))&&cancel(`output-limit`)},observeOutputChunk=(e,t)=>{let n=Buffer.isBuffer(e)?e:Buffer.from(e);if(N||!l.onOutputChunk)return n;try{l.onOutputChunk(n,t)===!1&&cancel(`output-limit`)}catch(e){U=e,cancel(`output-limit`)}return n},onOutputError=(e,t)=>{W??=t,!N&&l.tolerateOutputError?.[t]!==!0&&shouldTerminateOnOutput(l.terminateOnOutputError,t)&&(G=c(e,`Command ${t} stream failed`),Object.assign(G,{outputErrorStream:t}),cancel(`signal`))};K.stdout?.once(`error`,e=>onOutputError(e,`stdout`)),K.stderr?.once(`error`,e=>onOutputError(e,`stderr`));let be=[{stream:`stdout`,capture:T,maxBytes:ie,mode:O},{stream:`stderr`,capture:E,maxBytes:ae,mode:k}];for(let{stream:e,capture:t,maxBytes:n,mode:r}of be)K[e]?.on(`data`,i=>{let a=observeOutputChunk(i,e);appendPreservedOutputLines({capture:t,chunk:a,stream:e,preserveOutputLine:l.preserveOutputLine,maxPreservedOutputLines:ue,maxPendingLineBytes:le}),captureOutput(t,a,n,e,r),armNoOutputTimer()});let xe;if(l.beforeInput){Y.stdin?.once(`error`,e=>{m(e,`EPIPE`)||(xe??=c(e,`Command input failed`),cancel(`signal`))});try{if(Y.pid===void 0||!Y.stdin)throw Error(`Child input admission has no spawned process`);let e=l.beforeInput(Y.pid,Y.spawnargs);if(e!==void 0)throw g(e)&&Promise.resolve(e).catch(()=>void 0),TypeError(`Child input admission must complete synchronously`);pe=!0,Y.stdin.end(p)}catch(e){xe=c(e,`Child input admission failed`),cancel(`signal`)}}let Z=await K.finally(()=>{F=!0,clearTimers(),_e?.()}).catch(e=>{throw failedProcess(e)});Z.timedOut&&(N??=`timeout`);let Q=await X.catch(e=>{throw failedProcess(e)}),$=Z.signal??P?.signal??Y.signalCode??null;if(Q===`normal`&&$&&!(me&&l.requireProcessTreeExtinction)&&(Q=`uncertain`),xe)throw failedProcess(xe,Q);if(G)throw failedProcess(G,Q);if(U!==void 0)throw failedProcess(c(U,`Command output observer failed`),Q);let Se=!N&&q.usesWindowsExitCodeShim&&typeof Y.pid==`number`&&Z.code===void 0&&Z.cause===void 0&&!Z.timedOut&&!Z.isCanceled&&!Z.isMaxBuffer&&!Z.isTerminated;if(Z.failed&&!N&&!isPlainCommandExitFailure(Z)&&!isPlainCommandSignalFailure(Z)&&!Se&&(Z.exitCode!==0||W===void 0||l.tolerateOutputError?.[W]!==!0)){let e=createSanitizedCommandError(Z),t=typeof Y.pid==`number`?Q===`normal`?`uncertain`:Q:`normal`;throw W&&Object.assign(e,{outputErrorStream:W}),failedProcess(e,t)}let Ce=N===`signal`||N===`output-limit`,we=resolveProcessExitCode({explicitCode:Z.exitCode??P?.code,childExitCode:Y.exitCode,resolvedSignal:$,usesWindowsExitCodeShim:q.usesWindowsExitCodeShim,timedOut:N===`timeout`,noOutputTimedOut:N===`no-output-timeout`,killIssuedByTimeout:N===`timeout`||N===`no-output-timeout`,killIssuedByAbort:Ce});N??=$!=null||Z.isTerminated?`signal`:`exit`;let Te=(N===`timeout`||N===`no-output-timeout`)&&(we==null||we===0)?124:we;for(let{stream:e,capture:t}of be)flushPreservedOutputLine({capture:t,stream:e,preserveOutputLine:l.preserveOutputLine,maxPreservedOutputLines:ue,maxPendingLineBytes:le});if(ce)for(let e of B){let t=e.stream===`stdout`?T:E;t.chunks.push(e.buffer),t.bytes+=e.buffer.byteLength}let Ee=finalizeCapturedOutput(T,O,i),De=finalizeCapturedOutput(E,k,i),Oe={pid:Y.pid,stdoutTruncatedBytes:T.truncatedBytes||void 0,stderrTruncatedBytes:E.truncatedBytes||void 0,preservedStdoutLines:T.preservedLines.length>0?T.preservedLines:void 0,preservedStderrLines:E.preservedLines.length>0?E.preservedLines:void 0,code:Te,signal:$,killed:Y.killed,killIssuedByAbort:Ce||void 0,cleanup:Q,termination:N===`output-limit`?`signal`:N,noOutputTimedOut:N===`no-output-timeout`,outputLimitExceeded:N===`output-limit`||void 0,...W?{outputErrorStream:W}:{}};return a?{...Oe,stdout:Ee,stderr:De,windowsEncoding:j}:{...Oe,stdout:i?Ee.toString(`utf8`):oe({buffer:Ee,windowsEncoding:j}),stderr:i?De.toString(`utf8`):oe({buffer:De,windowsEncoding:j})}}async function runCommandBuffered(e,n={}){if(n.signal?.aborted)return{stdout:Buffer.alloc(0),stderr:Buffer.alloc(0),code:null,signal:null,killed:!1,termination:`signal`,...n.signal.reason instanceof Error?{error:n.signal.reason}:{}};let r={stdout:[],stderr:[]},i={stdout:0,stderr:0},a=u(t(n.maxCombinedOutputBytes),{min:1}),o,appendChunk=(e,t)=>{if(n.discardOutput?.[t])return!0;let s=resolveMaxOutputBytes(n.maxOutputBytes,t),c=i.stdout+i.stderr,l=a===void 0?1/0:Math.max(0,a-c),u=Math.max(0,Math.min(s-i[t],l));if(u>0){let n=e.byteLength>u?copyOwnedBuffer(e.subarray(0,u)):e;r[t].push(n),i[t]+=n.byteLength}return e.byteLength>u?(o??=t,!1):!0},capturedOutput=e=>Buffer.concat(r[e],i[e]);try{let t=await runCommandWithTimeout(e,{baseEnv:n.baseEnv,cwd:n.cwd,env:n.env,input:n.input,killProcessTree:n.killProcessTree??!0,killGraceMs:n.killGraceMs,onOutputChunk:appendChunk,outputCapture:`discard`,signal:n.signal,timeoutMs:n.timeoutMs,noOutputTimeoutMs:n.noOutputTimeoutMs,tolerateOutputError:{stdout:n.discardOutput?.stdout||n.tolerateOutputError?.stdout,stderr:n.discardOutput?.stderr||n.tolerateOutputError?.stderr},terminateOnOutputError:n.terminateOnOutputError}),r=t.outputLimitExceeded?`output-limit`:t.termination;return{stdout:capturedOutput(`stdout`),stderr:capturedOutput(`stderr`),code:r===`exit`?t.code:null,signal:t.signal,killed:t.killed,termination:r,...o?{outputLimitStream:o}:{},...t.outputErrorStream?{errorStream:t.outputErrorStream}:{},...t.cleanup===`uncertain`?{error:new CommandProcessCleanupError}:{}}}catch(e){let t=e instanceof Error?e:/* @__PURE__ */ Error(`Command execution failed`),n=t,r=n.outputErrorStream===`stdout`||n.outputErrorStream===`stderr`?n.outputErrorStream:void 0;return{stdout:capturedOutput(`stdout`),stderr:capturedOutput(`stderr`),code:typeof n.exitCode==`number`?n.exitCode:null,signal:null,killed:!1,termination:`error`,...r?{errorStream:r}:{},error:readCommandProcessFailure(t)?.cleanup===`uncertain`&&!hasCommandProcessCleanupError(t)?new CommandProcessCleanupError({cause:t}):t}}}export{runCommandBuffered,runCommandWithTimeout};