Open History to see the last commit
1/**
2 * Code wrapping utilities for the Cloudflare Worker.
3 * Extracted for testability without a live worker_loader binding.
4 */
5
6import type { ToolResultPayload, ToolSchema } from '../types'
7
8// Tool names are interpolated into generated JS as (1) function identifiers
9// and (2) string literals. Rejecting anything outside this pattern closes
10// the injection vector that would otherwise let a malicious tool name
11// break out of the wrapper.
12const VALID_TOOL_NAME = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/
13
14// Reserved words and contextual keywords that look like identifiers but can't
15// be used as JS function names. Catching them here gives callers a clear
16// "Invalid tool name" error at generation time instead of a cryptic
17// SyntaxError when the wrapped code is eval'd.
18const RESERVED_TOOL_NAMES = new Set([
19 'break',
20 'case',
21 'catch',
22 'class',
23 'const',
24 'continue',
25 'debugger',
26 'default',
27 'delete',
28 'do',
29 'else',
30 'enum',
31 'export',
32 'extends',
33 'false',
34 'finally',
35 'for',
36 'function',
37 'if',
38 'import',
39 'in',
40 'instanceof',
41 'new',
42 'null',
43 'return',
44 'super',
45 'switch',
46 'this',
47 'throw',
48 'true',
49 'try',
50 'typeof',
51 'var',
52 'void',
53 'while',
54 'with',
55 'yield',
56 'let',
57 'static',
58 'implements',
59 'interface',
60 'package',
61 'private',
62 'protected',
63 'public',
64 'await',
65 'async',
66])
67
68function assertSafeToolName(name: string): void {
69 if (!VALID_TOOL_NAME.test(name)) {
70 throw new Error(
71 `Invalid tool name '${name}': must match ${VALID_TOOL_NAME} (letters, digits, _, $; cannot start with a digit)`,
72 )
73 }
74 if (RESERVED_TOOL_NAMES.has(name)) {
75 throw new Error(`Invalid tool name '${name}': reserved JavaScript keyword`)
76 }
77}
78
79/**
80 * Generate tool wrapper code that collects calls or returns cached results.
81 *
82 * Tool calls are identified by a sequential index (__toolCallIdx) rather than
83 * by hashing the input. This avoids mismatches when re-executing code whose
84 * inputs contain non-deterministic values (e.g. random UUIDs).
85 */
86export function generateToolWrappers(
87 tools: Array<ToolSchema>,
88 toolResults?: Record<string, ToolResultPayload>,
89): string {
90 const wrappers: Array<string> = []
91
92 for (const tool of tools) {
93 assertSafeToolName(tool.name)
94 if (toolResults) {
95 wrappers.push(`
96 async function ${tool.name}(input) {
97 const callId = 'tc_' + (__toolCallIdx++);
98 const result = __toolResults[callId];
99 if (!result) {
100 __pendingToolCalls.push({ id: callId, name: '${tool.name}', args: input });
101 throw new __ToolCallNeeded(callId);
102 }
103 if (!result.success) {
104 throw new Error(result.error || 'Tool call failed');
105 }
106 return result.value;
107 }
108 `)
109 } else {
110 wrappers.push(`
111 async function ${tool.name}(input) {
112 const callId = 'tc_' + (__toolCallIdx++);
113 __pendingToolCalls.push({ id: callId, name: '${tool.name}', args: input });
114 throw new __ToolCallNeeded(callId);
115 }
116 `)
117 }
118 }
119
120 return wrappers.join('\n')
121}
122
123/**
124 * Wrap user code in an async IIFE with tool wrappers
125 */
126export function wrapCode(
127 code: string,
128 tools: Array<ToolSchema>,
129 toolResults?: Record<string, ToolResultPayload>,
130): string {
131 const toolWrappers = generateToolWrappers(tools, toolResults)
132 const toolResultsJson = toolResults ? JSON.stringify(toolResults) : '{}'
133
134 return `
135 (async function() {
136 // Tool call tracking (sequential index for stable IDs across re-executions)
137 let __toolCallIdx = 0;
138 const __pendingToolCalls = [];
139 const __toolResults = ${toolResultsJson};
140 const __logs = [];
141
142 // Special error class for tool calls
143 class __ToolCallNeeded extends Error {
144 constructor(callId) {
145 super('Tool call needed: ' + callId);
146 this.callId = callId;
147 }
148 }
149
150 // Console capture
151 const console = {
152 log: (...args) => __logs.push(args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
153 error: (...args) => __logs.push('ERROR: ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
154 warn: (...args) => __logs.push('WARN: ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
155 info: (...args) => __logs.push('INFO: ' + args.map(a => typeof a === 'object' ? JSON.stringify(a) : String(a)).join(' ')),
156 };
157
158 // Tool wrappers
159 ${toolWrappers}
160
161 try {
162 // Execute user code
163 const __userResult = await (async function() {
164 ${code}
165 })();
166
167 return {
168 status: 'done',
169 success: true,
170 value: __userResult,
171 logs: __logs
172 };
173 } catch (__error) {
174 if (__error instanceof __ToolCallNeeded) {
175 // Tool calls needed - return pending calls
176 return {
177 status: 'need_tools',
178 toolCalls: __pendingToolCalls,
179 logs: __logs
180 };
181 }
182
183 // Regular error
184 return {
185 status: 'done',
186 success: false,
187 error: {
188 name: __error.name || 'Error',
189 message: __error.message || String(__error),
190 stack: __error.stack
191 },
192 logs: __logs
193 };
194 }
195 })()
196 `
197}