@brian-agent/codemode 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +373 -2
- package/dist/cloudflare.d.ts +53 -0
- package/dist/cloudflare.d.ts.map +1 -0
- package/dist/cloudflare.js +64 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/declarations.d.ts +43 -0
- package/dist/declarations.d.ts.map +1 -0
- package/dist/declarations.js +320 -0
- package/dist/declarations.js.map +1 -0
- package/dist/identifier.d.ts +6 -0
- package/dist/identifier.d.ts.map +1 -0
- package/dist/identifier.js +13 -0
- package/dist/identifier.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/portable.d.ts +15 -0
- package/dist/portable.d.ts.map +1 -0
- package/dist/portable.js +12 -0
- package/dist/portable.js.map +1 -0
- package/dist/runtime/execution.d.ts +66 -0
- package/dist/runtime/execution.d.ts.map +1 -0
- package/dist/runtime/execution.js +494 -0
- package/dist/runtime/execution.js.map +1 -0
- package/dist/runtime/host.d.ts +13 -0
- package/dist/runtime/host.d.ts.map +1 -0
- package/dist/runtime/host.js +86 -0
- package/dist/runtime/host.js.map +1 -0
- package/dist/runtime/inline.d.ts +63 -0
- package/dist/runtime/inline.d.ts.map +1 -0
- package/dist/runtime/inline.js +80 -0
- package/dist/runtime/inline.js.map +1 -0
- package/dist/runtime/prelude-source.d.ts +45 -0
- package/dist/runtime/prelude-source.d.ts.map +1 -0
- package/dist/runtime/prelude-source.js +520 -0
- package/dist/runtime/prelude-source.js.map +1 -0
- package/dist/runtime/protocol.d.ts +110 -0
- package/dist/runtime/protocol.d.ts.map +1 -0
- package/dist/runtime/protocol.js +15 -0
- package/dist/runtime/protocol.js.map +1 -0
- package/dist/runtime/remote.d.ts +102 -0
- package/dist/runtime/remote.d.ts.map +1 -0
- package/dist/runtime/remote.js +175 -0
- package/dist/runtime/remote.js.map +1 -0
- package/dist/runtime/vm.d.ts +24 -0
- package/dist/runtime/vm.d.ts.map +1 -0
- package/dist/runtime/vm.js +293 -0
- package/dist/runtime/vm.js.map +1 -0
- package/dist/runtime/worker.d.ts +2 -0
- package/dist/runtime/worker.d.ts.map +1 -0
- package/dist/runtime/worker.js +38 -0
- package/dist/runtime/worker.js.map +1 -0
- package/dist/source.d.ts +36 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +98 -0
- package/dist/source.js.map +1 -0
- package/dist/types.d.ts +246 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/wasm.d.ts +12 -0
- package/dist/wasm.d.ts.map +1 -0
- package/dist/wasm.js +24 -0
- package/dist/wasm.js.map +1 -0
- package/package.json +75 -5
|
@@ -0,0 +1,520 @@
|
|
|
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 image block `{ type: "image", data, mimeType }`, and `exit()` ends the script
|
|
13
|
+
* successfully. `console.*` appends text items marked as console output.
|
|
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
|
+
* `settle(id, ok, payload, propertiesJson)` settles call `id`; a rejection's `Error` gets the own properties of the
|
|
21
|
+
* `propertiesJson` object, except `name`, `message`, and `stack`.
|
|
22
|
+
* `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the
|
|
23
|
+
* tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.
|
|
24
|
+
* `stalled()` reports a script that has not finished while no host call is pending: with no timers
|
|
25
|
+
* or I/O in the VM, nothing can ever resume it.
|
|
26
|
+
* `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.
|
|
27
|
+
* `bridge(kind, a, b, c)` with kind "call" or "global" (id, name, argsJson),
|
|
28
|
+
* "output" ("text" or "console", text) or ("image", data, mimeType), or "done" (ok, valueJsonOrErrorJson, writesJson).
|
|
29
|
+
*
|
|
30
|
+
* Before anything else the prelude freezes the built-ins and makes the built-in globals read-only.
|
|
31
|
+
* The prelude shares them with the script, so a script that patched one (for example
|
|
32
|
+
* `Array.prototype.toJSON`) could otherwise corrupt what the prelude reports to the host.
|
|
33
|
+
*/
|
|
34
|
+
export const MAX_STORE_VALUE_CHARS = 256 * 1024;
|
|
35
|
+
export const MAX_STORE_TOTAL_CHARS = 1024 * 1024;
|
|
36
|
+
/**
|
|
37
|
+
* Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and
|
|
38
|
+
* base64 image data, and items. The host keeps all output until the script ends, so without a
|
|
39
|
+
* limit a script that prints in a loop grows the host's memory until it crashes. The item limit
|
|
40
|
+
* covers loops that print empty strings.
|
|
41
|
+
*/
|
|
42
|
+
export const MAX_OUTPUT_CHARS = 16 * 1024 * 1024;
|
|
43
|
+
export const MAX_OUTPUT_ITEMS = 100_000;
|
|
44
|
+
const IMAGE_HELPER_EXPECTS = 'image expects a non-empty image URL string, an object with image_url, or an image block { type: "image", data, mimeType }';
|
|
45
|
+
export const PRELUDE_SOURCE = `(function (bridge, toolsJson, globalsJson, storeJson) {
|
|
46
|
+
"use strict";
|
|
47
|
+
|
|
48
|
+
// Freeze every object reachable from the built-in globals, plus the intrinsics that are only
|
|
49
|
+
// reachable from instances (iterator and generator prototypes, %TypedArray%).
|
|
50
|
+
//
|
|
51
|
+
// Freezing alone breaks ordinary code through the "override mistake": a data property that is
|
|
52
|
+
// read-only on a prototype cannot be assigned on an instance either, so
|
|
53
|
+
// this.name = "MyError" in an Error subclass would throw. Commonly overridden properties
|
|
54
|
+
// become accessors whose setter defines an own property on the instance instead.
|
|
55
|
+
(function lockdown() {
|
|
56
|
+
const OVERRIDABLE = new Set(["constructor", "name", "message", "toString", "toLocaleString", "valueOf", "toJSON"]);
|
|
57
|
+
const seen = new Set([globalThis]);
|
|
58
|
+
const queue = [];
|
|
59
|
+
const add = (value) => {
|
|
60
|
+
if ((typeof value === "object" && value !== null) || typeof value === "function") {
|
|
61
|
+
if (!seen.has(value)) {
|
|
62
|
+
seen.add(value);
|
|
63
|
+
queue.push(value);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
// Accessors from an object literal have no own prototype object, unlike function expressions,
|
|
69
|
+
// whose prototype.constructor would be converted again without end.
|
|
70
|
+
function allowOverride(object, key, value, enumerable) {
|
|
71
|
+
const { get, set } = Object.getOwnPropertyDescriptor(
|
|
72
|
+
{
|
|
73
|
+
get accessor() {
|
|
74
|
+
return value;
|
|
75
|
+
},
|
|
76
|
+
set accessor(next) {
|
|
77
|
+
if (this === object) {
|
|
78
|
+
throw new TypeError("Cannot assign to read only property '" + String(key) + "' of a built-in");
|
|
79
|
+
}
|
|
80
|
+
if ((typeof this !== "object" || this === null) && typeof this !== "function") return;
|
|
81
|
+
Object.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });
|
|
82
|
+
},
|
|
83
|
+
},
|
|
84
|
+
"accessor",
|
|
85
|
+
);
|
|
86
|
+
Object.defineProperty(object, key, { get, set, enumerable, configurable: false });
|
|
87
|
+
add(get);
|
|
88
|
+
add(set);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
for (const key of Reflect.ownKeys(globalThis)) {
|
|
92
|
+
const descriptor = Object.getOwnPropertyDescriptor(globalThis, key);
|
|
93
|
+
add(descriptor.value);
|
|
94
|
+
add(descriptor.get);
|
|
95
|
+
add(descriptor.set);
|
|
96
|
+
if ("value" in descriptor && descriptor.configurable) {
|
|
97
|
+
Object.defineProperty(globalThis, key, { writable: false, configurable: false });
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
add(Object.getPrototypeOf(function* () {}));
|
|
101
|
+
add(Object.getPrototypeOf(async function () {}));
|
|
102
|
+
add(Object.getPrototypeOf(async function* () {}));
|
|
103
|
+
add(Object.getPrototypeOf(Int8Array));
|
|
104
|
+
add(Object.getPrototypeOf([][Symbol.iterator]()));
|
|
105
|
+
add(Object.getPrototypeOf(new Map()[Symbol.iterator]()));
|
|
106
|
+
add(Object.getPrototypeOf(new Set()[Symbol.iterator]()));
|
|
107
|
+
add(Object.getPrototypeOf(""[Symbol.iterator]()));
|
|
108
|
+
add(Object.getPrototypeOf(/a/[Symbol.matchAll]("")));
|
|
109
|
+
if (typeof Iterator === "function") {
|
|
110
|
+
if (typeof Iterator.prototype.map === "function") add(Object.getPrototypeOf([].values().map((x) => x)));
|
|
111
|
+
if (typeof Iterator.from === "function") add(Object.getPrototypeOf(Iterator.from({ next() {} })));
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
while (queue.length > 0) {
|
|
115
|
+
const object = queue.pop();
|
|
116
|
+
add(Object.getPrototypeOf(object));
|
|
117
|
+
const descriptors = Object.getOwnPropertyDescriptors(object);
|
|
118
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
119
|
+
const descriptor = descriptors[key];
|
|
120
|
+
if ("value" in descriptor) {
|
|
121
|
+
add(descriptor.value);
|
|
122
|
+
if (
|
|
123
|
+
descriptor.writable &&
|
|
124
|
+
descriptor.configurable &&
|
|
125
|
+
(object === Object.prototype || OVERRIDABLE.has(key))
|
|
126
|
+
) {
|
|
127
|
+
allowOverride(object, key, descriptor.value, descriptor.enumerable);
|
|
128
|
+
}
|
|
129
|
+
} else {
|
|
130
|
+
add(descriptor.get);
|
|
131
|
+
add(descriptor.set);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
Object.freeze(object);
|
|
135
|
+
}
|
|
136
|
+
})();
|
|
137
|
+
const stringify = JSON.stringify;
|
|
138
|
+
const parse = JSON.parse;
|
|
139
|
+
const promiseThen = Promise.prototype.then;
|
|
140
|
+
const ErrorCtor = Error;
|
|
141
|
+
const TypeErrorCtor = TypeError;
|
|
142
|
+
const RangeErrorCtor = RangeError;
|
|
143
|
+
const pending = new Map();
|
|
144
|
+
let nextId = 1;
|
|
145
|
+
let finished = false;
|
|
146
|
+
// Thrown by exit() to unwind the script after it already reported success.
|
|
147
|
+
const EXIT = Object.freeze({});
|
|
148
|
+
|
|
149
|
+
function done(ok, payload, writes) {
|
|
150
|
+
if (finished) return;
|
|
151
|
+
finished = true;
|
|
152
|
+
bridge("done", ok, payload, writes);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function serialize(value) {
|
|
156
|
+
return value === undefined ? undefined : stringify(value);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// QuickJS stacks list frames only. Prefix "Name: message" like V8 so the
|
|
160
|
+
// text reads the same as a Node error, and drop this prelude's frames.
|
|
161
|
+
function errorText(error) {
|
|
162
|
+
const head = error.message ? error.name + ": " + error.message : String(error.name);
|
|
163
|
+
const frames =
|
|
164
|
+
typeof error.stack === "string"
|
|
165
|
+
? error.stack.split("\\n").filter((line) => line.trim() && !line.includes("codemode-prelude.js"))
|
|
166
|
+
: [];
|
|
167
|
+
return [head, ...frames].join("\\n");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function format(value) {
|
|
171
|
+
if (typeof value === "string") return value;
|
|
172
|
+
if (value instanceof ErrorCtor) return errorText(value);
|
|
173
|
+
try {
|
|
174
|
+
const json = stringify(value);
|
|
175
|
+
return json === undefined ? String(value) : json;
|
|
176
|
+
} catch {
|
|
177
|
+
return String(value);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// The host requires string fields. A script can set an error's name or message to anything, so
|
|
182
|
+
// they are coerced, and a value whose coercion throws gets a placeholder.
|
|
183
|
+
function describeError(error) {
|
|
184
|
+
try {
|
|
185
|
+
if (error instanceof ErrorCtor) {
|
|
186
|
+
return stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });
|
|
187
|
+
}
|
|
188
|
+
return stringify({ message: String(format(error)) });
|
|
189
|
+
} catch {
|
|
190
|
+
return stringify({ message: "The script threw a value that cannot be described" });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function caller(kind, name, spread) {
|
|
195
|
+
return (...args) =>
|
|
196
|
+
new Promise((resolve, reject) => {
|
|
197
|
+
let json;
|
|
198
|
+
try {
|
|
199
|
+
json = serialize(spread ? args : args[0]);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
reject(error);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
const id = nextId++;
|
|
205
|
+
pending.set(id, { resolve, reject });
|
|
206
|
+
bridge(kind, id, name, json);
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const tools = Object.create(null);
|
|
211
|
+
const allTools = [];
|
|
212
|
+
for (const { name, jsName, description } of parse(toolsJson)) {
|
|
213
|
+
const fn = caller("call", name);
|
|
214
|
+
// The first tool wins when two names normalize to the same identifier.
|
|
215
|
+
if (!(jsName in tools)) {
|
|
216
|
+
tools[jsName] = fn;
|
|
217
|
+
allTools.push(Object.freeze({ name: jsName, description }));
|
|
218
|
+
}
|
|
219
|
+
if (!(name in tools)) tools[name] = fn;
|
|
220
|
+
}
|
|
221
|
+
Object.freeze(tools);
|
|
222
|
+
Object.freeze(allTools);
|
|
223
|
+
|
|
224
|
+
// Reading a member that does not exist throws an error that names the close matches, instead of
|
|
225
|
+
// a later "not a function". \`in\` checks still work.
|
|
226
|
+
const comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
227
|
+
function guard(target, label, names, hint) {
|
|
228
|
+
return new Proxy(target, {
|
|
229
|
+
get(object, property, receiver) {
|
|
230
|
+
if (typeof property !== "string" || property in object || property in Object.prototype || property === "then" || property === "toJSON") {
|
|
231
|
+
return Reflect.get(object, property, receiver);
|
|
232
|
+
}
|
|
233
|
+
const wanted = comparable(property);
|
|
234
|
+
const exact = names.filter((name) => comparable(name) === wanted);
|
|
235
|
+
const close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));
|
|
236
|
+
let message = label + "." + property + " does not exist.";
|
|
237
|
+
if (close.length > 0) message += " Did you mean " + close.slice(0, 5).map((name) => label + "." + name).join(", ") + "?";
|
|
238
|
+
else if (names.length <= 20) message += " Available: " + names.join(", ") + ".";
|
|
239
|
+
if (hint) message += " " + hint;
|
|
240
|
+
message += ' Check for a member with "' + property + '" in ' + label + ".";
|
|
241
|
+
throw new TypeErrorCtor(message);
|
|
242
|
+
},
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
const toolsProxy = guard(
|
|
246
|
+
tools,
|
|
247
|
+
"tools",
|
|
248
|
+
allTools.map((tool) => tool.name),
|
|
249
|
+
"ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.",
|
|
250
|
+
);
|
|
251
|
+
|
|
252
|
+
const namespaces = new Map();
|
|
253
|
+
for (const { name, spread } of parse(globalsJson)) {
|
|
254
|
+
const fn = caller("global", name, spread);
|
|
255
|
+
const dot = name.indexOf(".");
|
|
256
|
+
if (dot === -1) {
|
|
257
|
+
Object.defineProperty(globalThis, name, { value: fn, enumerable: true });
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
const namespace = name.slice(0, dot);
|
|
261
|
+
if (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));
|
|
262
|
+
namespaces.get(namespace)[name.slice(dot + 1)] = fn;
|
|
263
|
+
}
|
|
264
|
+
for (const [namespace, members] of namespaces) {
|
|
265
|
+
Object.freeze(members);
|
|
266
|
+
const value = guard(members, namespace, Object.keys(members));
|
|
267
|
+
Object.defineProperty(globalThis, namespace, { value, enumerable: true });
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// key -> JSON text. Sizes count key and JSON characters.
|
|
271
|
+
const stored = new Map(Object.entries(parse(storeJson)));
|
|
272
|
+
const writes = new Map();
|
|
273
|
+
let storedChars = 0;
|
|
274
|
+
for (const [key, json] of stored) storedChars += key.length + json.length;
|
|
275
|
+
|
|
276
|
+
const STORE_HINT =
|
|
277
|
+
"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.";
|
|
278
|
+
|
|
279
|
+
function checkKey(name, key) {
|
|
280
|
+
if (typeof key !== "string") throw new TypeError(name + "() key must be a string");
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function store(key, value) {
|
|
284
|
+
checkKey("store", key);
|
|
285
|
+
const previous = stored.has(key) ? key.length + stored.get(key).length : 0;
|
|
286
|
+
if (value === undefined) {
|
|
287
|
+
stored.delete(key);
|
|
288
|
+
storedChars -= previous;
|
|
289
|
+
writes.set(key, undefined);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
let json;
|
|
293
|
+
try {
|
|
294
|
+
json = stringify(value);
|
|
295
|
+
} catch (error) {
|
|
296
|
+
throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable: " + format(error));
|
|
297
|
+
}
|
|
298
|
+
if (json === undefined) {
|
|
299
|
+
throw new TypeError("store(" + stringify(key) + ") value is not JSON-serializable");
|
|
300
|
+
}
|
|
301
|
+
if (json.length > ${MAX_STORE_VALUE_CHARS}) {
|
|
302
|
+
throw new RangeError(
|
|
303
|
+
"store(" + stringify(key) + ") value has " + json.length + " characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. " +
|
|
304
|
+
STORE_HINT,
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
const next = storedChars - previous + key.length + json.length;
|
|
308
|
+
if (next > ${MAX_STORE_TOTAL_CHARS}) {
|
|
309
|
+
throw new RangeError(
|
|
310
|
+
"store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). " +
|
|
311
|
+
STORE_HINT,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
stored.set(key, json);
|
|
315
|
+
storedChars = next;
|
|
316
|
+
writes.set(key, json);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function load(key) {
|
|
320
|
+
checkKey("load", key);
|
|
321
|
+
const json = stored.get(key);
|
|
322
|
+
return json === undefined ? undefined : parse(json);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function serializeWrites() {
|
|
326
|
+
const entries = [];
|
|
327
|
+
for (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);
|
|
328
|
+
return stringify(entries);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
Object.defineProperty(globalThis, "store", { value: store, enumerable: true });
|
|
332
|
+
Object.defineProperty(globalThis, "load", { value: load, enumerable: true });
|
|
333
|
+
|
|
334
|
+
let outputChars = 0;
|
|
335
|
+
let outputItems = 0;
|
|
336
|
+
|
|
337
|
+
// Past the output limits the script fails: done() reports the error, so catching it does not
|
|
338
|
+
// resume output, and the host ends the script.
|
|
339
|
+
function output(kind, data, mimeType) {
|
|
340
|
+
if (finished) return;
|
|
341
|
+
outputChars += data.length;
|
|
342
|
+
outputItems++;
|
|
343
|
+
if (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {
|
|
344
|
+
const error = new RangeErrorCtor(
|
|
345
|
+
"script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. " +
|
|
346
|
+
"Print a summary instead, or write large data to a file with a tool.",
|
|
347
|
+
);
|
|
348
|
+
done(false, describeError(error));
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
bridge("output", kind, data, mimeType);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Primitives become their string form, everything else JSON.
|
|
355
|
+
function outputText(value) {
|
|
356
|
+
if (value === undefined || value === null || typeof value !== "object" && typeof value !== "function") {
|
|
357
|
+
return String(value);
|
|
358
|
+
}
|
|
359
|
+
const json = stringify(value);
|
|
360
|
+
return json === undefined ? String(value) : json;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function text(value) {
|
|
364
|
+
let rendered;
|
|
365
|
+
try {
|
|
366
|
+
rendered = outputText(value);
|
|
367
|
+
} catch (error) {
|
|
368
|
+
throw new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));
|
|
369
|
+
}
|
|
370
|
+
output("text", rendered);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function imageUrl(value) {
|
|
374
|
+
if (typeof value === "string") return value;
|
|
375
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
376
|
+
throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
377
|
+
}
|
|
378
|
+
if (value.image_url !== undefined) {
|
|
379
|
+
if (typeof value.image_url !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
380
|
+
return value.image_url;
|
|
381
|
+
}
|
|
382
|
+
if (typeof value.type !== "string") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
383
|
+
if (value.type !== "image") {
|
|
384
|
+
throw new TypeErrorCtor('image only accepts image blocks, got "' + value.type + '"');
|
|
385
|
+
}
|
|
386
|
+
if (typeof value.data !== "string" || value.data === "") throw new TypeErrorCtor("image expected image block data");
|
|
387
|
+
if (value.data.toLowerCase().startsWith("data:")) return value.data;
|
|
388
|
+
return "data:;base64," + value.data;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Base64 of the signatures of the formats providers accept inline (PNG, JPEG except
|
|
392
|
+
// JPEG-LS, GIF, "RIFF....WEBP"). Signatures start at byte 0, so their encodings are prefixes.
|
|
393
|
+
const IMAGE_SIGNATURES = [
|
|
394
|
+
["image/png", /^iVBORw0KGg/],
|
|
395
|
+
["image/jpeg", /^[/]9j[/](?!9)/],
|
|
396
|
+
["image/gif", /^R0lGOD[dl]h/],
|
|
397
|
+
["image/webp", /^UklG.{8}RUJQ/],
|
|
398
|
+
];
|
|
399
|
+
|
|
400
|
+
function image(value) {
|
|
401
|
+
const url = imageUrl(value);
|
|
402
|
+
if (url === "") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});
|
|
403
|
+
const colon = url.indexOf(":");
|
|
404
|
+
const scheme = colon === -1 ? "" : url.slice(0, colon).toLowerCase();
|
|
405
|
+
if (scheme === "http" || scheme === "https") {
|
|
406
|
+
throw new TypeErrorCtor("remote image URLs are not supported in tool outputs. Pass a base64 data URI instead");
|
|
407
|
+
}
|
|
408
|
+
const comma = url.indexOf(",");
|
|
409
|
+
const header = comma === -1 ? [] : url.slice(colon + 1, comma).split(";");
|
|
410
|
+
if (scheme !== "data" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== "base64")) {
|
|
411
|
+
throw new TypeErrorCtor("invalid image output. Pass a base64 data URI instead");
|
|
412
|
+
}
|
|
413
|
+
// Providers reject the whole request on a bad image, and a persisted image block would be
|
|
414
|
+
// resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type
|
|
415
|
+
// is ignored in favor of the detected one, as providers also reject mismatches.
|
|
416
|
+
const data = url.slice(comma + 1).replace(/\\s+/g, "");
|
|
417
|
+
if (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {
|
|
418
|
+
throw new TypeErrorCtor("invalid image output. The image data is not valid base64 (truncated or corrupted?)");
|
|
419
|
+
}
|
|
420
|
+
const head = data.slice(0, 16);
|
|
421
|
+
const signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));
|
|
422
|
+
if (!signature) {
|
|
423
|
+
throw new TypeErrorCtor("invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image");
|
|
424
|
+
}
|
|
425
|
+
output("image", data, signature[0]);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function exit() {
|
|
429
|
+
let writesJson;
|
|
430
|
+
try {
|
|
431
|
+
writesJson = serializeWrites();
|
|
432
|
+
} catch (error) {
|
|
433
|
+
done(false, describeError(error));
|
|
434
|
+
throw EXIT;
|
|
435
|
+
}
|
|
436
|
+
done(true, undefined, writesJson);
|
|
437
|
+
throw EXIT;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
const console = {};
|
|
441
|
+
for (const level of ["log", "info", "warn", "error", "debug"]) {
|
|
442
|
+
console[level] = (...args) => {
|
|
443
|
+
output("console", args.map(format).join(" "));
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
Object.freeze(console);
|
|
447
|
+
|
|
448
|
+
Object.defineProperty(globalThis, "tools", { value: toolsProxy, enumerable: true });
|
|
449
|
+
Object.defineProperty(globalThis, "ALL_TOOLS", { value: allTools, enumerable: true });
|
|
450
|
+
Object.defineProperty(globalThis, "console", { value: console, enumerable: true });
|
|
451
|
+
Object.defineProperty(globalThis, "text", { value: text, enumerable: true });
|
|
452
|
+
Object.defineProperty(globalThis, "image", { value: image, enumerable: true });
|
|
453
|
+
Object.defineProperty(globalThis, "exit", { value: exit, enumerable: true });
|
|
454
|
+
|
|
455
|
+
return {
|
|
456
|
+
settle(id, ok, payload, propertiesJson) {
|
|
457
|
+
const entry = pending.get(id);
|
|
458
|
+
if (!entry) return;
|
|
459
|
+
pending.delete(id);
|
|
460
|
+
if (!ok) {
|
|
461
|
+
const error = new ErrorCtor(payload);
|
|
462
|
+
if (propertiesJson !== undefined) {
|
|
463
|
+
const properties = parse(propertiesJson);
|
|
464
|
+
for (const key of Object.keys(properties)) {
|
|
465
|
+
if (key === "name" || key === "message" || key === "stack") continue;
|
|
466
|
+
Object.defineProperty(error, key, { value: properties[key], writable: true, enumerable: true, configurable: true });
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
entry.reject(error);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
let value;
|
|
473
|
+
try {
|
|
474
|
+
value = payload === undefined ? undefined : parse(payload);
|
|
475
|
+
} catch (error) {
|
|
476
|
+
entry.reject(error);
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
entry.resolve(value);
|
|
480
|
+
},
|
|
481
|
+
run(fn) {
|
|
482
|
+
let promise;
|
|
483
|
+
try {
|
|
484
|
+
promise = fn(toolsProxy, console);
|
|
485
|
+
} catch (error) {
|
|
486
|
+
done(false, describeError(error));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
promiseThen.call(
|
|
490
|
+
promise,
|
|
491
|
+
(value) => {
|
|
492
|
+
let json;
|
|
493
|
+
try {
|
|
494
|
+
json = serialize(value);
|
|
495
|
+
} catch (error) {
|
|
496
|
+
done(false, describeError(error));
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
done(true, json, serializeWrites());
|
|
500
|
+
},
|
|
501
|
+
(error) => {
|
|
502
|
+
done(false, describeError(error));
|
|
503
|
+
},
|
|
504
|
+
);
|
|
505
|
+
},
|
|
506
|
+
stalled() {
|
|
507
|
+
if (finished || pending.size > 0) return false;
|
|
508
|
+
done(
|
|
509
|
+
false,
|
|
510
|
+
stringify({
|
|
511
|
+
name: "Error",
|
|
512
|
+
message:
|
|
513
|
+
"The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.",
|
|
514
|
+
}),
|
|
515
|
+
);
|
|
516
|
+
return true;
|
|
517
|
+
},
|
|
518
|
+
};
|
|
519
|
+
})`;
|
|
520
|
+
//# sourceMappingURL=prelude-source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prelude-source.js","sourceRoot":"","sources":["../../src/runtime/prelude-source.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,GAAG,IAAI,CAAC;AAChD,MAAM,CAAC,MAAM,qBAAqB,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AACjD,MAAM,CAAC,MAAM,gBAAgB,GAAG,OAAO,CAAC;AAExC,MAAM,oBAAoB,GACzB,2HAA2H,CAAC;AAE7H,MAAM,CAAC,MAAM,cAAc,GAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAgQhB,qBAAqB;;8GAEmE,qBAAqB;;;;;eAKpH,qBAAqB;;iDAEa,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAiChD,gBAAgB,qBAAqB,gBAAgB;;2CAEhC,gBAAgB,kBAAkB,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BA+BhE,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;sEAGK,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;gEAG1C,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;;4CAoBxD,IAAI,CAAC,SAAS,CAAC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqH7E,CAAC","sourcesContent":["/**\n * JavaScript evaluated inside the QuickJS VM before the script runs.\n *\n * The VM is its own wasm instance, so nothing here guards a realm boundary.\n * The prelude keeps the host bridge in a closure so the script cannot call it\n * directly, and builds `tools`, `ALL_TOOLS`, the output helpers (`text`, `image`,\n * `exit`, `console`), and globals on top of it. Tool arguments and results cross\n * as JSON strings and are parsed on this side.\n *\n * Output helpers: `text(value)` appends a text item (non-strings are\n * JSON-stringified), `image(urlOrItem)` appends an image from a base64 `data:` URL, an\n * `{ image_url }` object, or an image block `{ type: \"image\", data, mimeType }`, and `exit()` ends the script\n * successfully. `console.*` appends text items marked as console output.\n *\n * `store(key, value)` and `load(key)` are synchronous: they work on a snapshot of\n * JSON text passed in as `storeJson`, and the keys the script wrote are reported\n * with a successful \"done\".\n *\n * Evaluates to a function `(bridge, toolsJson, globalsJson, storeJson) => { settle, run, stalled }`.\n * `settle(id, ok, payload, propertiesJson)` settles call `id`; a rejection's `Error` gets the own properties of the\n * `propertiesJson` object, except `name`, `message`, and `stack`.\n * `toolsJson` lists `{ name, jsName, description }`: `tools[jsName]` and `tools[name]` call the\n * tool, and `ALL_TOOLS` lists `{ name: jsName, description }`.\n * `stalled()` reports a script that has not finished while no host call is pending: with no timers\n * or I/O in the VM, nothing can ever resume it.\n * `globalsJson` lists `{ name, spread }`; `a.b` names are grouped into a frozen `a` object.\n * `bridge(kind, a, b, c)` with kind \"call\" or \"global\" (id, name, argsJson),\n * \"output\" (\"text\" or \"console\", text) or (\"image\", data, mimeType), or \"done\" (ok, valueJsonOrErrorJson, writesJson).\n *\n * Before anything else the prelude freezes the built-ins and makes the built-in globals read-only.\n * The prelude shares them with the script, so a script that patched one (for example\n * `Array.prototype.toJSON`) could otherwise corrupt what the prelude reports to the host.\n */\nexport const MAX_STORE_VALUE_CHARS = 256 * 1024;\nexport const MAX_STORE_TOTAL_CHARS = 1024 * 1024;\n/**\n * Output one script may produce with `text()`, `image()`, and `console.*`: characters of text and\n * base64 image data, and items. The host keeps all output until the script ends, so without a\n * limit a script that prints in a loop grows the host's memory until it crashes. The item limit\n * covers loops that print empty strings.\n */\nexport const MAX_OUTPUT_CHARS = 16 * 1024 * 1024;\nexport const MAX_OUTPUT_ITEMS = 100_000;\n\nconst IMAGE_HELPER_EXPECTS =\n\t'image expects a non-empty image URL string, an object with image_url, or an image block { type: \"image\", data, mimeType }';\n\nexport const PRELUDE_SOURCE: string = `(function (bridge, toolsJson, globalsJson, storeJson) {\n\t\"use strict\";\n\n\t// Freeze every object reachable from the built-in globals, plus the intrinsics that are only\n\t// reachable from instances (iterator and generator prototypes, %TypedArray%).\n\t//\n\t// Freezing alone breaks ordinary code through the \"override mistake\": a data property that is\n\t// read-only on a prototype cannot be assigned on an instance either, so\n\t// this.name = \"MyError\" in an Error subclass would throw. Commonly overridden properties\n\t// become accessors whose setter defines an own property on the instance instead.\n\t(function lockdown() {\n\t\tconst OVERRIDABLE = new Set([\"constructor\", \"name\", \"message\", \"toString\", \"toLocaleString\", \"valueOf\", \"toJSON\"]);\n\t\tconst seen = new Set([globalThis]);\n\t\tconst queue = [];\n\t\tconst add = (value) => {\n\t\t\tif ((typeof value === \"object\" && value !== null) || typeof value === \"function\") {\n\t\t\t\tif (!seen.has(value)) {\n\t\t\t\t\tseen.add(value);\n\t\t\t\t\tqueue.push(value);\n\t\t\t\t}\n\t\t\t}\n\t\t};\n\n\t\t// Accessors from an object literal have no own prototype object, unlike function expressions,\n\t\t// whose prototype.constructor would be converted again without end.\n\t\tfunction allowOverride(object, key, value, enumerable) {\n\t\t\tconst { get, set } = Object.getOwnPropertyDescriptor(\n\t\t\t\t{\n\t\t\t\t\tget accessor() {\n\t\t\t\t\t\treturn value;\n\t\t\t\t\t},\n\t\t\t\t\tset accessor(next) {\n\t\t\t\t\t\tif (this === object) {\n\t\t\t\t\t\t\tthrow new TypeError(\"Cannot assign to read only property '\" + String(key) + \"' of a built-in\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ((typeof this !== \"object\" || this === null) && typeof this !== \"function\") return;\n\t\t\t\t\t\tObject.defineProperty(this, key, { value: next, writable: true, enumerable: true, configurable: true });\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"accessor\",\n\t\t\t);\n\t\t\tObject.defineProperty(object, key, { get, set, enumerable, configurable: false });\n\t\t\tadd(get);\n\t\t\tadd(set);\n\t\t}\n\n\t\tfor (const key of Reflect.ownKeys(globalThis)) {\n\t\t\tconst descriptor = Object.getOwnPropertyDescriptor(globalThis, key);\n\t\t\tadd(descriptor.value);\n\t\t\tadd(descriptor.get);\n\t\t\tadd(descriptor.set);\n\t\t\tif (\"value\" in descriptor && descriptor.configurable) {\n\t\t\t\tObject.defineProperty(globalThis, key, { writable: false, configurable: false });\n\t\t\t}\n\t\t}\n\t\tadd(Object.getPrototypeOf(function* () {}));\n\t\tadd(Object.getPrototypeOf(async function () {}));\n\t\tadd(Object.getPrototypeOf(async function* () {}));\n\t\tadd(Object.getPrototypeOf(Int8Array));\n\t\tadd(Object.getPrototypeOf([][Symbol.iterator]()));\n\t\tadd(Object.getPrototypeOf(new Map()[Symbol.iterator]()));\n\t\tadd(Object.getPrototypeOf(new Set()[Symbol.iterator]()));\n\t\tadd(Object.getPrototypeOf(\"\"[Symbol.iterator]()));\n\t\tadd(Object.getPrototypeOf(/a/[Symbol.matchAll](\"\")));\n\t\tif (typeof Iterator === \"function\") {\n\t\t\tif (typeof Iterator.prototype.map === \"function\") add(Object.getPrototypeOf([].values().map((x) => x)));\n\t\t\tif (typeof Iterator.from === \"function\") add(Object.getPrototypeOf(Iterator.from({ next() {} })));\n\t\t}\n\n\t\twhile (queue.length > 0) {\n\t\t\tconst object = queue.pop();\n\t\t\tadd(Object.getPrototypeOf(object));\n\t\t\tconst descriptors = Object.getOwnPropertyDescriptors(object);\n\t\t\tfor (const key of Reflect.ownKeys(descriptors)) {\n\t\t\t\tconst descriptor = descriptors[key];\n\t\t\t\tif (\"value\" in descriptor) {\n\t\t\t\t\tadd(descriptor.value);\n\t\t\t\t\tif (\n\t\t\t\t\t\tdescriptor.writable &&\n\t\t\t\t\t\tdescriptor.configurable &&\n\t\t\t\t\t\t(object === Object.prototype || OVERRIDABLE.has(key))\n\t\t\t\t\t) {\n\t\t\t\t\t\tallowOverride(object, key, descriptor.value, descriptor.enumerable);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tadd(descriptor.get);\n\t\t\t\t\tadd(descriptor.set);\n\t\t\t\t}\n\t\t\t}\n\t\t\tObject.freeze(object);\n\t\t}\n\t})();\n\tconst stringify = JSON.stringify;\n\tconst parse = JSON.parse;\n\tconst promiseThen = Promise.prototype.then;\n\tconst ErrorCtor = Error;\n\tconst TypeErrorCtor = TypeError;\n\tconst RangeErrorCtor = RangeError;\n\tconst pending = new Map();\n\tlet nextId = 1;\n\tlet finished = false;\n\t// Thrown by exit() to unwind the script after it already reported success.\n\tconst EXIT = Object.freeze({});\n\n\tfunction done(ok, payload, writes) {\n\t\tif (finished) return;\n\t\tfinished = true;\n\t\tbridge(\"done\", ok, payload, writes);\n\t}\n\n\tfunction serialize(value) {\n\t\treturn value === undefined ? undefined : stringify(value);\n\t}\n\n\t// QuickJS stacks list frames only. Prefix \"Name: message\" like V8 so the\n\t// text reads the same as a Node error, and drop this prelude's frames.\n\tfunction errorText(error) {\n\t\tconst head = error.message ? error.name + \": \" + error.message : String(error.name);\n\t\tconst frames =\n\t\t\ttypeof error.stack === \"string\"\n\t\t\t\t? error.stack.split(\"\\\\n\").filter((line) => line.trim() && !line.includes(\"codemode-prelude.js\"))\n\t\t\t\t: [];\n\t\treturn [head, ...frames].join(\"\\\\n\");\n\t}\n\n\tfunction format(value) {\n\t\tif (typeof value === \"string\") return value;\n\t\tif (value instanceof ErrorCtor) return errorText(value);\n\t\ttry {\n\t\t\tconst json = stringify(value);\n\t\t\treturn json === undefined ? String(value) : json;\n\t\t} catch {\n\t\t\treturn String(value);\n\t\t}\n\t}\n\n\t// The host requires string fields. A script can set an error's name or message to anything, so\n\t// they are coerced, and a value whose coercion throws gets a placeholder.\n\tfunction describeError(error) {\n\t\ttry {\n\t\t\tif (error instanceof ErrorCtor) {\n\t\t\t\treturn stringify({ name: String(error.name), message: String(error.message), stack: errorText(error) });\n\t\t\t}\n\t\t\treturn stringify({ message: String(format(error)) });\n\t\t} catch {\n\t\t\treturn stringify({ message: \"The script threw a value that cannot be described\" });\n\t\t}\n\t}\n\n\tfunction caller(kind, name, spread) {\n\t\treturn (...args) =>\n\t\t\tnew Promise((resolve, reject) => {\n\t\t\t\tlet json;\n\t\t\t\ttry {\n\t\t\t\t\tjson = serialize(spread ? args : args[0]);\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tconst id = nextId++;\n\t\t\t\tpending.set(id, { resolve, reject });\n\t\t\t\tbridge(kind, id, name, json);\n\t\t\t});\n\t}\n\n\tconst tools = Object.create(null);\n\tconst allTools = [];\n\tfor (const { name, jsName, description } of parse(toolsJson)) {\n\t\tconst fn = caller(\"call\", name);\n\t\t// The first tool wins when two names normalize to the same identifier.\n\t\tif (!(jsName in tools)) {\n\t\t\ttools[jsName] = fn;\n\t\t\tallTools.push(Object.freeze({ name: jsName, description }));\n\t\t}\n\t\tif (!(name in tools)) tools[name] = fn;\n\t}\n\tObject.freeze(tools);\n\tObject.freeze(allTools);\n\n\t// Reading a member that does not exist throws an error that names the close matches, instead of\n\t// a later \"not a function\". \\`in\\` checks still work.\n\tconst comparable = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, \"\");\n\tfunction guard(target, label, names, hint) {\n\t\treturn new Proxy(target, {\n\t\t\tget(object, property, receiver) {\n\t\t\t\tif (typeof property !== \"string\" || property in object || property in Object.prototype || property === \"then\" || property === \"toJSON\") {\n\t\t\t\t\treturn Reflect.get(object, property, receiver);\n\t\t\t\t}\n\t\t\t\tconst wanted = comparable(property);\n\t\t\t\tconst exact = names.filter((name) => comparable(name) === wanted);\n\t\t\t\tconst close = exact.length > 0 ? exact : names.filter((name) => wanted && (comparable(name).includes(wanted) || wanted.includes(comparable(name))));\n\t\t\t\tlet message = label + \".\" + property + \" does not exist.\";\n\t\t\t\tif (close.length > 0) message += \" Did you mean \" + close.slice(0, 5).map((name) => label + \".\" + name).join(\", \") + \"?\";\n\t\t\t\telse if (names.length <= 20) message += \" Available: \" + names.join(\", \") + \".\";\n\t\t\t\tif (hint) message += \" \" + hint;\n\t\t\t\tmessage += ' Check for a member with \"' + property + '\" in ' + label + \".\";\n\t\t\t\tthrow new TypeErrorCtor(message);\n\t\t\t},\n\t\t});\n\t}\n\tconst toolsProxy = guard(\n\t\ttools,\n\t\t\"tools\",\n\t\tallTools.map((tool) => tool.name),\n\t\t\"ALL_TOOLS lists every tool; searchTools(query) finds tools by topic.\",\n\t);\n\n\tconst namespaces = new Map();\n\tfor (const { name, spread } of parse(globalsJson)) {\n\t\tconst fn = caller(\"global\", name, spread);\n\t\tconst dot = name.indexOf(\".\");\n\t\tif (dot === -1) {\n\t\t\tObject.defineProperty(globalThis, name, { value: fn, enumerable: true });\n\t\t\tcontinue;\n\t\t}\n\t\tconst namespace = name.slice(0, dot);\n\t\tif (!namespaces.has(namespace)) namespaces.set(namespace, Object.create(null));\n\t\tnamespaces.get(namespace)[name.slice(dot + 1)] = fn;\n\t}\n\tfor (const [namespace, members] of namespaces) {\n\t\tObject.freeze(members);\n\t\tconst value = guard(members, namespace, Object.keys(members));\n\t\tObject.defineProperty(globalThis, namespace, { value, enumerable: true });\n\t}\n\n\t// key -> JSON text. Sizes count key and JSON characters.\n\tconst stored = new Map(Object.entries(parse(storeJson)));\n\tconst writes = new Map();\n\tlet storedChars = 0;\n\tfor (const [key, json] of stored) storedChars += key.length + json.length;\n\n\tconst STORE_HINT =\n\t\t\"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.\";\n\n\tfunction checkKey(name, key) {\n\t\tif (typeof key !== \"string\") throw new TypeError(name + \"() key must be a string\");\n\t}\n\n\tfunction store(key, value) {\n\t\tcheckKey(\"store\", key);\n\t\tconst previous = stored.has(key) ? key.length + stored.get(key).length : 0;\n\t\tif (value === undefined) {\n\t\t\tstored.delete(key);\n\t\t\tstoredChars -= previous;\n\t\t\twrites.set(key, undefined);\n\t\t\treturn;\n\t\t}\n\t\tlet json;\n\t\ttry {\n\t\t\tjson = stringify(value);\n\t\t} catch (error) {\n\t\t\tthrow new TypeError(\"store(\" + stringify(key) + \") value is not JSON-serializable: \" + format(error));\n\t\t}\n\t\tif (json === undefined) {\n\t\t\tthrow new TypeError(\"store(\" + stringify(key) + \") value is not JSON-serializable\");\n\t\t}\n\t\tif (json.length > ${MAX_STORE_VALUE_CHARS}) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"store(\" + stringify(key) + \") value has \" + json.length + \" characters of JSON, more than the limit of ${MAX_STORE_VALUE_CHARS}. \" +\n\t\t\t\t\tSTORE_HINT,\n\t\t\t);\n\t\t}\n\t\tconst next = storedChars - previous + key.length + json.length;\n\t\tif (next > ${MAX_STORE_TOTAL_CHARS}) {\n\t\t\tthrow new RangeError(\n\t\t\t\t\"store is full: stored values would exceed ${MAX_STORE_TOTAL_CHARS} characters of JSON. Delete keys with store(key, undefined). \" +\n\t\t\t\t\tSTORE_HINT,\n\t\t\t);\n\t\t}\n\t\tstored.set(key, json);\n\t\tstoredChars = next;\n\t\twrites.set(key, json);\n\t}\n\n\tfunction load(key) {\n\t\tcheckKey(\"load\", key);\n\t\tconst json = stored.get(key);\n\t\treturn json === undefined ? undefined : parse(json);\n\t}\n\n\tfunction serializeWrites() {\n\t\tconst entries = [];\n\t\tfor (const [key, json] of writes) entries.push(json === undefined ? [key] : [key, json]);\n\t\treturn stringify(entries);\n\t}\n\n\tObject.defineProperty(globalThis, \"store\", { value: store, enumerable: true });\n\tObject.defineProperty(globalThis, \"load\", { value: load, enumerable: true });\n\n\tlet outputChars = 0;\n\tlet outputItems = 0;\n\n\t// Past the output limits the script fails: done() reports the error, so catching it does not\n\t// resume output, and the host ends the script.\n\tfunction output(kind, data, mimeType) {\n\t\tif (finished) return;\n\t\toutputChars += data.length;\n\t\toutputItems++;\n\t\tif (outputChars > ${MAX_OUTPUT_CHARS} || outputItems > ${MAX_OUTPUT_ITEMS}) {\n\t\t\tconst error = new RangeErrorCtor(\n\t\t\t\t\"script output exceeded the limit of ${MAX_OUTPUT_CHARS} characters or ${MAX_OUTPUT_ITEMS} text(), image(), and console calls. \" +\n\t\t\t\t\t\"Print a summary instead, or write large data to a file with a tool.\",\n\t\t\t);\n\t\t\tdone(false, describeError(error));\n\t\t\tthrow error;\n\t\t}\n\t\tbridge(\"output\", kind, data, mimeType);\n\t}\n\n\t// Primitives become their string form, everything else JSON.\n\tfunction outputText(value) {\n\t\tif (value === undefined || value === null || typeof value !== \"object\" && typeof value !== \"function\") {\n\t\t\treturn String(value);\n\t\t}\n\t\tconst json = stringify(value);\n\t\treturn json === undefined ? String(value) : json;\n\t}\n\n\tfunction text(value) {\n\t\tlet rendered;\n\t\ttry {\n\t\t\trendered = outputText(value);\n\t\t} catch (error) {\n\t\t\tthrow new TypeErrorCtor(error instanceof ErrorCtor ? error.message : String(error));\n\t\t}\n\t\toutput(\"text\", rendered);\n\t}\n\n\tfunction imageUrl(value) {\n\t\tif (typeof value === \"string\") return value;\n\t\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\t\tthrow new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\t}\n\t\tif (value.image_url !== undefined) {\n\t\t\tif (typeof value.image_url !== \"string\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\t\treturn value.image_url;\n\t\t}\n\t\tif (typeof value.type !== \"string\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\tif (value.type !== \"image\") {\n\t\t\tthrow new TypeErrorCtor('image only accepts image blocks, got \"' + value.type + '\"');\n\t\t}\n\t\tif (typeof value.data !== \"string\" || value.data === \"\") throw new TypeErrorCtor(\"image expected image block data\");\n\t\tif (value.data.toLowerCase().startsWith(\"data:\")) return value.data;\n\t\treturn \"data:;base64,\" + value.data;\n\t}\n\n\t// Base64 of the signatures of the formats providers accept inline (PNG, JPEG except\n\t// JPEG-LS, GIF, \"RIFF....WEBP\"). Signatures start at byte 0, so their encodings are prefixes.\n\tconst IMAGE_SIGNATURES = [\n\t\t[\"image/png\", /^iVBORw0KGg/],\n\t\t[\"image/jpeg\", /^[/]9j[/](?!9)/],\n\t\t[\"image/gif\", /^R0lGOD[dl]h/],\n\t\t[\"image/webp\", /^UklG.{8}RUJQ/],\n\t];\n\n\tfunction image(value) {\n\t\tconst url = imageUrl(value);\n\t\tif (url === \"\") throw new TypeErrorCtor(${JSON.stringify(IMAGE_HELPER_EXPECTS)});\n\t\tconst colon = url.indexOf(\":\");\n\t\tconst scheme = colon === -1 ? \"\" : url.slice(0, colon).toLowerCase();\n\t\tif (scheme === \"http\" || scheme === \"https\") {\n\t\t\tthrow new TypeErrorCtor(\"remote image URLs are not supported in tool outputs. Pass a base64 data URI instead\");\n\t\t}\n\t\tconst comma = url.indexOf(\",\");\n\t\tconst header = comma === -1 ? [] : url.slice(colon + 1, comma).split(\";\");\n\t\tif (scheme !== \"data\" || comma === -1 || header.slice(1).every((part) => part.toLowerCase() !== \"base64\")) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. Pass a base64 data URI instead\");\n\t\t}\n\t\t// Providers reject the whole request on a bad image, and a persisted image block would be\n\t\t// resent on every later turn. Line breaks from wrapped base64 are dropped. The declared type\n\t\t// is ignored in favor of the detected one, as providers also reject mismatches.\n\t\tconst data = url.slice(comma + 1).replace(/\\\\s+/g, \"\");\n\t\tif (data.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(data)) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. The image data is not valid base64 (truncated or corrupted?)\");\n\t\t}\n\t\tconst head = data.slice(0, 16);\n\t\tconst signature = IMAGE_SIGNATURES.find(([, pattern]) => pattern.test(head));\n\t\tif (!signature) {\n\t\t\tthrow new TypeErrorCtor(\"invalid image output. The image data is not a PNG, JPEG, GIF, or WebP image\");\n\t\t}\n\t\toutput(\"image\", data, signature[0]);\n\t}\n\n\tfunction exit() {\n\t\tlet writesJson;\n\t\ttry {\n\t\t\twritesJson = serializeWrites();\n\t\t} catch (error) {\n\t\t\tdone(false, describeError(error));\n\t\t\tthrow EXIT;\n\t\t}\n\t\tdone(true, undefined, writesJson);\n\t\tthrow EXIT;\n\t}\n\n\tconst console = {};\n\tfor (const level of [\"log\", \"info\", \"warn\", \"error\", \"debug\"]) {\n\t\tconsole[level] = (...args) => {\n\t\t\toutput(\"console\", args.map(format).join(\" \"));\n\t\t};\n\t}\n\tObject.freeze(console);\n\n\tObject.defineProperty(globalThis, \"tools\", { value: toolsProxy, enumerable: true });\n\tObject.defineProperty(globalThis, \"ALL_TOOLS\", { value: allTools, enumerable: true });\n\tObject.defineProperty(globalThis, \"console\", { value: console, enumerable: true });\n\tObject.defineProperty(globalThis, \"text\", { value: text, enumerable: true });\n\tObject.defineProperty(globalThis, \"image\", { value: image, enumerable: true });\n\tObject.defineProperty(globalThis, \"exit\", { value: exit, enumerable: true });\n\n\treturn {\n\t\tsettle(id, ok, payload, propertiesJson) {\n\t\t\tconst entry = pending.get(id);\n\t\t\tif (!entry) return;\n\t\t\tpending.delete(id);\n\t\t\tif (!ok) {\n\t\t\t\tconst error = new ErrorCtor(payload);\n\t\t\t\tif (propertiesJson !== undefined) {\n\t\t\t\t\tconst properties = parse(propertiesJson);\n\t\t\t\t\tfor (const key of Object.keys(properties)) {\n\t\t\t\t\t\tif (key === \"name\" || key === \"message\" || key === \"stack\") continue;\n\t\t\t\t\t\tObject.defineProperty(error, key, { value: properties[key], writable: true, enumerable: true, configurable: true });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tentry.reject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet value;\n\t\t\ttry {\n\t\t\t\tvalue = payload === undefined ? undefined : parse(payload);\n\t\t\t} catch (error) {\n\t\t\t\tentry.reject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tentry.resolve(value);\n\t\t},\n\t\trun(fn) {\n\t\t\tlet promise;\n\t\t\ttry {\n\t\t\t\tpromise = fn(toolsProxy, console);\n\t\t\t} catch (error) {\n\t\t\t\tdone(false, describeError(error));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpromiseThen.call(\n\t\t\t\tpromise,\n\t\t\t\t(value) => {\n\t\t\t\t\tlet json;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tjson = serialize(value);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tdone(false, describeError(error));\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tdone(true, json, serializeWrites());\n\t\t\t\t},\n\t\t\t\t(error) => {\n\t\t\t\t\tdone(false, describeError(error));\n\t\t\t\t},\n\t\t\t);\n\t\t},\n\t\tstalled() {\n\t\t\tif (finished || pending.size > 0) return false;\n\t\t\tdone(\n\t\t\t\tfalse,\n\t\t\t\tstringify({\n\t\t\t\t\tname: \"Error\",\n\t\t\t\t\tmessage:\n\t\t\t\t\t\t\"The script is waiting on a promise that can never settle: no tool call is pending, and timers do not exist here.\",\n\t\t\t\t}),\n\t\t\t);\n\t\t\treturn true;\n\t\t},\n\t};\n})`;\n"]}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import type { CodemodeDuring, CodemodeOutputItem } from "../types.ts";
|
|
2
|
+
import type { CodemodeWasmModule } from "../wasm.ts";
|
|
3
|
+
/**
|
|
4
|
+
* Messages between the host (main thread) and the worker. Tool arguments,
|
|
5
|
+
* results, and values cross as JSON strings: the worker passes them into and
|
|
6
|
+
* out of the QuickJS VM as strings and never builds structured values itself.
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Everything a VM needs to run one script, independent of where it runs. Plain data, so it can
|
|
10
|
+
* cross a `postMessage` or a Workers RPC call unchanged.
|
|
11
|
+
*/
|
|
12
|
+
export interface VmStartData {
|
|
13
|
+
code: string;
|
|
14
|
+
/** `jsName` is the identifier the script uses; `description` is listed in `ALL_TOOLS`. */
|
|
15
|
+
tools: {
|
|
16
|
+
name: string;
|
|
17
|
+
jsName: string;
|
|
18
|
+
description: string;
|
|
19
|
+
}[];
|
|
20
|
+
globals: {
|
|
21
|
+
name: string;
|
|
22
|
+
spread: boolean;
|
|
23
|
+
}[];
|
|
24
|
+
memoryLimitBytes: number | undefined;
|
|
25
|
+
/** Snapshot for `load()`: key to JSON text. */
|
|
26
|
+
store: Record<string, string>;
|
|
27
|
+
/**
|
|
28
|
+
* Run deterministically (`CodemodeSandboxBase.start()`): UTC, a virtual clock starting at `startedAt` (ms since
|
|
29
|
+
* the epoch) that moves only with delivered results, randomness from `seed`, no `WeakRef`, results applied in
|
|
30
|
+
* `seq` order, and `started`/`idle` messages.
|
|
31
|
+
*/
|
|
32
|
+
deterministic?: {
|
|
33
|
+
startedAt: number;
|
|
34
|
+
seed: number;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export interface WorkerData extends VmStartData {
|
|
38
|
+
/** Compiled `quickjs-wasi` module. Structured clone shares the compiled code with the worker. */
|
|
39
|
+
wasm: CodemodeWasmModule;
|
|
40
|
+
/**
|
|
41
|
+
* One Int32 the host sets to non-zero before terminating the worker. The VM's interrupt handler
|
|
42
|
+
* polls it, because Bun's `worker.terminate()` cannot stop a thread that is spinning in wasm.
|
|
43
|
+
*/
|
|
44
|
+
interrupt: SharedArrayBuffer;
|
|
45
|
+
}
|
|
46
|
+
/** JSON-encoded `{ name?, message, stack? }` of an error thrown by the script. */
|
|
47
|
+
export type ScriptErrorJson = string;
|
|
48
|
+
export type WorkerToHostMessage = {
|
|
49
|
+
type: "call";
|
|
50
|
+
id: number;
|
|
51
|
+
target: "tool" | "global";
|
|
52
|
+
name: string;
|
|
53
|
+
args: string | undefined;
|
|
54
|
+
} | {
|
|
55
|
+
type: "output";
|
|
56
|
+
item: CodemodeOutputItem;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* `writes` is a JSON array of `[key, json]` for `store()` and `[key]` for deletions. Deterministic mode: `during`
|
|
60
|
+
* is the result the VM was processing when the script finished (0: its first run) and the calls issued by then.
|
|
61
|
+
*/
|
|
62
|
+
| {
|
|
63
|
+
type: "done";
|
|
64
|
+
ok: true;
|
|
65
|
+
value: string | undefined;
|
|
66
|
+
writes: string;
|
|
67
|
+
during?: CodemodeDuring;
|
|
68
|
+
} | {
|
|
69
|
+
type: "done";
|
|
70
|
+
ok: false;
|
|
71
|
+
error: ScriptErrorJson;
|
|
72
|
+
during?: CodemodeDuring;
|
|
73
|
+
}
|
|
74
|
+
/** The VM failed outside the script's control, for example a wasm trap. */
|
|
75
|
+
| {
|
|
76
|
+
type: "crash";
|
|
77
|
+
message: string;
|
|
78
|
+
}
|
|
79
|
+
/** Deterministic mode, before the script runs: what the VM is, so a replay can refuse a different one. */
|
|
80
|
+
| {
|
|
81
|
+
type: "started";
|
|
82
|
+
fingerprint: string;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Deterministic mode, after the script waits again: having processed result `seq` (0: the script's first run), it
|
|
86
|
+
* has issued `issued` calls in total.
|
|
87
|
+
*/
|
|
88
|
+
| {
|
|
89
|
+
type: "idle";
|
|
90
|
+
seq: number;
|
|
91
|
+
issued: number;
|
|
92
|
+
};
|
|
93
|
+
export type HostToWorkerMessage =
|
|
94
|
+
/**
|
|
95
|
+
* `payload` is the JSON result when `ok`, otherwise the error message. Deterministic mode: `seq` numbers the
|
|
96
|
+
* results from 1 in the order the VM applies them, and the VM's clock reads `now` while it processes this one.
|
|
97
|
+
*/
|
|
98
|
+
{
|
|
99
|
+
type: "result";
|
|
100
|
+
id: number;
|
|
101
|
+
ok: boolean;
|
|
102
|
+
payload: string | undefined;
|
|
103
|
+
seq?: number;
|
|
104
|
+
now?: number;
|
|
105
|
+
/** Deterministic mode, `ok: false`: a JSON object whose properties the script's `Error` gets. */
|
|
106
|
+
properties?: string;
|
|
107
|
+
};
|
|
108
|
+
export declare function isWorkerToHostMessage(value: unknown): value is WorkerToHostMessage;
|
|
109
|
+
export declare function isHostToWorkerMessage(value: unknown): value is HostToWorkerMessage;
|
|
110
|
+
//# sourceMappingURL=protocol.d.ts.map
|