UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1 lines • 45.9 kB
import{Cn as e,Dn as t,Q as n,gt as r,kn as i,s as a,t as o,x as s}from"./openclaw-state-read-subsystem-Dwoo5bcz.mjs";import{Pt as c}from"./openclaw-state-read-src-RL5xtYG2.mjs";import{t as l}from"./openclaw-state-read-deferred-B75K7ut7.mjs";import{a as u,n as d}from"./openclaw-state-read-pid-alive-C5QrpWWk.mjs";import{a as f}from"./openclaw-state-read-runtime-binary-BjmkF9EB.mjs";import{i as p,r as ee,t as m}from"./openclaw-state-read-runtime-worker-url-C8NPtAdy.mjs";import{n as h,t as te}from"./openclaw-state-read-error-graph-internal-Cj78mC_c.mjs";import{n as ne,r as g,t as _}from"./openclaw-state-read-service-child-group-ownership-aAyqDp8X.mjs";import{deserialize as v,serialize as y}from"node:v8";import{accessSync as b,constants as x,opendirSync as re,readFileSync as S,statSync as ie}from"node:fs";import ae,{join as C}from"node:path";import{fileURLToPath as w}from"node:url";import{spawn as T,spawnSync as E}from"node:child_process";import{readFile as D,readdir as O,rm as k}from"node:fs/promises";import{tmpdir as A}from"node:os";import{randomBytes as j}from"node:crypto";import{AsyncLocalStorage as M,AsyncResource as N}from"node:async_hooks";import{Buffer as P}from"node:buffer";import{setTimeout as F}from"node:timers/promises";import{EventEmitter as I}from"node:events";import{Socket as L}from"node:net";import{inspectChildWaitState as oe,isSupported as se,reapChild as R}from"@openclaw/proc-safe/reaper";const z=e(Symbol.for(`openclaw.childRuntimeViability`),()=>({observations:/* @__PURE__ */ new Map,initialPath:process.execPath,initialIdentity:executableIdentity(process.execPath)})),B=/(?:dyld[^\n]*:\s*Library not loaded:|error while loading shared libraries:)/i,V=/(?:dyld[^\n]*:\s*Symbol not found:|symbol lookup error:|Error loading shared library|version [`'"][^`'"\r\n]+[`'"] not found)/i;function executableIdentity(e){try{return formatExecutableIdentity(ie(e))}catch{return}}function formatExecutableIdentity({dev:e,ino:t,size:n,mtimeMs:r,mode:i}){return`${e}:${t}:${n}:${r}:${i}`}function publishRuntimeViability(e,t){return(c(t,`ENOENT`)||c(t,`ENOTDIR`))&&recordUnavailableRuntime(e,t),{execPath:e,available:!(z.execPath===e&&z.failure)}}function readChildRuntimeViability(e){let t=e?.execPath??process.execPath;if(z.execPath===t&&z.failure)return{execPath:t,available:!1};try{b(t,x.X_OK)}catch(e){return publishRuntimeViability(t,e)}return publishRuntimeViability(t)}function recoverUnavailableRuntime(){if(z.execPath!==process.execPath||!z.failure||!z.recover||z.recoveryStarted)return;z.recoveryStarted=!0;let e=z.recover;r(()=>Promise.resolve().then(e).catch(()=>({status:`report-only`,reason:`Automatic runtime recovery is report-only: service or restart preparation failed. Inspect the service runtime and restart through its owner.`})).then(e=>{o(`gateway/runtime`).warn(`${e.status}: ${e.reason}`)}))}function runtimeProbeOptions(e={}){return{encoding:`utf8`,cwd:e.cwd??ae.parse(process.execPath).root,env:e.env??{...process.env,NODE_OPTIONS:void 0},timeout:1e3,maxBuffer:8192}}function formatMissingChildRuntimeWarning(e){return e.available?void 0:`The Node.js runtime this Gateway started with (${s(e.execPath)}) can no longer start worker processes, likely because it was upgraded or removed. Restart the Gateway.`}function assertChildRuntimeAvailable(){if(z.execPath===process.execPath&&z.failure)throw z.failure}function recordUnavailableRuntime(e,t,n){if(z.execPath===e&&z.failure)return z.failure;z.execPath=e;let r=formatMissingChildRuntimeWarning({execPath:e,available:!1}),i=n?.trim();return z.failure=Object.assign(Error(i?`${r}\n${i}`:r,{cause:t}),{code:`NODE_RUNTIME_UNAVAILABLE`}),o(`gateway/runtime`).error(z.failure.message),recoverUnavailableRuntime(),z.failure}function needsRuntimeProbe(e){return!!(e.error||e.signal===`SIGABRT`||V.test(e.stderr??``))}function classifyRuntimeProbe(e,t,n,r){if(z.execPath===e&&z.failure)return z.failure;let i=e!==z.initialPath||n!==z.initialIdentity;return B.test(t.stderr)||V.test(t.stderr)||c(t.error,`ENOENT`)||c(t.error,`ENOTDIR`)||i&&(t.signal===`SIGABRT`||c(t.error,`ENOEXEC`)||c(t.error,`EACCES`)||c(t.error,`EPERM`))?recordUnavailableRuntime(e,r,t.stderr):void 0}function classifyChildRuntimeFailure(e){if(e.started)return;let t=e.execPath??process.execPath;if(z.execPath===t&&z.failure)return z.failure;if(B.test(e.stderr??``)||e.error&&!readChildRuntimeViability({execPath:t}).available)return recordUnavailableRuntime(t,e.error,e.stderr);if(needsRuntimeProbe(e))return classifyRuntimeProbe(t,E(t,[`--version`],runtimeProbeOptions()),t===z.initialPath?executableIdentity(t):void 0,e.error)}function observeChildRuntime(e,t=process.execPath){let n=!1,r,i=``;return e.once(`message`,()=>{n=!0,i=``}),e.on(`error`,e=>{r??=e}),e.stderr?.on(`data`,e=>{n||(i=(i+e.toString()).slice(-8192))}),()=>e.exitCode===0&&!r?void 0:classifyChildRuntimeFailure({execPath:t,error:r,stderr:i,signal:e.signalCode,started:n})}function waitForBrokerChildCompletion(e){return new Promise(t=>{let n=e.exitCode!=null||e.signalCode!=null,r=!e.connected,i=0,finish=()=>{n&&r&&i===0&&(e.removeListener(`exit`,onExit),e.removeListener(`error`,onError),e.removeListener(`disconnect`,onDisconnect),t())},onExit=()=>{n=!0,finish()},onError=()=>{e.pid===void 0&&(n=!0,r=!0,finish())},onDisconnect=()=>{r=!0,finish()};e.once(`exit`,onExit),e.on(`error`,onError),e.once(`disconnect`,onDisconnect);for(let t of e.stdio??[])t&&!t.closed&&(i++,t.once(`close`,()=>{i--,finish()}));finish()})}function isContinuationByte(e){return e!==void 0&&(e&192)==128}function truncateUtf8Suffix(e,t){if(t<=0)return``;if(e.length<=t&&P.byteLength(e)<=t)return e;let n=P.from(Number.isInteger(t)?e.slice(-t-1):e),r=n.byteLength-t;for(;r<n.byteLength&&isContinuationByte(n[r]);)r+=1;return n.subarray(r).toString(`utf8`)}function observeBrokerChildDiagnostics(e){let t=process.execPath,n=!1;e.once(`message`,()=>{n=!0});let r=``;return e.stderr?.setEncoding(`utf8`).on(`data`,e=>{r=truncateUtf8Suffix(r+e,2048)}),()=>{let i=a(r).trim();return classifyChildRuntimeFailure({execPath:t,stderr:r,signal:e.signalCode,started:n})??/* @__PURE__ */ Error(`exited with code=${e.exitCode??`null`} signal=${e.signalCode??`none`}${i?`\nstderr:\n${i}`:``}`)}}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}}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?w(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 H=/* @__PURE__ */ new WeakMap,holdReadable=()=>{};function holdPipe(e){let t={read:e.read.bind(e),resumed:!1,onResume:()=>{t.resumed=!0}};H.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=H.get(e);if(t)return e.read=t.read,H.delete(e),e.removeListener(`resume`,t.onResume),e.removeListener(`readable`,holdReadable),t}var BrokerChild=class extends I{constructor(e,t,n){super(),this.requestId=e,this.transmit=n,this.callbackContext=new N(`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=l(),this.completion=l(),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}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 I,{ref(){},unref(){}})),this.opened.resolve(),setImmediate(()=>{this.closed||(this.emit(`spawn`),setImmediate(()=>{for(let[e,t]of this.stdio.entries())e>0&&t instanceof L&&!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),this.failSends(e);let t=this.connected;this.connected=!1,this.channel=void 0,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.closed=!0,this.completion.resolve(),this.emit(`close`,this.exitCode,this.signalCode))}kill(e=`SIGTERM`){return!this.exited&&(this.killed=!0,this.transmit({type:`kill`,id:this.requestId,signal:e}).catch(e=>this.fail(i(e,`Spawn broker signal delivery failed`))),!0)}send(e,t,n,r,a){let o=typeof t==`function`?t:typeof n==`function`?n:r;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,N.bind(e=>{o?o(e):e&&this.emit(`error`,e)}));let c=typeof t==`function`?void 0:t;return this.transmit({type:`ipc`,id:this.requestId,sequence:s,message:e},c,a).catch(e=>this.finishSend(s,i(e,`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(e=>this.fail(i(e,`Spawn broker disconnect failed`))))}ref(){}unref(){}[Symbol.dispose](){this.kill(`SIGTERM`)}};const U=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=S(`/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=E(`ps`,e,{encoding:`utf8`,timeout:500});return t.error||t.status!==0?void 0:t.stdout}catch{return}}function readProcStatFields(e){try{let t=S(`/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=re(`/proc/${e}/task`);t();){let t=n.readSync();if(!t)return;let r=parseProcessGroupId(t.name);if(r)try{yield*parsePositivePids(S(`/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<U,visit=(e,a,o)=>{if(!withinBounds(o)||!hasCapacity()||readUnixProcessIdentity(e,i)!==a)return;let s=readUnixProcessChildren(e,()=>withinBounds(o)&&hasCapacity()&&r++<U&&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=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 W=/* @__PURE__ */ new WeakSet,G=/* @__PURE__ */ new Map,K=3e4;let q,J=0,Y=!1;function schedule(e){let t=performance.now()+e;q&&J<=t||(clearTimeout(q),J=t,q=setTimeout(()=>void tick(),e).unref())}function onExit(){schedule(25)}async function tick(){if(q=void 0,Y)schedule(25);else{Y=!0;try{for(let[e,t]of G)if(performance.now()>=t)G.delete(e);else try{process.kill(-e,0)}catch(t){c(t,`ESRCH`)&&G.delete(e)}if(G.size===0)return;for(let e of await O(`/proc/self/task`)){let t;try{t=await D(`/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 D(`/proc/${t}/stat`,`utf8`)}catch{continue}let[r,i,a]=n.slice(n.lastIndexOf(`)`)+2).split(` `);if(G.has(Number(a))&&t!==Number(a)&&Number(i)===process.pid&&r===`Z`)try{if(!se()){G.clear();return}oe(t).kind===`exited`&&R(t)}catch{}}}}catch{}finally{Y=!1,G.size>0?schedule(1e3):(clearTimeout(q),q=void 0,process.off(`SIGCHLD`,onExit))}}}function scheduleAdoptedChildZombieReapAfterExit(e,t,n=K){if(process.platform!==`linux`||!t||e.pid===void 0||W.has(e))return;let r=e.pid;W.add(e);let start=()=>{G.size===0&&process.on(`SIGCHLD`,onExit),G.set(r,performance.now()+Math.max(K,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`||!c(e,`EPERM`))return!1;try{return process.kill(-4194305,t),!1}catch(e){return c(e,`EPERM`)}}function isProcessGroupGone(e){try{return process.kill(-e,0),!1}catch(t){return c(t,`ESRCH`)?!0:isDeniedProcessGroupProbe(t)?ne(e):!1}}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!c(e,`ESRCH`)}}const X=5e3;function isBrokerChildGroupAlive(e){if(isProcessGroupGone(e.pid))return!1;let t=d(e.pid);if(e.isLeaderAlive)return e.isLeaderAlive()||u(e.pid)?e.startedAt===null||t===null||t===e.startedAt:!1;if(e.startedAt===null||t===null&&!u(e.pid))throw new SpawnBrokerError(`Spawn broker group leader identity is unavailable for pid=${e.pid}`);return t===null||t===e.startedAt}function signalRevalidatedGroupMembers(e,n,{snapshot:r,signaled:i}){if(!_())throw new SpawnBrokerError(`Spawn broker cannot verify the process table belongs to its PID namespace`);let a=r.filter(t=>t.pid!==process.pid&&t.pgid===e&&!u(t.pid));if(!a.length)return 0;let o=new Map(a.map(e=>[e.pid,d(e.pid)])),s;for(let r of g(1e3)){if(r.pid===process.pid||r.pgid!==e||!o.has(r.pid))continue;let a=o.get(r.pid);if(a===null){if(!u(r.pid))throw new SpawnBrokerError(`Spawn broker cannot identify remaining group member pid=${r.pid}`);continue}if(d(r.pid)!==a)continue;let c=`${r.pid}:${a}`;if(i.get(c)!==n){try{process.kill(r.pid,n)}catch(e){if(t(e)!==`ESRCH`){s??={error:e};continue}}i.set(c,n)}}if(s)throw s.error;return a.length}function terminateRetainedBrokerChildGroup(e){let n=!1,r=!1,i,a,o=`SIGTERM`,s=/* @__PURE__ */ new Map,signalMembers=()=>{try{signalRevalidatedGroupMembers(e.pid,o,{snapshot:[...g(1e3)],signaled:s})}catch(e){i=e}},signal=r=>{if(!n){if(!isBrokerChildGroupAlive(e))n=!0;else{o=r;try{process.kill(-e.pid,r)}catch(e){if(isDeniedProcessGroupProbe(e,r))a=e,signalMembers();else if(t(e)===`ESRCH`)n=!0;else throw e}}}},force=()=>{n||r||(r=!0,signal(`SIGKILL`))};return{force,settled:(async()=>{let t=performance.now()+X,r=t+2e3;try{for(signal(`SIGTERM`);!n&&isBrokerChildGroupAlive(e);){if(performance.now()>=t&&force(),a&&!n&&signalMembers(),performance.now()>=r)throw new SpawnBrokerError(`Spawn broker child cleanup could not be confirmed for pid=${e.pid}`,{cause:i??a});await F(50)}}finally{n=!0}})()}}function terminateLostBrokerChild(e,t,n){if(t&&n){if(n.pid!==e)throw new SpawnBrokerError(`Spawn broker cleanup identity changed`);return terminateRetainedBrokerChildGroup(n)}let r=killProcessTree(e,{detached:t,graceMs:X}),i=performance.now()+X+2e3;return{force:()=>r?.force(),settled:(async()=>{for(;;){if(t){if(r?.exited(),u(e)&&isProcessGroupGone(e))break}else if(u(e)&&(r?.exited()??!0))break;if(performance.now()>=i)throw new SpawnBrokerError(`Spawn broker child cleanup could not be confirmed for pid=${e}`);await F(50)}})()}}function terminateBrokerProcessGroup(e){let n=!1,r,i,a=`SIGTERM`,o=/* @__PURE__ */ new Map,s,signalMembers=()=>{try{signalRevalidatedGroupMembers(e,a,{snapshot:[...g(1e3)],signaled:o})}catch(e){r=e}},signal=n=>{a=n;try{process.kill(-e,n)}catch(e){isDeniedProcessGroupProbe(e,n)?(i=e,signalMembers()):t(e)!==`ESRCH`&&(r=e)}},retire=()=>{n=!0,clearTimeout(s)},force=()=>{n||(isProcessGroupGone(e)?retire():(clearTimeout(s),signal(`SIGKILL`)))};return{force,settled:(async()=>{if(isProcessGroupGone(e)){retire();return}signal(`SIGTERM`),s=setTimeout(force,X);let t=performance.now()+X+2e3;try{for(;!isProcessGroupGone(e);){if(performance.now()>=t)throw new SpawnBrokerError(`Spawn broker group cleanup could not be confirmed for pgid=${e}`,{cause:r??i});i&&signalMembers(),await F(50)}}finally{retire()}})()}}var BrokerFileReads=class{constructor(e){this.host=e,this.pending=/* @__PURE__ */ new Map,this.sequence=0}get size(){return this.pending.size}async read(e,t){return(await this.request({filePath:e},t)).buffer}async readPage(e,t,n){return this.request({filePath:e,page:t},n)}async request(e,t){if(t?.throwIfAborted(),await this.host.ready(),t?.throwIfAborted(),!this.host.canAdmit())throw new SpawnBrokerError(`Spawn broker cannot admit a raw file read`);let n=++this.sequence,r=l();this.pending.set(n,{chunks:[],result:r});let abort=()=>{r.reject(t?.reason),this.host.send({type:`cancel-read-file`,id:n}).catch(()=>{})};t?.addEventListener(`abort`,abort,{once:!0}),this.host.send({type:`read-file`,id:n,...e}).catch(r.reject);try{return await r.promise}finally{t?.removeEventListener(`abort`,abort),this.pending.delete(n)}}receive(e){if(e.type!==`file-read-chunk`&&e.type!==`file-read-result`)return!1;let t=this.pending.get(e.id);return t&&(e.type===`file-read-chunk`?t.chunks.push(e.bytes):e.error?t.result.reject(Object.assign(e.error,{code:e.code})):t.result.resolve(e.page??{buffer:Buffer.concat(t.chunks)})),!0}fail(e){for(let t of this.pending.values())t.result.reject(e);this.pending.clear()}};const Z=1048576,ce=268435456,Q=`openclaw-spawn-broker-frame`;function createBrokerSender(e){let t=0,n=0,r=0,a=Promise.resolve(),write=(t,n,r)=>new Promise((a,o)=>{try{let launch=()=>e(t,n,e=>e?o(e):a());r?r(launch):launch()}catch(e){o(i(e,`Spawn broker IPC write failed`))}}),enqueue=(e,r)=>{if(t+e>268435456||n>=1024)return Promise.reject(new SpawnBrokerError(`Spawn broker IPC capacity exceeded`));t+=e,n+=1;let i=a.then(r);return a=i.then(()=>{},()=>{}),i.finally(()=>{t-=e,--n})};return Object.assign((e,t,n)=>{let i=y(e),a=i.byteLength;if(a>Z&&t)return Promise.reject(new SpawnBrokerError(`Spawn broker handle metadata exceeds one IPC frame`));let o=++r;return enqueue(a,async()=>{if(a<=Z)await write(e,t,n);else for(let e=0;e<a;e+=Z){let t={kind:Q,id:o,total:a,offset:e,bytes:i.subarray(e,e+Z)};await write(t,void 0,e+Z>=a?n:void 0)}})},{reserve(e){return enqueue(Z,()=>e(async e=>{if(y(e).byteLength>Z)throw new SpawnBrokerError(`Spawn broker reserved publication exceeds one IPC frame`);await write(e)}))}})}function createBrokerReceiver(){let e,clear=()=>{e=void 0};return{receive(t){if(!t||typeof t!=`object`||!(`kind`in t)||t.kind!==Q)return clear(),t;let n=t;if(!Number.isSafeInteger(n.id)||!Number.isSafeInteger(n.total)||n.total<=Z||n.total>268435456||!Number.isSafeInteger(n.offset)||!Buffer.isBuffer(n.bytes)||n.bytes.length===0||n.bytes.length>Z)throw new SpawnBrokerError(`Invalid spawn broker IPC frame`);let r=e?.id===n.id?e:void 0;if(!r){if(n.offset!==0)throw new SpawnBrokerError(`Spawn broker receive capacity exceeded`);e=r={id:n.id,total:n.total,received:0,chunks:[]}}if(r.total!==n.total||r.received!==n.offset||r.received+n.bytes.length>r.total)throw new SpawnBrokerError(`Out-of-order spawn broker IPC frame`);if(r.chunks.push(n.bytes),r.received+=n.bytes.length,!(r.received<r.total))return clear(),v(Buffer.concat(r.chunks,r.total))},clear}}function createNativeResourceAuthority(){let e=`oc-br-${j(16).toString(`hex`)}`,t=C(A(),e),n=process.platform===`win32`?void 0:Buffer.byteLength(C(t,`resource.sock`))<=103?t:C(`/tmp`,e),r=j(32).toString(`hex`);return{directory:n,secret:r,endpoint:n?C(n,`resource.sock`):`\\\\.\\pipe\\oc-br-${r}`}}const le=new Map([EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Error].map(e=>[e.name,e]));function decodeNativeWorkerFailure(e){let t=/* @__PURE__ */ new Map,decode=e=>{if(e.kind===`value`)return e.value;let n=t.get(e);if(n)return n;let r=le.get(e.constructorName)??Error,i=e.constructorName===`AggregateError`?AggregateError([],e.message):e.constructorName===`SuppressedError`?new SuppressedError(void 0,void 0,e.message):new r(e.message);t.set(e,i),i.name=e.name,i.stack=e.stack;let defineField=(e,t,n=!1)=>{Object.defineProperty(i,e,{value:t,writable:!0,configurable:!0,enumerable:n})};for(let t of[`code`,`errcode`,`errno`])e[t]!==void 0&&defineField(t,e[t],!0);e.cause&&defineField(`cause`,decode(e.cause)),e.errors&&defineField(`errors`,e.errors.map(decode));for(let t of[`error`,`suppressed`]){let n=e[t];n&&defineField(t,decode(n))}return i};return decode(e)}const $=15e3,ue=process.hrtime.bigint.bind(process.hrtime);function spawnBrokerStartupNowMs(){return Number(ue()/1000000n)}var BrokerNativeResourceCloseError=class extends Error{constructor(e){super(`Native resource cleanup failed`),this.payload=e,this.name=`BrokerNativeResourceCloseError`}},BrokerResourceClaims=class{constructor(e){this.host=e,this.claims=/* @__PURE__ */ new Map,this.bufferedBytes=0,this.bufferedMessages=0,this.closeSequence=0,this.sealed=!1}get size(){return this.claims.size}get hasOpenClaims(){return[...this.claims.values()].some(e=>!e.closed)}get hasReferencedClaims(){return[...this.claims.values()].some(e=>!e.closed&&(e.referenced||!e.ready||!e.created||e.settling||e.ownerMessages.size>0))}get admissionClosed(){return this.failure!==void 0||this.sealed}capture(e,t){if(this.admissionClosed)throw this.failure??new SpawnBrokerError(`Native resource source is sealed`);let n=y(e);if(n.length>268435456)throw new SpawnBrokerError(`Native resource input exceeds IPC capacity`);let r=v(n),a={attachment:r,callbacks:t,inContext:M.snapshot(),attached:l(),ready:!1,created:!1,closed:!1,referenced:!0,settling:!1,lastSequence:0,ownerSequence:0,ownerMessages:/* @__PURE__ */ new Map};a.attached.promise.catch(()=>{}),this.claims.set(r.id,a),this.host.refreshReference();let active=()=>{if(this.claims.get(r.id)!==a)throw new SpawnBrokerError(`Native resource claim is released`);if(a.failure)throw a.failure};return{attachment:r,setReferenced:e=>{a.referenced!==e&&(a.referenced=e,this.host.refreshReference())},receive:e=>{if(e.id!==r.id)throw new SpawnBrokerError(`Native resource response belongs to another claim`);this.receive(e)},ownerMessage:e=>{if(active(),a.closed)throw new SpawnBrokerError(`Native resource is closed`);let t=a.ownerSequence+1,n=y({type:`resource-owner`,id:r.id,sequence:t,value:e});if(this.bufferedBytes+n.length>268435456||this.bufferedMessages>=1024)throw new SpawnBrokerError(`Native resource owner delivery capacity exceeded`);a.ownerSequence=t;let o=v(n);return a.ownerMessages.set(t,{request:o,size:n.length}),this.bufferedBytes+=n.length,this.bufferedMessages++,this.host.refreshReference(),(async()=>{await a.attached.promise,active();let e=a.ownerMessages.get(t);!a.closed&&e&&await this.host.transmit(e.request)})().catch(e=>{let t=i(e,`Native resource owner delivery failed`);this.claims.get(r.id)===a&&!a.closed&&!a.failure&&a.inContext(()=>a.callbacks.failed(t))}),{sequence:t}},close:()=>{if(a.closed)return Promise.resolve();try{active()}catch(e){return Promise.reject(i(e,`Native resource is unavailable`))}if(a.pending)return a.pending.completion.promise;let e=--this.closeSequence,t=l();return t.promise.catch(()=>{}),a.pending={requestId:e,completion:t},a.settling=!0,this.host.refreshReference(),(async()=>{await a.attached.promise,active(),!a.closed&&a.pending?.requestId===e&&await this.host.transmit({type:`resource-close`,id:r.id,requestId:e})})().catch(n=>{a.pending?.requestId===e&&(a.pending=void 0,t.reject(i(n,`Native resource close delivery failed`)))}),t.promise},release:()=>{if(this.claims.get(r.id)===a){if(!a.closed)throw new SpawnBrokerError(`Native resource must close before release`);this.host.transmit({type:`resource-release`,id:r.id}).catch(()=>{}),this.remove(a)}},abandonUnattached:()=>{if(this.claims.get(r.id)!==a)return;if(a.ready||a.created)throw new SpawnBrokerError(`Attached native resource cannot be abandoned`);let e=new SpawnBrokerError(`Native resource was never dispatched`);a.attached.reject(e),a.pending?.completion.reject(e),this.remove(a)}}}receive(e){let t=this.claims.get(e.id);if(!(!t||t.failure&&e.type!==`resource-closed`)){if(e.type===`resource-ready`){if(this.host.markReady(e.pid,e.generation),t.ready)return;t.ready=!0,t.attached.resolve()}else if(e.type===`resource-created`){if(t.created)return;t.created=!0}else if(e.type===`resource-owner-received`||e.type===`resource-owner-rejected`){let n=t.ownerMessages.get(e.sequence);if(n){if(t.ownerMessages.delete(e.sequence),this.bufferedBytes-=n.size,this.bufferedMessages--,e.type===`resource-owner-rejected`){let n=i(decodeNativeWorkerFailure(e.error),`Native resource owner callback failed`);t.settling=!0,this.host.refreshReference(),t.inContext(()=>t.callbacks.failed(n))}this.host.refreshReference()}return}else if(e.type===`resource-owner`){if(e.sequence<=t.lastSequence)return;t.lastSequence=e.sequence,t.inContext(()=>t.callbacks.message(e));return}else if(e.type===`resource-closed`){if(t.closed)return;t.closed=!0,this.clearOwnerMessages(t),t.pending?.completion.resolve(),t.pending=void 0}else if(e.type===`resource-close-error`){if(t.pending?.requestId===e.requestId){let n=t.pending;t.pending=void 0,n.completion.reject(e.resourceError?new BrokerNativeResourceCloseError(e.error):i(decodeNativeWorkerFailure(e.error),`Native resource cleanup failed`))}}else if(e.type===`resource-failed`){let n=i(decodeNativeWorkerFailure(e.error),`Native resource failed`);t.settling=!0,this.host.refreshReference(),t.inContext(()=>t.callbacks.failed(n));return}this.host.refreshReference(),t.inContext(()=>t.callbacks.message(e))}}closeAdmission(){this.sealed=!0}seal(){return this.sealPromise||=(this.closeAdmission(),this.host.transmit({type:`resource-seal`}).then(()=>{for(let e of this.claims.values())e.attached.resolve()},e=>{throw h(e),e})),this.sealPromise}closeBeforeStartup(){for(let e of this.claims.values())this.receive({type:`resource-closed`,id:e.attachment.id,requestId:0})}fail(e){h(e),this.failure??=e;let t=[...this.claims.values()].filter(t=>this.rejectClaim(t,e)),n=te(t,t=>t.inContext(()=>t.callbacks.failed(e)));if(n.length)throw AggregateError(n,`Native resource failure callback failed`)}rejectClaim(e,t){return e.failure||e.closed?!1:(e.failure=t,e.settling=!0,this.host.refreshReference(),e.attached.reject(t),e.pending?.completion.reject(t),e.pending=void 0,!0)}clearOwnerMessages(e){for(let t of e.ownerMessages.values())this.bufferedBytes-=t.size,this.bufferedMessages--;e.ownerMessages.clear()}remove(e){this.clearOwnerMessages(e),this.claims.delete(e.attachment.id),this.host.refreshReference()}};const de=[100,250,500,1e3,2e3];var SpawnBrokerHost=class{constructor(e={}){this.options=e,this.runInContext=M.snapshot(),this.readiness=l(),this.available=!1,this.hasBeenReady=!1,this.closing=!1,this.generation=0,this.consecutiveFailures=0,this.sequence=0,this.requests=/* @__PURE__ */ new Map,this.fileReads=new BrokerFileReads({ready:()=>this.ready(),send:e=>this.transmit(e),canAdmit:()=>!this.resourceClaims&&!this.closing&&this.requests.size+this.fileReads.size<256}),this.cleanups=/* @__PURE__ */ new Set,this.cleanupErrors=[],this.startupDeadline=0,this.onParentExit=()=>{this.process?.connected&&this.process.disconnect();for(let e of this.cleanups)e.force()},this.readFilePage=this.fileReads.readPage.bind(this.fileReads),this.workerUrl=e.workerUrl??ee(f.spawnBroker),this.entryPath=w(this.workerUrl),e.nativeResources&&(this.resourceAuthority=createNativeResourceAuthority(),this.resourceClaims=new BrokerResourceClaims({transmit:async e=>{this.available||await this.ready(),await this.transmit(e)},markReady:(e,t)=>{if(!this.markNativeReady)throw new SpawnBrokerError(`Native resource broker unavailable`);this.markNativeReady(e,t)},refreshReference:()=>this.refreshNativeReference()})),this.readiness.promise.catch(()=>{}),this.start(),process.once(`exit`,this.onParentExit)}get pid(){return this.process?.pid}get hasOpenNativeResourceClaims(){return this.resourceClaims?.hasOpenClaims??!1}get nativeResourceAdmissionClosed(){return(this.resourceClaims?.admissionClosed??!1)||this.process?.connected===!1}ready(){return this.closing?Promise.reject(new SpawnBrokerError(`Spawn broker is closing`)):this.readiness.promise}readFile(e,t){return this.fileReads.read(e,t)}captureNativeResource(e,t){if(!this.resourceClaims||!this.resourceAuthority||this.closing||this.requests.size+this.resourceClaims.size>=256)throw new SpawnBrokerError(`Native resource broker is unavailable or at capacity`);return this.resourceClaims.capture({...e,...e.moduleUrl.startsWith(`file:`)&&p(w(e.moduleUrl))?{sourceLoaderUrl:import.meta.resolve(`tsx/esm/api`)}:{},endpoint:this.resourceAuthority.endpoint,secret:this.resourceAuthority.secret,generation:this.generation-1,startupDeadline:this.available?void 0:this.startupDeadline,id:++this.sequence},t)}sealNativeResources(){return this.resourceClaims&&!this.available?Promise.reject(new SpawnBrokerError(`Native resource broker is not ready for cleanup`)):this.resourceClaims?.seal()??Promise.reject(new SpawnBrokerError(`Native resources are disabled`))}serviceNativeResources(){this.serviceStartup?.()}refreshNativeReference(){this.resourceClaims&&this.process&&(this.closing||this.resourceClaims.hasReferencedClaims||this.requests.size>0?(this.process.ref(),process.ref(this.process.stderr),this.process.channel?.ref?.()):(this.process.unref(),process.unref(this.process.stderr),this.process.channel?.unref?.()))}spawn(e,t,n,r){let i=brokerSpawnOptions(n);if(!i)throw Error(`Unsupported spawn broker stdio or process options`);return this.admit({type:r?`prepare-spawn`:`spawn`,id:++this.sequence,argv:[e,...t],options:i},r).child}spawnExeca(e,t){let n=++this.sequence,r=this.admit({type:`spawn-execa`,id:n,argv:e,options:t});return{child:r.child,result:r.result.promise,cancel:()=>{this.transmit({type:`cancel`,id:n}).catch(e=>r.child.fail(i(e,`Spawn broker cancellation delivery failed`)))}}}admit(e,t){let n=new BrokerChild(e.id,e.argv,(e,t,n)=>this.transmit(e,t,n)),r=e.type===`spawn-execa`?l():void 0;r&&r.promise.catch(()=>{});let i={child:n,initiateSpawn:t,result:r,childClosed:!1,resultSettled:!r,detached:e.options.detached===!0||e.type===`spawn-execa`&&e.options.killDescendants===!0},fail=e=>{r?.reject(e),n.fail(e)};return!this.available||this.closing||this.requests.size+this.fileReads.size+(this.resourceClaims?.size??0)>=256?(n.markNotStarted(),queueMicrotask(()=>fail(new SpawnBrokerError(`Spawn broker is unavailable`))),i):(this.requests.set(e.id,i),this.refreshNativeReference(),n.waitForClose().then(()=>{i.childClosed=!0,this.retire(e.id,i)}),this.transmit(e).catch(t=>{i.nativeInitiated||(e.type===`prepare-spawn`&&n.markNotStarted(),this.requests.delete(e.id),this.refreshNativeReference()),fail(new SpawnBrokerError(`Spawn broker request delivery failed`,{cause:t}))}),i)}retire(e,t){t.childClosed&&t.resultSettled&&!t.nativeInitiated&&(this.requests.delete(e),this.refreshNativeReference())}retainCleanup(e){this.cleanups.add(e),e.settled.then(()=>this.cleanups.delete(e),t=>{this.cleanupErrors.push(i(t,`Spawn broker cleanup failed`)),this.cleanups.delete(e)})}transmit(e,t,n){return!this.available||!this.sendMessage?Promise.reject(new SpawnBrokerError(`Spawn broker is unavailable`)):this.sendMessage(e,t,n)}start(){if(this.closing)return;try{assertChildRuntimeAvailable()}catch(e){this.readiness.reject(e);return}let e=this.generation++,t={type:`bootstrap`,...this.resourceAuthority?{nativeResource:{...this.resourceAuthority,generation:e}}:{}};if(y(t).byteLength>1024)throw new SpawnBrokerError(`Spawn broker bootstrap exceeds its IPC bound`);let n=T(process.execPath,m(this.workerUrl),{stdio:[`inherit`,`ignore`,`pipe`,`ipc`],detached:!0,serialization:`advanced`});this.process=n;let r=observeBrokerChildDiagnostics(n),a=!1,o=this.brokerClosed=waitForBrokerChildCompletion(n).then(()=>{a&&n.pid&&(n.exitCode!==0||n.signalCode!==null)&&this.cleanupErrors.push(new SpawnBrokerError(`Spawn broker shutdown failed`,{cause:r()}))}),s=createBrokerReceiver(),u=l(),d=!1,f=!1;this.startupDeadline=spawnBrokerStartupNowMs()+$;let checkStartup=()=>{!d&&!f&&spawnBrokerStartupNowMs()>=this.startupDeadline&&fail(/* @__PURE__ */ Error(`readiness deadline exceeded after 15000ms`))},p=this.resourceClaims?void 0:setTimeout(checkStartup,$);this.serviceStartup=checkStartup;let fail=e=>{if(d)return;let t=classifyChildRuntimeFailure({error:e,started:f})??e;a=this.closing,d=!0,clearTimeout(p),this.markNativeReady=void 0,s.clear(),this.available=!1,this.resourceClaims?.closeAdmission(),this.sendMessage=void 0,n.connected&&n.disconnect();let r=new SpawnBrokerError(t&&c(t,`NODE_RUNTIME_UNAVAILABLE`)?t.message:this.hasBeenReady?`Spawn broker exited; command outcome is unavailable`:`Spawn broker failed before readiness: ${t?.message??`channel lost`}`,{cause:t}),i=this.readiness;this.readiness=l(),this.readiness.promise.catch(()=>{}),i.reject(r),this.fileReads.fail(r);for(let e of this.requests.values()){if(e.pid&&!e.childClosed){let t=e.pid;if(this.closing){let r;this.retainCleanup({force:()=>r?.force(),settled:u.promise.then(async()=>{(n.exitCode!==0||n.signalCode!==null)&&(r=terminateLostBrokerChild(t,e.detached),await r.settled)})})}else this.retainCleanup(terminateLostBrokerChild(t,e.detached))}e.result?.reject(r),e.child.fail(r)}if(this.requests.clear(),this.refreshNativeReference(),n.pid&&process.platform!==`win32`){let e=n.pid,t;this.retainCleanup({force:()=>t?.force(),settled:u.promise.then(async()=>{t=terminateBrokerProcessGroup(e),await t.settled})})}if(this.resourceClaims||this.closing||!this.hasBeenReady||c(t,`NODE_RUNTIME_UNAVAILABLE`)){this.readiness.reject(r),this.resourceClaims?.fail(r);return}let o=de[this.consecutiveFailures++];o===void 0?this.readiness.reject(r):this.restartTimer=setTimeout(()=>this.start(),o)},markReady=(t,r)=>{if(d||t!==n.pid||r!==e)throw new SpawnBrokerError(`Native resource readiness does not match the captured broker`);f||(f=!0,clearTimeout(p),this.hasBeenReady=!0,this.consecutiveFailures=0,this.available=!0,this.readiness.resolve(),this.runInContext(()=>this.options.onReady?.(t,e>0)))};this.markNativeReady=markReady,n.once(`error`,fail),n.once(`exit`,()=>{d||(a=this.closing),u.resolve(),f?fail(r()):o.then(()=>fail(r()))}),n.once(`disconnect`,()=>{f&&fail(/* @__PURE__ */ Error(`IPC channel disconnected`))}),n.on(`message`,(t,n)=>{if(d||this.closing){n instanceof L&&n.destroy();return}let r;try{r=s.receive(t)}catch(e){fail(i(e,`Spawn broker receive failed`));return}if(r===void 0)return;let a=r;if(a.type===`startup-failed`){if(!f&&this.resourceClaims){let e=this.resourceClaims;this.brokerClosed?.then(()=>e.closeBeforeStartup()).catch(e=>{this.cleanupErrors.push(i(e,`Spawn broker startup cleanup failed`))})}fail(Object.assign(Error(a.error.message),a.error));return}if(a.type===`ready`){try{markReady(a.pid,e)}catch(e){fail(i(e,`Spawn broker readiness failed`))}return}if(a.type===`resource-ready`||a.type===`resource-created`||a.type===`resource-target`||a.type===`resource-owner`||a.type===`resource-owner-received`||a.type===`resource-owner-rejected`||a.type===`resource-closed`||a.type===`resource-close-error`||a.type===`resource-failed`){try{this.resourceClaims?.receive(a)}catch(e){fail(i(e,`Spawn broker native resource receive failed`))}return}if(this.fileReads.receive(a))return;let o=this.requests.get(a.id);if(!o)n instanceof L&&n.destroy(),a.type===`pipe`?this.transmit({type:`pipe-received`,id:a.id,fd:a.fd}).catch(fail):a.type===`prepared`&&this.transmit({type:`launch`,id:a.id,allowed:!1}).catch(fail);else if((a.type===`owned`||a.type===`error`)&&(o.nativeInitiated?.resolve(),o.nativeInitiated=void 0),a.type===`prepared`){let e=o.initiateSpawn;o.initiateSpawn=void 0;let t=this.brokerClosed,n=e?o.nativeInitiated??=l():void 0,r=t&&n?Promise.race([n.promise,t]):Promise.reject(/* @__PURE__ */ Error(`Spawn broker retirement is unavailable`));r.catch(()=>{}),this.transmit({type:`launch`,id:a.id,allowed:!0},void 0,t=>{if(!e||!n||o.childClosed)throw new SpawnBrokerError(`Spawn broker launch grant is unavailable`);return e(t,r)}).catch(()=>{this.transmit({type:`launch`,id:a.id,allowed:!1}).catch(fail)})}else if(a.type===`owned`)o.pid=a.pid,o.childClosed&&(this.retainCleanup(terminateLostBrokerChild(a.pid,o.detached)),this.retire(a.id,o));else if(a.type===`pipe`){try{if(a.closed&&a.fd===0){let e=new L;o.child.attachPipe(a.fd,e),e.destroy()}else if(n instanceof L)a.fd===0?restoreStdinPipe(n):holdPipe(n),o.child.attachPipe(a.fd,n);else throw new SpawnBrokerError(`Spawn broker pipe transfer failed`)}catch(e){n instanceof L&&n.destroy(),fail(i(e,`Spawn broker pipe setup failed`));return}this.transmit({type:`pipe-received`,id:a.id,fd:a.fd}).catch(fail)}else if(a.type===`pipe-prefix`){let e=o.child.stdio[a.fd];e instanceof L&&a.bytes.length>0&&e.unshift(a.bytes)}else a.type===`execa-result`?(o.pid===void 0&&a.result.failed&&o.child.markNotStarted(),o.result?.resolve(a.result),o.resultSettled=!0,this.retire(a.id,o)):(a.type===`error`&&a.resultUnavailable&&o.result&&(o.result.reject(Object.assign(Error(a.error.message),a.error)),o.resultSettled=!0),o.child.receive(a),this.retire(a.id,o))});try{n.send(t,e=>{e&&fail(e)})}catch(e){fail(i(e,`Spawn broker bootstrap delivery failed`))}d||(this.sendMessage=createBrokerSender((e,t,r)=>n.send(e,t,{keepOpen:!0},r))),this.refreshNativeReference()}async waitForCleanup(){if(await Promise.allSettled([...this.cleanups].map(e=>e.settled)),this.cleanupErrors.length)throw AggregateError(this.cleanupErrors,`Spawn broker cleanup did not complete`)}close(){return this.resourceClaims?.hasOpenClaims?Promise.reject(new SpawnBrokerError(`Native resource claims must close before broker shutdown`)):this.closePromise??=this.closeInternal()}async closeInternal(){this.closing=!0,this.refreshNativeReference(),this.readiness.reject(new SpawnBrokerError(`Spawn broker is closing`)),this.fileReads.fail(new SpawnBrokerError(`Spawn broker is closing`)),clearTimeout(this.restartTimer);try{let e=this.process;e&&e.exitCode===null&&e.signalCode===null&&(this.resourceClaims?this.transmit({type:`shutdown`}).catch(()=>{e.connected&&e.disconnect()}):e.connected&&e.disconnect()),await this.brokerClosed;try{await this.waitForCleanup()}finally{this.resourceAuthority?.directory&&this.hasBeenReady&&await k(this.resourceAuthority.directory,{recursive:!0,force:!0})}}finally{process.removeListener(`exit`,this.onParentExit)}}};function createSpawnBrokerHost(e){return new SpawnBrokerHost(e)}const fe=new n(Symbol(`spawnBroker`));function getSpawnBroker(){return fe.getStore()}export{observeChildRuntime as _,decodeNativeWorkerFailure as a,createBrokerSender as c,killProcessTree as d,BrokerChild as f,classifyChildRuntimeFailure as g,assertChildRuntimeAvailable as h,spawnBrokerStartupNowMs as i,isChildProcessTreeAlive as l,truncateUtf8Suffix as m,createSpawnBrokerHost as n,ce as o,SpawnBrokerError as p,BrokerNativeResourceCloseError as r,createBrokerReceiver as s,getSpawnBroker as t,scheduleAdoptedChildZombieReapAfterExit as u};