Skip to content

Commit 681535c

Browse files
authored
fix(code-mode): bound and simplify worker lifecycles (#114945)
* fix(code-mode): bound and simplify worker lifecycles * fix(code-mode): keep worker input internal * fix(code-mode): retry failed wasm initialization safely * docs(code-mode): explain live node tool budget invariant * test(code-mode): prove hostless promises fail without worker churn
1 parent 817aec8 commit 681535c

11 files changed

Lines changed: 717 additions & 399 deletions
Lines changed: 238 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,238 @@
1+
/** Sandboxed guest globals and host bridge for Code Mode QuickJS cells. */
2+
import { CODE_MODE_SWARM_CONTROLLER_SOURCE } from "./code-mode-swarm-controller-source.js";
3+
4+
export const CODE_MODE_CONTROLLER_SOURCE = String.raw`
5+
(() => {
6+
const output = [];
7+
const pending = new Map();
8+
const catalog = Array.isArray(globalThis.__openclawCatalog) ? globalThis.__openclawCatalog : [];
9+
const apiFiles = Array.isArray(globalThis.__openclawApiFiles) ? globalThis.__openclawApiFiles : [];
10+
const namespaceDescriptors = Array.isArray(globalThis.__openclawNamespaces) ? globalThis.__openclawNamespaces : [];
11+
const hostRequest = globalThis.__openclawHostRequest;
12+
delete globalThis.__openclawHostRequest;
13+
const bridgeSequences = new Map();
14+
15+
function safe(value) {
16+
if (value === undefined) return null;
17+
try {
18+
return JSON.parse(JSON.stringify(value));
19+
} catch {
20+
if (value instanceof Error) {
21+
return { name: value.name, message: value.message };
22+
}
23+
if (value === null) return null;
24+
const type = typeof value;
25+
if (type === "string" || type === "number" || type === "boolean") return value;
26+
return String(value);
27+
}
28+
}
29+
30+
function asText(value) {
31+
if (typeof value === "string") return value;
32+
const encoded = JSON.stringify(safe(value));
33+
return typeof encoded === "string" ? encoded : String(value);
34+
}
35+
36+
function request(method, args) {
37+
const methodName = String(method);
38+
const sequence = (bridgeSequences.get(methodName) ?? 0) + 1;
39+
bridgeSequences.set(methodName, sequence);
40+
const bridgeId = "bridge:" + methodName + ":" + String(sequence);
41+
const id = String(hostRequest(methodName, JSON.stringify(safe(args ?? [])), bridgeId));
42+
return new Promise((resolve, reject) => {
43+
pending.set(id, { resolve, reject });
44+
});
45+
}
46+
47+
${CODE_MODE_SWARM_CONTROLLER_SOURCE}
48+
49+
function namespaceFunction(namespaceId, path) {
50+
const callablePath = Object.freeze((Array.isArray(path) ? path : []).map((entry) => String(entry)));
51+
return (...args) => request("namespace", [namespaceId, callablePath, args]);
52+
}
53+
54+
function deserializeNamespaceValue(namespaceId, value) {
55+
if (!value || typeof value !== "object") return null;
56+
if (value.kind === "function") {
57+
return namespaceFunction(namespaceId, Array.isArray(value.path) ? value.path.slice() : []);
58+
}
59+
if (value.kind === "array") {
60+
return Object.freeze((Array.isArray(value.items) ? value.items : []).map((item) => deserializeNamespaceValue(namespaceId, item)));
61+
}
62+
if (value.kind === "object") {
63+
const object = Object.create(null);
64+
for (const entry of Array.isArray(value.entries) ? value.entries : []) {
65+
const key = Array.isArray(entry) && typeof entry[0] === "string" ? entry[0] : "";
66+
if (!key) continue;
67+
Object.defineProperty(object, key, {
68+
value: deserializeNamespaceValue(namespaceId, entry[1]),
69+
enumerable: true,
70+
});
71+
}
72+
return Object.freeze(object);
73+
}
74+
return safe(value.value);
75+
}
76+
77+
function settle(id, ok, payload) {
78+
const entry = pending.get(String(id));
79+
if (!entry) return false;
80+
pending.delete(String(id));
81+
let parsed = null;
82+
try {
83+
parsed = JSON.parse(String(payload));
84+
} catch {
85+
parsed = String(payload);
86+
}
87+
if (ok) {
88+
entry.resolve(parsed);
89+
} else {
90+
const error = new Error(typeof parsed === "string" ? parsed : parsed?.message ?? "nested tool failed");
91+
entry.reject(error);
92+
}
93+
return true;
94+
}
95+
96+
function nodeHandle(descriptor) {
97+
const handle = Object.create(null);
98+
Object.defineProperties(handle, {
99+
id: { value: descriptor.id, enumerable: true },
100+
name: { value: descriptor.name, enumerable: true },
101+
invoke: {
102+
value: (command, params) => request("nodes", ["invoke", descriptor.id, command, params]),
103+
enumerable: true,
104+
},
105+
});
106+
if (typeof descriptor.listDirCommand === "string") {
107+
Object.defineProperty(handle, "listDir", {
108+
value: (path) => request("nodes", ["invoke", descriptor.id, descriptor.listDirCommand, { path }]),
109+
enumerable: true,
110+
});
111+
}
112+
return Object.freeze(handle);
113+
}
114+
115+
const nodes = Object.freeze({
116+
list: () => request("nodes", ["list"]),
117+
get: async (idOrName) => nodeHandle(await request("nodes", ["get", idOrName])),
118+
});
119+
120+
const baseTools = Object.create(null);
121+
Object.defineProperties(baseTools, {
122+
search: { value: (query, options) => request("search", [query, options]), enumerable: true },
123+
describe: { value: (id) => request("describe", [id]), enumerable: true },
124+
call: { value: (id, input) => request("call", [id, input]), enumerable: true },
125+
callValue: { value: (id, input) => request("callValue", [id, input]), enumerable: true },
126+
});
127+
const skills = Object.freeze({
128+
list: () => request("skillsList", []),
129+
read: (name) => request("skillsRead", [name]),
130+
});
131+
132+
if (globalThis.__openclawSwarmEnabled === true) {
133+
Object.defineProperties(globalThis, {
134+
agents: {
135+
value: Object.freeze({ run: runAgent }),
136+
enumerable: true,
137+
},
138+
phase: { value: (title) => swarmNote("phase", title), enumerable: true },
139+
log: { value: (message) => swarmNote("log", message), enumerable: true },
140+
});
141+
}
142+
143+
function normalizeApiPath(value) {
144+
const text = String(value ?? "").trim().replace(/^\/+/, "");
145+
if (!text || text.split("/").some((segment) => !segment || segment === "." || segment === "..")) {
146+
throw new Error("invalid API file path");
147+
}
148+
return text;
149+
}
150+
151+
const apiFileMap = new Map();
152+
for (const file of apiFiles) {
153+
if (!file || typeof file !== "object") continue;
154+
const path = typeof file.path === "string" ? file.path : "";
155+
const content = typeof file.content === "string" ? file.content : "";
156+
if (!path || !content) continue;
157+
apiFileMap.set(path, Object.freeze({
158+
path,
159+
content,
160+
description: typeof file.description === "string" ? file.description : undefined,
161+
bytes: file.bytes,
162+
}));
163+
}
164+
const api = Object.freeze({
165+
list: async (prefix = "") => {
166+
// list takes a directory prefix, so tolerate a trailing slash (API.list("mcp/"))
167+
// that read's exact-path normalizer would otherwise reject as an empty segment.
168+
const rawPrefix = prefix == null ? "" : String(prefix).trim().replace(/\/+$/, "");
169+
const normalizedPrefix = rawPrefix === "" ? "" : normalizeApiPath(rawPrefix);
170+
const files = [...apiFileMap.values()]
171+
.filter((file) => !normalizedPrefix || file.path === normalizedPrefix || file.path.startsWith(normalizedPrefix.replace(/\/?$/, "/")))
172+
.map((file) => Object.freeze({
173+
path: file.path,
174+
description: file.description,
175+
bytes: file.bytes,
176+
}));
177+
return { files };
178+
},
179+
read: async (path) => {
180+
const normalizedPath = normalizeApiPath(path);
181+
const file = apiFileMap.get(normalizedPath);
182+
if (!file) throw new Error("Unknown API file: " + normalizedPath);
183+
return file;
184+
},
185+
});
186+
187+
const safeNameCounts = new Map();
188+
for (const tool of catalog) {
189+
const name = typeof tool?.name === "string" ? tool.name : "";
190+
if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name)) continue;
191+
safeNameCounts.set(name, (safeNameCounts.get(name) ?? 0) + 1);
192+
}
193+
for (const tool of catalog) {
194+
const name = typeof tool?.name === "string" ? tool.name : "";
195+
const id = typeof tool?.id === "string" ? tool.id : "";
196+
if (!id || safeNameCounts.get(name) !== 1 || Object.prototype.hasOwnProperty.call(baseTools, name)) {
197+
continue;
198+
}
199+
Object.defineProperty(baseTools, name, {
200+
value: (input) => request("callValue", [id, input]),
201+
enumerable: true,
202+
});
203+
}
204+
205+
const namespaceGlobals = Object.create(null);
206+
for (const descriptor of namespaceDescriptors) {
207+
const id = typeof descriptor?.id === "string" ? descriptor.id : "";
208+
const globalName = typeof descriptor?.globalName === "string" ? descriptor.globalName : "";
209+
if (!id || !/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(globalName)) continue;
210+
const scope = deserializeNamespaceValue(id, descriptor.scope);
211+
Object.defineProperty(namespaceGlobals, globalName, {
212+
value: scope,
213+
enumerable: true,
214+
});
215+
const existingGlobal = Object.getOwnPropertyDescriptor(globalThis, globalName);
216+
if (existingGlobal && existingGlobal.configurable === false) continue;
217+
Object.defineProperty(globalThis, globalName, {
218+
value: scope,
219+
enumerable: true,
220+
configurable: true,
221+
});
222+
}
223+
224+
Object.defineProperties(globalThis, {
225+
ALL_TOOLS: { value: Object.freeze(catalog.slice()), enumerable: true },
226+
API: { value: api, enumerable: true },
227+
nodes: { value: nodes, enumerable: true },
228+
namespaces: { value: Object.freeze(namespaceGlobals), enumerable: true },
229+
skills: { value: skills, enumerable: true },
230+
tools: { value: Object.freeze(baseTools), enumerable: true },
231+
text: { value: (value) => output.push({ type: "text", text: asText(value) }), enumerable: true },
232+
json: { value: (value) => output.push({ type: "json", value: safe(value) }), enumerable: true },
233+
yield_control: { value: (reason) => request("yield", [reason]), enumerable: true },
234+
__openclawSettleBridge: { value: settle },
235+
__openclawTakeOutput: { value: () => output.splice(0) },
236+
});
237+
})();
238+
`;

‎src/agents/code-mode-execution.ts‎

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
toToolSearchConfig,
1818
type CodeModeConfig,
1919
type CodeModeLanguage,
20+
type CodeModeSettlementMode,
2021
type CodeModeWorkerResult,
2122
type SettledBridgeRequest,
2223
} from "./code-mode-runtime.js";
@@ -36,6 +37,7 @@ import {
3637
snapshotState,
3738
storeSnapshotState,
3839
telemetry,
40+
waitForPendingBridgeSettlement,
3941
type PendingBridgeState,
4042
} from "./code-mode-state.js";
4143
import { normalizeCodeModeWorkerResult, runCodeModeWorker } from "./code-mode-worker.js";
@@ -156,29 +158,28 @@ function usableResumeBudgetMs(deadlineMs: number, config: CodeModeConfig): numbe
156158
}
157159

158160
async function waitForPending(
159-
pending: PendingBridgeState[],
161+
pending: readonly PendingBridgeState[],
162+
settlementMode: CodeModeSettlementMode,
160163
timeoutMs: number,
161164
signal?: AbortSignal,
162-
waitForAll = false,
163165
): Promise<boolean> {
164166
// Abort wins even over already-settled requests: callers treat `false` as
165167
// "do not resume the guest", which is what a cancelled exec/wait needs.
166168
if (signal?.aborted) {
167169
return false;
168170
}
169-
if (!waitForAll && pending.some((entry) => entry.settled)) {
170-
return true;
171-
}
172-
const pendingPromises = pending.filter((entry) => !entry.settled).map((entry) => entry.promise);
173-
if (pendingPromises.length === 0) {
171+
const required = pendingBridgeStatesForSettlement(pending, settlementMode);
172+
if (
173+
required.length === 0 ||
174+
(settlementMode.kind === "awaiting" && required.some((entry) => entry.settled)) ||
175+
required.every((entry) => entry.settled)
176+
) {
174177
return true;
175178
}
176179
let timer: ReturnType<typeof setTimeout> | undefined;
177180
let onAbort: (() => void) | undefined;
178181
try {
179-
const bridgeReady = waitForAll
180-
? Promise.all(pendingPromises).then(() => true)
181-
: Promise.race(pendingPromises).then(() => true);
182+
const bridgeReady = waitForPendingBridgeSettlement(pending, settlementMode).then(() => true);
182183
return await Promise.race([
183184
bridgeReady,
184185
new Promise<boolean>((resolve) => {
@@ -296,10 +297,10 @@ async function settleCodeModeResult(params: {
296297
}),
297298
);
298299
const ready = await waitForPending(
299-
pendingBridgeStatesForSettlement(pending, result.settlementMode),
300+
pending,
301+
result.settlementMode,
300302
remainingMs,
301303
params.signal,
302-
result.settlementMode.kind === "draining",
303304
);
304305
const resumeBudgetMs = ready
305306
? usableResumeBudgetMs(settleDeadline, params.config)
@@ -496,10 +497,10 @@ export async function runWait(params: {
496497
const deadlineMs = Date.now() + state.config.timeoutMs;
497498
try {
498499
const ready = await waitForPending(
499-
pendingBridgeStatesForSettlement(state.pending, state.settlementMode),
500+
state.pending,
501+
state.settlementMode,
500502
Math.max(1, deadlineMs - Date.now()),
501503
params.signal,
502-
state.settlementMode.kind === "draining",
503504
);
504505
const resumeBudgetMs = ready ? usableResumeBudgetMs(deadlineMs, state.config) : undefined;
505506
if (!ready || resumeBudgetMs === undefined) {

‎src/agents/code-mode-headless.test.ts‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -601,6 +601,60 @@ describe("headless Code Mode", () => {
601601
expect(tool.execute).toHaveBeenCalledOnce();
602602
});
603603

604+
it("counts first-class node operations against the headless tool budget", async () => {
605+
const nodesTool = fakeTool("nodes", async () => jsonResult({ nodes: [] }));
606+
607+
const result = expectFailed(
608+
await runCodeModeScriptHeadless({
609+
ctx: createHeadlessHarness([nodesTool]),
610+
code: `
611+
await nodes.list();
612+
await nodes.list();
613+
return true;
614+
`,
615+
maxToolCalls: 1,
616+
wallClockMs: 5_000,
617+
}),
618+
);
619+
620+
expect(result.code).toBe("tool_budget_exceeded");
621+
expect(result.toolCallCount).toBe(2);
622+
expect(nodesTool.execute).toHaveBeenCalledOnce();
623+
});
624+
625+
it("fails an awaiting promise without bridge work before resuming a worker", async () => {
626+
const result = expectFailed(
627+
await runCodeModeScriptHeadless({
628+
ctx: createHeadlessHarness(),
629+
code: "await new Promise(() => {}); return true;",
630+
wallClockMs: 5_000,
631+
}),
632+
);
633+
634+
expect(result.code).toBe("internal_error");
635+
expect(result.error).toContain("pending without host work");
636+
expect(result.toolCallCount).toBe(0);
637+
});
638+
639+
it("bounds output and returned values across separate worker legs", async () => {
640+
const tool = fakeTool("output_boundary", async () => jsonResult({ ok: true }));
641+
642+
const result = expectFailed(
643+
await runCodeModeScriptHeadless({
644+
ctx: createHeadlessHarness([tool]),
645+
code: `
646+
text("x".repeat(700));
647+
await tools.call("openclaw:core:output_boundary", {});
648+
return "y".repeat(700);
649+
`,
650+
overrides: { maxOutputBytes: 1_024 },
651+
}),
652+
);
653+
654+
expect(result.code).toBe("output_limit_exceeded");
655+
expect(tool.execute).toHaveBeenCalledOnce();
656+
});
657+
604658
it("honors cron payload tool budgets above the old headless cap", async () => {
605659
const tool = fakeTool("budgeted", async () => jsonResult({ ok: true }));
606660
const result = expectCompleted(

0 commit comments

Comments
 (0)