UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

371 lines (370 loc) • 14.3 kB
import { n as MAX_TIMER_TIMEOUT_MS } from "./number-coercion-D6u-4YD8.mjs"; import { d as sleepWithAbort, n as computeBackoff } from "./src-BPmQBLJp.mjs"; import { s as getGatewayRestartDrainSignal } from "./gateway-work-admission-79pid1hQ.mjs"; import "./backoff-B-fIQi7C.mjs"; import { D as NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND, E as NODE_WORKER_SUPERVISOR_CANCEL_COMMAND, O as NODE_WORKER_SUPERVISOR_STATUS_COMMAND, v as NODE_WORKER_CAPACITY_EXHAUSTED_ERROR_CODE } from "./node-commands-BfMJIlXP.mjs"; import { u as isAgentRunRestartAbortReason } from "./run-termination-0Ig0-bk6.mjs"; import { t as NODE_WORKER_IDLE_RETENTION_PROTOCOL_FEATURE } from "./worker-admission-1P4EM7n_.mjs"; import { t as raceNodeWorkerOperation } from "./node-worker-abort-BCKtSFqU.mjs"; import { i as NODE_WORKER_INFERENCE_SETUP_ERROR, l as resolveNodeWorkerExecutionIssue, n as NODE_RUNNER_UPDATE_REQUIRED_ISSUE, o as createNodeRunnerInventoryIssueError } from "./node-runner-inventory-CixlIhG-.mjs"; import { n as serializeNodeEvent, t as buildNodeInvokeRequest } from "./node-invoke-request-DwLtMARG.mjs"; import { t as boundedWorkerError } from "./worker-error-BEppTEpI.mjs"; import { i as nodeWorkerTurnMatchesIdentity, n as NODE_WORKER_STATUS_WAIT_MAX_MS, r as nodeWorkerPlanHash, u as parseNodeWorkerSupervisorReceipt } from "./node-supervisor-protocol-BD491Brs.mjs"; import { n as measureWorkerProcessTurnBytes } from "./worker-process-protocol-BD8BDPsH.mjs"; import { t as WORKER_ADMISSION_DEADLINE_MS, u as parseWorkerAdmissionDeadlineResult } from "./worker-connection-contract-BJwfj7x3.mjs"; import { t as WorkerNodeLostError } from "./worker-node-loss-C_5DPByT.mjs"; import { n as WorkerRunnerUnavailableError, t as WorkerRunnerCapacityError } from "./tunnel-contract-CtbXolg4.mjs"; import { createHash, randomUUID } from "node:crypto"; //#region src/gateway/worker-environments/node-launch-adapter.ts function nodeWorkerSpawnResultFromReceipt(e) { return { ...e.state === "interrupted" ? { nodeLoss: new WorkerNodeLostError() } : {}, stdout: e.state === "completed" ? e.resultJson : "", stderr: e.state === "completed" ? "" : e.errorText, code: e.state === "completed" ? 0 : 1, signal: null, killed: e.state === "cancelled" || e.state === "interrupted", termination: "exit" }; } const DEFAULT_RPC_TIMEOUT_MS = 3e4; const DEFAULT_POLL_INTERVAL_MS = 250; const MAX_RETRY_DELAY_MS = 2e3; const DEFAULT_CANCELLATION_TIMEOUT_MS = 3e4; const DEFAULT_AVAILABILITY_TIMEOUT_MS = 1e4; const MAX_ADMISSION_ATTEMPTS = 5; const ADMISSION_REARM_BACKOFF = { initialMs: 1e3, maxMs: 3e4, factor: 2, jitter: .1 }; const RETRYABLE_NODE_WORKER_TRANSPORT_CODES = /* @__PURE__ */ new Set([ "DISCONNECTED", "NOT_CONNECTED", "PAIRING_CHANGED", "PRIVATE_DIALECT_UNAVAILABLE", "ROUTE_CHANGED", "TIMEOUT", "UNAVAILABLE" ]); var NodeWorkerLaunchTransportError = class extends Error { constructor(e, t) { super(t); this.code = e; } }; function isTerminalReceipt(e) { return e.state !== "pending" && e.state !== "running"; } function rearmNodeWorkerLaunchInput(e, t) { const n = createHash("sha256").update(`${e.launchId}:admission-rearm:${t}`).digest("hex"); return { ...e, launchId: n, descriptor: { ...e.descriptor, assignment: { ...e.descriptor.assignment, turnId: n } } }; } function measureNodeWorkerLaunchBytes(e, t) { const n = t.descriptor.admission.handshake.protocolFeatures.includes("node-worker-idle-retention-v1") ? { ...t, idleRetention: true } : t; return Math.max(...[n, rearmNodeWorkerLaunchInput(n, 1)].flatMap((t) => [Buffer.byteLength(serializeNodeEvent("node.invoke.request", buildNodeInvokeRequest({ id: randomUUID(), nodeId: e, command: NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND, params: t, timeoutMs: MAX_TIMER_TIMEOUT_MS, idempotencyKey: t.launchId })), "utf8"), measureWorkerProcessTurnBytes(t.descriptor, t.idleRetention)])); } function expectedIdentity(e) { return { launchId: e.launchId, planHash: nodeWorkerPlanHash(e), environmentId: e.descriptor.admission.environmentId, sessionId: e.descriptor.admission.sessionId, ownerEpoch: e.descriptor.admission.ownerEpoch, placementGeneration: e.placementGeneration, runId: e.descriptor.assignment.runId }; } function validateReceipt(e, t) { if (!nodeWorkerTurnMatchesIdentity(e, t)) throw new Error("node worker supervisor receipt identity mismatch"); return e; } function parseInvokeReceipt(e) { if (!e) throw new Error("node worker supervisor response omitted payload JSON"); let t; try { t = JSON.parse(e); } catch { throw new Error("node worker supervisor response contained malformed JSON"); } if (t === null) return null; const n = parseNodeWorkerSupervisorReceipt(t); if (!n) throw new Error("node worker supervisor response violated the private receipt contract"); return n; } function signalError(e, t) { return e.reason instanceof Error ? e.reason : new Error(t); } function createDeadline(e) { if (!Number.isFinite(e.timeoutMs) || e.timeoutMs <= 0) throw new Error(`${e.label} timeout must be a positive finite number`); const t = new AbortController(); const n = e.now() + e.timeoutMs; const expire = () => { e.parent?.remainingMs(); t.abort(/* @__PURE__ */ new Error(`${e.label} timed out`)); }; const r = setTimeout(expire, e.timeoutMs); r.unref?.(); const i = e.parent?.signal ?? e.signal; return { signal: i ? AbortSignal.any([i, t.signal]) : t.signal, remainingMs: () => { e.parent?.remainingMs(); const t = Math.max(0, n - e.now()); if (t === 0) expire(); return t; }, dispose: () => clearTimeout(r) }; } function createNodeWorkerLaunchAdapter(e) { const t = e.now ?? Date.now; const n = e.sleep ?? sleepWithAbort; const findNode = async (e) => { let t; try { t = await raceNodeWorkerOperation(e.transport.getCurrentNode(e.deviceId), e.signal); } catch (t) { if (e.signal.aborted) throw t; throw new NodeWorkerLaunchTransportError("UNAVAILABLE", "device worker node discovery is unavailable"); } if (!t) throw new NodeWorkerLaunchTransportError("NOT_CONNECTED", "device worker node is not currently connected"); return t; }; const invoke = async (t) => { if (!t.isAuthorized()) throw new NodeWorkerLaunchTransportError("APPROVAL_AUTHORITY_CLOSED", "node worker authority closed"); const n = t.deadline.remainingMs(); t.deadline.signal.throwIfAborted(); const r = e.getTransport(); if (!r) throw new NodeWorkerLaunchTransportError("UNAVAILABLE", "device worker node transport is unavailable"); const i = Math.min(DEFAULT_RPC_TIMEOUT_MS, n); const a = i < n ? new AbortController() : void 0; const o = a ? setTimeout(() => a.abort(/* @__PURE__ */ new Error("node worker RPC timed out")), i) : void 0; o?.unref?.(); const s = a ? AbortSignal.any([t.deadline.signal, a.signal]) : t.deadline.signal; try { const e = await findNode({ transport: r, deviceId: t.deviceId, signal: s }); if (t.command === "worker.launch.v1" && (e.workerHost.environmentSession !== 1 || resolveNodeWorkerExecutionIssue(e.workerHost))) throw createNodeRunnerInventoryIssueError(e.nodeId, NODE_RUNNER_UPDATE_REQUIRED_ISSUE); t.prepareLaunch?.(e); if (!t.prepareLaunch && t.idleRetention && e.workerHost.idleRetention !== true) throw new NodeWorkerLaunchTransportError("PRIVATE_DIALECT_UNAVAILABLE", "node worker idle retention is unavailable"); const n = e.workerHost.statusWait === 1; const a = r.invoke({ node: e, command: t.command, params: t.command === "worker.status.v1" && n ? { ...t.payload, waitMs: Math.min(NODE_WORKER_STATUS_WAIT_MAX_MS, Math.max(1, Math.floor(i * .75))) } : t.payload, timeoutMs: i, signal: s, idempotencyKey: t.command === "worker.launch.v1" ? t.payload.launchId : void 0, isDispatchAuthorized: t.isAuthorized, ...t.onDispatchReady ? { onDispatchReady: t.onDispatchReady } : {} }); const o = await raceNodeWorkerOperation(a, s); if (!o.ok) { const e = o.error?.code ?? "UNAVAILABLE"; if (e === "WORKER_CAPACITY_EXHAUSTED") throw new WorkerRunnerCapacityError(); const n = o.error?.message?.trim(); throw new NodeWorkerLaunchTransportError(e, boundedWorkerError(`node worker supervisor ${t.command} failed (${e})${n ? `: ${n}` : ""}`)); } return { receipt: parseInvokeReceipt(o.payloadJSON), statusWait: n }; } catch (e) { if (a?.signal.aborted && !t.deadline.signal.aborted) throw new NodeWorkerLaunchTransportError("TIMEOUT", "node worker RPC timed out"); throw e; } finally { clearTimeout(o); } }; const waitBeforeRetry = async (e, t) => { const r = t.remainingMs(); t.signal.throwIfAborted(); await raceNodeWorkerOperation(n(Math.min(e, r), t.signal), t.signal); return Math.min(e * 2, MAX_RETRY_DELAY_MS); }; const cancelUntilTerminal = async (e) => { const n = createDeadline({ now: t, timeoutMs: DEFAULT_CANCELLATION_TIMEOUT_MS, signal: e.request.cancellationSignal, label: "node worker cancellation" }); let r = DEFAULT_POLL_INTERVAL_MS; try { while (!n.signal.aborted && n.remainingMs() > 0) { if (!e.request.isCancellationAuthorized()) throw new Error("node worker cancellation authority closed before terminal settlement"); try { const { receipt: t } = await invoke({ deviceId: e.request.deviceId, command: NODE_WORKER_SUPERVISOR_CANCEL_COMMAND, payload: e.expected, isAuthorized: e.request.isCancellationAuthorized, deadline: n }); if (t) { const n = validateReceipt(t, e.expected); if (isTerminalReceipt(n)) return n; r = DEFAULT_POLL_INTERVAL_MS; } } catch (e) { if (n.signal.aborted) break; if (!(e instanceof NodeWorkerLaunchTransportError) || !RETRYABLE_NODE_WORKER_TRANSPORT_CODES.has(e.code)) throw e; } r = await waitBeforeRetry(r, n); } } finally { n.dispose(); } throw new Error("node worker cancellation did not produce a terminal receipt before its deadline"); }; const launch = async (e) => { const n = getGatewayRestartDrainSignal(); const r = { ...e.input }; let i = r; const a = { ...e, input: i }; let o = expectedIdentity(i); let s = 1; const c = createDeadline({ now: t, timeoutMs: e.timeoutMs, ...e.signal ? { signal: e.signal } : {}, label: "node worker launch" }); const l = createDeadline({ now: t, timeoutMs: DEFAULT_AVAILABILITY_TIMEOUT_MS, parent: c, label: "node worker availability" }); const u = { ...c, signal: l.signal }; let d = false; let f = false; let p = false; let m = DEFAULT_POLL_INTERVAL_MS; const markDispatchReady = () => { d = true; if (!f) { f = true; l.dispose(); a.onDispatchReady?.(); } }; try { while (true) { if (c.signal.aborted) throw signalError(c.signal, "node worker launch aborted"); if (!a.isDispatchAuthorized()) throw new Error("node worker launch authority closed"); const e = d; try { const { receipt: e, statusWait: n } = await invoke({ deviceId: a.deviceId, command: p ? NODE_WORKER_SUPERVISOR_STATUS_COMMAND : NODE_WORKER_SUPERVISOR_LAUNCH_COMMAND, payload: p ? { launchId: i.launchId } : i, ...!p && i.idleRetention ? { idleRetention: true } : {}, ...!p && !d ? { prepareLaunch: (e) => { if (i.descriptor.assignment.inference === "runtime-local" && e.workerHost.nativeInference !== 1) throw new Error(NODE_WORKER_INFERENCE_SETUP_ERROR); if (e.workerHost.idleRetention === true && i.descriptor.admission.handshake.protocolFeatures.includes("node-worker-idle-retention-v1")) i.idleRetention = true; else delete i.idleRetention; o = expectedIdentity(i); } } : {}, isAuthorized: Object.assign(() => { if (!f) l.remainingMs(); return a.isDispatchAuthorized(); }, a.isDispatchAuthorized), deadline: u, ...!p ? { onDispatchReady: markDispatchReady } : {} }); if (!e) p = false; else { if (!p) markDispatchReady(); const l = validateReceipt(e, o); d = true; if (isTerminalReceipt(l)) { const e = l.state === "completed" ? parseWorkerAdmissionDeadlineResult(JSON.parse(l.resultJson)) : void 0; const n = computeBackoff(ADMISSION_REARM_BACKOFF, s); const u = a.credentialExpiresAtMs === void 0 || t() + n + 12e4 <= a.credentialExpiresAtMs; if (e && s < MAX_ADMISSION_ATTEMPTS && u) { d = false; await waitBeforeRetry(n, c); i = rearmNodeWorkerLaunchInput(r, s++); o = expectedIdentity(i); p = false; m = DEFAULT_POLL_INTERVAL_MS; continue; } return l; } p = true; m = DEFAULT_POLL_INTERVAL_MS; if (n) continue; } } catch (t) { if (!p && !e && t instanceof NodeWorkerLaunchTransportError && t.code === "INVALID_REQUEST") { d = false; throw t; } if (c.signal.aborted || !f && l.signal.aborted || !a.isDispatchAuthorized()) throw t; if (!(t instanceof NodeWorkerLaunchTransportError) || !RETRYABLE_NODE_WORKER_TRANSPORT_CODES.has(t.code)) throw t; p = false; } m = await waitBeforeRetry(m, f ? c : l); } } catch (t) { if (n.aborted && isAgentRunRestartAbortReason(c.signal.reason)) throw c.signal.reason; if (!f && l.signal.aborted && !c.signal.aborted) throw new WorkerRunnerUnavailableError(); if (t instanceof WorkerRunnerCapacityError) throw t; if (!d) throw t; let r; try { r = await cancelUntilTerminal({ request: a, expected: o }); } catch (n) { const r = new AggregateError([t, n], "node worker launch failed and cancellation could not be confirmed", { cause: n }); throw t instanceof NodeWorkerLaunchTransportError && (t.code === "DISCONNECTED" || t.code === "NOT_CONNECTED") && !e.signal?.aborted ? new WorkerNodeLostError({ cause: r }) : r; } if (c.signal.aborted || !a.isDispatchAuthorized()) return r; throw t; } finally { l.dispose(); c.dispose(); } }; return { launch }; } //#endregion export { nodeWorkerSpawnResultFromReceipt as i, createNodeWorkerLaunchAdapter as n, measureNodeWorkerLaunchBytes as r, RETRYABLE_NODE_WORKER_TRANSPORT_CODES as t };