Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

runner.ts

99 lines3.9 KB

1/**
2 * The program that runs inside the sandbox: one `node` process per
3 * `execute`. Generated code awaits real tool calls: a request goes out on
4 * stdout, the host answers on stdin, and the code continues where it
5 * stopped. Nothing is replayed.
6 *
7 * Protocol lines on stdout start with a per-execution marker; everything else
8 * is ignored. The marker keeps ordinary output from being read as protocol.
9 * It is not a security boundary: code in the sandbox can reach the same
10 * stdout, so the host validates every message.
11 */
12​
13export type RunnerMessage =
14 | { type: 'log'; line: string }
15 | { type: 'tool'; id: string; name: string; args: unknown }
16 | { type: 'done'; success: true; value?: unknown }
17 | {
18 type: 'done'
19 success: false
20 error: { name: string; message: string; stack?: string }
21 }
22​
23export type ToolReply =
24 | { id: string; success: true; value?: unknown }
25 | { id: string; success: false; error: string }
26​
27const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
28​
29export function runnerSource(
30 code: string,
31 toolNames: Array<string>,
32 marker: string,
33): string {
34 for (const name of toolNames) {
35 if (!IDENTIFIER.test(name)) {
36 throw new Error(`Invalid tool name '${name}': must be a JS identifier`)
37 }
38 }
39 // Code and names travel as JSON literals, so nothing needs escaping.
40 return `'use strict';
41try { require('node:fs').unlinkSync(__filename) } catch {}
42const __marker = ${JSON.stringify(marker)};
43const __out = process.stdout.write.bind(process.stdout);
44// A leading newline keeps a protocol line whole after raw writes without one.
45const __send = (m) => __out('\\n' + __marker + JSON.stringify(m) + '\\n');
46const __norm = (e) => {
47 if (e instanceof Error) return { name: e.name || 'Error', message: e.message || String(e), stack: e.stack };
48 if (e && typeof e === 'object') {
49 const s = (k) => { try { return typeof e[k] === 'string' ? e[k] : undefined } catch { return undefined } };
50 return { name: s('name') || 'Error', message: s('message') || 'Error' };
51 }
52 return { name: 'Error', message: String(e) };
53};
54const __fmt = (a) => {
55 if (typeof a === 'string') return a;
56 try { const j = JSON.stringify(a); if (j !== undefined) return j } catch {}
57 try { return String(a) } catch { return '[Unserializable]' }
58};
59const __log = (prefix) => (...args) => __send({ type: 'log', line: prefix + args.map(__fmt).join(' ') });
60globalThis.console = { log: __log(''), info: __log('INFO: '), warn: __log('WARN: '), error: __log('ERROR: '), debug: __log('') };
61​
62const __pending = new Map();
63let __next = 0;
64const __finish = (m) => {
65 let line;
66 try { line = '\\n' + __marker + JSON.stringify(m) + '\\n' }
67 catch (e) { line = '\\n' + __marker + JSON.stringify({ type: 'done', success: false, error: __norm(e) }) + '\\n' }
68 // Pipes are asynchronous on some platforms: exit only once the line is flushed.
69 // The host then kills the process group, including anything the code spawned.
70 __out(line, () => process.exit(0));
71};
72require('node:readline').createInterface({ input: process.stdin }).on('line', (line) => {
73 let m;
74 try { m = JSON.parse(line) }
75 catch {
76 __finish({ type: 'done', success: false, error: { name: 'Error', message: 'Tool result was not valid JSON.' } });
77 return;
78 }
79 const p = __pending.get(m && m.id);
80 if (!p) return;
81 __pending.delete(m.id);
82 if (m.success) p.resolve(m.value); else p.reject(new Error(m.error || 'Tool call failed'));
83});
84const __tool = (name) => (args) => new Promise((resolve, reject) => {
85 const id = 'tc_' + __next++;
86 __pending.set(id, { resolve, reject });
87 __send({ type: 'tool', id, name, args });
88});
89const __names = ${JSON.stringify(toolNames)};
90(async () => {
91 const AsyncFunction = (async () => {}).constructor;
92 const fn = new AsyncFunction(...__names, ${JSON.stringify(code)});
93 return fn(...__names.map(__tool));
94})().then(
95 (value) => __finish({ type: 'done', success: true, value }),
96 (error) => __finish({ type: 'done', success: false, error: __norm(error) }),
97);