openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 8.49 kB
JavaScript
import{c as toErrorObject}from"./error-coercion-B-1Loz4b.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{AsyncResource}from"node:async_hooks";import{fileURLToPath}from"node:url";import{EventEmitter}from"node:events";import{Socket}from"node:net";
//!src/process/spawn-broker/protocol.ts
const MAX_OWNED_CHILDREN=512;const MAX_MCP_CHILDREN=448;function childCapacityError(e,t){let n=0;let r=0;for(const t of e){n++;if(t===`mcp`)r++}if(n>=MAX_OWNED_CHILDREN)return`Spawn broker child capacity exceeded (${MAX_OWNED_CHILDREN}); close running processes before retrying`;if(t===`mcp`&&r>=MAX_MCP_CHILDREN)return`Spawn broker MCP child capacity exceeded (${MAX_MCP_CHILDREN}); 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}}
//!src/process/spawn-broker/pipe.ts
function brokerSpawnOptions(e){const t=e.stdio??`pipe`;const n=typeof t===`string`?[t,t,t]:[...t];const r=[];for(let e=0;e<Math.max(3,n.length);e+=1){const t=n[e]??(e<3?`pipe`:`ignore`);if(t===`inherit`&&e!==0)return;if(t!==`pipe`&&t!==`ignore`&&t!==`inherit`&&t!==`ipc`)return;r.push(t)}if(e.signal||e.timeout||e.killSignal)throw new Error(`Unsupported spawn broker cancellation options`);return{cwd:e.cwd instanceof URL?fileURLToPath(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 readers=/* @__PURE__ */ new WeakMap;const holdReadable=()=>{};function holdPipe(e){const t={read:e.read.bind(e),resumed:false,onResume:()=>{t.resumed=true}};readers.set(e,t);e.on(`resume`,t.onResume);e.on(`readable`,holdReadable);e.read=()=>null}function restoreStdinPipe(e){const 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:false,ended:true,endEmitted:true,reading:false})}function stopPipeReads(e){const 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=false}function releasePipe(e){const t=restoreReader(e);if(!t)return;process.nextTick(()=>{if(e.destroyed)return;e.emit(`readable`);if(t.resumed)e.resume()})}function restoreReader(e){const t=readers.get(e);if(!t)return;e.read=t.read;readers.delete(e);e.removeListener(`resume`,t.onResume);e.removeListener(`readable`,holdReadable);return t}
//!src/process/spawn-broker/child.ts
var BrokerChild=class extends EventEmitter{constructor(e,t,n,r=false){super();this.requestId=e;this.transmit=n;this.fileOutputPending=r;this.callbackContext=new AsyncResource(`OpenClawSpawnBrokerChild`);this.stdin=null;this.stdout=null;this.stderr=null;this.connected=false;this.killed=false;this.exitCode=null;this.signalCode=null;this.stdio=[null,null,null,null,null];this.opened=createDeferredCore();this.completion=createDeferredCore();this.pipes=/* @__PURE__ */ new Set;this.sends=/* @__PURE__ */ new Map;this.sendSequence=0;this.spawnReceived=false;this.eventsReleased=false;this.pendingEventOverflow=false;this.pendingEvents=[];this.exited=false;this.closed=false;this.processNotStarted=false;this.spawnfile=t[0];this.spawnargs=[...t];this.opened.promise.catch(()=>{});this.on(`error`,()=>{})}markNotStarted(){this.processNotStarted=true}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=false;this.finishClose()}attachPipe(e,t){t.emit=this.callbackContext.bind(t.emit.bind(t));this.stdio[e]=t;if(e===0)this.stdin=t;if(e===1)this.stdout=t;if(e===2)this.stderr=t;this.pipes.add(t);let n=false;const acknowledge=t=>{if(n)return;n=true;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;this.spawnReceived=true;this.pid=e.pid;this.spawnfile=e.spawnfile;this.spawnargs=e.spawnargs;this.connected=e.connected;this.stdio.splice(e.stdioLength);while(this.stdio.length<e.stdioLength)this.stdio.push(null);if(this.connected)this.channel=Object.assign(new EventEmitter,{ref(){},unref(){}});this.opened.resolve();setImmediate(()=>{if(this.closed)return;this.emit(`spawn`);setImmediate(()=>{for(const[e,t]of this.stdio.entries())if(e>0&&t instanceof Socket&&!t.destroyed)releasePipe(t);this.eventsReleased=true;for(const e of this.pendingEvents.splice(0))e()})});return}if(!this.eventsReleased&&(this.spawnReceived||e.type!==`error`)){this.deferEvent(()=>this.emitMessage(e));return}this.emitMessage(e)}deferEvent(e){if(this.pendingEventOverflow)return;if(this.pendingEvents.length>=64){this.pendingEventOverflow=true;this.pendingEvents.splice(0);this.pendingEvents.push(()=>{this.kill(`SIGKILL`);this.failNow(new SpawnBrokerError(`Spawn broker startup event capacity exceeded`))});return}this.pendingEvents.push(e)}emitMessage(e){switch(e.type){case`error`:{const t=Object.assign(new Error(e.error.message),e.error);this.opened.reject(t);this.emit(`error`,t);if(!this.pid){this.exited=true;this.finishClose()}break}case`exit`:this.exited=true;this.exitCode=e.code;this.signalCode=e.signal;this.stdin?.destroy();this.emit(`exit`,e.code,e.signal);process.nextTick(()=>{for(const e of this.pipes)if(e.readable)e.resume()});this.finishClose();break;case`ipc-sent`:this.finishSend(e.sequence,e.error?Object.assign(new Error(e.error.message),e.error):null);break;case`disconnect`:this.failSends(/* @__PURE__ */ new Error(`Child process IPC channel is closed`));this.connected=false;this.channel=void 0;this.emit(`disconnect`);this.finishClose();break;case`ipc`:this.emit(`message`,e.message);break;case`closed`:this.finishClose()}}fail(e){if(this.spawnReceived&&!this.eventsReleased){this.deferEvent(()=>this.failNow(e));return}this.failNow(e)}failNow(e){if(this.closed)return;this.opened.reject(e);const t=this.connected;this.connected=false;this.channel=void 0;this.failSends(e);if(t)this.emit(`disconnect`);if(!this.exited)this.emit(`error`,e);for(const t of this.pipes)t.destroy(e);this.exited=true;this.finishClose()}finishClose(){if(!this.exited||this.channel||this.pipes.size>0||this.closed||this.fileOutputPending)return;this.closed=true;this.completion.resolve();this.emit(`close`,this.exitCode,this.signalCode)}kill(e=`SIGTERM`){if(this.exited)return false;this.killed=true;this.transmit({type:`kill`,id:this.requestId,signal:e}).catch(e=>this.fail(toErrorObject(e,`Spawn broker signal delivery failed`)));return true}send(e,t,n,r,i){const a=typeof t===`function`?t:typeof n===`function`?n:r;if(!this.connected||this.sends.size>=1024){const e=/* @__PURE__ */ new Error(this.connected?`Child process IPC capacity exceeded`:`Child process IPC channel is closed`);queueMicrotask(()=>a?a(e):this.emit(`error`,e));return false}const o=++this.sendSequence;this.sends.set(o,AsyncResource.bind(e=>{if(a)a(e);else if(e)this.emit(`error`,e)}));const s=typeof t===`function`?void 0:t;this.transmit({type:`ipc`,id:this.requestId,sequence:o,message:e},s,i).catch(e=>this.finishSend(o,toErrorObject(e,`Spawn broker IPC delivery failed`)));return true}finishSend(e,t){const n=this.sends.get(e);this.sends.delete(e);n?.(t)}failSends(e){for(const t of this.sends.keys())this.finishSend(t,e)}disconnect(){if(!this.connected)return;this.connected=false;this.transmit({type:`disconnect`,id:this.requestId}).catch(e=>this.fail(toErrorObject(e,`Spawn broker disconnect failed`)))}ref(){}unref(){}[Symbol.dispose](){this.kill(`SIGTERM`)}};export{SpawnBrokerError as a,restoreStdinPipe as i,brokerSpawnOptions as n,childCapacityError as o,holdPipe as r,BrokerChild as t};