@fractaal/pi-codemode 0.86.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 +190 -0
- package/dist/declarations.d.ts +58 -0
- package/dist/declarations.d.ts.map +1 -0
- package/dist/declarations.js +334 -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 +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/runtime/host.d.ts +35 -0
- package/dist/runtime/host.d.ts.map +1 -0
- package/dist/runtime/host.js +368 -0
- package/dist/runtime/host.js.map +1 -0
- package/dist/runtime/prelude-source.d.ts +43 -0
- package/dist/runtime/prelude-source.d.ts.map +1 -0
- package/dist/runtime/prelude-source.js +510 -0
- package/dist/runtime/prelude-source.js.map +1 -0
- package/dist/runtime/protocol.d.ts +69 -0
- package/dist/runtime/protocol.d.ts.map +1 -0
- package/dist/runtime/protocol.js +10 -0
- package/dist/runtime/protocol.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 +137 -0
- package/dist/runtime/worker.js.map +1 -0
- package/dist/source.d.ts +35 -0
- package/dist/source.d.ts.map +1 -0
- package/dist/source.js +92 -0
- package/dist/source.js.map +1 -0
- package/dist/types.d.ts +137 -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 +68 -0
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Worker thread entry. One worker runs one script inside a fresh QuickJS VM
|
|
3
|
+
* (a separate wasm instance), relays tool calls and output to the host, and
|
|
4
|
+
* reports the result. The host terminates the worker when the script settles,
|
|
5
|
+
* times out, or is aborted; the worker exists so that a spinning script never
|
|
6
|
+
* blocks the host thread.
|
|
7
|
+
*
|
|
8
|
+
* Importing this module starts the worker. Hosts that bundle their code (for
|
|
9
|
+
* example a Bun compiled executable) add a file that imports
|
|
10
|
+
* `@earendil-works/pi-codemode/worker` as a separate entrypoint and pass its URL
|
|
11
|
+
* or embedded-module string specifier as `workerUrl`.
|
|
12
|
+
*/
|
|
13
|
+
import { parentPort, workerData } from "node:worker_threads";
|
|
14
|
+
import { JSException, MAX_STACK_SIZE, QuickJS } from "quickjs-wasi";
|
|
15
|
+
import { PRELUDE_SOURCE } from "./prelude-source.js";
|
|
16
|
+
import { isHostToWorkerMessage } from "./protocol.js";
|
|
17
|
+
function post(message) {
|
|
18
|
+
parentPort?.postMessage(message);
|
|
19
|
+
}
|
|
20
|
+
function crash(error) {
|
|
21
|
+
post({ type: "crash", message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* QuickJS writes engine diagnostics to fd 1 and 2, which the default shim
|
|
25
|
+
* forwards to the host's stdout and stderr. That output belongs to the host
|
|
26
|
+
* application (for example a TUI), so it is discarded. Reporting every byte as
|
|
27
|
+
* written keeps libc from retrying.
|
|
28
|
+
*/
|
|
29
|
+
function discardOutput(memory) {
|
|
30
|
+
return {
|
|
31
|
+
fd_write(_fd, iovsPtr, iovsLen, nwrittenPtr) {
|
|
32
|
+
const view = new DataView(memory.buffer);
|
|
33
|
+
let written = 0;
|
|
34
|
+
for (let i = 0; i < iovsLen; i++) {
|
|
35
|
+
written += view.getUint32(iovsPtr + i * 8 + 4, true);
|
|
36
|
+
}
|
|
37
|
+
view.setUint32(nwrittenPtr, written, true);
|
|
38
|
+
return 0;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
function describeException(error) {
|
|
43
|
+
const head = error.message ? `${error.name}: ${error.message}` : error.name;
|
|
44
|
+
const stack = error.stack?.trimEnd();
|
|
45
|
+
return JSON.stringify({ name: error.name, message: error.message, stack: stack ? `${head}\n${stack}` : head });
|
|
46
|
+
}
|
|
47
|
+
async function main(data) {
|
|
48
|
+
const interrupt = new Int32Array(data.interrupt);
|
|
49
|
+
const vm = await QuickJS.create({
|
|
50
|
+
wasm: data.wasm,
|
|
51
|
+
memoryLimit: data.memoryLimitBytes,
|
|
52
|
+
// Without a guard, deep recursion overflows the wasm stack and traps instead of throwing a
|
|
53
|
+
// catchable RangeError.
|
|
54
|
+
maxStackSize: MAX_STACK_SIZE,
|
|
55
|
+
interruptHandler: () => Atomics.load(interrupt, 0) !== 0,
|
|
56
|
+
wasi: discardOutput,
|
|
57
|
+
});
|
|
58
|
+
// Called from the prelude with primitives only.
|
|
59
|
+
const bridge = vm.newFunction("bridge", (kind, a, b, c) => {
|
|
60
|
+
switch (kind.toString()) {
|
|
61
|
+
case "call":
|
|
62
|
+
case "global":
|
|
63
|
+
post({
|
|
64
|
+
type: "call",
|
|
65
|
+
id: a.toNumber(),
|
|
66
|
+
target: kind.toString() === "call" ? "tool" : "global",
|
|
67
|
+
name: b.toString(),
|
|
68
|
+
args: c === undefined || c.isUndefined ? undefined : c.toString(),
|
|
69
|
+
});
|
|
70
|
+
break;
|
|
71
|
+
case "output":
|
|
72
|
+
post({
|
|
73
|
+
type: "output",
|
|
74
|
+
item: a.toString() === "image"
|
|
75
|
+
? { type: "image", data: b.toString(), mimeType: c.toString() }
|
|
76
|
+
: { type: "text", text: b.toString() },
|
|
77
|
+
});
|
|
78
|
+
break;
|
|
79
|
+
case "done":
|
|
80
|
+
if (a.toBoolean()) {
|
|
81
|
+
post({
|
|
82
|
+
type: "done",
|
|
83
|
+
ok: true,
|
|
84
|
+
value: b === undefined || b.isUndefined ? undefined : b.toString(),
|
|
85
|
+
writes: c.toString(),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
post({ type: "done", ok: false, error: b.toString() });
|
|
90
|
+
}
|
|
91
|
+
break;
|
|
92
|
+
}
|
|
93
|
+
return vm.undefined;
|
|
94
|
+
});
|
|
95
|
+
// The VM lives until the host terminates the worker, so these handles are never disposed.
|
|
96
|
+
const api = vm.withScope((scope) => scope.escape(vm.callFunction(vm.evalCode(PRELUDE_SOURCE, "codemode-prelude.js"), vm.undefined, bridge, vm.newString(JSON.stringify(data.tools)), vm.newString(JSON.stringify(data.globals)), vm.newString(JSON.stringify(data.store)))));
|
|
97
|
+
const settle = api.getProp("settle");
|
|
98
|
+
const run = api.getProp("run");
|
|
99
|
+
const stalled = api.getProp("stalled");
|
|
100
|
+
/** Run queued jobs, then fail a script that waits on nothing that can ever resume it. */
|
|
101
|
+
const drain = () => {
|
|
102
|
+
vm.executePendingJobs();
|
|
103
|
+
vm.callFunction(stalled, api).dispose();
|
|
104
|
+
};
|
|
105
|
+
parentPort?.on("message", (message) => {
|
|
106
|
+
if (!isHostToWorkerMessage(message))
|
|
107
|
+
return;
|
|
108
|
+
try {
|
|
109
|
+
vm.withScope(() => {
|
|
110
|
+
vm.callFunction(settle, api, vm.newNumber(message.id), message.ok ? vm.true : vm.false, message.payload === undefined ? vm.undefined : vm.newString(message.payload));
|
|
111
|
+
});
|
|
112
|
+
drain();
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
crash(error);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
// The prefix shares the first line with the script so reported line numbers
|
|
119
|
+
// match the script as written.
|
|
120
|
+
let fn;
|
|
121
|
+
try {
|
|
122
|
+
fn = vm.evalCode(`(async (tools, console) => {${data.code}\n})`, "codemode.js");
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (!(error instanceof JSException))
|
|
126
|
+
throw error;
|
|
127
|
+
post({ type: "done", ok: false, error: describeException(error) });
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
vm.callFunction(run, api, fn).dispose();
|
|
131
|
+
fn.dispose();
|
|
132
|
+
drain();
|
|
133
|
+
}
|
|
134
|
+
if (parentPort) {
|
|
135
|
+
main(workerData).catch(crash);
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=worker.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker.js","sourceRoot":"","sources":["../../src/runtime/worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAsB,cAAc,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACxF,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,qBAAqB,EAA6C,MAAM,eAAe,CAAC;AAEjG,SAAS,IAAI,CAAC,OAA4B;IACzC,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,KAAK,CAAC,KAAc;IAC5B,IAAI,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAC9G,CAAC;AAED;;;;;GAKG;AACH,SAAS,aAAa,CAAC,MAA4C;IAClE,OAAO;QACN,QAAQ,CAAC,GAAW,EAAE,OAAe,EAAE,OAAe,EAAE,WAAmB;YAC1E,MAAM,IAAI,GAAG,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACzC,IAAI,OAAO,GAAG,CAAC,CAAC;YAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE,CAAC;gBAClC,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC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B,IAAI,CAAC,UAAwB,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;AAC7C,CAAC","sourcesContent":["/**\n * Worker thread entry. One worker runs one script inside a fresh QuickJS VM\n * (a separate wasm instance), relays tool calls and output to the host, and\n * reports the result. The host terminates the worker when the script settles,\n * times out, or is aborted; the worker exists so that a spinning script never\n * blocks the host thread.\n *\n * Importing this module starts the worker. Hosts that bundle their code (for\n * example a Bun compiled executable) add a file that imports\n * `@earendil-works/pi-codemode/worker` as a separate entrypoint and pass its URL\n * or embedded-module string specifier as `workerUrl`.\n */\nimport { parentPort, workerData } from \"node:worker_threads\";\nimport { JSException, type JSValueHandle, MAX_STACK_SIZE, QuickJS } from \"quickjs-wasi\";\nimport { PRELUDE_SOURCE } from \"./prelude-source.ts\";\nimport { isHostToWorkerMessage, type WorkerData, type WorkerToHostMessage } from \"./protocol.ts\";\n\nfunction post(message: WorkerToHostMessage): void {\n\tparentPort?.postMessage(message);\n}\n\nfunction crash(error: unknown): void {\n\tpost({ type: \"crash\", message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) });\n}\n\n/**\n * QuickJS writes engine diagnostics to fd 1 and 2, which the default shim\n * forwards to the host's stdout and stderr. That output belongs to the host\n * application (for example a TUI), so it is discarded. Reporting every byte as\n * written keeps libc from retrying.\n */\nfunction discardOutput(memory: { readonly buffer: ArrayBufferLike }) {\n\treturn {\n\t\tfd_write(_fd: number, iovsPtr: number, iovsLen: number, nwrittenPtr: number): number {\n\t\t\tconst view = new DataView(memory.buffer);\n\t\t\tlet written = 0;\n\t\t\tfor (let i = 0; i < iovsLen; i++) {\n\t\t\t\twritten += view.getUint32(iovsPtr + i * 8 + 4, true);\n\t\t\t}\n\t\t\tview.setUint32(nwrittenPtr, written, true);\n\t\t\treturn 0;\n\t\t},\n\t};\n}\n\nfunction describeException(error: JSException): string {\n\tconst head = error.message ? `${error.name}: ${error.message}` : error.name;\n\tconst stack = error.stack?.trimEnd();\n\treturn JSON.stringify({ name: error.name, message: error.message, stack: stack ? `${head}\\n${stack}` : head });\n}\n\nasync function main(data: WorkerData): Promise<void> {\n\tconst interrupt = new Int32Array(data.interrupt);\n\tconst vm = await QuickJS.create({\n\t\twasm: data.wasm,\n\t\tmemoryLimit: data.memoryLimitBytes,\n\t\t// Without a guard, deep recursion overflows the wasm stack and traps instead of throwing a\n\t\t// catchable RangeError.\n\t\tmaxStackSize: MAX_STACK_SIZE,\n\t\tinterruptHandler: () => Atomics.load(interrupt, 0) !== 0,\n\t\twasi: discardOutput,\n\t});\n\n\t// Called from the prelude with primitives only.\n\tconst bridge = vm.newFunction(\"bridge\", (kind, a, b, c) => {\n\t\tswitch (kind.toString()) {\n\t\t\tcase \"call\":\n\t\t\tcase \"global\":\n\t\t\t\tpost({\n\t\t\t\t\ttype: \"call\",\n\t\t\t\t\tid: a.toNumber(),\n\t\t\t\t\ttarget: kind.toString() === \"call\" ? \"tool\" : \"global\",\n\t\t\t\t\tname: b.toString(),\n\t\t\t\t\targs: c === undefined || c.isUndefined ? undefined : c.toString(),\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"output\":\n\t\t\t\tpost({\n\t\t\t\t\ttype: \"output\",\n\t\t\t\t\titem:\n\t\t\t\t\t\ta.toString() === \"image\"\n\t\t\t\t\t\t\t? { type: \"image\", data: b.toString(), mimeType: c.toString() }\n\t\t\t\t\t\t\t: { type: \"text\", text: b.toString() },\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"done\":\n\t\t\t\tif (a.toBoolean()) {\n\t\t\t\t\tpost({\n\t\t\t\t\t\ttype: \"done\",\n\t\t\t\t\t\tok: true,\n\t\t\t\t\t\tvalue: b === undefined || b.isUndefined ? undefined : b.toString(),\n\t\t\t\t\t\twrites: c.toString(),\n\t\t\t\t\t});\n\t\t\t\t} else {\n\t\t\t\t\tpost({ type: \"done\", ok: false, error: b.toString() });\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t\treturn vm.undefined;\n\t});\n\n\t// The VM lives until the host terminates the worker, so these handles are never disposed.\n\tconst api = vm.withScope((scope) =>\n\t\tscope.escape(\n\t\t\tvm.callFunction(\n\t\t\t\tvm.evalCode(PRELUDE_SOURCE, \"codemode-prelude.js\"),\n\t\t\t\tvm.undefined,\n\t\t\t\tbridge,\n\t\t\t\tvm.newString(JSON.stringify(data.tools)),\n\t\t\t\tvm.newString(JSON.stringify(data.globals)),\n\t\t\t\tvm.newString(JSON.stringify(data.store)),\n\t\t\t),\n\t\t),\n\t);\n\tconst settle = api.getProp(\"settle\");\n\tconst run = api.getProp(\"run\");\n\tconst stalled = api.getProp(\"stalled\");\n\t/** Run queued jobs, then fail a script that waits on nothing that can ever resume it. */\n\tconst drain = () => {\n\t\tvm.executePendingJobs();\n\t\tvm.callFunction(stalled, api).dispose();\n\t};\n\n\tparentPort?.on(\"message\", (message: unknown) => {\n\t\tif (!isHostToWorkerMessage(message)) return;\n\t\ttry {\n\t\t\tvm.withScope(() => {\n\t\t\t\tvm.callFunction(\n\t\t\t\t\tsettle,\n\t\t\t\t\tapi,\n\t\t\t\t\tvm.newNumber(message.id),\n\t\t\t\t\tmessage.ok ? vm.true : vm.false,\n\t\t\t\t\tmessage.payload === undefined ? vm.undefined : vm.newString(message.payload),\n\t\t\t\t);\n\t\t\t});\n\t\t\tdrain();\n\t\t} catch (error) {\n\t\t\tcrash(error);\n\t\t}\n\t});\n\n\t// The prefix shares the first line with the script so reported line numbers\n\t// match the script as written.\n\tlet fn: JSValueHandle;\n\ttry {\n\t\tfn = vm.evalCode(`(async (tools, console) => {${data.code}\\n})`, \"codemode.js\");\n\t} catch (error) {\n\t\tif (!(error instanceof JSException)) throw error;\n\t\tpost({ type: \"done\", ok: false, error: describeException(error) });\n\t\treturn;\n\t}\n\tvm.callFunction(run, api, fn).dispose();\n\tfn.dispose();\n\tdrain();\n}\n\nif (parentPort) {\n\tmain(workerData as WorkerData).catch(crash);\n}\n"]}
|
package/dist/source.d.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codemode source format: JavaScript, optionally preceded by one options line.
|
|
3
|
+
*
|
|
4
|
+
* ```js
|
|
5
|
+
* // @options: {"max_output_tokens": 2000, "timeout_ms": 30000}
|
|
6
|
+
* const text = await tools.read({ path: "package.json" });
|
|
7
|
+
* text(JSON.parse(text).name);
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export declare const CODEMODE_OPTIONS_PREFIX = "// @options:";
|
|
11
|
+
/**
|
|
12
|
+
* Lark grammar for providers with grammar-constrained tool input. It only fixes the shape of the
|
|
13
|
+
* options line; the options JSON and the code are checked by {@link parseCodemodeSource}.
|
|
14
|
+
*/
|
|
15
|
+
export declare const CODEMODE_SOURCE_GRAMMAR: string;
|
|
16
|
+
export interface CodemodeSourceOptions {
|
|
17
|
+
/** Token budget for the script's output. */
|
|
18
|
+
maxOutputTokens?: number;
|
|
19
|
+
/** Hard deadline for the whole script in milliseconds, including tool calls. */
|
|
20
|
+
timeoutMs?: number;
|
|
21
|
+
}
|
|
22
|
+
export interface ParsedCodemodeSource {
|
|
23
|
+
/** The script with the options line replaced by an empty line, so line numbers are unchanged. */
|
|
24
|
+
code: string;
|
|
25
|
+
options: CodemodeSourceOptions;
|
|
26
|
+
}
|
|
27
|
+
export declare class CodemodeSourceError extends Error {
|
|
28
|
+
constructor(message: string);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Split an optional first-line `// @options: {...}` from the script. Throws
|
|
32
|
+
* {@link CodemodeSourceError} for empty input and invalid options.
|
|
33
|
+
*/
|
|
34
|
+
export declare function parseCodemodeSource(input: string): ParsedCodemodeSource;
|
|
35
|
+
//# sourceMappingURL=source.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"source.d.ts","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,eAAO,MAAM,uBAAuB,iBAAiB,CAAC;AAOtD;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAQnC,CAAC;AAEF,MAAM,WAAW,qBAAqB;IACrC,4CAA4C;IAC5C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,gFAAgF;IAChF,SAAS,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,oBAAoB;IACpC,iGAAiG;IACjG,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,qBAAqB,CAAC;CAC/B;AAED,qBAAa,mBAAoB,SAAQ,KAAK;IAC7C,YAAY,OAAO,EAAE,MAAM,EAG1B;CACD;AA8CD;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,oBAAoB,CAevE"}
|
package/dist/source.js
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codemode source format: JavaScript, optionally preceded by one options line.
|
|
3
|
+
*
|
|
4
|
+
* ```js
|
|
5
|
+
* // @options: {"max_output_tokens": 2000, "timeout_ms": 30000}
|
|
6
|
+
* const text = await tools.read({ path: "package.json" });
|
|
7
|
+
* text(JSON.parse(text).name);
|
|
8
|
+
* ```
|
|
9
|
+
*/
|
|
10
|
+
export const CODEMODE_OPTIONS_PREFIX = "// @options:";
|
|
11
|
+
const SUPPORTED_FIELDS = ["max_output_tokens", "timeout_ms"];
|
|
12
|
+
const SUPPORTED_FIELDS_TEXT = "`max_output_tokens` and `timeout_ms`";
|
|
13
|
+
/** Largest delay `setTimeout` supports, which bounds `timeout_ms`. */
|
|
14
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
15
|
+
/**
|
|
16
|
+
* Lark grammar for providers with grammar-constrained tool input. It only fixes the shape of the
|
|
17
|
+
* options line; the options JSON and the code are checked by {@link parseCodemodeSource}.
|
|
18
|
+
*/
|
|
19
|
+
export const CODEMODE_SOURCE_GRAMMAR = String.raw `
|
|
20
|
+
start: options_source | plain_source
|
|
21
|
+
options_source: OPTIONS_LINE NEWLINE SOURCE
|
|
22
|
+
plain_source: SOURCE
|
|
23
|
+
|
|
24
|
+
OPTIONS_LINE: /[ \t]*\/\/ @options:[^\r\n]*/
|
|
25
|
+
NEWLINE: /\r?\n/
|
|
26
|
+
SOURCE: /[\s\S]+/
|
|
27
|
+
`;
|
|
28
|
+
export class CodemodeSourceError extends Error {
|
|
29
|
+
constructor(message) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = "CodemodeSourceError";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function isSafeInteger(value) {
|
|
35
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
|
|
36
|
+
}
|
|
37
|
+
function parseOptions(directive) {
|
|
38
|
+
if (directive === "") {
|
|
39
|
+
throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);
|
|
40
|
+
}
|
|
41
|
+
let value;
|
|
42
|
+
try {
|
|
43
|
+
value = JSON.parse(directive);
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
throw new CodemodeSourceError(`@options must be valid JSON with supported fields ${SUPPORTED_FIELDS_TEXT}: ${error instanceof Error ? error.message : String(error)}`);
|
|
47
|
+
}
|
|
48
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
49
|
+
throw new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);
|
|
50
|
+
}
|
|
51
|
+
const fields = value;
|
|
52
|
+
for (const key of Object.keys(fields)) {
|
|
53
|
+
if (!SUPPORTED_FIELDS.includes(key)) {
|
|
54
|
+
throw new CodemodeSourceError(`@options only supports ${SUPPORTED_FIELDS_TEXT}; got \`${key}\``);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const options = {};
|
|
58
|
+
const { max_output_tokens, timeout_ms } = fields;
|
|
59
|
+
if (max_output_tokens !== undefined) {
|
|
60
|
+
if (!isSafeInteger(max_output_tokens)) {
|
|
61
|
+
throw new CodemodeSourceError("@options field `max_output_tokens` must be a non-negative safe integer");
|
|
62
|
+
}
|
|
63
|
+
options.maxOutputTokens = max_output_tokens;
|
|
64
|
+
}
|
|
65
|
+
if (timeout_ms !== undefined) {
|
|
66
|
+
if (!isSafeInteger(timeout_ms) || timeout_ms === 0 || timeout_ms > MAX_TIMEOUT_MS) {
|
|
67
|
+
throw new CodemodeSourceError(`@options field \`timeout_ms\` must be a positive integer up to ${MAX_TIMEOUT_MS}`);
|
|
68
|
+
}
|
|
69
|
+
options.timeoutMs = timeout_ms;
|
|
70
|
+
}
|
|
71
|
+
return options;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Split an optional first-line `// @options: {...}` from the script. Throws
|
|
75
|
+
* {@link CodemodeSourceError} for empty input and invalid options.
|
|
76
|
+
*/
|
|
77
|
+
export function parseCodemodeSource(input) {
|
|
78
|
+
if (input.trim() === "") {
|
|
79
|
+
throw new CodemodeSourceError('Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {"max_output_tokens": 1000}`.');
|
|
80
|
+
}
|
|
81
|
+
const newline = input.indexOf("\n");
|
|
82
|
+
const firstLine = (newline === -1 ? input : input.slice(0, newline)).replace(/\r$/, "");
|
|
83
|
+
const trimmed = firstLine.trimStart();
|
|
84
|
+
if (!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX))
|
|
85
|
+
return { code: input, options: {} };
|
|
86
|
+
const code = newline === -1 ? "" : input.slice(newline);
|
|
87
|
+
if (code.trim() === "") {
|
|
88
|
+
throw new CodemodeSourceError("The @options line must be followed by JavaScript source on subsequent lines");
|
|
89
|
+
}
|
|
90
|
+
return { code, options: parseOptions(trimmed.slice(CODEMODE_OPTIONS_PREFIX.length).trim()) };
|
|
91
|
+
}
|
|
92
|
+
//# sourceMappingURL=source.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"source.js","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQ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,GAAG,CAAC,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IACxF,MAAM,OAAO,GAAG,SAAS,CAAC,SAAS,EAAE,CAAC;IACtC,IAAI,CAAC,OAAO,CAAC,UAAU,CAAC,uBAAuB,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IACtF,MAAM,IAAI,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IACxD,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;QACxB,MAAM,IAAI,mBAAmB,CAAC,6EAA6E,CAAC,CAAC;IAC9G,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC;AAC9F,CAAC","sourcesContent":["/**\n * Codemode source format: JavaScript, optionally preceded by one options line.\n *\n * ```js\n * // @options: {\"max_output_tokens\": 2000, \"timeout_ms\": 30000}\n * const text = await tools.read({ path: \"package.json\" });\n * text(JSON.parse(text).name);\n * ```\n */\n\nexport const CODEMODE_OPTIONS_PREFIX = \"// @options:\";\n\nconst SUPPORTED_FIELDS = [\"max_output_tokens\", \"timeout_ms\"] as const;\nconst SUPPORTED_FIELDS_TEXT = \"`max_output_tokens` and `timeout_ms`\";\n/** Largest delay `setTimeout` supports, which bounds `timeout_ms`. */\nconst MAX_TIMEOUT_MS = 2_147_483_647;\n\n/**\n * Lark grammar for providers with grammar-constrained tool input. It only fixes the shape of the\n * options line; the options JSON and the code are checked by {@link parseCodemodeSource}.\n */\nexport const CODEMODE_SOURCE_GRAMMAR = String.raw`\nstart: options_source | plain_source\noptions_source: OPTIONS_LINE NEWLINE SOURCE\nplain_source: SOURCE\n\nOPTIONS_LINE: /[ \\t]*\\/\\/ @options:[^\\r\\n]*/\nNEWLINE: /\\r?\\n/\nSOURCE: /[\\s\\S]+/\n`;\n\nexport interface CodemodeSourceOptions {\n\t/** Token budget for the script's output. */\n\tmaxOutputTokens?: number;\n\t/** Hard deadline for the whole script in milliseconds, including tool calls. */\n\ttimeoutMs?: number;\n}\n\nexport interface ParsedCodemodeSource {\n\t/** The script with the options line replaced by an empty line, so line numbers are unchanged. */\n\tcode: string;\n\toptions: CodemodeSourceOptions;\n}\n\nexport class CodemodeSourceError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"CodemodeSourceError\";\n\t}\n}\n\nfunction isSafeInteger(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\nfunction parseOptions(directive: string): CodemodeSourceOptions {\n\tif (directive === \"\") {\n\t\tthrow new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);\n\t}\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(directive);\n\t} catch (error) {\n\t\tthrow new CodemodeSourceError(\n\t\t\t`@options must be valid JSON with supported fields ${SUPPORTED_FIELDS_TEXT}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t);\n\t}\n\tif (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n\t\tthrow new CodemodeSourceError(`@options must be a JSON object with supported fields ${SUPPORTED_FIELDS_TEXT}`);\n\t}\n\tconst fields = value as Record<string, unknown>;\n\tfor (const key of Object.keys(fields)) {\n\t\tif (!(SUPPORTED_FIELDS as readonly string[]).includes(key)) {\n\t\t\tthrow new CodemodeSourceError(`@options only supports ${SUPPORTED_FIELDS_TEXT}; got \\`${key}\\``);\n\t\t}\n\t}\n\tconst options: CodemodeSourceOptions = {};\n\tconst { max_output_tokens, timeout_ms } = fields;\n\tif (max_output_tokens !== undefined) {\n\t\tif (!isSafeInteger(max_output_tokens)) {\n\t\t\tthrow new CodemodeSourceError(\"@options field `max_output_tokens` must be a non-negative safe integer\");\n\t\t}\n\t\toptions.maxOutputTokens = max_output_tokens;\n\t}\n\tif (timeout_ms !== undefined) {\n\t\tif (!isSafeInteger(timeout_ms) || timeout_ms === 0 || timeout_ms > MAX_TIMEOUT_MS) {\n\t\t\tthrow new CodemodeSourceError(\n\t\t\t\t`@options field \\`timeout_ms\\` must be a positive integer up to ${MAX_TIMEOUT_MS}`,\n\t\t\t);\n\t\t}\n\t\toptions.timeoutMs = timeout_ms;\n\t}\n\treturn options;\n}\n\n/**\n * Split an optional first-line `// @options: {...}` from the script. Throws\n * {@link CodemodeSourceError} for empty input and invalid options.\n */\nexport function parseCodemodeSource(input: string): ParsedCodemodeSource {\n\tif (input.trim() === \"\") {\n\t\tthrow new CodemodeSourceError(\n\t\t\t'Expected JavaScript source text (non-empty). Provide JS only, optionally with a first line `// @options: {\"max_output_tokens\": 1000}`.',\n\t\t);\n\t}\n\tconst newline = input.indexOf(\"\\n\");\n\tconst firstLine = (newline === -1 ? input : input.slice(0, newline)).replace(/\\r$/, \"\");\n\tconst trimmed = firstLine.trimStart();\n\tif (!trimmed.startsWith(CODEMODE_OPTIONS_PREFIX)) return { code: input, options: {} };\n\tconst code = newline === -1 ? \"\" : input.slice(newline);\n\tif (code.trim() === \"\") {\n\t\tthrow new CodemodeSourceError(\"The @options line must be followed by JavaScript source on subsequent lines\");\n\t}\n\treturn { code, options: parseOptions(trimmed.slice(CODEMODE_OPTIONS_PREFIX.length).trim()) };\n}\n"]}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { CodemodeWasmModule } from "./wasm.ts";
|
|
2
|
+
export interface CodemodeToolContext {
|
|
3
|
+
/**
|
|
4
|
+
* Aborted when the script finishes (including unawaited calls), the
|
|
5
|
+
* execution times out, the caller aborts, or the sandbox is closed.
|
|
6
|
+
*/
|
|
7
|
+
signal: AbortSignal;
|
|
8
|
+
}
|
|
9
|
+
/** A JSON Schema document. Only used to render declarations; values are not validated against it. */
|
|
10
|
+
export type CodemodeJsonSchema = {
|
|
11
|
+
[key: string]: unknown;
|
|
12
|
+
} | boolean;
|
|
13
|
+
export interface CodemodeTool {
|
|
14
|
+
/**
|
|
15
|
+
* The script calls tools as `tools.<id>(args)`, where `<id>` is the name with characters that
|
|
16
|
+
* are not valid in identifiers replaced by `_` (see `toCodemodeIdentifier`), and also as
|
|
17
|
+
* `tools["<name>"](args)`. Globals are called as `<name>(args)` and must be identifiers, or
|
|
18
|
+
* `<namespace>.<member>`, which groups them into a frozen namespace object.
|
|
19
|
+
*/
|
|
20
|
+
name: string;
|
|
21
|
+
/** Shown as a doc comment in {@link renderDeclarations}, and listed in `ALL_TOOLS` for tools. */
|
|
22
|
+
description?: string;
|
|
23
|
+
/** Schema of the single argument. Rendered as the parameter type; `unknown` when omitted. */
|
|
24
|
+
inputSchema?: CodemodeJsonSchema;
|
|
25
|
+
/** Schema of the resolved value. Rendered as the promise type; `unknown` when omitted. */
|
|
26
|
+
outputSchema?: CodemodeJsonSchema;
|
|
27
|
+
/** Globals only: `execute` receives all call arguments as an array instead of the first one. */
|
|
28
|
+
spread?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Globals only: TypeScript parameter list and return type for {@link renderDeclarations}, for
|
|
31
|
+
* example `(type: string, id?: string): Promise<Model[]>`. Replaces the rendering from the schemas.
|
|
32
|
+
*/
|
|
33
|
+
signature?: string;
|
|
34
|
+
/**
|
|
35
|
+
* `args` is whatever the script passed, after a JSON round trip. The return
|
|
36
|
+
* value must be JSON-serializable; a thrown error surfaces in the script as
|
|
37
|
+
* an `Error` with the same message.
|
|
38
|
+
*/
|
|
39
|
+
execute(args: unknown, context: CodemodeToolContext): Promise<unknown> | unknown;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* One item of the script's output, in the order the script produced it: `text()` and `console.*`
|
|
43
|
+
* produce text items, `image()` image items. `data` is base64.
|
|
44
|
+
*/
|
|
45
|
+
export type CodemodeOutputItem = {
|
|
46
|
+
type: "text";
|
|
47
|
+
text: string;
|
|
48
|
+
} | {
|
|
49
|
+
type: "image";
|
|
50
|
+
data: string;
|
|
51
|
+
mimeType: string;
|
|
52
|
+
};
|
|
53
|
+
export type CodemodeCallStatus = "ok" | "error" | "cancelled";
|
|
54
|
+
export interface CodemodeCall {
|
|
55
|
+
name: string;
|
|
56
|
+
status: CodemodeCallStatus;
|
|
57
|
+
durationMs: number;
|
|
58
|
+
}
|
|
59
|
+
export type CodemodeErrorKind =
|
|
60
|
+
/** The script threw or failed to parse. `name` and `stack` come from the script's error. */
|
|
61
|
+
"script"
|
|
62
|
+
/** The overall deadline expired. The worker was terminated. */
|
|
63
|
+
| "timeout"
|
|
64
|
+
/** The caller's signal fired or the sandbox was closed. The worker was terminated. */
|
|
65
|
+
| "aborted"
|
|
66
|
+
/** The worker or VM failed outside the script's control (for example a wasm trap or a missing worker file). */
|
|
67
|
+
| "sandbox";
|
|
68
|
+
export interface CodemodeError {
|
|
69
|
+
kind: CodemodeErrorKind;
|
|
70
|
+
name?: string;
|
|
71
|
+
message: string;
|
|
72
|
+
stack?: string;
|
|
73
|
+
}
|
|
74
|
+
/** Keys the script changed with `store()`. Only successful executions report writes. */
|
|
75
|
+
export interface CodemodeStoreWrites {
|
|
76
|
+
set: Record<string, unknown>;
|
|
77
|
+
/** Keys stored as `undefined`. */
|
|
78
|
+
delete: string[];
|
|
79
|
+
}
|
|
80
|
+
/** `output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`. */
|
|
81
|
+
export type CodemodeResult = {
|
|
82
|
+
ok: true;
|
|
83
|
+
value: unknown;
|
|
84
|
+
output: CodemodeOutputItem[];
|
|
85
|
+
calls: CodemodeCall[];
|
|
86
|
+
storeWrites: CodemodeStoreWrites;
|
|
87
|
+
} | {
|
|
88
|
+
ok: false;
|
|
89
|
+
error: CodemodeError;
|
|
90
|
+
output: CodemodeOutputItem[];
|
|
91
|
+
calls: CodemodeCall[];
|
|
92
|
+
};
|
|
93
|
+
export interface CodemodeSandboxOptions {
|
|
94
|
+
tools?: CodemodeTool[];
|
|
95
|
+
/**
|
|
96
|
+
* Functions exposed as top-level identifiers instead of on `tools`, for host helpers such as
|
|
97
|
+
* attaching an image to the result. They behave like tools (JSON round trip, promise result)
|
|
98
|
+
* but are not recorded in `result.calls`. Names must be identifiers and may not shadow the
|
|
99
|
+
* built-in globals (`tools`, `ALL_TOOLS`, `console`, `text`, `image`, `exit`, `store`, `load`).
|
|
100
|
+
*/
|
|
101
|
+
globals?: CodemodeTool[];
|
|
102
|
+
/**
|
|
103
|
+
* Overall deadline per execution, including time spent in tools. `Infinity` disables the
|
|
104
|
+
* deadline; the execution then only ends when the script settles or is aborted.
|
|
105
|
+
* Default: 300000.
|
|
106
|
+
*/
|
|
107
|
+
timeoutMs?: number;
|
|
108
|
+
/**
|
|
109
|
+
* Maximum memory the QuickJS VM may allocate. Allocations beyond it fail inside the script as
|
|
110
|
+
* `InternalError: out of memory`. Default: no limit beyond wasm32's 4 GiB address space.
|
|
111
|
+
*/
|
|
112
|
+
memoryLimitBytes?: number;
|
|
113
|
+
/**
|
|
114
|
+
* Compiled `quickjs-wasi/quickjs.wasm`, usually from {@link loadQuickJSWasm}. Default:
|
|
115
|
+
* `loadQuickJSWasm()`, the file in the installed `quickjs-wasi` package. Pass it when that file
|
|
116
|
+
* is not on disk, for example in a Bun compiled executable.
|
|
117
|
+
*/
|
|
118
|
+
wasm?: CodemodeWasmModule | Promise<CodemodeWasmModule>;
|
|
119
|
+
/**
|
|
120
|
+
* Worker entry that imports `@earendil-works/pi-codemode/worker`. Default: this package's own
|
|
121
|
+
* worker file. Pass it when this package is bundled, since the default is resolved relative to
|
|
122
|
+
* the module that creates the sandbox. Bun compiled executables require the relative string
|
|
123
|
+
* specifier of an embedded build entrypoint; other hosts usually use a URL.
|
|
124
|
+
*/
|
|
125
|
+
workerUrl?: string | URL;
|
|
126
|
+
}
|
|
127
|
+
export interface CodemodeExecuteOptions {
|
|
128
|
+
signal?: AbortSignal;
|
|
129
|
+
/** Overrides the sandbox default for this execution. */
|
|
130
|
+
timeoutMs?: number;
|
|
131
|
+
/**
|
|
132
|
+
* Values the script reads with `load(key)`. Must be JSON-serializable. The script's own
|
|
133
|
+
* `store()` calls come back as `result.storeWrites`; persisting them is up to the caller.
|
|
134
|
+
*/
|
|
135
|
+
store?: Readonly<Record<string, unknown>>;
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAEpD,MAAM,WAAW,mBAAmB;IACnC;;;OAGG;IACH,MAAM,EAAE,WAAW,CAAC;CACpB;AAED,qGAAqG;AACrG,MAAM,MAAM,kBAAkB,GAAG;IAAE,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CAAE,GAAG,OAAO,CAAC;AAEtE,MAAM,WAAW,YAAY;IAC5B;;;;;OAKG;IACH,IAAI,EAAE,MAAM,CAAC;IACb,iGAAiG;IACjG,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6FAA6F;IAC7F,WAAW,CAAC,EAAE,kBAAkB,CAAC;IACjC,0FAA0F;IAC1F,YAAY,CAAC,EAAE,kBAAkB,CAAC;IAClC,gGAAgG;IAChG,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,C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E,CAAA;CAAE,CAAC;AAE5F,MAAM,WAAW,sBAAsB;IACtC,KAAK,CAAC,EAAE,YAAY,EAAE,CAAC;IACvB;;;;;OAKG;IACH,OAAO,CAAC,EAAE,YAAY,EAAE,CAAC;IACzB;;;;OAIG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;OAIG;IACH,IAAI,CAAC,EAAE,kBAAkB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAC;IACxD;;;;;OAKG;IACH,SAAS,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;CACzB;AAED,MAAM,WAAW,sBAAsB;IACtC,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,wDAAwD;IACxD,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;OAGG;IACH,KAAK,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC1C"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { CodemodeWasmModule } from \"./wasm.ts\";\n\nexport interface CodemodeToolContext {\n\t/**\n\t * Aborted when the script finishes (including unawaited calls), the\n\t * execution times out, the caller aborts, or the sandbox is closed.\n\t */\n\tsignal: AbortSignal;\n}\n\n/** A JSON Schema document. Only used to render declarations; values are not validated against it. */\nexport type CodemodeJsonSchema = { [key: string]: unknown } | boolean;\n\nexport interface CodemodeTool {\n\t/**\n\t * The script calls tools as `tools.<id>(args)`, where `<id>` is the name with characters that\n\t * are not valid in identifiers replaced by `_` (see `toCodemodeIdentifier`), and also as\n\t * `tools[\"<name>\"](args)`. Globals are called as `<name>(args)` and must be identifiers, or\n\t * `<namespace>.<member>`, which groups them into a frozen namespace object.\n\t */\n\tname: string;\n\t/** Shown as a doc comment in {@link renderDeclarations}, and listed in `ALL_TOOLS` for tools. */\n\tdescription?: string;\n\t/** Schema of the single argument. Rendered as the parameter type; `unknown` when omitted. */\n\tinputSchema?: CodemodeJsonSchema;\n\t/** Schema of the resolved value. Rendered as the promise type; `unknown` when omitted. */\n\toutputSchema?: CodemodeJsonSchema;\n\t/** Globals only: `execute` receives all call arguments as an array instead of the first one. */\n\tspread?: boolean;\n\t/**\n\t * Globals only: TypeScript parameter list and return type for {@link renderDeclarations}, for\n\t * example `(type: string, id?: string): Promise<Model[]>`. Replaces the rendering from the schemas.\n\t */\n\tsignature?: string;\n\t/**\n\t * `args` is whatever the script passed, after a JSON round trip. The return\n\t * value must be JSON-serializable; a thrown error surfaces in the script as\n\t * an `Error` with the same message.\n\t */\n\texecute(args: unknown, context: CodemodeToolContext): Promise<unknown> | unknown;\n}\n\n/**\n * One item of the script's output, in the order the script produced it: `text()` and `console.*`\n * produce text items, `image()` image items. `data` is base64.\n */\nexport type CodemodeOutputItem = { type: \"text\"; text: string } | { type: \"image\"; data: string; mimeType: string };\n\nexport type CodemodeCallStatus = \"ok\" | \"error\" | \"cancelled\";\n\nexport interface CodemodeCall {\n\tname: string;\n\tstatus: CodemodeCallStatus;\n\tdurationMs: number;\n}\n\nexport type CodemodeErrorKind =\n\t/** The script threw or failed to parse. `name` and `stack` come from the script's error. */\n\t| \"script\"\n\t/** The overall deadline expired. The worker was terminated. */\n\t| \"timeout\"\n\t/** The caller's signal fired or the sandbox was closed. The worker was terminated. */\n\t| \"aborted\"\n\t/** The worker or VM failed outside the script's control (for example a wasm trap or a missing worker file). */\n\t| \"sandbox\";\n\nexport interface CodemodeError {\n\tkind: CodemodeErrorKind;\n\tname?: string;\n\tmessage: string;\n\tstack?: string;\n}\n\n/** Keys the script changed with `store()`. Only successful executions report writes. */\nexport interface CodemodeStoreWrites {\n\tset: Record<string, unknown>;\n\t/** Keys stored as `undefined`. */\n\tdelete: string[];\n}\n\n/** `output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`. */\nexport type CodemodeResult =\n\t| {\n\t\t\tok: true;\n\t\t\tvalue: unknown;\n\t\t\toutput: CodemodeOutputItem[];\n\t\t\tcalls: CodemodeCall[];\n\t\t\tstoreWrites: CodemodeStoreWrites;\n\t }\n\t| { ok: false; error: CodemodeError; output: CodemodeOutputItem[]; calls: CodemodeCall[] };\n\nexport interface CodemodeSandboxOptions {\n\ttools?: CodemodeTool[];\n\t/**\n\t * Functions exposed as top-level identifiers instead of on `tools`, for host helpers such as\n\t * attaching an image to the result. They behave like tools (JSON round trip, promise result)\n\t * but are not recorded in `result.calls`. Names must be identifiers and may not shadow the\n\t * built-in globals (`tools`, `ALL_TOOLS`, `console`, `text`, `image`, `exit`, `store`, `load`).\n\t */\n\tglobals?: CodemodeTool[];\n\t/**\n\t * Overall deadline per execution, including time spent in tools. `Infinity` disables the\n\t * deadline; the execution then only ends when the script settles or is aborted.\n\t * Default: 300000.\n\t */\n\ttimeoutMs?: number;\n\t/**\n\t * Maximum memory the QuickJS VM may allocate. Allocations beyond it fail inside the script as\n\t * `InternalError: out of memory`. Default: no limit beyond wasm32's 4 GiB address space.\n\t */\n\tmemoryLimitBytes?: number;\n\t/**\n\t * Compiled `quickjs-wasi/quickjs.wasm`, usually from {@link loadQuickJSWasm}. Default:\n\t * `loadQuickJSWasm()`, the file in the installed `quickjs-wasi` package. Pass it when that file\n\t * is not on disk, for example in a Bun compiled executable.\n\t */\n\twasm?: CodemodeWasmModule | Promise<CodemodeWasmModule>;\n\t/**\n\t * Worker entry that imports `@earendil-works/pi-codemode/worker`. Default: this package's own\n\t * worker file. Pass it when this package is bundled, since the default is resolved relative to\n\t * the module that creates the sandbox. Bun compiled executables require the relative string\n\t * specifier of an embedded build entrypoint; other hosts usually use a URL.\n\t */\n\tworkerUrl?: string | URL;\n}\n\nexport interface CodemodeExecuteOptions {\n\tsignal?: AbortSignal;\n\t/** Overrides the sandbox default for this execution. */\n\ttimeoutMs?: number;\n\t/**\n\t * Values the script reads with `load(key)`. Must be JSON-serializable. The script's own\n\t * `store()` calls come back as `result.storeWrites`; persisting them is up to the caller.\n\t */\n\tstore?: Readonly<Record<string, unknown>>;\n}\n"]}
|
package/dist/wasm.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A compiled `WebAssembly.Module` of `quickjs-wasi/quickjs.wasm`. Typed opaquely because the Node
|
|
3
|
+
* type definitions do not declare the WebAssembly globals (they live in the DOM lib).
|
|
4
|
+
*/
|
|
5
|
+
export type CodemodeWasmModule = object;
|
|
6
|
+
/**
|
|
7
|
+
* Read and compile the QuickJS wasm once per path. `path` defaults to the file in the installed
|
|
8
|
+
* `quickjs-wasi` package; pass it when that file lives elsewhere, for example embedded in a Bun
|
|
9
|
+
* compiled executable. A failed load is retried on the next call.
|
|
10
|
+
*/
|
|
11
|
+
export declare function loadQuickJSWasm(path?: string): Promise<CodemodeWasmModule>;
|
|
12
|
+
//# sourceMappingURL=wasm.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wasm.d.ts","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAGA;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC;AAQxC;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAc1E"}
|
package/dist/wasm.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
const modules = new Map();
|
|
4
|
+
/**
|
|
5
|
+
* Read and compile the QuickJS wasm once per path. `path` defaults to the file in the installed
|
|
6
|
+
* `quickjs-wasi` package; pass it when that file lives elsewhere, for example embedded in a Bun
|
|
7
|
+
* compiled executable. A failed load is retried on the next call.
|
|
8
|
+
*/
|
|
9
|
+
export function loadQuickJSWasm(path) {
|
|
10
|
+
const resolved = path ?? createRequire(import.meta.url).resolve("quickjs-wasi/quickjs.wasm");
|
|
11
|
+
let module = modules.get(resolved);
|
|
12
|
+
if (!module) {
|
|
13
|
+
const { WebAssembly } = globalThis;
|
|
14
|
+
module = readFile(resolved)
|
|
15
|
+
.then((bytes) => WebAssembly.compile(bytes))
|
|
16
|
+
.catch((error) => {
|
|
17
|
+
modules.delete(resolved);
|
|
18
|
+
throw error;
|
|
19
|
+
});
|
|
20
|
+
modules.set(resolved, module);
|
|
21
|
+
}
|
|
22
|
+
return module;
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=wasm.js.map
|
package/dist/wasm.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"wasm.js","sourceRoot":"","sources":["../src/wasm.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAY5C,MAAM,OAAO,GAAG,IAAI,GAAG,EAAuC,CAAC;AAE/D;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAAC,IAAa;IAC5C,MAAM,QAAQ,GAAG,IAAI,IAAI,aAAa,CAAC,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,2BAA2B,CAAC,CAAC;IAC7F,IAAI,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACnC,IAAI,CAAC,MAAM,EAAE,CAAC;QACb,MAAM,EAAE,WAAW,EAAE,GAAG,UAA2D,CAAC;QACpF,MAAM,GAAG,QAAQ,CAAC,QAAQ,CAAC;aACzB,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,WAAW,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;aAC3C,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;YACzB,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YACzB,MAAM,KAAK,CAAC;QACb,CAAC,CAAC,CAAC;QACJ,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAC/B,CAAC;IACD,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import { readFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\n\n/**\n * A compiled `WebAssembly.Module` of `quickjs-wasi/quickjs.wasm`. Typed opaquely because the Node\n * type definitions do not declare the WebAssembly globals (they live in the DOM lib).\n */\nexport type CodemodeWasmModule = object;\n\ninterface WebAssemblyGlobal {\n\tcompile(bytes: Uint8Array): Promise<CodemodeWasmModule>;\n}\n\nconst modules = new Map<string, Promise<CodemodeWasmModule>>();\n\n/**\n * Read and compile the QuickJS wasm once per path. `path` defaults to the file in the installed\n * `quickjs-wasi` package; pass it when that file lives elsewhere, for example embedded in a Bun\n * compiled executable. A failed load is retried on the next call.\n */\nexport function loadQuickJSWasm(path?: string): Promise<CodemodeWasmModule> {\n\tconst resolved = path ?? createRequire(import.meta.url).resolve(\"quickjs-wasi/quickjs.wasm\");\n\tlet module = modules.get(resolved);\n\tif (!module) {\n\t\tconst { WebAssembly } = globalThis as unknown as { WebAssembly: WebAssemblyGlobal };\n\t\tmodule = readFile(resolved)\n\t\t\t.then((bytes) => WebAssembly.compile(bytes))\n\t\t\t.catch((error: unknown) => {\n\t\t\t\tmodules.delete(resolved);\n\t\t\t\tthrow error;\n\t\t\t});\n\t\tmodules.set(resolved, module);\n\t}\n\treturn module;\n}\n"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@fractaal/pi-codemode",
|
|
3
|
+
"version": "0.86.0",
|
|
4
|
+
"description": "Sandboxed JavaScript execution where the only capability is calling injected tools",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"source": "./src/index.ts",
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./declarations": {
|
|
15
|
+
"source": "./src/declarations.ts",
|
|
16
|
+
"types": "./dist/declarations.d.ts",
|
|
17
|
+
"import": "./dist/declarations.js"
|
|
18
|
+
},
|
|
19
|
+
"./source": {
|
|
20
|
+
"source": "./src/source.ts",
|
|
21
|
+
"types": "./dist/source.d.ts",
|
|
22
|
+
"import": "./dist/source.js"
|
|
23
|
+
},
|
|
24
|
+
"./worker": {
|
|
25
|
+
"source": "./src/runtime/worker.ts",
|
|
26
|
+
"types": "./dist/runtime/worker.d.ts",
|
|
27
|
+
"import": "./dist/runtime/worker.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"README.md"
|
|
33
|
+
],
|
|
34
|
+
"scripts": {
|
|
35
|
+
"clean": "shx rm -rf dist",
|
|
36
|
+
"build": "tsc -p tsconfig.build.json",
|
|
37
|
+
"test": "vitest --run",
|
|
38
|
+
"prepublishOnly": "npm run clean && npm run build"
|
|
39
|
+
},
|
|
40
|
+
"keywords": [
|
|
41
|
+
"pi",
|
|
42
|
+
"codemode",
|
|
43
|
+
"sandbox",
|
|
44
|
+
"quickjs",
|
|
45
|
+
"wasm"
|
|
46
|
+
],
|
|
47
|
+
"author": "Earendil Works",
|
|
48
|
+
"license": "MIT",
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "git+https://github.com/fractaal/pi.git",
|
|
52
|
+
"directory": "packages/codemode"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=22.19.0"
|
|
56
|
+
},
|
|
57
|
+
"dependencies": {
|
|
58
|
+
"quickjs-wasi": "3.6.2"
|
|
59
|
+
},
|
|
60
|
+
"devDependencies": {
|
|
61
|
+
"shx": "0.4.0",
|
|
62
|
+
"vitest": "4.1.11"
|
|
63
|
+
},
|
|
64
|
+
"homepage": "https://github.com/fractaal/pi",
|
|
65
|
+
"bugs": {
|
|
66
|
+
"url": "https://github.com/fractaal/pi/issues"
|
|
67
|
+
}
|
|
68
|
+
}
|