返回源码地图

packages/codemode/src/runtime/prelude-source.ts

v1.0.1 · a7229ddc2181 · 09/20:1.0.1累计输出限制;非全部VM安全审计

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1/**
2 * JavaScript evaluated inside the QuickJS VM before the script runs.
3 *
4 * The VM is its own wasm instance, so nothing here guards a realm boundary.
5 * The prelude keeps the host bridge in a closure so the script cannot call it
6 * directly, and builds `tools`, `ALL_TOOLS`, the output helpers (`text`, `image`,
7 * `exit`, `console`), and globals on top of it. Tool arguments and results cross
8 * as JSON strings and are parsed on this side.
9 *
10 * Output helpers: `text(value)` appends a text item (non-strings are
11 * JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an
12 * `{ image_url }` object, or an MCP `ImageContent` block, and `exit()` ends the script
13 * successfully. `console.*` appends text items like `text()`.
14 *
15 * `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of
16 * JSON text passed in as `storeJson`, and the keys the script wrote are reported
17 * with a successful "done".
18 *
19 * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.
20 * `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the
21 * tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.
22 * `stalled()` reports a script that has not finished while no host call is pending: with no timers
23 * or I/O in the VM, nothing can ever resume it.
24 * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
25 * `bridge(kind, a, b, c)` with kind "call" or "global" (id, name, argsJson),
26 * "output" ("text", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
27 */
28export const MAX_STORE_VALUE_CHARS = 256 * 1024;
29export const MAX_STORE_TOTAL_CHARS = 1024 * 1024;
30/**
31 * Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and
32 * base64 image data, and items. The host keeps all output until the script ends, so without a
33 * limit a script that prints in a loop grows the host's memory until it crashes. The item limit
34 * covers loops that print empty strings.
35 */
36export const MAX_OUTPUT_CHARS = 16 * 1024 * 1024;
37export const MAX_OUTPUT_ITEMS = 100_000;
38
39const IMAGE_HELPER_EXPECTS =
40 "image expects a non-empty image URL string, an object with image_url, or a raw MCP image block";
41
42export const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson, storeJson) {
43 "use strict";
44 const stringify = JSON.stringify;
45 const parse = JSON.parse;
46 const promiseThen = Promise.prototype.then;
47 const ErrorCtor = Error;
48 const TypeErrorCtor = TypeError;
49 const RangeErrorCtor = RangeError;
50 const pending = new Map();
51 let nextId = 1;
52 let finished = false;
53 // Thrown by exit() to unwind the script after it already reported success.
54 const EXIT = Object.freeze({});
55
56 function done(ok, payload, writes) {
57 if (finished) return;
58 finished = true;
59 bridge("done", ok, payload, writes);
60 }
61
62 function serialize(value) {
63 return value === undefined ? undefined : stringify(value);
64 }
65
66 // QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
67 // text reads the same as a Node error, and drop this prelude's frames.
68 function errorText(error) {
69 const head = error.message ? error.name + ": " + error.message : String(error.name);
70 const frames =
71 typeof error.stack === "string"
72 ? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
73 : [];
74 return [head, ...frames].join("\\n");
75 }
76
77 function format(value) {
78 if (typeof value === "string") return value;
79 if (value instanceof ErrorCtor) return errorText(value);
80 try {
81 const json = stringify(value);
82 return json === undefined ? String(value) : json;
83 } catch {
84 return String(value);
85 }
86 }
87
88 function describeError(error) {
89 if (error instanceof ErrorCtor) {
90 return stringify({ name: error.name, message: error.message, stack: errorText(error) });
91 }
92 return stringify({ message: format(error) });
93 }
94
95 function caller(kind, name, spread) {
96 return (...args) =>
97 new Promise((resolve, reject) => {
98 let json;
99 try {
100 json = serialize(spread ? args : args[0]);
101 } catch (error) {
102 reject(error);
103 return;
104 }
105 const id = nextId++;
106 pending.set(id, { resolve, reject });
107 bridge(kind, id, name, json);
108 });
109 }
110
111 const tools = Object.create(null);
112 const allTools = [];
113 for (const { name, jsName, description } of parse(toolsJson)) {
114 const fn = caller("call", name);
115 // The first tool wins when two names normalize to the same identifier.
116 if (!(jsName in tools)) {
117 tools[jsName] = fn;
118 allTools.push(Object.freeze({ name: jsName, description }));
119 }
120 if (!(name in tools)) tools[name] = fn;
121 }
122 Object.freeze(tools);
123 Object.freeze(allTools);
124
125 // Reading a member that does not exist throws an error that names the close matches, instead of
126 // a later "not a function". \`in\` checks still work.
127 const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
128 function guard(target, label, names, hint) {
129 return new Proxy(target, {
130 get(object, property, receiver) {
131 if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
132 return Reflect.get(object, property, receiver);
133 }
134 const wanted = comparable(property);
135 const exact = names.filter((name) => comparable(name) === wanted);
136 const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
137 let message = label + "." + property + " does not exist.";
138 if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
139 else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
140 if (hint) message += " " + hint;
141 message += ' Check for a member with "' + property + '" in ' + label + ".";
142 throw new TypeErrorCtor(message);
143 },
144 });
145 }
146 const toolsProxy = guard(
147 tools,
148 "tools",
149 allTools.map((tool) => tool.name),
150 "ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
151 );
152
153 const namespaces = new Map();
154 for (const { name, spread } of parse(globalsJson)) {
155 const fn = caller("global", name, spread);
156 const dot = name.indexOf(".");
157 if (dot === -1) {
158 Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
159 continue;
160 }
161 const namespace = name.slice(0, dot);
162 if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
163 namespaces.get(namespace)[name.slice(dot + 1)] = fn;
164 }
165 for (const [namespace, members] of namespaces) {
166 Object.freeze(members);
167 const value = guard(members, namespace, Object.keys(members));
168 Object.defineProperty(globalThis, namespace, { value, enumerable: true });
169 }
170
171 // key -> JSON text. Sizes count key and JSON characters.
172 const stored = new Map(Object.entries(parse(storeJson)));
173 const writes = new Map();
174 let storedChars = 0;
175 for (const [key, json] of stored) storedChars += key.length + json.length;
176
177 const STORE_HINT =
178 "store() is for small state such as IDs or summaries. Show images with image(), keep large data in variables, or write it to a file with a tool.";
179
180 function checkKey(name, key) {
181 if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
182 }
183
184 function store(key, value) {
185 checkKey("store", key);
186 const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
187 if (value === undefined) {
188 stored.delete(key);
189 storedChars -= previous;
190 writes.set(key, undefined);
191 return;
192 }
193 let json;
194 try {
195 json = stringify(value);
196 } catch (error) {
197 throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
198 }
199 if (json === undefined) {
200 throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
201 }
202 if (json.length > ${MAX_STORE_VALUE_CHARS}) {
203 throw new RangeError(
204 "store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. " +
205 STORE_HINT,
206 );
207 }
208 const next = storedChars - previous + key.length + json.length;
209 if (next > ${MAX_STORE_TOTAL_CHARS}) {
210 throw new RangeError(
211 "store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). " +
212 STORE_HINT,
213 );
214 }
215 stored.set(key, json);
216 storedChars = next;
217 writes.set(key, json);
218 }
219
220 function load(key) {
221 checkKey("load", key);
222 const json = stored.get(key);
223 return json === undefined ? undefined : parse(json);
224 }
225
226 function serializeWrites() {
227 const entries = [];
228 for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
229 return stringify(entries);
230 }
231
232 Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
233 Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
234
235 let outputChars = 0;
236 let outputItems = 0;
237
238 // Past the output limits the script fails: done() reports the error, so catching it does not
239 // resume output, and the host ends the script.
240 function output(kind, data, mimeType) {
241 if (finished) return;
242 outputChars += data.length;
243 outputItems++;
244 if (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {
245 const error = new RangeErrorCtor(
246 "script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. " +
247 "Print a summary instead, or write large data to a file with a tool.",
248 );
249 done(false, describeError(error));
250 throw error;
251 }
252 bridge("output", kind, data, mimeType);
253 }
254
255 // Primitives become their string form, everything else JSON.
256 function outputText(value) {
257 if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
258 return String(value);
259 }
260 const json = stringify(value);
261 return json === undefined ? String(value) : json;
262 }
263
264 function text(value) {
265 let rendered;
266 try {
267 rendered = outputText(value);
268 } catch (error) {
269 throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
270 }
271 output("text", rendered);
272 }
273
274 function imageUrl(value) {
275 if (typeof value === "string") return value;
276 if (typeof value !== "object" || value === null || Array.isArray(value)) {
277 throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
278 }
279 if (value.image_url !== undefined) {
280 if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
281 return value.image_url;
282 }
283 if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
284 if (value.type !== "image") {
285 throw new TypeErrorCtor('image only accepts MCP image blocks, got "' + value.type + '"');
286 }
287 if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected MCP image data");
288 if (value.data.toLowerCase().startsWith("data:")) return value.data;
289 return "data:;base64," + value.data;
290 }
291
292 // Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
293 // JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
294 const IMAGE_SIGNATURES = [
295 ["image/png", /^iVBORw0KGg/],
296 ["image/jpeg", /^[/]9j[/](?!9)/],
297 ["image/gif", /^R0lGOD[dl]h/],
298 ["image/webp", /^UklG.{8}RUJQ/],
299 ];
300
301 function image(value) {
302 const url = imageUrl(value);
303 if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
304 const colon = url.indexOf(":");
305 const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
306 if (scheme === "http" || scheme === "https") {
307 throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
308 }
309 const comma = url.indexOf(",");
310 const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
311 if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
312 throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
313 }
314 // Providers reject the whole request on a bad image, and a persisted image block would be
315 // resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
316 // is ignored in favor of the detected one, as providers also reject mismatches.
317 const data = url.slice(comma + 1).replace(/\\s+/g, "");
318 if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
319 throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
320 }
321 const head = data.slice(0, 16);
322 const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
323 if (!signature) {
324 throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
325 }
326 output("image", data, signature[0]);
327 }
328
329 function exit() {
330 let writesJson;
331 try {
332 writesJson = serializeWrites();
333 } catch (error) {
334 done(false, describeError(error));
335 throw EXIT;
336 }
337 done(true, undefined, writesJson);
338 throw EXIT;
339 }
340
341 const console = {};
342 for (const level of ["log", "info", "warn", "error", "debug"]) {
343 console[level] = (...args) => {
344 output("text", args.map(format).join(" "));
345 };
346 }
347 Object.freeze(console);
348
349 Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
350 Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
351 Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
352 Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
353 Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
354 Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
355
356 return {
357 settle(id, ok, payload) {
358 const entry = pending.get(id);
359 if (!entry) return;
360 pending.delete(id);
361 if (!ok) {
362 entry.reject(new ErrorCtor(payload));
363 return;
364 }
365 let value;
366 try {
367 value = payload === undefined ? undefined : parse(payload);
368 } catch (error) {
369 entry.reject(error);
370 return;
371 }
372 entry.resolve(value);
373 },
374 run(fn) {
375 let promise;
376 try {
377 promise = fn(toolsProxy, console);
378 } catch (error) {
379 done(false, describeError(error));
380 return;
381 }
382 promiseThen.call(
383 promise,
384 (value) => {
385 let json;
386 try {
387 json = serialize(value);
388 } catch (error) {
389 done(false, describeError(error));
390 return;
391 }
392 done(true, json, serializeWrites());
393 },
394 (error) => {
395 done(false, describeError(error));
396 },
397 );
398 },
399 stalled() {
400 if (finished || pending.size > 0) return false;
401 done(
402 false,
403 stringify({
404 name: "Error",
405 message:
406 "The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
407 }),
408 );
409 return true;
410 },
411 };
412})`;