openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
397 lines (396 loc) • 13.5 kB
JavaScript
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as runInDetachedAsyncContext } from "./detached-async-context-D_mi-wUl.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as PluginRuntimeCloseRetainedError } from "./runtime-close-error-Ak-r7PLO.mjs";
import { r as getBoundLegacyPluginSdkResourceHost } from "./legacy-sdk-resource-host-BiedXayN.mjs";
import { i as resolveRuntimeWorkerThreadExecArgv } from "./runtime-worker-url-DRDkoS4J.mjs";
import { a as resolveRuntimeProcessEntrypointUrl } from "./runtime-process-url-CoHTemu-.mjs";
import { a as WorkerTaskError } from "./src-Dkfkl2Oz.mjs";
import { t as WorkerTaskPool } from "./worker-task-pool-BshJjv1P.mjs";
import { t as runBestEffortCleanup } from "./non-fatal-cleanup-CRJjL6BT.mjs";
import { i as codeModeFailureCode, n as CodeModeHeadlessAbortError, r as CodeModeHeadlessTimeoutError, t as CODE_MODE_WORKER_WATCHDOG_GRACE_MS } from "./code-mode-worker-types-DkuJ9oOv.mjs";
import { n as EMPTY_CODE_MODE_OUTPUT } from "./code-mode-json-rc1Zn-6x.mjs";
import { n as prepareCodeModeNodeCatalog, t as codeModeNodeInitialization } from "./code-mode-node-input-Bk63cIJO.mjs";
import { channel } from "node:diagnostics_channel";
//#region src/agents/code-mode-node-progress.ts
const HEADER_BYTES = 64;
var CodeModeNodeProgress = class {
constructor(e) {
this.buffer = typeof e === "number" ? new SharedArrayBuffer(HEADER_BYTES + e) : e;
this.state = new Int32Array(this.buffer, 0, 2);
this.headers = new DataView(this.buffer);
this.bytes = Buffer.from(this.buffer, HEADER_BYTES);
}
get deadline() {
return this.headers.getFloat64(56);
}
set deadline(e) {
this.headers.setFloat64(56, e);
}
get networkContentObserved() {
return Atomics.load(this.state, 1) === 1;
}
observeNetworkContent() {
Atomics.store(this.state, 1, 1);
}
append(e) {
const t = Atomics.load(this.state, 0);
const [n, r, i] = this.header(t);
const a = (n === 0 ? "[" : ",") + e;
const o = r + Buffer.byteLength(a);
const s = r === i ? this.bytes.write(a, i) : 0;
const c = 8 + (1 - t) * 24;
this.headers.setFloat64(c, n + 1);
this.headers.setFloat64(c + 8, o);
this.headers.setFloat64(c + 16, i + s);
Atomics.store(this.state, 0, 1 - t);
return n + 1;
}
resetOutput() {
const e = 1 - Atomics.load(this.state, 0);
for (let t = 0; t < 3; t++) this.headers.setFloat64(8 + e * 24 + t * 8, 0);
Atomics.store(this.state, 0, e);
}
output() {
const [e, t, n] = this.header(Atomics.load(this.state, 0));
const r = e === 0 ? "[]" : this.bytes.toString("utf8", 0, n);
return {
count: e,
source: e === 0 || t + 1 <= this.bytes.length ? {
kind: "complete",
json: e === 0 ? r : r + "]"
} : {
kind: "prefix",
json: r,
originalBytes: t + 1
}
};
}
header(e) {
const t = 8 + e * 24;
return [
this.headers.getFloat64(t),
this.headers.getFloat64(t + 8),
this.headers.getFloat64(t + 16)
];
}
};
//#endregion
//#region src/agents/code-mode-node.ts
function prepareInput(e) {
if (e.kind === "resume") return e;
const { [codeModeNodeInitialization]: t, catalog: n, namespaces: r, apiFiles: i, swarmEnabled: a, ...o } = e;
return {
...o,
initialization: t ?? prepareCodeModeNodeCatalog({
catalog: n,
namespaces: r,
apiFiles: i,
swarmEnabled: a
})[codeModeNodeInitialization]
};
}
const retiringPools = /* @__PURE__ */ new Set();
const idlePools = /* @__PURE__ */ new Map();
const poolLifetimes = /* @__PURE__ */ new WeakMap();
let nextPoolId = 0;
const MAX_IDLE_POOLS = 8;
const memoryPressure = channel("openclaw.memory.critical");
const gcStorm = channel("openclaw.code-mode.gc-storm");
let nextGcStormRetirementAt = 0;
function removeIdlePool(e) {
idlePools.get(e)?.job.cancel();
idlePools.delete(e);
if (!idlePools.size) memoryPressure.unsubscribe(retireIdlePools);
}
function newestIdlePool(e, t, n) {
let r;
for (const i of idlePools.keys()) if (i.memoryLimitBytes === n && i.lifetime === e && i.url === t && !i.tasks.isClosed) r = i;
return r;
}
function retireIdlePool(e, t = "memory_pressure") {
if (!idlePools.has(e)) return;
runBestEffortCleanup({
cleanup: () => closePool(e, t),
onError: (e) => process.emitWarning(`Code Mode worker retirement failed: ${formatErrorMessage(e)}`)
});
}
function retireIdlePools() {
for (const e of idlePools.keys()) retireIdlePool(e);
}
async function closePool(e, t) {
removeIdlePool(e);
gcStorm.unsubscribe(e.onGcStorm);
retiringPools.add(e);
await e.tasks.close(void 0, e.draining ? "gc-storm" : t);
retiringPools.delete(e);
e.lifetime?.pools.delete(e);
}
function capturePoolLifetime() {
const e = getBoundLegacyPluginSdkResourceHost();
if (!e) return;
e.assertOpen();
let t = poolLifetimes.get(e);
if (!t) {
const n = e.scheduler.scope();
const r = /* @__PURE__ */ new Set();
t = {
scheduler: n,
pools: r
};
e.adopt(t, { release: async () => {
n.beginClose();
const e = await Promise.allSettled([...r].map((e) => closePool(e, "shutdown")));
await n.stop();
const t = e.flatMap((e) => e.status === "rejected" ? [e.reason] : []);
if (t.length) throw new PluginRuntimeCloseRetainedError(new AggregateError(t, "Code Mode workers failed to retire"));
} });
poolLifetimes.set(e, t);
}
t.scheduler.signal.throwIfAborted();
return t;
}
async function takePool(e, t) {
const n = capturePoolLifetime();
let r;
for (;;) {
t.throwIfAborted();
n?.scheduler.signal.throwIfAborted();
r = resolveRuntimeProcessEntrypointUrl("codeModeNode");
const e = /* @__PURE__ */ new Set([...[...retiringPools].filter((e) => e.lifetime === n || e.lifetime?.scheduler.signal.aborted), ...[...idlePools.keys()].filter((e) => e.lifetime === n && (e.url !== r.href || e.tasks.isClosed))]);
if (!e.size) break;
await Promise.all([...e].map((e) => closePool(e, "rotation")));
}
const i = newestIdlePool(n, r.href, e);
if (i) {
removeIdlePool(i);
return i;
}
const a = {
id: `code-mode-node:${++nextPoolId}`,
lifetime: n,
url: r.href,
memoryLimitBytes: e,
onGcStorm(e) {
if (e !== a.id || a.draining || performance.now() < nextGcStormRetirementAt) return;
nextGcStormRetirementAt = performance.now() + 6e4;
a.draining = true;
retireIdlePool(a);
},
tasks: new WorkerTaskPool({
workerUrl: r,
workerClass: "singleton",
idleTimeoutMs: 0,
restartOnError: false,
sharedCompute: true,
onRetirementFailure: () => {
retiringPools.add(a);
},
workerOptions: {
execArgv: [...resolveRuntimeWorkerThreadExecArgv(r), ...process.versions.bun ? [] : ["--experimental-vm-modules"]],
env: {},
resourceLimits: {
maxOldGenerationSizeMb: Math.max(1, Math.floor(e / 1048576) - 4),
maxYoungGenerationSizeMb: 4
}
}
})
};
gcStorm.subscribe(a.onGcStorm);
n?.pools.add(a);
return a;
}
async function releasePool(e) {
const { lifetime: t } = e;
if (e.draining) {
await closePool(e, "gc-storm");
return;
}
if (!t || t.scheduler.signal.aborted || e.tasks.isClosed) {
await closePool(e, t?.scheduler.signal.aborted ? "shutdown" : "dispose");
return;
}
if (e.url !== resolveRuntimeProcessEntrypointUrl("codeModeNode").href) {
await closePool(e, "rotation");
return;
}
if (idlePools.size >= MAX_IDLE_POOLS) {
await closePool(e, "eviction");
return;
}
const n = newestIdlePool(t, e.url, e.memoryLimitBytes);
idlePools.set(e, {
expired: false,
job: runInDetachedAsyncContext(() => t.scheduler.schedule({
id: `code-mode-worker-surplus:${++nextPoolId}`,
delayMs: 18e4,
run: () => {
const n = idlePools.get(e);
if (n) n.expired = true;
return newestIdlePool(t, e.url, e.memoryLimitBytes) === e ? void 0 : closePool(e, "idle-expiry");
}
}))
});
if (idlePools.size === 1) memoryPressure.subscribe(retireIdlePools);
if (n && idlePools.get(n)?.expired) runInDetachedAsyncContext(() => retireIdlePool(n, "idle-expiry"));
}
function failure(e, t) {
return {
status: "failed",
code: t,
error: formatErrorMessage(e),
failurePhase: "host",
bridgeDispatchStarted: false,
output: EMPTY_CODE_MODE_OUTPUT
};
}
function continuation(e) {
let t = "owned";
let n;
return {
executor: "node",
retainedBytes: e.memoryLimitBytes,
resume(n, r) {
if (t !== "owned") return Promise.resolve(failure("code mode continuation is no longer available", "runtime_unavailable"));
t = "resumed";
return run(e, n, r);
},
dispose() {
if (t === "resumed" || t === "disposed") return Promise.resolve();
t = "disposing";
return n ??= closePool(e, "dispose").then(() => {
t = "disposed";
}).finally(() => {
n = void 0;
});
}
};
}
async function run(e, t, n, r = performance.now()) {
const i = n.inlineHost;
i?.onWorkerAssigned?.(e.id);
const a = new CodeModeNodeProgress(t.config.maxOutputBytes);
const o = new AbortController();
const s = n.signal ? AbortSignal.any([n.signal, o.signal]) : o.signal;
let c;
let l = 0;
let u = false;
try {
const d = performance.now() - r;
if (t.config.timeoutMs <= d || n.timeoutMs <= d) throw new CodeModeHeadlessTimeoutError();
const f = await e.tasks.run(() => {
l = Math.max(0, t.config.timeoutMs - (performance.now() - r));
if (l <= 0) throw new CodeModeHeadlessTimeoutError();
return {
...prepareInput(t),
progress: a.buffer,
inlineHost: Boolean(i),
gcAttribution: {
workerId: e.id,
...i?.gcAttribution
},
config: {
...t.config,
timeoutMs: l
}
};
}, {
timeoutMs: Math.min(n.timeoutMs, t.config.timeoutMs) - d,
hostTimeout: "owner",
signal: s,
onNotification: (t) => {
if (isRecord(t) && t.status === "failure") i?.onFailure?.(t.error, t.failurePhase === "bridge" || t.failurePhase === "guest" || t.failurePhase === "input" ? t.failurePhase : "host", e.id);
},
inputBytes: t.kind === "exec" ? t.source.length * 2 : 0,
onInputConsumed: () => {
if (t.kind === "exec" && a.deadline > 0) c = setTimeout(() => o.abort(new CodeModeHeadlessTimeoutError()), Math.max(0, a.deadline - performance.timeOrigin - performance.now()));
i?.onInputConsumed?.();
},
onRequest: async (e, t) => {
clearTimeout(c);
if (!i || !isRecord(e) || e.status !== "boundary") throw new Error("invalid code mode worker boundary");
if (e.networkContentObserved === true) i?.onNetworkContent?.();
const n = i.onBoundary(e, {
...t,
maxTimeoutMs: l
});
a.resetOutput();
const { onConsumed: r, ...o } = await n;
return {
input: o,
onConsumed: r,
timeoutMs: o.kind === "continue" ? o.timeoutMs : CODE_MODE_WORKER_WATCHDOG_GRACE_MS
};
}
});
if (f.networkContentObserved === true) i?.onNetworkContent?.();
if (f.status === "waiting") {
u = true;
return {
...f,
continuation: continuation(e)
};
}
await releasePool(e);
u = true;
return f;
} catch (t) {
const r = s.aborted ? s.reason : t;
const o = r instanceof CodeModeHeadlessTimeoutError || t instanceof WorkerTaskError && t.code === "timeout";
const c = o && a.deadline ? "guest" : "host";
i?.onFailure?.(t, c, e.id);
if (o) {
if (a.networkContentObserved) i?.onNetworkContent?.();
return {
...failure("code mode timeout exceeded", "timeout"),
failurePhase: c,
output: a.output(),
...a.networkContentObserved ? { networkContentObserved: true } : {}
};
}
if (n.signal?.aborted || r instanceof CodeModeHeadlessAbortError) return failure("code mode execution aborted", "aborted");
if (t instanceof WorkerTaskError && isRecord(t.cause) && (t.cause.code === "ERR_WORKER_OUT_OF_MEMORY" || t.cause.code === "ERR_CODE_MODE_GC_THRASH")) {
if (a.networkContentObserved) i?.onNetworkContent?.();
return {
...failure(`${t.cause.code === "ERR_CODE_MODE_GC_THRASH" ? "Code Mode worker stopped after sustained garbage collection near its JavaScript heap limit" : `Code Mode worker exhausted its ${Math.floor(e.memoryLimitBytes / 1048576)} MiB JavaScript heap`}. Paginate or narrow tool results and avoid retaining large arrays. Inspect any completed actions before retrying.`, "runtime_unavailable"),
output: a.output(),
...a.networkContentObserved ? { networkContentObserved: true } : {}
};
}
return failure(t, t instanceof WorkerTaskError ? "runtime_unavailable" : codeModeFailureCode(t));
} finally {
clearTimeout(c);
if (!u) await closePool(e, "dispose");
}
}
const nodeCodeModeExecutor = {
id: "node",
async execute(e, t) {
const n = performance.now();
const r = new AbortController();
const i = t.signal ? AbortSignal.any([t.signal, r.signal]) : r.signal;
const a = setTimeout(() => r.abort(new CodeModeHeadlessTimeoutError()), Math.max(0, Math.min(e.config.timeoutMs, t.timeoutMs)));
const o = takePool(e.config.memoryLimitBytes, i);
let s;
try {
s = await racePromiseWithAbortSignal(o, i);
} catch (e) {
runBestEffortCleanup({
cleanup: () => o.then((e) => closePool(e, "dispose"), () => void 0),
onError: (e) => process.emitWarning(`Code Mode worker retirement failed: ${formatErrorMessage(e)}`)
});
if (i.aborted) {
const e = i.reason instanceof CodeModeHeadlessTimeoutError;
return failure(e ? "code mode timeout exceeded" : "code mode execution aborted", e ? "timeout" : "aborted");
}
throw e;
} finally {
clearTimeout(a);
}
return run(s, e, t, n);
}
};
//#endregion
export { nodeCodeModeExecutor };