UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

411 lines (410 loc) • 14.5 kB
import { l as isRecord } from "../../../record-coerce-CVPuDqcc.mjs"; import { t as _usingCtx } from "../../../usingCtx-rhpPzaNq.mjs"; import { n as ToolInputError } from "../../../tool-input-error-B1hgavSw.mjs"; import { n as serveWorkerTasks } from "../../../worker-task-server-J1vG-XRl.mjs"; import "../../../string-coerce-runtime-BwAZZDf5.mjs"; import { a as normalizeSourceStack, i as buildUserSource, n as SOURCE_LOCATION_KEY, o as CODE_MODE_CONTROLLER_SOURCE, r as USER_SOURCE_FILE, t as prepareSource } from "../../../code-mode-executor-runtime-b8mqxmMw.mjs"; import { a as captureCodeModeValue, i as captureCodeModeOutput, r as boundCodeModeError } from "../../../code-mode-json-rc1Zn-6x.mjs"; import "../../../worker-task-server-552KxucS.mjs"; import { i as QuickJS, n as JSException, r as MAX_STACK_SIZE, t as EvalFlags } from "../../../dist-C_QeB1qg.mjs"; import { threadId } from "node:worker_threads"; //#region extensions/code-mode-quickjs/src/code-mode.worker.ts let controllerBytecode; var CodeModeWorkerFailure = class extends Error { constructor(e, t, n) { super(t); this.code = e; this.failurePhase = n; this.name = "CodeModeWorkerFailure"; } }; function notifyWorkerFailure(e, t, n) { e?.notify({ status: "failure", error: t instanceof Error ? { name: t.name, message: t.message, stack: t.stack } : String(t), failurePhase: n }); } function formatQuickJsError(e, t, n, r) { const i = t ? `${e}: ${t}` : e; const a = normalizeSourceStack(n, r); if (!a || a.split(/\r?\n/, 1)[0] === i) return i; return `${i}\n${a}`; } function readSourceLocation(e) { const t = e.global.getOwnPropertyDescriptor(SOURCE_LOCATION_KEY); if (!t) return; try { if (t.writable || t.configurable || t.enumerable || !t.value?.isString) return; const e = JSON.parse(t.value.toString()); if (!isRecord(e)) return; const { file: n, lineOffset: r, lineCount: i, columnOffset: a, endColumn: o } = e; const isOffset = (e) => typeof e === "number" && Number.isSafeInteger(e) && e >= 0; if (n !== "openclaw-code-mode:user.js" || !isOffset(r) || !isOffset(i) || i === 0 || !isOffset(a) || !isOffset(o) || o === 0 || !Number.isSafeInteger(r + i) || i === 1 && o <= a) return; return { file: n, lineOffset: r, lineCount: i, columnOffset: a, endColumn: o }; } catch { return; } finally { t.value?.dispose(); t.get?.dispose(); t.set?.dispose(); } } function errorMessage(e, t) { if (e instanceof JSException) return formatQuickJsError(e.name, e.message, e.stack, t); return e instanceof Error ? e.message || String(e) : String(e); } function trackPromiseRejection(e, t, n) { const r = e.vm; r.global.getProp("__openclawTrackRejection").consume((i) => r.callFunction(i, r.undefined, e, t, n ? r.true : r.false).dispose()); } function createHostRequestHandler(e) { return (t, n, r, i) => { if (e.bridge.pendingRequests.length >= e.config.maxPendingToolCalls) { e.bridge.admissionFailure ??= new CodeModeWorkerFailure("invalid_input", "too many pending code mode tool calls", "input"); throw e.bridge.admissionFailure; } const a = t.toString(); if (a !== "search" && a !== "describe" && a !== "callValue" && a !== "resultSave" && a !== "resultLoad" && a !== "resultDelete" && a !== "nodes" && a !== "yield" && a !== "namespace" && a !== "agentSpawn" && a !== "agentWait" && a !== "skillsList" && a !== "skillsSearch" && a !== "skillsRead" && a !== "sleep" && a !== "swarmNote") throw new Error("unsupported code mode bridge method"); const o = JSON.parse(n.toString()); if (!Array.isArray(o)) throw new Error("invalid code mode bridge arguments: expected an array"); const s = r?.toString(); if (!s?.startsWith(`bridge:${a}:`) || !/^bridge:[A-Za-z]+:[1-9]\d*$/u.test(s)) throw new Error("invalid code mode bridge id"); if (e.bridge.pendingRequests.some((e) => e.id === s)) throw new Error("duplicate code mode bridge id"); e.bridge.pendingRequests.push({ id: s, method: a, args: o }); const c = i?.isString ? i.toString().slice(0, 8192) : ""; return e.vm.newString(normalizeSourceStack(c, readSourceLocation(e.vm)) ?? ""); }; } function createHostCancelRequestHandler(e) { return (t) => { const n = t.toString(); const r = e.bridge.pendingRequests.findIndex((e) => e.id === n); if (r >= 0) { e.bridge.pendingRequests.splice(r, 1); e.bridge.canceledRequestIds.push(n); } return e.vm.undefined; }; } async function createVm(e, t) { let n = performance.now() + e.config.timeoutMs; let r = false; let i = false; const deadlineReached = () => !i && performance.now() >= n; const a = { wasm: e.wasmModule, extensions: e.wasmExtensions, memoryLimit: e.config.memoryLimitBytes, maxStackSize: MAX_STACK_SIZE, timezoneOffset: 0, onUnhandledRejection: trackPromiseRejection, interruptHandler: () => { r = deadlineReached(); return r; } }; const o = await (e.kind === "resume" ? QuickJS.restore(e.continuation, a) : QuickJS.create(a)).catch((e) => { throw r ? new CodeModeWorkerFailure("timeout", "code mode timeout exceeded", "host") : e; }); try { if (e.kind === "resume") e.continuation.memory = /* @__PURE__ */ new Uint8Array(); const a = [ ["__openclawHostRequest", createHostRequestHandler({ vm: o, bridge: t, config: e.config })], ["__openclawHostCancelRequest", createHostCancelRequestHandler({ vm: o, bridge: t })], ["__openclawHostTakeBridgeReply", () => { const e = t.replies?.[t.replyIndex]; if (!e) return o.undefined; t.replyIndex++; const n = o.newObject(); try { try { var r = _usingCtx(); const t = r.u(o.newString(e.id)); const i = r.u(o.newString(e.json)); o.defineProp(n, "id", t); o.defineProp(n, "ok", e.ok ? o.true : o.false); o.defineProp(n, "json", i); } catch (e) { r.e = e; } finally { r.d(); } } catch (e) { n.dispose(); throw e; } finally { e.json = ""; } return n; }], ["__openclawHostObserveNetworkContent", () => { t.networkContentObserved = true; return o.undefined; }] ]; for (const [t, n] of a) if (e.kind === "resume") o.registerHostCallback(t, n); else o.newFunction(t, n).consume((e) => o.global.setProp(t, e)); if (e.kind === "exec") { for (const [t, n] of [ ["__openclawCatalog", e.catalog], ["__openclawNamespaces", e.namespaces], ["__openclawApiFiles", e.apiFiles ?? []], ["__openclawSwarmEnabled", e.swarmEnabled === true], ["__openclawMaxPendingToolCalls", e.config.maxPendingToolCalls], ["__openclawMaxOutputBytes", e.config.maxOutputBytes] ]) o.hostToHandle(n).consume((e) => o.global.setProp(t, e)); controllerBytecode ??= o.compile(CODE_MODE_CONTROLLER_SOURCE, "openclaw-code-mode:controller.js"); o.evalBytecode(controllerBytecode).dispose(); } return { vm: o, didTimeout: () => r || deadlineReached(), pauseBudget: () => { r ||= deadlineReached(); i = true; }, setBudget: (e) => { i = false; r = false; n = performance.now() + e; } }; } catch (e) { o.dispose(); throw r ? new CodeModeWorkerFailure("timeout", "code mode timeout exceeded", "host") : e; } } function takeOutput(e) { return e.global.getProp("__openclawTakeOutputJson").consume((t) => e.callFunction(t, e.undefined).consume((e) => { const t = JSON.parse(e.toString()); return Array.isArray(t) ? t : []; })); } function takeOutputSafely(e) { try { return takeOutput(e); } catch { return []; } } function captureWorkerResult(e, t, n = false) { const r = captureCodeModeOutput(e.output, t.maxOutputBytes); if (e.status === "completed") return { ...e, output: r, value: captureCodeModeValue(e.value, t.maxOutputBytes, n ? Math.min(t.memoryLimitBytes, t.maxSnapshotBytes) : t.maxOutputBytes) }; return e.status === "failed" ? { ...e, output: r, error: boundCodeModeError(e.error, t.maxOutputBytes) } : { ...e, output: r }; } function failedWorkerResult(e, t, n = [], r = "host") { return { status: "failed", code: e, error: t, failurePhase: r, bridgeDispatchStarted: false, output: n }; } function workerFailureResult(e, t = [], n) { const r = e instanceof CodeModeWorkerFailure ? e : void 0; const i = e instanceof ToolInputError; return failedWorkerResult(r?.code ?? (i ? "invalid_input" : "internal_error"), errorMessage(e, n), t, r?.failurePhase ?? (i ? "input" : "host")); } async function readCompletedResult(e, t) { const n = await e.resolvePromise(t); if ("error" in n) return n.error.consume((t) => { const n = t.isError; const r = e.global.getProp("__openclawEncodeError").consume((n) => e.callFunction(n, e.undefined, t).consume((e) => e.toString())); const i = JSON.parse(r); const { bridgeCode: a } = i; if (a === null && n && i.name === "ReferenceError" && /^(?:require|module|process) is not defined$/u.test(i.message)) throw new CodeModeWorkerFailure("invalid_input", "code mode module access is disabled.", "input"); const o = formatQuickJsError(i.name, i.message, i.stack, readSourceLocation(e)); throw new CodeModeWorkerFailure(a ?? "internal_error", o, a === null ? "guest" : "bridge"); }); return n.value.consume((e) => JSON.parse(e.toString())); } async function run(e, t) { const n = performance.now(); const r = e.kind === "exec" ? prepareSource(e.source) : ""; const i = { ...e.config, timeoutMs: Math.min(e.config.timeoutMs - (performance.now() - n), e.kind === "exec" ? e.executionTimeoutMs ?? Infinity : Infinity) }; if (i.timeoutMs <= 0) throw new CodeModeWorkerFailure("timeout", "code mode timeout exceeded", "host"); const a = { pendingRequests: e.kind === "resume" ? [...e.pendingRequests ?? []] : [], canceledRequestIds: [], replyIndex: 0 }; const { vm: o, didTimeout: s, setBudget: c, pauseBudget: l } = await createVm({ ...e, config: i }, a); const u = e.config.timeoutMs; let prepare = () => { if (e.kind === "exec") { const t = buildUserSource(r, e.prelude); o.newString(JSON.stringify(t.location)).consume((e) => o.global.defineProp(SOURCE_LOCATION_KEY, e)); o.evalCode(t.source, USER_SOURCE_FILE, EvalFlags.ASYNC).dispose(); return; } settleRequests(o, a, e.settledRequests); }; const d = await (async () => { let e = []; let n = t?.consumeInput; try { for (;;) { prepare(); n?.(); n = void 0; o.executePendingJobs(); if (a.admissionFailure) throw a.admissionFailure; const s = o.global.getProp("__openclawAdmissionError").consume((e) => o.callFunction(e, o.undefined).consume((e) => e.isString ? e.toString() : void 0)); if (s) throw new CodeModeWorkerFailure("invalid_input", s, "input"); o.global.getProp("__openclawDrainQueuedRequests").consume((e) => o.callFunction(e, o.undefined).dispose()); e = takeOutput(o); const d = o.global.getProp("__openclawResult"); try { try { var r = _usingCtx(); const s = d.isPromise && d.promiseState === 0; if (s && a.pendingRequests.length === 0) throw new ToolInputError("code mode promise is pending without host work"); const f = a.pendingRequests.map((e) => e.id); if (s || d.promiseState !== 2 && f.length > 0) { const r = s ? { kind: "awaiting" } : { kind: "draining", requiredRequestIds: f }; if (t) { l(); const s = await t.request({ status: "boundary", ...a.networkContentObserved ? { networkContentObserved: true } : {}, pendingRequests: a.pendingRequests, canceledRequestIds: a.canceledRequestIds, settlementMode: r, output: captureCodeModeOutput(e, i.maxOutputBytes), memoryUsedBytes: o.getMemoryUsage().memoryUsedSize }); e = []; n = s.consumed; const d = s.input; if (d.kind === "continue") { if (!Number.isFinite(d.timeoutMs) || d.timeoutMs <= 0 || d.timeoutMs > u) throw new Error("invalid code mode continuation budget"); c(d.timeoutMs); a.pendingRequests = d.pendingRequests; a.canceledRequestIds = []; prepare = () => settleRequests(o, a, d.settledRequests); continue; } if (d.kind !== "checkpoint") throw new Error("invalid code mode continuation"); n(); n = void 0; } const d = o.snapshot(); const p = QuickJS.serializeSnapshot({ ...d, memory: /* @__PURE__ */ new Uint8Array() }); if (d.memory.byteLength + p.byteLength > i.maxSnapshotBytes) throw new CodeModeWorkerFailure("snapshot_limit_exceeded", "code mode snapshot limit exceeded", "guest"); return { status: "waiting", continuation: d, pendingRequests: a.pendingRequests, canceledRequestIds: a.canceledRequestIds, settlementMode: r, output: e }; } const p = await readCompletedResult(o, d); const m = r.u(o.global.getProp("__openclawUnhandledRejection").consume((e) => o.callFunction(e, o.undefined))); if (m.isPromise) await readCompletedResult(o, m); return { status: "completed", value: p, output: e }; } catch (e) { r.e = e; } finally { r.d(); } } finally { d.dispose(); } } } catch (n) { const r = s(); const i = e.length > 0 ? e : takeOutputSafely(o); const a = r ? failedWorkerResult("timeout", "code mode timeout exceeded", i, "guest") : workerFailureResult(n, i, readSourceLocation(o)); notifyWorkerFailure(t, n, a.failurePhase); return a; } finally { o.dispose(); } })(); return a.networkContentObserved ? { ...d, networkContentObserved: true } : d; } function settleRequests(e, t, n) { t.replies = n; t.replyIndex = 0; try { e.global.getProp("__openclawSettleBridge").consume((t) => e.callFunction(t, e.undefined).dispose()); } finally { t.replies = void 0; t.replyIndex = 0; for (const e of n) e.json = ""; n.length = 0; } } async function main(e, t) { t?.notify({ status: "worker", workerId: `code-mode-quickjs:${threadId}` }); const { config: n } = e; try { return captureWorkerResult(await run(e, t), n, e.retainFinalValue === true); } catch (e) { const r = workerFailureResult(e); notifyWorkerFailure(t, e, r.failurePhase); return captureWorkerResult(r, n); } } serveWorkerTasks((e, t) => main(e, t), { transferList: (e) => e.status === "waiting" ? [e.continuation.memory.buffer] : [] }); //#endregion export {};