UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

225 lines (224 loc) • 8.62 kB
import { b as NODE_WORKER_DESKTOP_LAUNCH_COMMAND, x as NODE_WORKER_DESKTOP_STREAM_COMMAND } from "./node-commands-BfMJIlXP.mjs"; import { t as raceNodeWorkerOperation } from "./node-worker-abort-BCKtSFqU.mjs"; import { t as DesktopSessionStaleOwnerError } from "./session-registry-0QrwKuF4.mjs"; import { t as parseNodeWorkerResponse } from "./node-worker-response-CDXcKXUT.mjs"; import { n as snapshotWorkerNodeCarrierBinding, t as isWorkerNodeCarrierBindingCurrent } from "./node-carrier-binding-eAgn9G8N.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/gateway/worker-environments/node-desktop-carrier.ts const APP_LAUNCH_TIMEOUT_MS = 3e4; function snapshotNodeDesktopBinding(e) { const t = "Worker environment node desktop owner is not active"; const n = snapshotWorkerNodeCarrierBinding(e, t); if (!e.desktop) throw new Error(t); return { ...n, desktop: structuredClone(e.desktop) }; } function isBindingCurrent(e, t) { const n = e.get(t.environmentId); return Boolean(n && isWorkerNodeCarrierBindingCurrent(n, t) && n.desktop !== null && isDeepStrictEqual(n.desktop, t.desktop)); } function requireLaunchReady(e) { if (!e.ok) throw new Error(e.error?.message?.trim() || "worker node desktop stream closed before attachment"); const t = parseNodeWorkerResponse(e.payloadJSON || "null", "Worker environment node desktop launcher"); if (!isDeepStrictEqual(t, { status: "ready" })) throw new Error("Worker environment node desktop launcher returned an invalid result"); } /** Carries one durable worker environment's desktop over its private node connection. */ function createWorkerNodeDesktopCarrier(e) { let t; const n = /* @__PURE__ */ new Set(); const r = /* @__PURE__ */ new Set(); const i = /* @__PURE__ */ new Map(); const bindingIsCurrent = (n, r, i) => t === r && isBindingCurrent(e.store, n) && r.transport.isCurrent(i, false); const findCurrentNode = async (e, t, n) => { n.throwIfAborted(); const r = await raceNodeWorkerOperation(t.transport.getCurrentNode(e.nodeDeviceId), n, { aborted: "Worker environment node desktop operation aborted", failed: "Node desktop operation failed" }); n.throwIfAborted(); if (!r || !bindingIsCurrent(e, t, r)) throw new Error("Worker environment node desktop connection is not current"); return r; }; const stopOperation = async (e) => { if ("stream" in e) { await e.stream.stop(); return; } e.controller.abort(/* @__PURE__ */ new Error("Worker environment node desktop owner stopped")); await e.operation.catch(() => void 0); }; const stopOwnedOperations = async (e, t) => { const n = [...r, ...i.values()].filter((n) => n.binding.environmentId === e && (t === void 0 || n.binding.ownerEpoch === t)); await Promise.all(n.map(stopOperation)); }; const claimOwner = async (t) => { let n; try { n = e.desktopRegistry.claimOwnerEpoch(t.environmentId, t.ownerEpoch); } catch (e) { if (e instanceof DesktopSessionStaleOwnerError) throw new Error("Worker environment node desktop owner epoch is stale", { cause: e }); throw e; } if (!n) return; const a = [...r, ...i.values()].filter((e) => e.binding.environmentId === t.environmentId && e.binding.ownerEpoch < t.ownerEpoch); await e.desktopRegistry.stopSuperseded(t.environmentId, t.ownerEpoch); await Promise.all(a.map(stopOperation)); }; const observe = async (i) => { const a = snapshotNodeDesktopBinding(i.record); const o = { binding: a, stream: e.desktopRegistry.createStream({ sourceKey: a.environmentId, ownerEpoch: a.ownerEpoch, onStopped: () => { r.delete(o); } }) }; const s = i.requester?.signal ? AbortSignal.any([o.stream.signal, i.requester.signal]) : o.stream.signal; const assertRequesterCurrent = () => { s.throwIfAborted(); if (i.requester?.isCurrent() === false) throw new Error("Desktop observer connection is no longer current"); }; assertRequesterCurrent(); r.add(o); n.add(a.environmentId); try { await claimOwner(a); assertRequesterCurrent(); await e.desktopRegistry.activate({ sourceKey: a.environmentId, ownerEpoch: a.ownerEpoch, teardown: async () => { await stopOwnedOperations(a.environmentId, a.ownerEpoch); } }); assertRequesterCurrent(); const n = t; if (!n) throw new Error("Worker environment node desktop runtime is unavailable"); const r = await findCurrentNode(a, n, s); assertRequesterCurrent(); if (!o.stream.reserve()) throw new Error("Worker environment desktop observer limit reached"); const c = n.streamBroker.mint({ nodeId: r.nodeId, connId: r.connId, pairingGeneration: r.pairingGeneration }); const l = await o.stream.connect(c, () => n.transport.invoke({ node: r, command: NODE_WORKER_DESKTOP_STREAM_COMMAND, params: { ticket: c.ticket, attachPath: c.attachPath, port: a.desktop.port, ...a.desktop.username ? { username: a.desktop.username } : {}, ...a.desktop.passwordFilePath ? { passwordFilePath: a.desktop.passwordFilePath } : {} }, timeoutMs: 0, signal: s, isDispatchAuthorized: () => !s.aborted && i.requester?.isCurrent() !== false && bindingIsCurrent(a, n, r) })); assertRequesterCurrent(); if (!bindingIsCurrent(a, n, r)) throw new Error("Worker environment node desktop owner changed before attachment"); const u = a.desktop.username ? "ard-account" : "vnc-password"; if (l.auth !== u || !l.vncPassword) throw new Error("Worker environment node desktop did not provide managed authentication"); const { DESKTOP_OBSERVE_PATH: d, mintDesktopObserverToken: f } = await import("./observe-bridge-BNslmUCS.mjs"); assertRequesterCurrent(); if (!bindingIsCurrent(a, n, r)) throw new Error("Worker environment node desktop owner changed before publication"); const p = o.stream.publish(); if (!p) throw new Error("Worker environment node desktop owner changed before publication"); const m = Date.now(); const h = f({ sourceKey: a.environmentId, ownerEpoch: a.ownerEpoch, control: i.control, requester: i.requester, attachment: p, onAbandon: o.stream.stop, preauth: a.desktop.username ? { auth: "ard-account", credentials: { username: a.desktop.username, password: l.vncPassword } } : { auth: "vnc-password", credentials: { password: l.vncPassword } }, nowMs: m }); o.stream.expireAt(h.expiresAtMs); return { transport: "rfb", wsPath: `${d}?token=${h.token}`, expiresAtMs: h.expiresAtMs, control: i.control }; } catch (e) { await o.stream.stop(); throw e; } }; const launchApp = (e) => { const r = snapshotNodeDesktopBinding(e.record); const a = r.desktop.apps?.find((t) => t.id === e.app.id); if (!a || !isDeepStrictEqual(a, e.app)) return Promise.reject(/* @__PURE__ */ new Error("Worker environment node desktop app descriptor is not current")); const o = `${r.environmentId}\0${a.id}`; const s = i.get(o); if (s?.binding.ownerEpoch === r.ownerEpoch && isDeepStrictEqual(s.app, a)) return s.operation; const c = new AbortController(); const l = Promise.resolve().then(async () => { await claimOwner(r); if (s) { s.controller.abort(/* @__PURE__ */ new Error("Worker environment node desktop launch owner replaced")); await s.operation.catch(() => void 0); } c.signal.throwIfAborted(); const e = t; if (!e) throw new Error("Worker environment node desktop runtime is unavailable"); const n = await findCurrentNode(r, e, c.signal); if (i.get(o) !== u) throw new Error("Worker environment node desktop launch owner was replaced"); requireLaunchReady(await e.transport.invoke({ node: n, command: NODE_WORKER_DESKTOP_LAUNCH_COMMAND, params: a, timeoutMs: APP_LAUNCH_TIMEOUT_MS, signal: c.signal, isDispatchAuthorized: () => !c.signal.aborted && bindingIsCurrent(r, e, n) })); if (!bindingIsCurrent(r, e, n)) throw new Error("Worker environment node desktop launch owner changed"); }); const u = { binding: r, app: a, controller: c, operation: l }; i.set(o, u); n.add(r.environmentId); l.finally(() => { if (i.get(o) === u) i.delete(o); }).catch(() => void 0); return l; }; const stop = async (t, n) => { await Promise.all([e.desktopRegistry.stop(t, n), stopOwnedOperations(t, n)]); }; const stopAll = async () => { await Promise.all([...n].map((e) => stop(e))); }; return { bindRuntime(e) { t = e; }, launchApp, observe, stop, stopAll }; } //#endregion export { createWorkerNodeDesktopCarrier };