openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
19 lines • 33.3 kB
JavaScript
import{a as extractErrorCode,p as toErrorObject}from"./error-coercion-DlKnt6w-.mjs";import{t as killProcessTree}from"./kill-tree-CIjHhVfN.mjs";import{n as materializeErrorStack,t as collectSynchronousErrors}from"./error-graph-internal-Bt2pFJBM.mjs";import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{d as redactToolPayloadText}from"./redact-BT59pdZ_.mjs";import{t as hasErrnoCode}from"./errno-DUBt6SQQ.mjs";import{n as runtimeProcessEntrypoints}from"./runtime-process-entrypoints-Dnd1WskT.mjs";import{a as resolveRuntimeWorkerUrl,n as resolveRuntimeWorkerArgv,o as runtimeNeedsTypeScriptLoader}from"./runtime-worker-url-Dqf-I1cs.mjs";import{t as registerProcessExitCleanup}from"./process-exit-cleanup-BEXlfXfe.mjs";import{a as isPidDefinitelyDead,n as getProcessInstanceStartTime,o as isPidDefinitelyDeadAsync}from"./pid-alive-DDtSxW5l.mjs";import{s as prepareChildRuntimeFailure,t as assertChildRuntimeAvailable}from"./child-runtime-viability-1cqYEa1U.mjs";import{n as childCapacityError,t as SpawnBrokerError}from"./protocol-BkhQu-An.mjs";import{i as restoreStdinPipe,n as holdPipe,t as brokerSpawnOptions}from"./pipe-B2bexkN0.mjs";import{t as BrokerChild}from"./child-BRlwXXKV.mjs";import{t as getSpawnBrokerAdmission}from"./admission-AevV4KZ_.mjs";import{n as truncateUtf8Suffix}from"./utf8-truncate-B8GdsL7T.mjs";import{c as readLinuxProcessGroupMemberAsync,i as isOwnProcfsAsync,l as readLinuxProcessGroupMembersAsync,r as isOwnProcfs,u as readProcessGroupMembers}from"./service-child-group-ownership-CzRiJZ_p.mjs";import{a as isProcessGroupGone,i as isDeniedProcessGroupProbe,o as isProcessGroupGoneAsync,s as isProcessGroupGoneByKernel}from"./child-process-tree-nE5B-8SA.mjs";import{t as readCommandProcessStartTime}from"./command-process-identity-DdVvy1F9.mjs";import{t as GRACEFUL_CANCEL_TIMEOUT_MS}from"./cancellation-policy-BNa0Y54K.mjs";import{a as MAX_PENDING_BYTES,c as createBrokerSender,i as BrokerIpcAdmissionError,n as SPAWN_BROKER_STARTUP_TIMEOUT_MS,o as MAX_PENDING_MESSAGES,r as spawnBrokerStartupNowMs,s as createBrokerReceiver,t as BrokerNativeResourceCloseError}from"./resource-protocol-BTMqxPe1.mjs";import{t as decodeNativeWorkerFailure}from"./worker-native-error-B1RuZbYc.mjs";import{fileURLToPath}from"node:url";import path,{join}from"node:path";import{randomBytes}from"node:crypto";import{rm}from"node:fs/promises";import{tmpdir}from"node:os";import{spawn}from"node:child_process";import{Socket}from"node:net";import{deserialize,serialize}from"node:v8";import{AsyncLocalStorage}from"node:async_hooks";import{setTimeout as setTimeout$1}from"node:timers/promises";
//!src/process/spawn-broker/child-completion.ts
function waitForBrokerChildCompletion(e){return new Promise(t=>{let n=e.exitCode!=null||e.signalCode!=null;let r=!e.connected;let i=0;const finish=()=>{if(!n||!r||i!==0)return;e.removeListener(`exit`,onExit);e.removeListener(`error`,onError);e.removeListener(`disconnect`,onDisconnect);t()};const onExit=()=>{n=true;finish()};const onError=()=>{if(e.pid===void 0){n=true;r=true;finish()}};const onDisconnect=()=>{r=true;finish()};e.once(`exit`,onExit);e.on(`error`,onError);e.once(`disconnect`,onDisconnect);for(const t of e.stdio??[]){if(!t||t.closed)continue;i++;t.once(`close`,()=>{i--;finish()})}finish()})}
//!src/process/spawn-broker/child-diagnostics.ts
function observeBrokerChildDiagnostics(e){const t=process.execPath;let n=false;e.once(`message`,()=>{n=true});let r=``;e.stderr?.setEncoding(`utf8`).on(`data`,e=>{r=truncateUtf8Suffix(r+e,2048)});return async()=>{const i=redactToolPayloadText(r).trim();return await prepareChildRuntimeFailure({execPath:t,stderr:r,signal:e.signalCode,started:n})??/* @__PURE__ */ new Error(`exited with code=${e.exitCode??`null`} signal=${e.signalCode??`none`}${i?`\nstderr:\n${i}`:``}`)}}async function prepareBrokerFailureCause(e,t){try{return await e??t}catch(e){return new AggregateError(t?[t,e]:[e],`Spawn broker diagnosis failed`,{cause:t})}}function createBrokerFailureError(e,t){return new SpawnBrokerError(e&&hasErrnoCode(e,`NODE_RUNTIME_UNAVAILABLE`)?e.message:t?`Spawn broker exited; command outcome is unavailable`:`Spawn broker failed before readiness: ${e?.message??`channel lost`}`,{cause:e})}
//!src/process/spawn-broker/cleanup.ts
function isBrokerChildGroupAlive(e){if(isProcessGroupGone(e.pid))return false;const t=getProcessInstanceStartTime(e.pid);if(e.isLeaderAlive){if(e.isLeaderAlive())return e.startedAt===null||t===null||t===e.startedAt;if(!isPidDefinitelyDead(e.pid))return false;return e.startedAt===null||t===null||t===e.startedAt}if(e.startedAt===null||t===null&&!isPidDefinitelyDead(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,t,{snapshot:n,signaled:r}){if(!isOwnProcfs())throw new SpawnBrokerError(`Spawn broker cannot verify the process table belongs to its PID namespace`);const i=n.filter(t=>t.pid!==process.pid&&t.pgid===e&&!isPidDefinitelyDead(t.pid));if(!i.length)return 0;const a=new Map(i.map(e=>[e.pid,getProcessInstanceStartTime(e.pid)]));let o;for(const n of readProcessGroupMembers(1e3)){if(n.pid===process.pid||n.pgid!==e||!a.has(n.pid))continue;const i=a.get(n.pid);if(i===null){if(!isPidDefinitelyDead(n.pid))throw new SpawnBrokerError(`Spawn broker cannot identify remaining group member pid=${n.pid}`);continue}if(getProcessInstanceStartTime(n.pid)!==i)continue;const s=`${n.pid}:${i}`;if(r.get(s)===t)continue;try{process.kill(n.pid,t)}catch(e){if(extractErrorCode(e)!==`ESRCH`){o??={error:e};continue}}r.set(s,t)}if(o)throw o.error;return i.length}async function signalRevalidatedGroupMembersAsync(e,t,{snapshot:n,signaled:r}){if(!await isOwnProcfsAsync())throw new SpawnBrokerError(`Spawn broker cannot verify the process table belongs to its PID namespace`);const i=/* @__PURE__ */ new Map;for(const t of n)if(t.pid!==process.pid&&t.pgid===e&&!await isPidDefinitelyDeadAsync(t.pid))i.set(t.pid,await readCommandProcessStartTime(t.pid,{instance:true}));if(!i.size)return 0;let a;for await(const n of readLinuxProcessGroupMembersAsync(1e3)){if(n.pid===process.pid||n.pgid!==e||!i.has(n.pid))continue;const o=i.get(n.pid);if(o===null){if(!await isPidDefinitelyDeadAsync(n.pid))throw new SpawnBrokerError(`Spawn broker cannot identify remaining group member pid=${n.pid}`);continue}const s=await readLinuxProcessGroupMemberAsync(n.pid).catch(()=>void 0);const c=t();if(!c)return i.size;if(!s||s.pgid!==e||s.startedAt!==o)continue;const l=`${n.pid}:${o}`;if(r.get(l)===c)continue;try{process.kill(n.pid,c)}catch(e){if(extractErrorCode(e)!==`ESRCH`){a??={error:e};continue}}r.set(l,c)}if(a)throw a.error;return i.size}function terminateRetainedBrokerChildGroup(e){let t=false;let n=false;let r;let i;let a=`SIGTERM`;const o=/* @__PURE__ */ new Map;const signalMembers=()=>{try{signalRevalidatedGroupMembers(e.pid,a,{snapshot:[...readProcessGroupMembers(1e3)],signaled:o})}catch(e){r=e}};const signal=n=>{if(t)return;if(!isBrokerChildGroupAlive(e)){t=true;return}a=n;try{process.kill(-e.pid,n)}catch(e){if(isDeniedProcessGroupProbe(e,n)){i=e;signalMembers()}else if(extractErrorCode(e)===`ESRCH`)t=true;else throw e}};const force=()=>{if(t||n)return;n=true;signal(`SIGKILL`)};return{force,settled:(async()=>{const n=performance.now()+GRACEFUL_CANCEL_TIMEOUT_MS;const a=n+2e3;try{signal(`SIGTERM`);for(;;){if(t||!isBrokerChildGroupAlive(e))break;if(performance.now()>=n)force();if(i&&!t)signalMembers();if(performance.now()>=a)throw new SpawnBrokerError(`Spawn broker child cleanup could not be confirmed for pid=${e.pid}`,{cause:r??i});await setTimeout$1(50)}}finally{t=true}})()}}function terminateLostBrokerChild(e,t,n){if(t&&n){if(n.pid!==e)throw new SpawnBrokerError(`Spawn broker cleanup identity changed`);return terminateRetainedBrokerChildGroup(n)}const r=killProcessTree(e,{detached:t,graceMs:GRACEFUL_CANCEL_TIMEOUT_MS});const i=performance.now()+GRACEFUL_CANCEL_TIMEOUT_MS+2e3;return{force:()=>r?.force(),settled:(async()=>{for(;;){if(t){r?.exited();if(await isPidDefinitelyDeadAsync(e)&&await isProcessGroupGoneAsync(e))break}else if(await isPidDefinitelyDeadAsync(e)&&(r?.exited()??true))break;if(performance.now()>=i)throw new SpawnBrokerError(`Spawn broker child cleanup could not be confirmed for pid=${e}`);await setTimeout$1(50)}})()}}function terminateBrokerProcessGroup(e){let t=false;let n;let r;let i=`SIGTERM`;const a=/* @__PURE__ */ new Map;let o;const retire=()=>{t=true;clearTimeout(o)};const signalMembers=async()=>{try{const n=[];for await(const e of readLinuxProcessGroupMembersAsync(1e3))n.push(e);await signalRevalidatedGroupMembersAsync(e,()=>t?void 0:i,{snapshot:n,signaled:a})}catch(e){n=e}};const signal=async a=>{if(t||isProcessGroupGoneByKernel(e)){retire();return}i=a;try{process.kill(-e,a)}catch(e){if(isDeniedProcessGroupProbe(e,a)){r=e;await signalMembers()}else if(extractErrorCode(e)!==`ESRCH`)n=e}};const force=()=>{if(t)return;if(isProcessGroupGone(e)){retire();return}i=`SIGKILL`;clearTimeout(o);try{process.kill(-e,i)}catch(t){if(isDeniedProcessGroupProbe(t,i)){r=t;try{signalRevalidatedGroupMembers(e,i,{snapshot:[...readProcessGroupMembers(1e3)],signaled:a})}catch(e){n=e}}else if(extractErrorCode(t)!==`ESRCH`)n=t}};let s;const escalate=()=>{if(t||s)return;i=`SIGKILL`;s=(async()=>{if(await isProcessGroupGoneAsync(e))retire();else if(!t)await signal(`SIGKILL`)})().catch(e=>{n=e})};return{force,settled:(async()=>{try{if(await isProcessGroupGoneAsync(e))return;await signal(i);if(!t&&i===`SIGTERM`)o=setTimeout(escalate,GRACEFUL_CANCEL_TIMEOUT_MS);const a=performance.now()+GRACEFUL_CANCEL_TIMEOUT_MS+2e3;for(;;){await s;if(t||await isProcessGroupGoneAsync(e))break;if(performance.now()>=a)throw new SpawnBrokerError(`Spawn broker group cleanup could not be confirmed for pgid=${e}`,{cause:n??r});if(r)await signalMembers();await setTimeout$1(50)}}finally{retire();await s}})()}}
//!src/process/spawn-broker/commands.ts
function createBrokerCommandRequest(e,t,n){const r=e.type!==`spawn-execa`&&e.outputFile?createDeferredCore():void 0;const i=e.type===`spawn-execa`?createDeferredCore():void 0;r?.promise.catch(()=>{});i?.promise.catch(()=>{});return{child:new BrokerChild(e.id,e.argv,n,Boolean(r)),initiateSpawn:t,result:i,output:r,childClosed:false,resultSettled:!i&&!r,detached:e.options.detached===true||e.type===`spawn-execa`&&e.options.killDescendants===true}}function createBrokerCommands(e){const native=(t,n,r,i,a,o)=>{const s={type:i?`prepare-spawn`:`spawn`,id:e.nextId(),argv:[t,...n],options:r,execCgroup:a};if(o)s.outputFile=o;return e.admit(s,i)};return{spawn:(e,t,n,r,i)=>{const a=brokerSpawnOptions(n);if(!a)throw new Error(`Unsupported spawn broker stdio or process options`);return native(e,t,a,r,i).child},spawnToFile:(e,t,n,r,i,a)=>{const o=native(e,t,n,i,a,r);return{child:o.child,output:o.output.promise}},spawnExeca:(t,n,r)=>{const i=e.nextId();const a=e.admit({type:`spawn-execa`,id:i,argv:t,options:n,execCgroup:r});return{child:a.child,result:a.result.promise,cancel:()=>{e.cancel(i).catch(e=>a.child.fail(toErrorObject(e,`Spawn broker cancellation delivery failed`)))}}}}}function receiveBrokerCommandResponse(e,t,n,r){if(t.type===`pipe`){try{if(t.closed&&t.fd===0){const n=new Socket;e.child.attachPipe(t.fd,n);n.destroy()}else if(n instanceof Socket){if(t.fd===0)restoreStdinPipe(n);else holdPipe(n);e.child.attachPipe(t.fd,n)}else throw new SpawnBrokerError(`Spawn broker pipe transfer failed`)}catch(e){if(n instanceof Socket)n.destroy();throw e}return r({type:`pipe-received`,id:t.id,fd:t.fd})}else if(t.type===`pipe-prefix`){const n=e.child.stdio[t.fd];if(n instanceof Socket&&t.bytes.length>0)n.unshift(t.bytes)}else if(t.type===`file-output`){e.nativeClosed=true;if(`error`in t)e.output?.reject(Object.assign(new Error(t.error.message),t.error));else e.output?.resolve(t.bytes);e.resultSettled=true;e.child.settleFileOutput()}else if(t.type===`execa-result`){if(e.pid===void 0&&t.result.failed)e.child.markNotStarted();e.result?.resolve(t.result);e.resultSettled=true}else{if(t.type===`closed`)e.nativeClosed=true;else if(t.type===`error`&&t.notStarted)e.child.markNotStarted();if(t.type===`error`&&t.resultUnavailable&&e.output){e.output.reject(Object.assign(new Error(t.error.message),t.error));e.resultSettled=true;e.child.settleFileOutput()}if(t.type===`error`&&t.resultUnavailable&&e.result){e.result.reject(Object.assign(new Error(t.error.message),t.error));e.resultSettled=true}e.child.receive(t)}}
//!src/process/spawn-broker/file-reads.ts
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){t?.throwIfAborted();await this.host.ready();t?.throwIfAborted();if(!this.host.canAdmit())throw new SpawnBrokerError(`Spawn broker cannot admit a raw file read`);const n=++this.sequence;const r=createDeferredCore();this.pending.set(n,{chunks:[],result:r});const abort=()=>{r.reject(t?.reason);this.host.send({type:`cancel-read-file`,id:n}).catch(()=>{})};t?.addEventListener(`abort`,abort,{once:true});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 false;const t=this.pending.get(e.id);if(t){if(e.type===`file-read-chunk`)t.chunks.push(e.bytes);else if(e.error)t.result.reject(Object.assign(e.error,{code:e.code}));else t.result.resolve(e.page??{buffer:Buffer.concat(t.chunks)})}return true}fail(e){for(const t of this.pending.values())t.result.reject(e);this.pending.clear()}};
//!src/process/spawn-broker/socket-directory.ts
function fitsBrokerSocketPath(e,t){return process.platform===`win32`||Buffer.byteLength(path.join(e,t))<=103}
//!src/process/spawn-broker/resource-authority.ts
function createNativeResourceAuthority(){const e=`oc-br-${randomBytes(16).toString(`hex`)}`;const t=join(tmpdir(),e);const n=process.platform===`win32`?void 0:fitsBrokerSocketPath(t,`resource.sock`)?t:join(`/tmp`,e);const r=randomBytes(32).toString(`hex`);return{directory:n,secret:r,endpoint:n?join(n,`resource.sock`):`\\\\.\\pipe\\oc-br-${r}`}}
//!src/process/spawn-broker/resource-host.ts
var BrokerResourceClaims=class{constructor(e){this.host=e;this.claims=/* @__PURE__ */ new Map;this.bufferedBytes=0;this.bufferedMessages=0;this.closeSequence=0;this.sealed=false}get size(){return this.claims.size}get hasOpenClaims(){return[...this.claims.values()].some(e=>!e.closed)}get needsReference(){return[...this.claims.values()].some(e=>!e.closed&&(!e.created||Boolean(e.failure||e.pending)||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`);const n=serialize(e);if(n.length>268435456)throw new SpawnBrokerError(`Native resource input exceeds IPC capacity`);const r=deserialize(n);const i={attachment:r,callbacks:t,inContext:AsyncLocalStorage.snapshot(),attached:createDeferredCore(),ready:false,created:false,closed:false,lastSequence:0,ownerSequence:0,ownerMessages:/* @__PURE__ */ new Map};i.attached.promise.catch(()=>{});this.claims.set(r.id,i);this.host.refreshReference();const active=()=>{if(this.claims.get(r.id)!==i)throw new SpawnBrokerError(`Native resource claim is released`);if(i.failure)throw i.failure};return{attachment:r,receive:e=>{if(e.id!==r.id)throw new SpawnBrokerError(`Native resource response belongs to another claim`);this.receive(e)},ownerMessage:e=>{active();if(i.closed)throw new SpawnBrokerError(`Native resource is closed`);const t=i.ownerSequence+1;const n=serialize({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`);i.ownerSequence=t;const a=deserialize(n);i.ownerMessages.set(t,{request:a,size:n.length});this.bufferedBytes+=n.length;this.bufferedMessages++;this.host.refreshReference();(async()=>{await i.attached.promise;active();const e=i.ownerMessages.get(t);if(!i.closed&&e)await this.host.transmit(e.request)})().catch(e=>{const t=toErrorObject(e,`Native resource owner delivery failed`);if(this.claims.get(r.id)===i&&!i.closed&&!i.failure)i.inContext(()=>i.callbacks.failed(t))});return{sequence:t}},close:()=>{if(i.closed)return Promise.resolve();try{active()}catch(e){return Promise.reject(toErrorObject(e,`Native resource is unavailable`))}if(i.pending)return i.pending.completion.promise;const e=--this.closeSequence;const t=createDeferredCore();t.promise.catch(()=>{});i.pending={requestId:e,completion:t};this.host.refreshReference();(async()=>{await i.attached.promise;active();if(!i.closed&&i.pending?.requestId===e)await this.host.transmit({type:`resource-close`,id:r.id,requestId:e})})().catch(n=>{if(i.pending?.requestId===e){i.pending=void 0;this.host.refreshReference();t.reject(toErrorObject(n,`Native resource close delivery failed`))}});return t.promise},release:()=>{if(this.claims.get(r.id)!==i)return;if(!i.closed)throw new SpawnBrokerError(`Native resource must close before release`);this.host.transmit({type:`resource-release`,id:r.id}).catch(()=>{});this.remove(i)},abandonUnattached:()=>{if(this.claims.get(r.id)!==i)return;if(i.ready||i.created)throw new SpawnBrokerError(`Attached native resource cannot be abandoned`);const e=new SpawnBrokerError(`Native resource was never dispatched`);i.attached.reject(e);i.pending?.completion.reject(e);this.remove(i)}}}receive(e){const t=this.claims.get(e.id);if(!t||t.failure&&e.type!==`resource-closed`)return;if(e.type===`resource-ready`){this.host.markReady(e.pid,e.generation);if(t.ready)return;t.ready=true;t.attached.resolve()}else if(e.type===`resource-created`){if(t.created)return;t.created=true;this.host.refreshReference()}else if(e.type===`resource-owner-received`||e.type===`resource-owner-rejected`){const n=t.ownerMessages.get(e.sequence);if(n){t.ownerMessages.delete(e.sequence);this.bufferedBytes-=n.size;this.bufferedMessages--;this.host.refreshReference();if(e.type===`resource-owner-rejected`){const n=toErrorObject(decodeNativeWorkerFailure(e.error),`Native resource owner callback failed`);t.inContext(()=>t.callbacks.failed(n))}}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=true;this.clearOwnerMessages(t);t.pending?.completion.resolve();t.pending=void 0;this.host.refreshReference()}else if(e.type===`resource-close-error`){if(t.pending?.requestId===e.requestId){const n=t.pending;t.pending=void 0;this.host.refreshReference();n.completion.reject(e.resourceError?new BrokerNativeResourceCloseError(e.error):toErrorObject(decodeNativeWorkerFailure(e.error),`Native resource cleanup failed`))}}else if(e.type===`resource-failed`){const n=toErrorObject(decodeNativeWorkerFailure(e.error),`Native resource failed`);t.inContext(()=>t.callbacks.failed(n));return}t.inContext(()=>t.callbacks.message(e))}closeAdmission(){this.sealed=true}seal(){if(this.sealPromise)return this.sealPromise;this.closeAdmission();this.sealPromise=this.host.transmit({type:`resource-seal`}).then(()=>{for(const e of this.claims.values())e.attached.resolve()},e=>{materializeErrorStack(e);throw e});return this.sealPromise}closeBeforeStartup(){for(const e of this.claims.values())this.receive({type:`resource-closed`,id:e.attachment.id,requestId:0})}fail(e){materializeErrorStack(e);this.failure??=e;const t=[...this.claims.values()].filter(t=>this.rejectClaim(t,e));const n=collectSynchronousErrors(t,t=>t.inContext(()=>t.callbacks.failed(e)));if(n.length)throw new AggregateError(n,`Native resource failure callback failed`)}rejectClaim(e,t){if(e.failure||e.closed)return false;e.failure=t;this.host.refreshReference();e.attached.reject(t);e.pending?.completion.reject(t);e.pending=void 0;return true}clearOwnerMessages(e){for(const 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()}};
//!src/process/spawn-broker/host.ts
const RESTART_DELAYS=[100,250,500,1e3,2e3];const MAX_BOOTSTRAP_BYTES=1024;var BrokerHost=class{constructor(e={}){this.options=e;this.runInContext=AsyncLocalStorage.snapshot();this.readiness=createDeferredCore();this.available=false;this.hasBeenReady=false;this.closing=false;this.generation=0;this.consecutiveFailures=0;this.sequence=0;this.requests=/* @__PURE__ */ new Map;this.childAdmissions=/* @__PURE__ */ new Map;this.pendingSpawns=/* @__PURE__ */ new Set;this.fileReads=new BrokerFileReads({ready:()=>this.ready(),send:e=>this.transmit(e),canAdmit:()=>!this.resourceClaims&&!this.closing&&this.pendingSpawns.size+this.fileReads.size<256});this.cleanups=/* @__PURE__ */ new Set;this.cleanupErrors=[];this.startupDeadline=0;this.onParentExit=()=>{if(this.process?.connected)this.process.disconnect();for(const e of this.cleanups)e.force()};this.readFilePage=this.fileReads.readPage.bind(this.fileReads);this.commands=createBrokerCommands({nextId:()=>++this.sequence,admit:(e,t)=>this.admit(e,t),cancel:e=>this.transmit({type:`cancel`,id:e})});this.spawn=this.commands.spawn;this.spawnExeca=this.commands.spawnExeca;this.spawnToFile=this.commands.spawnToFile;this.workerUrl=e.workerUrl??resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.spawnBroker);this.entryPath=fileURLToPath(this.workerUrl);if(e.nativeResources){const{directory:e,...t}=createNativeResourceAuthority();this.resourceDirectory=e;this.resourceAuthority=t;this.resourceClaims=new BrokerResourceClaims({transmit:async e=>{if(!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();this.unregisterExitCleanup=registerProcessExitCleanup(this.onParentExit)}get pid(){return this.process?.pid}get hasOpenNativeResourceClaims(){return this.resourceClaims?.hasOpenClaims??false}get nativeResourceAdmissionClosed(){return(this.resourceClaims?.admissionClosed??false)||this.process?.connected===false}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.resourceClaims.size>=256)throw new SpawnBrokerError(`Native resource broker is unavailable or at capacity`);return this.resourceClaims.capture({...e,...e.moduleUrl.startsWith(`file:`)&&runtimeNeedsTypeScriptLoader(fileURLToPath(e.moduleUrl))?{sourceLoaderUrl:import.meta.resolve(`tsx/esm/api`)}:{},...this.resourceAuthority,generation:this.generation-1,startupDeadline:this.available?void 0:this.startupDeadline,id:++this.sequence},t)}sealNativeResources(){if(this.resourceClaims&&!this.available)return Promise.reject(new SpawnBrokerError(`Native resource broker is not ready for cleanup`));return this.resourceClaims?.seal()??Promise.reject(new SpawnBrokerError(`Native resources are disabled`))}serviceNativeResources(){this.serviceStartup?.()}refreshNativeReference(){if(!this.resourceClaims||!this.process)return;if(this.closing||this.resourceClaims.needsReference||this.requests.size>0){this.process.ref();process.ref(this.process.stderr);this.process.channel?.ref?.()}else{this.process.unref();process.unref(this.process.stderr);this.process.channel?.unref?.()}}admit(e,t){e.admission=getSpawnBrokerAdmission();const n=childCapacityError(this.childAdmissions.values(),e.admission);const r=createBrokerCommandRequest(e,t,this.transmit.bind(this));const{child:i,result:a,output:o}=r;const fail=e=>{r.resultSettled=true;a?.reject(e);o?.reject(e);i.settleFileOutput();i.fail(e)};if(!this.available||this.closing||this.pendingSpawns.size+this.fileReads.size>=256||n){i.markNotStarted();queueMicrotask(()=>fail(new SpawnBrokerError(this.available&&!this.closing?n??`Spawn broker startup capacity exceeded`:`Spawn broker is unavailable`)));return r}this.childAdmissions.set(e.id,e.admission);this.requests.set(e.id,r);this.pendingSpawns.add(e.id);this.refreshNativeReference();i.waitForClose().then(()=>{r.childClosed=true;this.retire(e.id,r)});this.transmit(e).catch(t=>{this.pendingSpawns.delete(e.id);if(t instanceof BrokerIpcAdmissionError)i.markNotStarted();else if(r.output){if(this.process?.connected)this.process.disconnect();return}if(!r.nativeInitiated&&e.type===`prepare-spawn`)i.markNotStarted();fail(new SpawnBrokerError(`Spawn broker request delivery failed`,{cause:t}))});return r}retire(e,t){if(t.childClosed&&t.resultSettled&&!t.nativeInitiated){if(t.child.notStarted||!t.recovering&&t.nativeClosed)this.childAdmissions.delete(e);else if(!t.recovering||t.pid===void 0)return;this.requests.delete(e);this.refreshNativeReference()}}retainCleanup(e,t){this.cleanups.add(e);e.settled.then(()=>{this.cleanups.delete(e);if(t!==void 0)this.childAdmissions.delete(t)},t=>{this.cleanupErrors.push(toErrorObject(t,`Spawn broker cleanup failed`));this.cleanups.delete(e)})}transmit(e,t,n){if(!this.available||!this.sendMessage)return Promise.reject(new SpawnBrokerError(`Spawn broker is unavailable`));return this.sendMessage(e,t,n)}start(){if(this.closing)return;try{assertChildRuntimeAvailable()}catch(e){this.readiness.reject(e);return}const e=this.generation++;const t={type:`bootstrap`,...this.resourceAuthority?{nativeResource:{...this.resourceAuthority,generation:e}}:{}};if(serialize(t).byteLength>MAX_BOOTSTRAP_BYTES)throw new SpawnBrokerError(`Spawn broker bootstrap exceeds its IPC bound`);const n=spawn(process.execPath,resolveRuntimeWorkerArgv(this.workerUrl),{stdio:[`inherit`,`ignore`,`pipe`,`ipc`],detached:true,serialization:`advanced`});this.process=n;const r=observeBrokerChildDiagnostics(n);let i=false;const a=waitForBrokerChildCompletion(n);let o;const prepareTerminalDiagnosis=()=>o??=d?r():a.then(r);let s;this.brokerClosed=a.then(async()=>{await s;if(i&&n.pid&&(n.exitCode!==0||n.signalCode!==null))this.cleanupErrors.push(new SpawnBrokerError(`Spawn broker shutdown failed`,{cause:await prepareTerminalDiagnosis().catch(e=>toErrorObject(e,`Spawn broker exit diagnosis failed`))}))});const c=createBrokerReceiver();const l=createDeferredCore();let u=false;let d=false;this.startupDeadline=spawnBrokerStartupNowMs()+SPAWN_BROKER_STARTUP_TIMEOUT_MS;const checkStartup=()=>{if(!u&&!d&&spawnBrokerStartupNowMs()>=this.startupDeadline)fail(/* @__PURE__ */ new Error(`readiness deadline exceeded after 15000ms`))};const f=this.resourceClaims?void 0:setTimeout(checkStartup,SPAWN_BROKER_STARTUP_TIMEOUT_MS);this.serviceStartup=checkStartup;const fail=(e,t=false)=>{if(u)return;i=this.closing;u=true;clearTimeout(f);this.markNativeReady=void 0;c.clear();this.available=false;this.resourceClaims?.closeAdmission();this.sendMessage=void 0;if(n.connected)n.disconnect();const r=this.readiness;this.readiness=createDeferredCore();this.readiness.promise.catch(()=>{});const o=this.requests;this.requests=/* @__PURE__ */ new Map;this.pendingSpawns.clear();const p=[];for(const[e,t]of o){t.recovering=true;if(t.pid&&!t.nativeClosed){const r=t.pid;if(this.closing){let i;this.retainCleanup({force:()=>i?.force(),settled:l.promise.then(async()=>{if(n.exitCode===0&&n.signalCode===null)return;i=terminateLostBrokerChild(r,t.detached);await i.settled})},e)}else this.retainCleanup(terminateLostBrokerChild(r,t.detached),e)}else if(t.child.notStarted||t.nativeClosed)this.childAdmissions.delete(e);if(t.output)p.push(t)}this.refreshNativeReference();if(n.pid&&process.platform!==`win32`){const e=n.pid;let t;this.retainCleanup({force:()=>t?.force(),settled:l.promise.then(async()=>{t=terminateBrokerProcessGroup(e);await t.settled})})}const m=t?prepareTerminalDiagnosis():prepareChildRuntimeFailure({error:e,started:d});s=prepareBrokerFailureCause(m,e).then(e=>{const t=createBrokerFailureError(e,this.hasBeenReady);r.reject(t);this.fileReads.fail(t);for(const e of o.values()){e.result?.reject(t);e.child.fail(t)}o.clear();if(p.length)Promise.allSettled([a,...[...this.cleanups].map(e=>e.settled)]).then(()=>{for(const e of p){e.output?.reject(t);e.child.settleFileOutput()}p.length=0});if(this.resourceClaims||this.closing||!this.hasBeenReady||hasErrnoCode(e,`NODE_RUNTIME_UNAVAILABLE`)){this.readiness.reject(t);this.resourceClaims?.fail(t);return}const n=RESTART_DELAYS[this.consecutiveFailures++];if(n===void 0){this.readiness.reject(t);return}this.restartTimer=setTimeout(()=>this.start(),n)})};const markReady=(t,r)=>{if(u||t!==n.pid||r!==e)throw new SpawnBrokerError(`Native resource readiness does not match the captured broker`);if(d)return;d=true;clearTimeout(f);this.hasBeenReady=true;this.consecutiveFailures=0;this.available=true;this.readiness.resolve();this.runInContext(()=>this.options.onReady?.(t,e>0))};this.markNativeReady=markReady;n.once(`error`,fail);n.once(`exit`,()=>{if(!u)i=this.closing;l.resolve();fail(void 0,true)});n.once(`disconnect`,()=>{if(d)fail(/* @__PURE__ */ new Error(`IPC channel disconnected`))});n.on(`message`,(t,n)=>{if(u||this.closing){if(n instanceof Socket)n.destroy();return}let r;try{r=c.receive(t)}catch(e){fail(toErrorObject(e,`Spawn broker receive failed`));return}if(r===void 0)return;const i=r;if(i.type===`startup-failed`){if(!d&&this.resourceClaims){const e=this.resourceClaims;this.brokerClosed?.then(()=>e.closeBeforeStartup()).catch(e=>{this.cleanupErrors.push(toErrorObject(e,`Spawn broker startup cleanup failed`))})}fail(Object.assign(new Error(i.error.message),i.error));return}if(i.type===`ready`){try{markReady(i.pid,e)}catch(e){fail(toErrorObject(e,`Spawn broker readiness failed`))}return}if(i.type===`resource-ready`||i.type===`resource-created`||i.type===`resource-target`||i.type===`resource-owner`||i.type===`resource-owner-received`||i.type===`resource-owner-rejected`||i.type===`resource-closed`||i.type===`resource-close-error`||i.type===`resource-failed`){try{this.resourceClaims?.receive(i)}catch(e){fail(toErrorObject(e,`Spawn broker native resource receive failed`))}return}if(this.fileReads.receive(i))return;if(i.type===`spawned`||i.type===`error`)this.pendingSpawns.delete(i.id);const a=this.requests.get(i.id);if(!a){if(n instanceof Socket)n.destroy();if(i.type===`pipe`)this.transmit({type:`pipe-received`,id:i.id,fd:i.fd}).catch(fail);else if(i.type===`prepared`)this.transmit({type:`launch`,id:i.id,allowed:false}).catch(fail);return}if(i.type===`owned`||i.type===`error`){a.nativeInitiated?.resolve();a.nativeInitiated=void 0}if(i.type===`prepared`){const e=a.initiateSpawn;a.initiateSpawn=void 0;const t=this.brokerClosed;const n=e?a.nativeInitiated??=createDeferredCore():void 0;const r=t&&n?Promise.race([n.promise,t]):Promise.reject(/* @__PURE__ */ new Error(`Spawn broker retirement is unavailable`));r.catch(()=>{});this.transmit({type:`launch`,id:i.id,allowed:true},void 0,t=>{if(!e||!n||a.childClosed)throw new SpawnBrokerError(`Spawn broker launch grant is unavailable`);return e(t,r)}).catch(()=>{this.transmit({type:`launch`,id:i.id,allowed:false}).catch(fail)})}else if(i.type===`owned`){a.pid=i.pid;if(a.childClosed){a.recovering=true;this.retainCleanup(terminateLostBrokerChild(i.pid,a.detached),i.id);this.retire(i.id,a)}}else{try{receiveBrokerCommandResponse(a,i,n,e=>this.transmit(e))?.catch(fail)}catch(e){fail(toErrorObject(e,`Spawn broker pipe setup failed`));return}this.retire(i.id,a)}});try{n.send(t,e=>{if(e)fail(e)})}catch(e){fail(toErrorObject(e,`Spawn broker bootstrap delivery failed`))}if(!u)this.sendMessage=createBrokerSender((e,t,r)=>n.send(e,t,{keepOpen:true},r));this.refreshNativeReference()}async waitForCleanup(){await Promise.allSettled([...this.cleanups].map(e=>e.settled));if(this.cleanupErrors.length)throw new AggregateError(this.cleanupErrors,`Spawn broker cleanup did not complete`)}close(){if(this.resourceClaims?.hasOpenClaims)return Promise.reject(new SpawnBrokerError(`Native resource claims must close before broker shutdown`));return this.closePromise??=this.closeInternal()}async closeInternal(){this.closing=true;this.refreshNativeReference();this.readiness.reject(new SpawnBrokerError(`Spawn broker is closing`));this.fileReads.fail(new SpawnBrokerError(`Spawn broker is closing`));clearTimeout(this.restartTimer);try{const e=this.process;if(e&&e.exitCode===null&&e.signalCode===null){if(this.resourceClaims)this.transmit({type:`shutdown`}).catch(()=>{if(e.connected)e.disconnect()});else if(e.connected)e.disconnect()}await this.brokerClosed;try{await this.waitForCleanup()}finally{if(this.resourceDirectory&&this.hasBeenReady)await rm(this.resourceDirectory,{recursive:true,force:true})}}finally{this.unregisterExitCleanup()}this.options.onClosed?.()}};const createSpawnBrokerHost=e=>new BrokerHost(e);export{terminateLostBrokerChild as n,waitForBrokerChildCompletion as r,createSpawnBrokerHost as t};