UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines (6 loc) • 17.3 kB
import{h as e}from"./plugin-preparation-record-coerce-CWNcHDAn.mjs";import{Y as t}from"./plugin-preparation-diagnostic-events-C0NITktC.mjs";import{p as n}from"./plugin-preparation-sleep-D6xG-JRB.mjs";import{t as r}from"./plugin-preparation-deferred-B75K7ut7.mjs";import{c as i,i as a,l as o,p as s,r as c}from"./plugin-preparation-service-child-group-ownership-DVaB1fex.mjs";import{AsyncResource as l}from"node:async_hooks";import{opendirSync as u,readFileSync as d}from"node:fs";import f,{readFile as p,readdir as m}from"node:fs/promises";import{fileURLToPath as h}from"node:url";import{stripVTControlCharacters as g}from"node:util";import{spawn as _,spawnSync as v}from"node:child_process";import{Socket as y}from"node:net";import{inspectChildWaitState as b,isSupported as x,reapChild as S}from"@openclaw/proc-safe/reaper";import{EventEmitter as C}from"node:events";const w=new t(Symbol(`spawnBroker`)),T={startupDisabled:!1};function getSpawnBroker(){let e=w.getStore();return T.startupDisabled||e===null?void 0:e??T.host}const E=new TextDecoder,D=/* @__PURE__ */ new Map([[` `,` `],[` `,` `],[`\b`,`\\b`],[`\f`,`\\f`],[`\r`,`\\r`],[` `,`\\t`]]);function renderOutput(e){let t=typeof e==`string`?e:E.decode(e);return t.endsWith(` `)&&(t=t.slice(0,t.endsWith(`\r `)?-2:-1)),g(t).replace(/[\p{Separator}\p{Other}]/gu,e=>{let t=D.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}}function childCapacityError(e,t){let n=0,r=0;for(let t of e)n++,t===`mcp`&&r++;if(n>=512)return`Spawn broker child capacity exceeded (512); close running processes before retrying`;if(t===`mcp`&&r>=448)return`Spawn broker MCP child capacity exceeded (448); close unused MCP sessions before retrying`}var SpawnBrokerError=class extends Error{constructor(e,t){super(e,t),this.code=`ERR_SPAWN_BROKER_UNAVAILABLE`,this.name=`SpawnBrokerError`}};function serializeBrokerError(e){return{message:e.message,code:e.code,errno:e.errno,syscall:e.syscall,path:e.path}}const O=4096;function killProcessTree(e,t){if(!Number.isFinite(e)||e<=0)return;if(process.platform===`win32`){if(t?.force===!0){signalProcessTreeWindowsAndWait(e,`SIGKILL`);return}killProcessTreeWindows(e,normalizeGraceMs(t?.graceMs));return}let n=t?.detached===!0||t?.detached!==!1&&isProcessGroupLeader(e),r=t?.detached===!1&&!n&&process.platform===`linux`,i=r?collectUnixProcessTree(e):void 0;if(r&&!i){signalProcessTreeUnix(e,t?.force===!0?`SIGKILL`:`SIGTERM`,!1);return}let a=!1,force=()=>{if(a)return;a=!0;let t=i?.filter(verifiedProcessInstanceAlive)??[];(n?isProcessAlive(-e):r?t.length>0:isProcessAlive(e))&&signalProcessTreeUnix(e,`SIGKILL`,n,i?t:void 0)};if(t?.force===!0){i?force():signalProcessTreeUnix(e,`SIGKILL`,n);return}signalProcessTreeUnix(e,`SIGTERM`,n,i);let o=normalizeGraceMs(t?.graceMs),s=setTimeout(force,o);r||s.unref();let c=!1;return{force:()=>{clearTimeout(s),force()},exited:()=>(c||=n?!isProcessAlive(-e):i?!i.some(capturedProcessInstanceMayBeAlive):!isProcessAlive(e),c&&(a=!0,clearTimeout(s)),c)}}function normalizeGraceMs(e){return typeof e!=`number`||!Number.isFinite(e)?3e3:Math.max(0,Math.min(6e4,Math.floor(e)))}function isProcessAlive(e){try{process.kill(e,0)}catch(e){if((typeof e==`object`&&e&&`code`in e?e.code:void 0)!==`EPERM`)return!1}if(e<0||process.platform!==`linux`)return!0;try{let t=d(`/proc/${e}/status`,`utf8`);return!(t.match(/^State:\s+(\S)/m)?.[1]===`Z`&&/^Threads:[ \t]+1[ \t]*$/m.test(t))}catch{return!0}}function parseProcessGroupId(e){if(typeof e!=`string`||!/^\d+$/.test(e.trim()))return;let t=Number(e.trim());return Number.isSafeInteger(t)&&t>0?t:void 0}function readPsOutput(e){try{let t=v(`ps`,e,{encoding:`utf8`,timeout:500});return t.error||t.status!==0?void 0:t.stdout}catch{return}}function readProcStatFields(e){try{let t=d(`/proc/${e}/stat`,`utf8`),n=t.lastIndexOf(`)`);return n<0?void 0:t.slice(n+1).trim().split(/\s+/)}catch{return}}function isProcessGroupLeader(e){return((process.platform===`linux`?parseProcessGroupId(readProcStatFields(e)?.[2]):void 0)??parseProcessGroupId(readPsOutput([`-p`,String(e),`-o`,`pgid=`])))===e}function parsePositivePids(e){return typeof e==`string`?e.trim().split(/\s+/u).map(e=>Number(e)).filter(e=>Number.isSafeInteger(e)&&e>0):[]}function readUnixProcessIdentity(e,t){return readUnixProcessInstance(e,t)?.identity}function readUnixProcessInstance(e,t){if(t!==void 0&&Date.now()>=t||process.platform!==`linux`)return;let n=readProcStatFields(e),r=Number(n?.[1]),i=n?.[19];if(i&&/^\d+$/u.test(i)&&Number.isSafeInteger(r))return{identity:`${e}:${i}`,ppid:r}}function verifiedProcessInstanceAlive(e){return!e.identity||!isProcessAlive(e.pid)?!1:readUnixProcessIdentity(e.pid)===e.identity}function capturedProcessInstanceMayBeAlive(e){if(!e.identity||!isProcessAlive(e.pid))return!1;let t=readUnixProcessIdentity(e.pid);return t===void 0||t===e.identity}function*readUnixProcessChildren(e,t){let n;try{for(n=u(`/proc/${e}/task`);t();){let t=n.readSync();if(!t)return;let r=parseProcessGroupId(t.name);if(r)try{yield*parsePositivePids(d(`/proc/${e}/task/${r}/children`,`utf8`))}catch{}}}catch{}finally{try{n?.closeSync()}catch{}}}function collectUnixProcessTree(e){if(process.platform!==`linux`)return;let t=[],n=/* @__PURE__ */ new Set([e]),r=0,i=Date.now()+500,a=readUnixProcessIdentity(e,i);if(!a||Date.now()>=i)return;let withinBounds=e=>Date.now()<i&&e<=128,hasCapacity=()=>n.size<O,visit=(e,a,o)=>{if(!withinBounds(o)||!hasCapacity()||readUnixProcessIdentity(e,i)!==a)return;let s=readUnixProcessChildren(e,()=>withinBounds(o)&&hasCapacity()&&r++<O&&readUnixProcessIdentity(e,i)===a);for(let r of s){if(!withinBounds(o+1)||!hasCapacity())return;if(n.has(r)||r===process.pid)continue;n.add(r);let a=readUnixProcessInstance(r,i);a&&a.ppid===e&&withinBounds(o+1)&&(visit(r,a.identity,o+1),t.push({pid:r,identity:a.identity}))}};return visit(e,a,0),[...t,{pid:e,identity:a}]}function signalProcessTreeUnix(e,t,n,r){if(n){signalUnixTarget(-e,t);return}let i=r??[{pid:e}];for(let e of i)(!r||verifiedProcessInstanceAlive(e))&&signalUnixTarget(e.pid,t)}function signalUnixTarget(e,t){try{process.kill(e,t)}catch{}}function runTaskkill(e,t){return new Promise(n=>{let r=!1,finish=e=>{r||(r=!0,clearTimeout(i),t?.(e),n())},i=setTimeout(()=>finish(null),3e3);i.unref?.();try{let t=_(`taskkill`,e,{stdio:`ignore`,detached:!0,windowsHide:!0});t.once(`error`,()=>finish(null)),t.once(`close`,e=>finish(e))}catch{finish(null)}})}function killProcessTreeWindows(e,t){let n=!1,r,forceKill=()=>{n||(n=!0,r!==void 0&&(clearTimeout(r),r=void 0),isProcessAlive(e)&&signalProcessTreeWindowsAndWait(e,`SIGKILL`))};signalProcessTreeWindowsAndWait(e,`SIGTERM`,e=>{e!==null&&e!==0&&forceKill()}),r=setTimeout(forceKill,t),r.unref()}function signalProcessTreeWindowsAndWait(e,t,n){return runTaskkill(t===`SIGKILL`?[`/F`,`/T`,`/PID`,String(e)]:[`/T`,`/PID`,String(e)],n)}const k=/* @__PURE__ */ new WeakSet,A=/* @__PURE__ */ new Map,j=3e4;let M,N=0,P=!1;function schedule(e){let t=performance.now()+e;M&&N<=t||(clearTimeout(M),N=t,M=setTimeout(()=>void tick(),e).unref())}function onExit(){schedule(25)}async function tick(){if(M=void 0,P)schedule(25);else{P=!0;try{for(let[e,t]of A)if(performance.now()>=t)A.delete(e);else try{process.kill(-e,0)}catch(t){n(t,`ESRCH`)&&A.delete(e)}if(A.size===0)return;for(let e of await m(`/proc/self/task`)){let t;try{t=await p(`/proc/self/task/${e}/children`,`utf8`)}catch{continue}for(let e of t.trim().split(/\s+/u).filter(Boolean)){let t=Number(e),n;try{n=await p(`/proc/${t}/stat`,`utf8`)}catch{continue}let[r,i,a]=n.slice(n.lastIndexOf(`)`)+2).split(` `);if(A.has(Number(a))&&t!==Number(a)&&Number(i)===process.pid&&r===`Z`)try{if(!x()){A.clear();return}b(t).kind===`exited`&&S(t)}catch{}}}}catch{}finally{P=!1,A.size>0?schedule(1e3):(clearTimeout(M),M=void 0,process.off(`SIGCHLD`,onExit))}}}function scheduleAdoptedChildZombieReapAfterExit(e,t,n=j){if(process.platform!==`linux`||!t||e.pid===void 0||k.has(e))return;let r=e.pid;k.add(e);let start=()=>{A.size===0&&process.on(`SIGCHLD`,onExit),A.set(r,performance.now()+Math.max(j,n)),onExit()};e.exitCode!==null||e.signalCode!==null?start():e.once(`exit`,start)}function shouldDetachChildForProcessTree(){return process.platform!==`win32`}function isDeniedProcessGroupProbe(e,t=0){if(process.platform!==`linux`||!n(e,`EPERM`))return!1;try{return process.kill(-4194305,t),!1}catch(e){return n(e,`EPERM`)}}function probeProcessGroup(e){try{return process.kill(-e,0),`alive`}catch(e){return n(e,`ESRCH`)?`gone`:isDeniedProcessGroupProbe(e)?`denied`:`alive`}}function isProcessGroupGoneByKernel(e){return probeProcessGroup(e)===`gone`}function isProcessGroupGone(e){let t=probeProcessGroup(e);return t===`gone`||t===`denied`&&c(e)}async function isProcessGroupGoneAsync(e){let t=probeProcessGroup(e);return t===`gone`||t===`denied`&&await a(e)}async function isChildProcessTreeAliveAsync(e){return typeof e.pid!=`number`||e.pid<=0?!1:shouldDetachChildForProcessTree()?!await isProcessGroupGoneAsync(e.pid):isChildProcessTreeAlive(e)}function isChildProcessTreeAlive(e){if(typeof e.pid!=`number`||e.pid<=0)return!1;if(shouldDetachChildForProcessTree())return!isProcessGroupGone(e.pid);try{return process.kill(e.pid,0),!0}catch(e){return!n(e,`ESRCH`)}}function readCommandProcessStartTime(e,t={}){return process.platform!==`linux`&&process.platform!==`android`?t.instance?o(e):i(e):f.readFile(`/proc/${e}/stat`,`utf8`).then(n=>t.child&&(t.child.exitCode!=null||t.child.signalCode!=null)?null:s(e,n)?.startedAt??null,()=>null)}function brokerSpawnOptions(e){let t=e.stdio??`pipe`,n=typeof t==`string`?[t,t,t]:[...t],r=[];for(let e=0;e<Math.max(3,n.length);e+=1){let t=n[e]??(e<3?`pipe`:`ignore`);if(t===`inherit`&&e!==0||t!==`pipe`&&t!==`ignore`&&t!==`inherit`&&t!==`ipc`)return;r.push(t)}if(e.signal||e.timeout||e.killSignal)throw Error(`Unsupported spawn broker cancellation options`);return{cwd:e.cwd instanceof URL?h(e.cwd):e.cwd,env:e.env?{...e.env}:{...process.env},argv0:e.argv0,detached:e.detached,shell:e.shell,windowsHide:e.windowsHide,windowsVerbatimArguments:e.windowsVerbatimArguments,serialization:e.serialization,uid:e.uid,gid:e.gid,stdio:r}}const F=/* @__PURE__ */ new WeakMap,holdReadable=()=>{};function holdPipe(e){let t={read:e.read.bind(e),resumed:!1,onResume:()=>{t.resumed=!0}};F.set(e,t),e.on(`resume`,t.onResume),e.on(`readable`,holdReadable),e.read=()=>null}function restoreStdinPipe(e){let t=Reflect.get(e,`_readableState`);if(!t||typeof t!=`object`||[`ended`,`endEmitted`,`reading`].some(e=>typeof Reflect.get(t,e)!=`boolean`))throw new SpawnBrokerError(`Spawn broker requires a Node readable state for stdin`);stopPipeReads(e),Object.assign(t,{readable:!1,ended:!0,endEmitted:!0,reading:!1})}function stopPipeReads(e){let t=Reflect.get(e,`_handle`);if(!t||typeof t!=`object`||!(`readStop`in t)||typeof t.readStop!=`function`||!(`reading`in t)||typeof t.reading!=`boolean`)throw new SpawnBrokerError(`Spawn broker requires a transferable Node pipe handle`);if(t.readStop()!==0)throw new SpawnBrokerError(`Spawn broker could not stop pipe reads`);t.reading=!1}function releasePipe(e){let t=restoreReader(e);t&&process.nextTick(()=>{e.destroyed||(e.emit(`readable`),t.resumed&&e.resume())})}function restoreReader(e){let t=F.get(e);if(t)return e.read=t.read,F.delete(e),e.removeListener(`resume`,t.onResume),e.removeListener(`readable`,holdReadable),t}var BrokerChild=class extends C{constructor(e,t,n,i=!1){super(),this.requestId=e,this.transmit=n,this.fileOutputPending=i,this.callbackContext=new l(`OpenClawSpawnBrokerChild`),this.stdin=null,this.stdout=null,this.stderr=null,this.connected=!1,this.killed=!1,this.exitCode=null,this.signalCode=null,this.stdio=[null,null,null,null,null],this.opened=r(),this.completion=r(),this.pipes=/* @__PURE__ */ new Set,this.sends=/* @__PURE__ */ new Map,this.sendSequence=0,this.spawnReceived=!1,this.eventsReleased=!1,this.pendingEventOverflow=!1,this.pendingEvents=[],this.exited=!1,this.closed=!1,this.processNotStarted=!1,this.spawnfile=t[0],this.spawnargs=[...t],this.opened.promise.catch(()=>{}),this.on(`error`,()=>{})}markNotStarted(){this.processNotStarted=!0}get notStarted(){return this.processNotStarted}ready(){return this.opened.promise}emit(e,...t){return this.callbackContext.runInAsyncScope(()=>super.emit(e,...t))}waitForClose(){return this.completion.promise}settleFileOutput(){this.fileOutputPending=!1,this.finishClose()}attachPipe(e,t){t.emit=this.callbackContext.bind(t.emit.bind(t)),this.stdio[e]=t,e===0&&(this.stdin=t),e===1&&(this.stdout=t),e===2&&(this.stderr=t),this.pipes.add(t);let n=!1,acknowledge=t=>{n||(n=!0,this.transmit({type:`output-drained`,id:this.requestId,fd:e,error:t?serializeBrokerError(t):void 0}).catch(()=>{}))};t.once(e===0?`finish`:`end`,()=>acknowledge()),t.on(`error`,acknowledge),t.once(`close`,()=>{acknowledge(),this.pipes.delete(t),this.finishClose()})}receive(e){if(e.type===`spawned`){if(this.spawnReceived||this.closed)return;for(this.spawnReceived=!0,this.pid=e.pid,this.spawnfile=e.spawnfile,this.spawnargs=e.spawnargs,this.connected=e.connected,this.stdio.splice(e.stdioLength);this.stdio.length<e.stdioLength;)this.stdio.push(null);this.connected&&(this.channel=Object.assign(new C,{ref(){},unref(){}})),this.opened.resolve(),setImmediate(()=>{this.closed||(this.emit(`spawn`),setImmediate(()=>{for(let[e,t]of this.stdio.entries())e>0&&t instanceof y&&!t.destroyed&&releasePipe(t);this.eventsReleased=!0;for(let e of this.pendingEvents.splice(0))e()}))})}else!this.eventsReleased&&(this.spawnReceived||e.type!==`error`)?this.deferEvent(()=>this.emitMessage(e)):this.emitMessage(e)}deferEvent(e){this.pendingEventOverflow||(this.pendingEvents.length>=64?(this.pendingEventOverflow=!0,this.pendingEvents.splice(0),this.pendingEvents.push(()=>{this.kill(`SIGKILL`),this.failNow(new SpawnBrokerError(`Spawn broker startup event capacity exceeded`))})):this.pendingEvents.push(e))}emitMessage(e){switch(e.type){case`error`:{let t=Object.assign(Error(e.error.message),e.error);this.opened.reject(t),this.emit(`error`,t),this.pid||(this.exited=!0,this.finishClose());break}case`exit`:this.exited=!0,this.exitCode=e.code,this.signalCode=e.signal,this.stdin?.destroy(),this.emit(`exit`,e.code,e.signal),process.nextTick(()=>{for(let e of this.pipes)e.readable&&e.resume()}),this.finishClose();break;case`ipc-sent`:this.finishSend(e.sequence,e.error?Object.assign(Error(e.error.message),e.error):null);break;case`disconnect`:this.failSends(/* @__PURE__ */ Error(`Child process IPC channel is closed`)),this.connected=!1,this.channel=void 0,this.emit(`disconnect`),this.finishClose();break;case`ipc`:this.emit(`message`,e.message);break;case`closed`:this.finishClose()}}fail(e){this.spawnReceived&&!this.eventsReleased?this.deferEvent(()=>this.failNow(e)):this.failNow(e)}failNow(e){if(this.closed)return;this.opened.reject(e);let t=this.connected;this.connected=!1,this.channel=void 0,this.failSends(e),t&&this.emit(`disconnect`),this.exited||this.emit(`error`,e);for(let t of this.pipes)t.destroy(e);this.exited=!0,this.finishClose()}finishClose(){!this.exited||this.channel||this.pipes.size>0||this.closed||this.fileOutputPending||(this.closed=!0,this.completion.resolve(),this.emit(`close`,this.exitCode,this.signalCode))}kill(t=`SIGTERM`){return!this.exited&&(this.killed=!0,this.transmit({type:`kill`,id:this.requestId,signal:t}).catch(t=>this.fail(e(t,`Spawn broker signal delivery failed`))),!0)}send(t,n,r,i,a){let o=typeof n==`function`?n:typeof r==`function`?r:i;if(!this.connected||this.sends.size>=1024){let e=/* @__PURE__ */ Error(this.connected?`Child process IPC capacity exceeded`:`Child process IPC channel is closed`);return queueMicrotask(()=>o?o(e):this.emit(`error`,e)),!1}let s=++this.sendSequence;this.sends.set(s,l.bind(e=>{o?o(e):e&&this.emit(`error`,e)}));let c=typeof n==`function`?void 0:n;return this.transmit({type:`ipc`,id:this.requestId,sequence:s,message:t},c,a).catch(t=>this.finishSend(s,e(t,`Spawn broker IPC delivery failed`))),!0}finishSend(e,t){let n=this.sends.get(e);this.sends.delete(e),n?.(t)}failSends(e){for(let t of this.sends.keys())this.finishSend(t,e)}disconnect(){this.connected&&(this.connected=!1,this.transmit({type:`disconnect`,id:this.requestId}).catch(t=>this.fail(e(t,`Spawn broker disconnect failed`))))}ref(){}unref(){}[Symbol.dispose](){this.kill(`SIGTERM`)}};export{getSpawnBroker as _,readCommandProcessStartTime as a,isDeniedProcessGroupProbe as c,isProcessGroupGoneByKernel as d,scheduleAdoptedChildZombieReapAfterExit as f,restoreExecaResult as g,childCapacityError as h,restoreStdinPipe as i,isProcessGroupGone as l,SpawnBrokerError as m,brokerSpawnOptions as n,isChildProcessTreeAlive as o,killProcessTree as p,holdPipe as r,isChildProcessTreeAliveAsync as s,BrokerChild as t,isProcessGroupGoneAsync as u};