-
Notifications
You must be signed in to change notification settings - Fork 452
Expand file tree
/
Copy pathnode-executor-server.ts
More file actions
155 lines (138 loc) · 4.53 KB
/
node-executor-server.ts
File metadata and controls
155 lines (138 loc) · 4.53 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
/**
* Standalone Node.js HTTP server that executes LLM-generated code in a VM sandbox.
*
* Tool calls from the sandboxed code are routed back to the caller via HTTP POSTs
* to the provided callbackUrl.
*
* Usage:
* npx tsx node-executor-server.ts
*
* Environment variables:
* PORT — listen port (default 3001)
* TIMEOUT_MS — execution timeout in milliseconds (default 30000)
*/
import {
createServer,
type IncomingMessage,
type ServerResponse
} from "node:http";
import * as vm from "node:vm";
const PORT = Number(process.env.PORT) || 3001;
const TIMEOUT_MS = Number(process.env.TIMEOUT_MS) || 30_000;
function readBody(req: IncomingMessage): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => chunks.push(chunk));
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8")));
req.on("error", reject);
});
}
interface ExecuteRequest {
code: string;
callbackUrl: string;
tools: string[];
}
async function handleExecute(
body: ExecuteRequest
): Promise<{ result: unknown; error?: string; logs: string[] }> {
const { code, callbackUrl, tools } = body;
const logs: string[] = [];
// Build a codemode proxy that routes tool calls back via HTTP
const codemode: Record<string, (args: unknown) => Promise<unknown>> = {};
for (const toolName of tools) {
codemode[toolName] = async (args: unknown) => {
const res = await fetch(`${callbackUrl}/${toolName}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(args ?? {})
});
const data = (await res.json()) as { result?: unknown; error?: string };
if (data.error) throw new Error(data.error);
return data.result;
};
}
const sandbox = {
codemode,
console: {
log: (...args: unknown[]) => logs.push(args.map(String).join(" ")),
error: (...args: unknown[]) =>
logs.push(`[error] ${args.map(String).join(" ")}`),
warn: (...args: unknown[]) =>
logs.push(`[warn] ${args.map(String).join(" ")}`)
},
fetch: globalThis.fetch,
setTimeout: globalThis.setTimeout,
clearTimeout: globalThis.clearTimeout,
URL,
Response,
Request,
Headers
};
const context = vm.createContext(sandbox);
try {
// The code is expected to be an async arrow function expression, e.g.:
// async () => { ... }
// We evaluate it to get the function, then call it.
const script = new vm.Script(`(${code})()`, {
filename: "codemode-exec.js"
});
const result = await script.runInContext(context, { timeout: TIMEOUT_MS });
return { result, logs };
} catch (err) {
return {
result: undefined,
error: err instanceof Error ? err.message : String(err),
logs
};
}
}
const server = createServer(
async (req: IncomingMessage, res: ServerResponse) => {
// CORS headers for local dev
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
if (req.method === "POST" && req.url === "/execute") {
try {
const raw = await readBody(req);
const body = JSON.parse(raw) as ExecuteRequest;
if (!body.code || !body.callbackUrl || !Array.isArray(body.tools)) {
res.writeHead(400, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
error: "Missing required fields: code, callbackUrl, tools"
})
);
return;
}
const result = await handleExecute(body);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(result));
} catch (err) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(
JSON.stringify({
error: err instanceof Error ? err.message : String(err)
})
);
}
return;
}
// Health check
if (req.method === "GET" && req.url === "/health") {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "ok" }));
return;
}
res.writeHead(404, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "Not found" }));
}
);
server.listen(PORT, () => {
console.log(`Node executor server listening on http://localhost:${PORT}`);
});