-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathcode-mode.ts
More file actions
1137 lines (1080 loc) · 34.4 KB
/
Copy pathcode-mode.ts
File metadata and controls
1137 lines (1080 loc) · 34.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from "node:crypto";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { Worker } from "node:worker_threads";
import {
isFutureDateTimestampMs,
resolveExpiresAtMsFromDurationSeconds,
} from "@openclaw/normalization-core/number-coercion";
import { isRecord } from "@openclaw/normalization-core/record-coerce";
import { uniqueValues } from "@openclaw/normalization-core/string-normalization";
import { Type } from "typebox";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import { resolveAgentConfig } from "./agent-scope-config.js";
import type { HookContext } from "./agent-tools.before-tool-call.js";
import {
CODE_MODE_EXEC_TOOL_NAME,
CODE_MODE_WAIT_TOOL_NAME,
isCodeModeControlTool,
markCodeModeControlTool,
} from "./code-mode-control-tools.js";
import {
createCodeModeNamespaceRuntime,
describeCodeModeNamespacesForPrompt,
type CodeModeNamespaceRuntime,
} from "./code-mode-namespaces.js";
import type { AgentToolUpdateCallback } from "./runtime/index.js";
import { optionalStringEnum } from "./schema/typebox.js";
import type { ToolDefinition } from "./sessions/index.js";
import {
addClientToolsToToolCatalog,
applyToolCatalogCompaction,
TOOL_CALL_RAW_TOOL_NAME,
TOOL_DESCRIBE_RAW_TOOL_NAME,
TOOL_SEARCH_CODE_MODE_TOOL_NAME,
TOOL_SEARCH_RAW_TOOL_NAME,
ToolSearchRuntime,
type ToolSearchCatalogEntry,
type ToolSearchCatalogRef,
type ToolSearchConfig,
type ToolSearchToolContext,
} from "./tool-search.js";
import {
asToolParamsRecord,
jsonResult,
ToolInputError,
type AnyAgentTool,
} from "./tools/common.js";
export {
CODE_MODE_EXEC_TOOL_NAME,
CODE_MODE_WAIT_TOOL_NAME,
isCodeModeControlTool,
} from "./code-mode-control-tools.js";
const DEFAULT_TIMEOUT_MS = 10_000;
const DEFAULT_MEMORY_LIMIT_BYTES = 64 * 1024 * 1024;
const DEFAULT_MAX_OUTPUT_BYTES = 64 * 1024;
const DEFAULT_MAX_SNAPSHOT_BYTES = 10 * 1024 * 1024;
const DEFAULT_MAX_PENDING_TOOL_CALLS = 16;
const DEFAULT_SNAPSHOT_TTL_SECONDS = 900;
const DEFAULT_SEARCH_LIMIT = 8;
const DEFAULT_MAX_SEARCH_LIMIT = 50;
const MAX_ACTIVE_CODE_MODE_RUNS = 64;
type CodeModeLanguage = "javascript" | "typescript";
export type CodeModeConfig = {
enabled: boolean;
runtime: "quickjs-wasi";
mode: "only";
languages: CodeModeLanguage[];
timeoutMs: number;
memoryLimitBytes: number;
maxOutputBytes: number;
maxSnapshotBytes: number;
maxPendingToolCalls: number;
snapshotTtlSeconds: number;
searchDefaultLimit: number;
maxSearchLimit: number;
};
type CodeModeBridgeMethod = "search" | "describe" | "call" | "yield" | "namespace";
type PendingBridgeRequest = {
id: string;
method: CodeModeBridgeMethod;
args: unknown[];
};
type SettledBridgeRequest = {
id: string;
ok: boolean;
value?: unknown;
error?: string;
};
type PendingBridgeState = PendingBridgeRequest & {
promise: Promise<SettledBridgeRequest>;
settled?: SettledBridgeRequest;
};
type CodeModeRunState = {
runId: string;
parentToolCallId: string;
ctx: ToolSearchToolContext;
config: CodeModeConfig;
snapshotBytes: Uint8Array;
pending: PendingBridgeState[];
output: unknown[];
createdAt: number;
expiresAt: number;
runtime: ToolSearchRuntime;
namespaceRuntime: CodeModeNamespaceRuntime;
};
type CodeModeToolContext = ToolSearchToolContext;
type CodeModeFailureCode =
| "invalid_input"
| "runtime_unavailable"
| "timeout"
| "output_limit_exceeded"
| "snapshot_limit_exceeded"
| "internal_error";
type CodeModeWorkerResult =
| {
status: "completed";
value: unknown;
output: unknown[];
}
| {
status: "waiting";
snapshotBytes: Uint8Array;
pendingRequests: PendingBridgeRequest[];
output: unknown[];
}
| {
status: "failed";
error: string;
code: CodeModeFailureCode;
output: unknown[];
};
const activeRuns = new Map<string, CodeModeRunState>();
const resumingRunIds = new Set<string>();
let typescriptRuntimePromise: Promise<typeof import("typescript")> | null = null;
let typescriptRuntimeForTest: typeof import("typescript") | null = null;
function normalizeCodeModeRawConfig(value: unknown): Record<string, unknown> | undefined {
const codeMode = value;
if (codeMode === true) {
return { enabled: true };
}
if (codeMode === false) {
return { enabled: false };
}
return isRecord(codeMode) ? codeMode : undefined;
}
function readCodeModeRawConfig(config?: OpenClawConfig, agentId?: string): Record<string, unknown> {
const tools = isRecord(config?.tools) ? config.tools : undefined;
const globalRaw = normalizeCodeModeRawConfig(tools?.codeMode) ?? {};
const agentRaw =
config && agentId
? normalizeCodeModeRawConfig(resolveAgentConfig(config, agentId)?.tools?.codeMode)
: undefined;
return agentRaw ? { ...globalRaw, ...agentRaw } : globalRaw;
}
function readBoolean(value: unknown, fallback: boolean): boolean {
return typeof value === "boolean" ? value : fallback;
}
function readPositiveInteger(value: unknown, fallback: number): number {
return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : fallback;
}
function clampInteger(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
function readLanguages(value: unknown): CodeModeLanguage[] {
if (!Array.isArray(value)) {
return ["javascript", "typescript"];
}
const languages = value.filter(
(entry): entry is CodeModeLanguage => entry === "javascript" || entry === "typescript",
);
return languages.length > 0 ? uniqueValues(languages) : ["javascript", "typescript"];
}
export function resolveCodeModeConfig(config?: OpenClawConfig, agentId?: string): CodeModeConfig {
const raw = readCodeModeRawConfig(config, agentId);
const maxSearchLimit = clampInteger(
readPositiveInteger(raw.maxSearchLimit, DEFAULT_MAX_SEARCH_LIMIT),
1,
DEFAULT_MAX_SEARCH_LIMIT,
);
return {
enabled: readBoolean(raw.enabled, false),
runtime: "quickjs-wasi",
mode: "only",
languages: readLanguages(raw.languages),
timeoutMs: clampInteger(readPositiveInteger(raw.timeoutMs, DEFAULT_TIMEOUT_MS), 100, 60_000),
memoryLimitBytes: clampInteger(
readPositiveInteger(raw.memoryLimitBytes, DEFAULT_MEMORY_LIMIT_BYTES),
1024 * 1024,
1024 * 1024 * 1024,
),
maxOutputBytes: clampInteger(
readPositiveInteger(raw.maxOutputBytes, DEFAULT_MAX_OUTPUT_BYTES),
1024,
10 * 1024 * 1024,
),
maxSnapshotBytes: clampInteger(
readPositiveInteger(raw.maxSnapshotBytes, DEFAULT_MAX_SNAPSHOT_BYTES),
1024,
256 * 1024 * 1024,
),
maxPendingToolCalls: clampInteger(
readPositiveInteger(raw.maxPendingToolCalls, DEFAULT_MAX_PENDING_TOOL_CALLS),
1,
128,
),
snapshotTtlSeconds: clampInteger(
readPositiveInteger(raw.snapshotTtlSeconds, DEFAULT_SNAPSHOT_TTL_SECONDS),
1,
24 * 60 * 60,
),
searchDefaultLimit: clampInteger(
readPositiveInteger(raw.searchDefaultLimit, DEFAULT_SEARCH_LIMIT),
1,
maxSearchLimit,
),
maxSearchLimit,
};
}
function toToolSearchConfig(config: CodeModeConfig): ToolSearchConfig {
return {
enabled: true,
mode: "tools",
codeTimeoutMs: config.timeoutMs,
searchDefaultLimit: config.searchDefaultLimit,
maxSearchLimit: config.maxSearchLimit,
};
}
function removeExpiredRuns(now = Date.now()): void {
for (const [runId, state] of activeRuns) {
if (!isFutureDateTimestampMs(state.expiresAt, { nowMs: now })) {
activeRuns.delete(runId);
resumingRunIds.delete(runId);
}
}
}
function resolveCodeModeSnapshotExpiresAt(now: number, ttlSeconds: number): number | undefined {
return resolveExpiresAtMsFromDurationSeconds(ttlSeconds, { nowMs: now });
}
function enforceActiveRunLimit(): void {
removeExpiredRuns();
if (activeRuns.size >= MAX_ACTIVE_CODE_MODE_RUNS) {
throw new ToolInputError("too many suspended code mode runs.");
}
}
function toJsonSafe(value: unknown): unknown {
if (value === undefined) {
return null;
}
try {
const serialized = JSON.stringify(value);
return serialized === undefined ? null : (JSON.parse(serialized) as unknown);
} catch {
if (value instanceof Error) {
return { name: value.name, message: value.message };
}
if (value === null) {
return null;
}
switch (typeof value) {
case "string":
case "number":
case "boolean":
return value;
case "bigint":
case "symbol":
case "function":
return String(value);
default:
return Object.prototype.toString.call(value);
}
}
}
function jsonByteLength(value: unknown): number {
return Buffer.byteLength(JSON.stringify(toJsonSafe(value)) ?? "null", "utf8");
}
class CodeModeLimitError extends ToolInputError {
readonly code: Extract<CodeModeFailureCode, "output_limit_exceeded" | "snapshot_limit_exceeded">;
constructor(
code: Extract<CodeModeFailureCode, "output_limit_exceeded" | "snapshot_limit_exceeded">,
message: string,
) {
super(message);
this.name = "CodeModeLimitError";
this.code = code;
}
}
function codeModeFailureCode(error: unknown): CodeModeFailureCode {
if (error instanceof CodeModeLimitError) {
return error.code;
}
return error instanceof ToolInputError ? "invalid_input" : "internal_error";
}
function enforceOutputLimit(output: unknown[], config: CodeModeConfig): void {
if (jsonByteLength(output) > config.maxOutputBytes) {
throw new CodeModeLimitError("output_limit_exceeded", "code mode output limit exceeded");
}
}
function enforceResultLimit(params: {
output: unknown[];
value?: unknown;
config: CodeModeConfig;
}): void {
enforceOutputLimit(params.output, params.config);
if (params.value !== undefined && jsonByteLength(params.value) > params.config.maxOutputBytes) {
throw new CodeModeLimitError("output_limit_exceeded", "code mode output limit exceeded");
}
}
function readCode(args: unknown): { code: string; language?: CodeModeLanguage } {
const params = asToolParamsRecord(args);
const codeParam = params.code;
const commandParam = params.command;
if (
typeof codeParam === "string" &&
typeof commandParam === "string" &&
codeParam !== commandParam
) {
throw new ToolInputError("code and command must match when both are provided.");
}
const code = typeof commandParam === "string" ? commandParam : codeParam;
if (typeof code !== "string" || !code.trim()) {
throw new ToolInputError("code or command must be a non-empty string.");
}
const language = params.language;
if (language !== undefined && language !== "javascript" && language !== "typescript") {
throw new ToolInputError("language must be javascript or typescript.");
}
return { code, language };
}
function readRunId(args: unknown): string {
const params = asToolParamsRecord(args);
const runId = params.runId ?? params.run_id;
if (typeof runId !== "string" || !runId.trim()) {
throw new ToolInputError("runId must be a non-empty string.");
}
return runId.trim();
}
function maskCodeLiteralsAndComments(code: string): string {
let masked = "";
let index = 0;
while (index < code.length) {
const char = code[index];
const next = code[index + 1];
if (char === "/" && next === "/") {
masked += " ";
index += 2;
while (index < code.length && code[index] !== "\n") {
masked += " ";
index += 1;
}
continue;
}
if (char === "/" && next === "*") {
masked += " ";
index += 2;
while (index < code.length) {
if (code[index] === "*" && code[index + 1] === "/") {
masked += " ";
index += 2;
break;
}
masked += code[index] === "\n" ? "\n" : " ";
index += 1;
}
continue;
}
if (char === "'" || char === '"') {
const quote = char;
masked += " ";
index += 1;
while (index < code.length) {
const current = code[index];
masked += current === "\n" ? "\n" : " ";
index += 1;
if (current === "\\") {
if (index < code.length) {
masked += code[index] === "\n" ? "\n" : " ";
index += 1;
}
continue;
}
if (current === quote) {
break;
}
}
continue;
}
masked += char;
index += 1;
}
return masked;
}
function rejectsModuleAccess(code: string): boolean {
const source = maskCodeLiteralsAndComments(code);
return /\bimport\b\s*(?:\.|\(|["'`{*]|\w)|\brequire\b\s*\(/u.test(source);
}
async function loadTypeScriptRuntime(): Promise<typeof import("typescript")> {
if (typescriptRuntimeForTest) {
return typescriptRuntimeForTest;
}
typescriptRuntimePromise ??= import("typescript");
return await typescriptRuntimePromise;
}
async function prepareSource(input: {
code: string;
language?: CodeModeLanguage;
config: CodeModeConfig;
}): Promise<string> {
const language = input.language ?? "javascript";
if (!input.config.languages.includes(language)) {
throw new ToolInputError(`code mode ${language} input is disabled.`);
}
if (rejectsModuleAccess(input.code)) {
throw new ToolInputError("code mode module access is disabled.");
}
if (language === "javascript") {
return input.code;
}
const ts = await loadTypeScriptRuntime();
const transformed = ts.transpileModule(input.code, {
compilerOptions: {
target: ts.ScriptTarget.ES2022,
module: ts.ModuleKind.ESNext,
importsNotUsedAsValues: ts.ImportsNotUsedAsValues.Remove,
sourceMap: false,
},
reportDiagnostics: true,
});
const diagnostics = transformed.diagnostics ?? [];
if (diagnostics.some((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error)) {
const message = diagnostics
.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"))
.join("\n");
throw new ToolInputError(`typescript transform failed: ${message}`);
}
if (rejectsModuleAccess(transformed.outputText)) {
throw new ToolInputError("code mode module access is disabled.");
}
return transformed.outputText;
}
function errorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message || String(error);
}
return String(error);
}
async function runBridgeRequest(params: {
runtime: ToolSearchRuntime;
namespaceRuntime: CodeModeNamespaceRuntime;
parentToolCallId: string;
request: PendingBridgeRequest;
signal?: AbortSignal;
onUpdate?: AgentToolUpdateCallback;
}): Promise<SettledBridgeRequest> {
try {
const values = Array.isArray(params.request.args) ? params.request.args : [];
let value: unknown;
switch (params.request.method) {
case "search": {
const query = values[0];
if (typeof query !== "string") {
throw new ToolInputError("search query must be a string.");
}
const options = isRecord(values[1]) ? values[1] : undefined;
value = await params.runtime.search(query, {
limit: typeof options?.limit === "number" ? options.limit : undefined,
});
break;
}
case "describe": {
const id = values[0];
if (typeof id !== "string") {
throw new ToolInputError("describe id must be a string.");
}
value = await params.runtime.describe(id);
break;
}
case "call": {
const id = values[0];
if (typeof id !== "string") {
throw new ToolInputError("call id must be a string.");
}
const described = await params.runtime.describe(id);
if (described.source === "mcp") {
throw new ToolInputError(
"MCP tools are available in code mode only through the MCP namespace.",
);
}
value = await params.runtime.callExactId(described.id, values[1] ?? {}, {
parentToolCallId: params.parentToolCallId,
signal: params.signal,
onUpdate: params.onUpdate,
});
break;
}
case "yield": {
value = { status: "yielded", reason: values[0] ?? null };
break;
}
case "namespace": {
const namespaceId = values[0];
const path = values[1];
const callArgs = values[2];
if (typeof namespaceId !== "string") {
throw new ToolInputError("namespace id must be a string.");
}
if (!Array.isArray(path) || !path.every((entry) => typeof entry === "string")) {
throw new ToolInputError("namespace path must be an array of strings.");
}
value = await params.namespaceRuntime.invoke(
namespaceId,
path,
Array.isArray(callArgs) ? callArgs : [],
async (request) => {
const entry = request.catalogId
? params.runtime
.namespaceEntries()
.find((candidate) => candidate.id === request.catalogId)
: params.runtime
.namespaceEntries()
.find(
(candidate) =>
candidate.name === request.toolName &&
candidate.sourceName === request.pluginId,
);
if (!entry) {
throw new ToolInputError(
`namespace tool is not visible in the run catalog: ${request.toolName}`,
);
}
const called = await params.runtime.callExactId(entry.id, request.input, {
parentToolCallId: params.parentToolCallId,
signal: params.signal,
onUpdate: params.onUpdate,
});
if (request.catalogId) {
return called.result;
}
return isRecord(called.result) && "details" in called.result
? called.result.details
: called.result;
},
);
break;
}
}
return { id: params.request.id, ok: true, value: toJsonSafe(value) };
} catch (error) {
return { id: params.request.id, ok: false, error: errorMessage(error) };
}
}
function resolveCodeModeWorkerUrl(currentModuleUrl: string): URL {
const currentPath = fileURLToPath(currentModuleUrl);
const distMarker = `${path.sep}dist${path.sep}`;
const distIndex = currentPath.lastIndexOf(distMarker);
if (distIndex >= 0) {
const distRoot = currentPath.slice(0, distIndex + distMarker.length - 1);
return pathToFileURL(path.join(distRoot, "agents", "code-mode.worker.js"));
}
const extension = path.extname(currentPath) || ".js";
return new URL(`./code-mode.worker${extension}`, currentModuleUrl);
}
function codeModeWorkerUrl(): URL {
return resolveCodeModeWorkerUrl(import.meta.url);
}
function failedCodeModeWorkerResult(
error: unknown,
code: CodeModeFailureCode,
): Extract<CodeModeWorkerResult, { status: "failed" }> {
return {
status: "failed",
error: errorMessage(error),
code,
output: [],
};
}
function isQuickJsInterruptedWorkerError(error: unknown): boolean {
return String(error) === "interrupted";
}
function normalizeCodeModeWorkerResult(result: CodeModeWorkerResult): CodeModeWorkerResult {
if (
result.status === "failed" &&
result.code === "timeout" &&
isQuickJsInterruptedWorkerError(result.error)
) {
return {
...result,
error: "code mode timeout exceeded",
};
}
return result;
}
async function runCodeModeWorker(
workerData: unknown,
timeoutMs: number,
workerUrl?: URL,
): Promise<CodeModeWorkerResult> {
let worker: Worker;
try {
worker = new Worker(workerUrl ?? codeModeWorkerUrl(), {
workerData,
});
} catch (error) {
return failedCodeModeWorkerResult(error, "runtime_unavailable");
}
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await new Promise<CodeModeWorkerResult>((resolve) => {
let settled = false;
const finish = (result: CodeModeWorkerResult) => {
if (settled) {
return;
}
settled = true;
resolve(result);
};
timer = setTimeout(() => {
void worker.terminate();
finish({
status: "failed",
error: "code mode worker timeout exceeded",
code: "timeout",
output: [],
});
}, timeoutMs);
worker.once("message", (message: unknown) => {
void worker.terminate();
const result = isRecord(message)
? (message as CodeModeWorkerResult)
: ({
status: "failed",
error: "invalid code mode worker response",
code: "internal_error",
output: [],
} satisfies CodeModeWorkerResult);
finish(normalizeCodeModeWorkerResult(result));
});
worker.once("error", (error) => {
finish(failedCodeModeWorkerResult(error, "runtime_unavailable"));
});
worker.once("exit", (code) => {
if (code !== 0) {
finish(
failedCodeModeWorkerResult(
new Error(`code mode worker exited with code ${code}`),
"runtime_unavailable",
),
);
}
});
});
} finally {
if (timer) {
clearTimeout(timer);
}
}
}
function snapshotState(params: {
pendingRequests: PendingBridgeRequest[];
snapshotBytes: Uint8Array;
parentToolCallId: string;
ctx: ToolSearchToolContext;
config: CodeModeConfig;
runtime: ToolSearchRuntime;
namespaceRuntime: CodeModeNamespaceRuntime;
output: unknown[];
signal?: AbortSignal;
onUpdate?: AgentToolUpdateCallback;
}) {
enforceActiveRunLimit();
if (params.snapshotBytes.byteLength > params.config.maxSnapshotBytes) {
throw new CodeModeLimitError("snapshot_limit_exceeded", "code mode snapshot limit exceeded");
}
enforceOutputLimit(params.output, params.config);
const runId = `cm_${randomUUID()}`;
const pending = params.pendingRequests.map((request) => {
const promise = runBridgeRequest({
runtime: params.runtime,
namespaceRuntime: params.namespaceRuntime,
parentToolCallId: params.parentToolCallId,
request,
signal: params.signal,
onUpdate: params.onUpdate,
});
const state: PendingBridgeState = { ...request, promise };
void promise.then((settled) => {
state.settled = settled;
});
return state;
});
const now = Date.now();
const expiresAt = resolveCodeModeSnapshotExpiresAt(now, params.config.snapshotTtlSeconds);
if (expiresAt === undefined) {
throw new ToolInputError("code mode run expiry is unavailable.");
}
activeRuns.set(runId, {
runId,
parentToolCallId: params.parentToolCallId,
ctx: params.ctx,
config: params.config,
snapshotBytes: params.snapshotBytes,
pending,
output: params.output,
createdAt: now,
expiresAt,
runtime: params.runtime,
namespaceRuntime: params.namespaceRuntime,
});
return {
status: "waiting" as const,
runId,
reason: codeModeWaitingReason(pending),
pendingToolCalls: pendingToolCalls(pending),
output: params.output,
telemetry: telemetry(params.runtime),
};
}
function codeModeWaitingReason(pending: readonly PendingBridgeState[]): "pending_tools" | "yield" {
return pending.length > 0 && pending.every((entry) => entry.method === "yield")
? "yield"
: "pending_tools";
}
function pendingToolCalls(pending: readonly PendingBridgeState[]) {
return pending.map((entry) => ({ id: entry.id, method: entry.method }));
}
function telemetry(runtime: ToolSearchRuntime) {
return {
...runtime.telemetry(),
visibleTools: [CODE_MODE_EXEC_TOOL_NAME, CODE_MODE_WAIT_TOOL_NAME],
};
}
function createCodeModeExecDescription(
ctx: CodeModeToolContext,
catalog?: readonly ToolSearchCatalogEntry[],
): string {
const namespacePrompt = describeCodeModeNamespacesForPrompt(ctx, catalog);
return (
'Run JavaScript or TypeScript in OpenClaw code mode. Use `return` to pass the final value back to the agent; awaited calls without a returned value complete as `null`. Node.js modules and `require`/`import` are NOT available; for any shell, file, network, or external action, use enabled catalog tools allowed by policy from inside your code: `tools.search(query)` to find catalog entries, `tools.describe(entry.id)` for the input schema, then `tools.call(entry.id, args)`. MCP tools are available only through the `MCP` namespace. Registered plugin namespaces are available as direct globals and through `namespaces` when their required tools are visible in the run catalog. The `language` field accepts only "javascript" or "typescript"; do not pass "bash", "shell", or other values.' +
(namespacePrompt ? `\n\n${namespacePrompt}` : "")
);
}
async function runExec(params: {
toolCallId: string;
ctx: CodeModeToolContext;
code: string;
language?: CodeModeLanguage;
signal?: AbortSignal;
onUpdate?: AgentToolUpdateCallback;
}) {
removeExpiredRuns();
const config = resolveCodeModeConfig(
params.ctx.runtimeConfig ?? params.ctx.config,
params.ctx.agentId,
);
if (!config.enabled) {
throw new ToolInputError("code mode is disabled.");
}
const runtime = new ToolSearchRuntime(params.ctx, toToolSearchConfig(config));
const catalog = runtime.all();
const namespaceRuntime = await createCodeModeNamespaceRuntime(
params.ctx,
runtime.namespaceEntries(),
);
let source: string;
try {
source = await prepareSource({ code: params.code, language: params.language, config });
} catch (error) {
return {
status: "failed" as const,
error: errorMessage(error),
code: codeModeFailureCode(error),
output: [],
telemetry: telemetry(runtime),
};
}
try {
const result = normalizeCodeModeWorkerResult(
await runCodeModeWorker(
{
kind: "exec",
source,
config,
catalog,
namespaces: namespaceRuntime.descriptors,
},
config.timeoutMs + 1000,
),
);
if (result.status === "waiting") {
return snapshotState({
pendingRequests: result.pendingRequests,
snapshotBytes: result.snapshotBytes,
parentToolCallId: params.toolCallId,
ctx: params.ctx,
config,
runtime,
namespaceRuntime,
output: result.output,
signal: params.signal,
onUpdate: params.onUpdate,
});
}
enforceResultLimit({
output: result.output,
value: result.status === "completed" ? result.value : undefined,
config,
});
return {
...result,
telemetry: telemetry(runtime),
};
} catch (error) {
return {
status: "failed" as const,
error: errorMessage(error),
code: codeModeFailureCode(error),
output: [],
telemetry: telemetry(runtime),
};
}
}
async function waitForPending(pending: PendingBridgeState[], timeoutMs: number): Promise<boolean> {
const pendingPromises = pending.filter((entry) => !entry.settled).map((entry) => entry.promise);
if (pendingPromises.length === 0) {
return true;
}
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
Promise.all(pendingPromises).then(() => true),
new Promise<boolean>((resolve) => {
timer = setTimeout(() => resolve(false), timeoutMs);
}),
]);
} finally {
if (timer) {
clearTimeout(timer);
}
}
}
async function runWait(params: {
toolCallId: string;
ctx: CodeModeToolContext;
runId: string;
signal?: AbortSignal;
onUpdate?: AgentToolUpdateCallback;
}) {
removeExpiredRuns();
const state = activeRuns.get(params.runId);
if (!state) {
throw new ToolInputError("code mode run is unavailable or expired.");
}
if (state.ctx.runId && params.ctx.runId && state.ctx.runId !== params.ctx.runId) {
throw new ToolInputError("code mode run belongs to a different agent run.");
}
if (
(state.ctx.sessionId && params.ctx.sessionId && state.ctx.sessionId !== params.ctx.sessionId) ||
(state.ctx.sessionKey &&
params.ctx.sessionKey &&
state.ctx.sessionKey !== params.ctx.sessionKey) ||
(state.ctx.agentId && params.ctx.agentId && state.ctx.agentId !== params.ctx.agentId)
) {
throw new ToolInputError("code mode run belongs to a different session.");
}
if (resumingRunIds.has(state.runId)) {
throw new ToolInputError("code mode run is already being resumed.");
}
resumingRunIds.add(state.runId);
try {
const ready = await waitForPending(state.pending, state.config.timeoutMs);
if (!ready) {
const pending = state.pending.filter((entry) => !entry.settled);
return {
status: "waiting" as const,
runId: state.runId,
reason: codeModeWaitingReason(pending.length > 0 ? pending : state.pending),
pendingToolCalls: pendingToolCalls(pending.length > 0 ? pending : state.pending),
output: state.output,
telemetry: telemetry(state.runtime),
};
}
activeRuns.delete(state.runId);
const settledRequests: SettledBridgeRequest[] = [];
for (const entry of state.pending) {
settledRequests.push(entry.settled ?? (await entry.promise));
}
const result = normalizeCodeModeWorkerResult(
await runCodeModeWorker(
{
kind: "resume",
snapshotBytes: state.snapshotBytes,
config: state.config,
settledRequests,
},
state.config.timeoutMs + 1000,
),
);
const output = [...state.output, ...result.output];
enforceOutputLimit(output, state.config);
if (result.status === "waiting") {
return snapshotState({
pendingRequests: result.pendingRequests,
snapshotBytes: result.snapshotBytes,
parentToolCallId: params.toolCallId,
ctx: state.ctx,
config: state.config,
runtime: state.runtime,
namespaceRuntime: state.namespaceRuntime,
output,
signal: params.signal,
onUpdate: params.onUpdate,
});
}
enforceResultLimit({
output,
value: result.status === "completed" ? result.value : undefined,
config: state.config,
});
return {
...result,
output,
telemetry: telemetry(state.runtime),
};
} catch (error) {
return {
status: "failed" as const,
error: errorMessage(error),
code: codeModeFailureCode(error),
output: state.output,
telemetry: telemetry(state.runtime),
};
} finally {
resumingRunIds.delete(state.runId);
}
}
export function createCodeModeTools(ctx: CodeModeToolContext): AnyAgentTool[] {
const execTool = markCodeModeControlTool({
name: CODE_MODE_EXEC_TOOL_NAME,
label: "exec",
description: createCodeModeExecDescription(ctx),
parameters: Type.Object({
code: Type.Optional(
Type.String({
description:
"JavaScript or TypeScript source to run. The `tools` object (search/describe/call), `ALL_TOOLS`, and registered namespace globals are available in scope; Node built-in modules are not.",
}),
),