openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6 lines • 11.5 kB
JavaScript
import{t as createDeferredCore}from"./deferred-QsZCoVH-.mjs";import{n as runtimeProcessEntrypoints}from"./runtime-process-entrypoints-Dnd1WskT.mjs";import{a as resolveRuntimeWorkerUrl,n as resolveRuntimeWorkerArgv}from"./runtime-worker-url-Dqf-I1cs.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{r as parseComputerUseCapabilityDescriptor}from"./computer-use-contract-CaYMDN7U.mjs";import{t as getProcessSupervisor}from"./supervisor-4YHLp8V6.mjs";import{r as parseComputerHostOutput,t as ComputerHostFinalizationError}from"./computer-protocol-BWphQiwZ.mjs";import{t as parseNodeWorkerComputerInput}from"./node-computer-protocol-DOoNoBGF.mjs";import{t as createPendingRequestRegistry}from"./pending-request-registry-Djltk4RU.mjs";import{t as computerRunOwner}from"./computer-owner-Cam-18ic.mjs";import{randomUUID}from"node:crypto";
//!src/gateway/desktop/computer-process.ts
const STARTUP_TIMEOUT_MS=6e4;const SHUTDOWN_TIMEOUT_MS=3e4;const MAX_MESSAGE_CHARS=33554432;function startComputerHostProcess(e){const t=getProcessSupervisor();const n=`gateway-computer:${randomUUID()}`;const r=t.acquireScopeCleanup(n,{processTree:`owned-only`});const i=createDeferredCore();const a=createPendingRequestRegistry();let o;let s;let c=true;let l=``;let u;const assertActive=()=>{e.assertCurrent();if(!c)throw u??/* @__PURE__ */ new Error(`Gateway computer process is closed`)};const send=e=>{if(!o?.stdin||o.stdin.destroyed||o.stdin.writableEnded)throw new Error(`Gateway computer process input is closed`);o.stdin.write(`${JSON.stringify(e)}\n`,e=>{if(e)fail(e)})};const close=e=>{if(s)return s;if(c&&o?.activity.resultSettled)u??=/* @__PURE__ */ new Error(`Gateway computer process exited`);c=false;const t=u??/* @__PURE__ */ new Error(`Gateway computer process is closed`);i.reject(t);a.rejectAll(t);s=(async()=>{await f;let t;let n;if(o){if(!o.activity.resultSettled)try{send({type:`stop`,...e?{execution:e}:{}})}catch{o.cancel(`manual-cancel`)}const r=setTimeout(()=>o?.cancel(`manual-cancel`),SHUTDOWN_TIMEOUT_MS).unref();try{t=await o.wait()}catch(e){n=e instanceof Error?e:new Error(String(e))}finally{clearTimeout(r)}}await r();if(n)throw n;if(t&&(t.exitCode!==0||t.exitSignal!==null))u??=/* @__PURE__ */ new Error(`Gateway computer helper shutdown failed (${t.exitSignal??`exit ${t.exitCode}`})`);if(u)throw new ComputerHostFinalizationError(u)})();s.catch(e=>{if(!(e instanceof ComputerHostFinalizationError))s=void 0});return s};const fail=e=>{u??=e;close().catch(()=>{})};const failWhileOpen=e=>{if(!s)fail(e instanceof Error?e:new Error(String(e)))};const receive=e=>{l+=e;if(l.length>MAX_MESSAGE_CHARS){fail(/* @__PURE__ */ new Error(`Gateway computer response exceeds the transport limit`));return}let t;while((t=l.indexOf(`
`))>=0){const e=l.slice(0,t);l=l.slice(t+1);try{const t=parseComputerHostOutput(JSON.parse(e));if(t.type===`ready`)i.resolve(parseComputerUseCapabilityDescriptor(t.computerUse));else if(t.type===`result`){const e=JSON.parse(t.payload);a.take(t.id)?.resolve(e)}else if(t.id)a.take(t.id)?.reject(new Error(t.message));else fail(new Error(t.message))}catch{fail(/* @__PURE__ */ new Error(`Invalid Gateway computer response`))}}};const d=setTimeout(()=>fail(/* @__PURE__ */ new Error(`Gateway computer provider startup timed out`)),STARTUP_TIMEOUT_MS).unref();i.promise.then(()=>clearTimeout(d),()=>clearTimeout(d));const f=Promise.resolve().then(async()=>{if(!c)return;try{const r=resolveRuntimeWorkerUrl(runtimeProcessEntrypoints.computerHost);assertActive();o=await t.spawn({scopeKey:n,mode:`child`,argv:[process.execPath,...resolveRuntimeWorkerArgv(r)],env:e.env,exactEnv:true,stdinMode:`pipe-open`,captureOutput:false,onStdout:receive,assertCurrent:assertActive});o.wait().then(()=>failWhileOpen(/* @__PURE__ */ new Error(`Gateway computer process exited`)),failWhileOpen);assertActive();send({type:`start`,pluginIds:e.pluginIds})}catch(e){failWhileOpen(e)}});return{ready:i.promise,isCurrent:()=>c,async invoke(e){await i.promise;const t=randomUUID();let n=false;const cancel=()=>{try{send({type:`cancel`,id:t})}catch{}};const abort=()=>{cancel();a.take(t)?.reject(e.signal?.reason??/* @__PURE__ */ new Error(`Computer invocation cancelled`))};const r=a.add(t,{value:void 0,timeoutMs:e.timeoutMs??6e4,timeoutError:()=>/* @__PURE__ */ new Error(`Gateway computer invocation timed out`),onTimeout:()=>{n=true;cancel()},dispose:()=>e.signal?.removeEventListener(`abort`,abort)});if(!r)throw new Error(`Gateway computer request already exists`);e.signal?.addEventListener(`abort`,abort,{once:true});try{assertActive();e.assertCurrent();e.signal?.throwIfAborted();send({type:`invoke`,id:t,command:e.command,paramsJSON:JSON.stringify(e.params),...e.sessionKey?{sessionKey:e.sessionKey}:{}})}catch(e){a.take(t)?.reject(e)}try{return await r.promise}catch(t){if(e.signal?.aborted||n||!c)await close();throw t}},close}}
//!src/gateway/desktop/computer-service.ts
const log=createSubsystemLogger(`gateway/computer`);function createGatewayComputerService(e){let t;let n=false;let r=false;let i;const configuredProvider=()=>{const t=e.getConfig();const n=e.getPluginRegistry();return n.nodeHostCommands.find(e=>{const r=n.plugins.find(t=>t.id===e.pluginId);return e.command.command===`computer.act`&&e.command.computerUse!==void 0&&r?.enabled===true&&r.status===`loaded`&&t.plugins?.enabled!==false&&t.plugins?.entries?.[e.pluginId]?.enabled===true})};const configuredDesktopTarget=()=>{const t=e.getConfig().desktop?.host;return t?.enabled&&t.managed&&t.port===void 0?`managed`:`native`};const assertRuntime=e=>{if(n||r||e.closed||t!==e||configuredProvider()?.command!==e.provider.command||e.desktopTarget!==configuredDesktopTarget()||e.desktop?.isCurrent()===false||e.process?.isCurrent()===false)throw new Error(`COMPUTER_DRIVER_UNAVAILABLE: Gateway computer generation is closed`)};const retire=(e,n)=>{if(e.closing)return e.closing;e.closed=true;clearTimeout(e.idleTimer);e.closing=(async()=>{let r;try{await e.process?.close(n)}catch(e){if(!(e instanceof ComputerHostFinalizationError))throw e;r=e}e.desktop?.release();e.execution?.releaseOwner();if(t===e)t=void 0;if(r)throw r})();e.closing.catch(()=>{e.closing=void 0});return e.closing};const retireForShutdown=async e=>{try{await retire(e)}catch(e){if(!(e instanceof ComputerHostFinalizationError))throw e;log.warn(e.message)}};const retireInBackground=e=>{retireForShutdown(e).catch(()=>{log.warn(`Computer cleanup failed; retaining its desktop owner for recovery`)})};const scheduleIdle=e=>{clearTimeout(e.idleTimer);if(e.closed||e.execution?.requests.size)return;e.idleTimer=setTimeout(()=>retireInBackground(e),e.execution?3e5:6e4).unref()};const assertAvailable=()=>{if(n||r)throw new Error(n?`Gateway computer service is stopped`:`Gateway computer provider is reloading`)};const prepare=async()=>{assertAvailable();const n=configuredProvider();if(t){if(t.provider.command===n?.command&&t.desktopTarget===configuredDesktopTarget()&&!t.closed&&t.desktop?.isCurrent()!==false&&t.process?.isCurrent()!==false){const e=t;await e.prepared;assertRuntime(e);return e}await retire(t);return await prepare()}if(!n)return;const r=createDeferredCore();const i={provider:n,desktopTarget:configuredDesktopTarget(),closed:false,prepared:r.promise};t=i;(async()=>{let t=process.env;if(i.desktopTarget===`managed`){if(!e.hostDesktopService)throw new Error(`Managed Gateway desktop is unavailable`);i.desktop=await e.hostDesktopService.acquireComputer({onStop:()=>retireForShutdown(i)});t=i.desktop.env}assertRuntime(i);i.process=startComputerHostProcess({env:t,pluginIds:[n.pluginId],assertCurrent:()=>assertRuntime(i)});const r=await i.process.ready;assertRuntime(i);i.computerUse=r;return r})().then(r.resolve,r.reject);try{await i.prepared;scheduleIdle(i);return i}catch(e){await retire(i);i.desktop?.release();throw e}};return{async reconcileRuntimePolicy(){const e=t;if(e&&e.desktopTarget!==configuredDesktopTarget())await retireForShutdown(e)},preparePluginReload({changedPluginIds:e}){const n=t?.provider??configuredProvider();const i=n!==void 0&&e.has(n.pluginId);if(i)r=true;return{drain:async()=>{if(i&&t)await retireForShutdown(t)},resume:()=>{if(i)r=false}}},async status({probe:n=true}={}){const r={configured:false,available:false};try{assertAvailable();const e=n?await prepare():t;if(e){assertRuntime(e);if(e.computerUse)return{configured:true,available:true,computerUse:e.computerUse}}}catch(e){r.error=e instanceof Error?e.message:String(e)}const a=configuredProvider();r.configured=a!==void 0;try{if(a){const t=e.getConfig();if(i?.command!==a.command||i.config!==t)i={command:a.command,config:t,computerUse:parseComputerUseCapabilityDescriptor(a.command.computerUse({config:t,env:process.env}))};r.computerUse=i.computerUse}else i=void 0}catch(e){r.error??=e instanceof Error?e.message:String(e)}return r},async invoke(e){const n=e.command===`computer.act`&&e.params.action===`__close_execution`;const r=parseNodeWorkerComputerInput(JSON.stringify(n?{operation:`close`,executionId:e.params.executionId,reason:e.params.reason??`completion`}:{operation:e.command===`screen.snapshot`?`snapshot`:`act`,providerGeneration:e.generation,params:e.params}));if(r.operation===`capabilities`)throw new Error(`Invalid computer invocation`);const i=t;if(!i){if(n)return{ok:true};throw new Error(`COMPUTER_STALE_OBSERVATION: refresh the Gateway computer before acting`)}const a=await i.prepared;const o=i.process;if(!o)throw new Error(`COMPUTER_STALE_OBSERVATION: Gateway computer is unavailable`);if(e.generation!==a.provider.generation){if(n)return{ok:true};throw new Error(`COMPUTER_STALE_OBSERVATION: Gateway computer generation changed`)}const s=r.operation===`close`?r.executionId:r.params.executionId;const c=i.execution;if(c&&(c.owner!==e.owner||c.logicalId!==s))throw new Error(`COMPUTER_HOST_BUSY: another execution owns the Gateway computer`);if(r.operation===`close`){if(!c)return{ok:true};await retire(i,{executionId:c.physicalId,reason:r.reason});return{ok:true}}if(i.closed||i.desktopTarget!==configuredDesktopTarget()||!o.isCurrent()||i.desktop?.isCurrent()===false)throw new Error(`COMPUTER_STALE_OBSERVATION: refresh the Gateway computer before acting`);assertRuntime(i);e.assertCurrent();e.signal?.throwIfAborted();e.ownerSignal?.throwIfAborted();const onOwnerClosed=()=>retireInBackground(i);const l=i.execution??={owner:e.owner,logicalId:s,physicalId:randomUUID(),requests:/* @__PURE__ */ new Map,settled:/* @__PURE__ */ new Set,releaseOwner:()=>e.ownerSignal?.removeEventListener(`abort`,onOwnerClosed)};if(!c)e.ownerSignal?.addEventListener(`abort`,onOwnerClosed,{once:true});const u=JSON.stringify({command:e.command,params:e.params});const d=l.requests.get(e.idempotencyKey);if(d){if(d.input!==u)throw new Error(`Computer idempotency key was reused with different input`);return await d.result}if(l.settled.has(e.idempotencyKey))throw new Error(`Computer request already settled; observe before issuing a new action`);clearTimeout(i.idleTimer);const f=o.invoke({command:e.command,params:{...r.params,executionId:l.physicalId},signal:e.signal,timeoutMs:e.timeoutMs,assertCurrent:()=>{assertRuntime(i);e.assertCurrent()}});l.requests.set(e.idempotencyKey,{input:u,result:f});try{return await f}finally{l.requests.delete(e.idempotencyKey);l.settled.add(e.idempotencyKey);scheduleIdle(i)}},async close(){n=true;if(t)await retireForShutdown(t)},revokeRunAuthority(e){const n=t;if(n?.execution?.owner===computerRunOwner(e))retireInBackground(n)}}}export{createGatewayComputerService};