UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

7 lines (6 loc) • 19.7 kB
import{o as e}from"./transcript-record-coerce-eN4p5mcq.mjs";import{i as t}from"./transcript-global-singleton-DIJgobpU.mjs";import{B as n,d as r}from"./transcript-plugin-instance-invocation-7pP9ZY8b.mjs";import{E as i,S as a,l as o,u as s,x as c}from"./transcript-worker-cpu-DTToyx8O.mjs";import{t as l}from"./transcript-detached-async-context-BKXaSw-L.mjs";import{t as u}from"./transcript-errno-CsW5NI8i.mjs";import{x as d}from"./transcript-sqlite-error-diagnostics-Bzt01wuM.mjs";import{t as f}from"./transcript-async-context-CWIqzhI4.mjs";import{f as p,t as m}from"./transcript-subsystem-er2pCebD.mjs";import{t as h}from"./transcript-deferred-B75K7ut7.mjs";import"./transcript-sqlite-post-commit-BDZjIt2B.mjs";import{n as g}from"./transcript-runtime-worker-url-D1R86-Xb.mjs";import{t as _}from"./transcript-runtime-process-url-BahjIwf7.mjs";import{channel as v}from"node:diagnostics_channel";import"node:v8";import{BroadcastChannel as y,MessageChannel as b,Worker as x,isMainThread as S,threadId as C}from"node:worker_threads";import w from"node:path";import{AsyncLocalStorage as T,AsyncResource as E}from"node:async_hooks";import{accessSync as D,constants as O,statSync as k}from"node:fs";import A from"node:fs/promises";import{fileURLToPath as j}from"node:url";import{stripVTControlCharacters as M}from"node:util";import{execFile as N,spawnSync as P}from"node:child_process";import{EventEmitter as F}from"node:events";import{Socket as I}from"node:net";const L=v(`openclaw.postgres.pool.self-root`);function startPool(){if(!S&&o()){let e={threadId:C,owner:p(process.argv[1]??``)};L.publish(e);let t=new y(`openclaw.postgres.pool.self-root`);t.unref(),t.postMessage(e),t.close(),m(`postgres`).warn(`PostgreSQL worker ${e.owner} (thread ${C}) has no inherited pool; starting its own four I/O services.`)}let e=new SharedArrayBuffer(4),t=Array.from({length:4},()=>({channel:new b,signal:new SharedArrayBuffer(8),peers:[]}));for(let e=0;e<t.length;e++)for(let n=e+1;n<t.length;n++){let{port1:r,port2:i}=new b;t[e].peers.push({port:r,signal:t[n].signal}),t[n].peers.push({port:i,signal:t[e].signal})}let n={services:t.map(({channel:e,signal:t})=>({port:e.port1,signal:t})),allocation:e,nextStep:a.nextStep},r=_(`postgresBridge`),i=g(r),l=[];a.endpoints=n,a.workers=l;let launch=e=>{let n=t[e],o=new Int32Array(n.signal),c=!1,d=new x(r,{workerData:{host:n.channel.port2,signal:n.signal,peers:n.peers},transferList:[n.channel.port2,...n.peers.map(({port:e})=>e)],execArgv:i});s(d,r),d.unref(),n.channel.port1.unref(),l[e]=d;let f=new Promise((e,t)=>{d.once(`error`,t),d.once(`exit`,()=>t(/* @__PURE__ */ Error(`PostgreSQL I/O service exited before readiness.${a.nextStep?` Run ${a.nextStep}.`:``}`))),d.once(`message`,()=>e())});f.catch(()=>{}),a.ready[e]=f,d.on(`error`,()=>{}),d.once(`exit`,()=>{c=!0,Atomics.store(o,1,1),Atomics.notify(o,1),u.add(e)}),Promise.resolve(Atomics.waitAsync(o,1,0).value).then(async()=>{c||await d.terminate()})},u=/* @__PURE__ */ new Set;a.refresh=()=>{for(let e of u){u.delete(e);let r={channel:new b,signal:new SharedArrayBuffer(8),peers:[]};t[e]=r,n.services[e]={port:r.channel.port1,signal:r.signal};for(let n=0;n<t.length;n++){if(n===e)continue;let i=t[n],{port1:a,port2:o}=new b;r.peers.push({port:a,signal:i.signal}),l[n].postMessage({watch:{port:o,signal:r.signal}},[o])}launch(e)}};try{for(let e=0;e<t.length;e++)launch(e)}catch(e){throw c(),e}return n}function getPostgresPool(){return a.nextStep||a.refresh?.(),a.endpoints??startPool()}function createPostgresPoolEndpoints(e=i()){if(!a.endpoints&&(!e||!Object.values(e.effectiveEngines).includes(`postgres`)))return;let t=getPostgresPool();return{...t,services:t.services.map(({port:e,signal:t})=>{let n=new b;return e.postMessage({host:n.port2},[n.port2]),{port:n.port1,signal:t}})}}function postgresPoolTransferList(e){return e?.services.map(({port:e})=>e)??[]}function selectPostgresPoolService(){let e=getPostgresPool(),t=(Atomics.add(new Uint32Array(e.allocation),0,1)>>>0)%4;return{...e.services[t],nextStep:e.nextStep}}function isNativeCommitReceipt(t){return e(t)&&t.version===1&&typeof t.sequence==`number`&&Number.isSafeInteger(t.sequence)&&t.sequence>=1&&Object.hasOwn(t,`facts`)}function isNativeSettlementReceipt(t){return e(t)&&(t.kind===`completed`||t.kind===`unknown`)&&(t.committed===void 0||isNativeCommitReceipt(t.committed))}t(Symbol.for(`openclaw.sqliteWorkerNativeCommitReceipts`),()=>/* @__PURE__ */ new WeakMap);function resolveSqliteWorkerFinishSettlement(e,t,n){return e??(n===`not-entered`&&!t?{kind:`completed`}:void 0)}const R=t(Symbol.for(`openclaw.sqliteWorkerOperationAdmission`),()=>new T);function createSqliteWorkerNativeReceiptOwner(t,n){let r=[],i=!1,a,o=0,s,invalidProtocol=e=>n(new d(`SQLite worker ${e} is invalid`,`outcome-unknown`)),installCommitted=e=>{if(e.sequence<=o)return;o=e.sequence;let s={facts:e.facts};a=s,i=!0;try{t(()=>{for(let e of r)e(s)})}catch(e){n(Object.assign(new d(`SQLite committed facts publication failed`,`outcome-unknown`),{cause:e}))}finally{i=!1}};return{get committed(){return a},get settlement(){return s},get observingCommit(){return i},observe(e){r.push(e)},receive(t){if(e(t)&&t.kind===`native-commit`){let e=t.committed;return isNativeCommitReceipt(e)?(installCommitted(e),!0):(invalidProtocol(`commit receipt`),!0)}if(e(t)&&t.kind===`native-settlement`){let e=t.settlement;return isNativeSettlementReceipt(e)?(e.committed!==void 0&&installCommitted(e.committed),s={kind:e.kind,...a?{committed:a}:{}},!0):(invalidProtocol(`native settlement`),!0)}return!1},finish(e){s=resolveSqliteWorkerFinishSettlement(s,a,e),i?queueMicrotask(()=>{r.length=0}):r.length=0}}}const z=new f(Symbol(`spawnBroker`)),B={startupDisabled:!1};function getSpawnBroker(){let e=z.getStore();return B.startupDisabled||e===null?void 0:e??B.host}const V=new TextDecoder,H=/* @__PURE__ */ new Map([[` `,` `],[` `,` `],[`\b`,`\\b`],[`\f`,`\\f`],[`\r`,`\\r`],[` `,`\\t`]]);function renderOutput(e){let t=typeof e==`string`?e:V.decode(e);return t.endsWith(` `)&&(t=t.slice(0,t.endsWith(`\r `)?-2:-1)),M(t).replace(/[\p{Separator}\p{Other}]/gu,e=>{let t=H.get(e);if(t!==void 0)return t;let n=e.codePointAt(0),r=n.toString(16);return n<=65535?`\\u${r.padStart(4,`0`)}`:`\\U${r}`})}function decodeExecaMessage(e,t){return e.messageOutputs?[e.message,...e.messageOutputs.map(e=>renderOutput(t[e]))].join(` `):e.message}function restoreError(e,t){let n=Error(decodeExecaMessage(e,t),{cause:e.cause?restoreError(e.cause,t):void 0});return Object.assign(n,{name:e.name,code:e.code})}function restoreExecaResult(e){let{error:t,...n}=e,r={...n,stdout:n.stdout,stderr:n.stderr,shortMessage:n.shortMessage,code:n.code};if(t){let e=restoreError(t,r);return Object.assign(e,r,{cause:e.cause})}return{...r,cause:void 0}}const U=t(Symbol.for(`openclaw.childRuntimeViability`),()=>({initialPath:process.execPath,initialIdentity:executableIdentity(process.execPath)})),W=/(?:dyld[^\n]*:\s*Library not loaded:|error while loading shared libraries:)/i,G=/(?: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(k(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(u(t,`ENOENT`)||u(t,`ENOTDIR`))&&recordUnavailableRuntime(e,t),{execPath:e,available:!(U.execPath===e&&U.failure)}}function readChildRuntimeViability(e){let t=e?.execPath??process.execPath;if(U.execPath===t&&U.failure)return{execPath:t,available:!1};try{D(t,O.X_OK)}catch(e){return publishRuntimeViability(t,e)}return publishRuntimeViability(t)}async function prepareChildRuntimeViability(e){let t=e?.execPath??process.execPath,n=!(U.execPath===t&&U.failure);if(n)try{let e=await probeChildRuntimeExecutable(t);n=!classifyRuntimeProbe(t,e,await A.stat(t).then(formatExecutableIdentity,()=>void 0),e.error)}catch(e){n=publishRuntimeViability(t,await A.stat(t).then(()=>e,e=>e)).available}return{publish:()=>({execPath:t,available:n&&publishRuntimeViability(t).available})}}function recoverUnavailableRuntime(){if(U.execPath!==process.execPath||!U.failure||!U.recover||U.recoveryStarted)return;U.recoveryStarted=!0;let e=U.recover;l(()=>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=>{m(`gateway/runtime`).warn(`${e.status}: ${e.reason}`)}))}function runtimeProbeOptions(e={}){return{encoding:`utf8`,cwd:e.cwd??w.parse(process.execPath).root,env:e.env??{...process.env,NODE_OPTIONS:void 0},timeout:1e3,maxBuffer:8192}}async function probeChildRuntimeExecutable(e,t={}){let n=getSpawnBroker();if(n){let r=n.spawnExeca([e,`--version`],{...runtimeProbeOptions(t),extendEnv:!1,stripFinalNewline:!1,stdin:`ignore`});r.child.once(`spawn`,()=>{r.child.stdout?.resume(),r.child.stderr?.resume()});let i=restoreExecaResult(await r.result);return await r.child.waitForClose(),{stdout:typeof i.stdout==`string`?i.stdout:``,stderr:typeof i.stderr==`string`?i.stderr:``,error:i instanceof Error?i:void 0,status:i.exitCode??null,signal:i.signal??null}}return new Promise(n=>{N(e,[`--version`],runtimeProbeOptions(t),(e,t,r)=>n({stdout:t,stderr:r,error:e??void 0,status:e?typeof e.code==`number`?e.code:null:0,signal:e?.signal??null}))})}function formatMissingChildRuntimeWarning(e){return e.available?void 0:`The Node.js runtime this Gateway started with (${r(e.execPath)}) can no longer start worker processes, likely because it was upgraded or removed. Restart the Gateway.`}function assertChildRuntimeAvailable(){if(U.execPath===process.execPath&&U.failure)throw U.failure}function recordUnavailableRuntime(e,t,n){if(U.execPath===e&&U.failure)return U.failure;U.execPath=e;let r=formatMissingChildRuntimeWarning({execPath:e,available:!1}),i=n?.trim();return U.failure=Object.assign(Error(i?`${r}\n${i}`:r,{cause:t}),{code:`NODE_RUNTIME_UNAVAILABLE`}),m(`gateway/runtime`).error(U.failure.message),recoverUnavailableRuntime(),U.failure}function needsRuntimeProbe(e){return!!(e.error||e.signal===`SIGABRT`||G.test(e.stderr??``))}function classifyRuntimeProbe(e,t,n,r){if(U.execPath===e&&U.failure)return U.failure;let i=e!==U.initialPath||n!==U.initialIdentity;return W.test(t.stderr)||G.test(t.stderr)||u(t.error,`ENOENT`)||u(t.error,`ENOTDIR`)||i&&(t.signal===`SIGABRT`||u(t.error,`ENOEXEC`)||u(t.error,`EACCES`)||u(t.error,`EPERM`))?recordUnavailableRuntime(e,r,t.stderr):void 0}function classifyChildRuntimeFailure(e){if(e.started)return;let t=e.execPath??process.execPath;if(U.execPath===t&&U.failure)return U.failure;if(W.test(e.stderr??``)||e.error&&!readChildRuntimeViability({execPath:t}).available)return recordUnavailableRuntime(t,e.error,e.stderr);if(needsRuntimeProbe(e))return classifyRuntimeProbe(t,P(t,[`--version`],runtimeProbeOptions()),t===U.initialPath?executableIdentity(t):void 0,e.error)}async function prepareChildRuntimeFailure(e){if(e.started)return;let t=e.execPath??process.execPath;if(U.execPath===t&&U.failure)return U.failure;if(W.test(e.stderr??``)||e.error&&!(await prepareChildRuntimeViability({execPath:t})).publish().available)return recordUnavailableRuntime(t,e.error,e.stderr);if(!e.error&&needsRuntimeProbe(e))return classifyRuntimeProbe(t,await probeChildRuntimeExecutable(t),t===U.initialPath?await A.stat(t).then(formatExecutableIdentity,()=>void 0):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))}),async()=>e.exitCode===0&&!r?void 0:prepareChildRuntimeFailure({execPath:t,error:r,stderr:i,signal:e.signalCode,started:n})}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}}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?j(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 K=/* @__PURE__ */ new WeakMap,holdReadable=()=>{};function holdPipe(e){let t={read:e.read.bind(e),resumed:!1,onResume:()=>{t.resumed=!0}};K.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=K.get(e);if(t)return e.read=t.read,K.delete(e),e.removeListener(`resume`,t.onResume),e.removeListener(`readable`,holdReadable),t}var BrokerChild=class extends F{constructor(e,t,n,r=!1){super(),this.requestId=e,this.transmit=n,this.fileOutputPending=r,this.callbackContext=new E(`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=h(),this.completion=h(),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 F,{ref(){},unref(){}})),this.opened.resolve(),setImmediate(()=>{this.closed||(this.emit(`spawn`),setImmediate(()=>{for(let[e,t]of this.stdio.entries())e>0&&t instanceof I&&!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(e=`SIGTERM`){return!this.exited&&(this.killed=!0,this.transmit({type:`kill`,id:this.requestId,signal:e}).catch(e=>this.fail(n(e,`Spawn broker signal delivery failed`))),!0)}send(e,t,r,i,a){let o=typeof t==`function`?t: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,E.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,n(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(n(e,`Spawn broker disconnect failed`))))}ref(){}unref(){}[Symbol.dispose](){this.kill(`SIGTERM`)}};export{postgresPoolTransferList as _,SpawnBrokerError as a,classifyChildRuntimeFailure as c,readChildRuntimeViability as d,getSpawnBroker as f,getPostgresPool as g,createPostgresPoolEndpoints as h,restoreStdinPipe as i,observeChildRuntime as l,R as m,brokerSpawnOptions as n,childCapacityError as o,createSqliteWorkerNativeReceiptOwner as p,holdPipe as r,assertChildRuntimeAvailable as s,BrokerChild as t,prepareChildRuntimeFailure as u,selectPostgresPoolService as v};