@ny4n/codemode 1.1.0 → 1.3.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/LICENSE +1 -0
- package/README.md +56 -7
- package/dist/declarations.d.ts +6 -21
- package/dist/declarations.d.ts.map +1 -1
- package/dist/declarations.js +100 -122
- package/dist/declarations.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/portable.d.ts +1 -1
- package/dist/portable.d.ts.map +1 -1
- package/dist/portable.js.map +1 -1
- package/dist/runtime/execution.d.ts +14 -2
- package/dist/runtime/execution.d.ts.map +1 -1
- package/dist/runtime/execution.js +158 -35
- package/dist/runtime/execution.js.map +1 -1
- package/dist/runtime/host.d.ts.map +1 -1
- package/dist/runtime/host.js +25 -11
- package/dist/runtime/host.js.map +1 -1
- package/dist/runtime/inline.d.ts.map +1 -1
- package/dist/runtime/inline.js +1 -0
- package/dist/runtime/inline.js.map +1 -1
- package/dist/runtime/prelude-source.d.ts +3 -1
- package/dist/runtime/prelude-source.d.ts.map +1 -1
- package/dist/runtime/prelude-source.js +16 -6
- package/dist/runtime/prelude-source.js.map +1 -1
- package/dist/runtime/protocol.d.ts +38 -3
- package/dist/runtime/protocol.d.ts.map +1 -1
- package/dist/runtime/protocol.js +6 -1
- package/dist/runtime/protocol.js.map +1 -1
- package/dist/runtime/remote.d.ts.map +1 -1
- package/dist/runtime/remote.js +5 -0
- package/dist/runtime/remote.js.map +1 -1
- package/dist/runtime/vm.d.ts +2 -0
- package/dist/runtime/vm.d.ts.map +1 -1
- package/dist/runtime/vm.js +131 -9
- package/dist/runtime/vm.js.map +1 -1
- package/dist/search.d.ts +33 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +112 -0
- package/dist/search.js.map +1 -0
- package/dist/source.d.ts +2 -1
- package/dist/source.d.ts.map +1 -1
- package/dist/source.js +8 -2
- package/dist/source.js.map +1 -1
- package/dist/types.d.ts +102 -4
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +6 -1
package/dist/source.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source.js","sourceRoot":"","sources":["../src/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,MAAM,CAAC,MAAM,uBAAuB,GAAG,cAAc,CAAC;AAEtD,MAAM,gBAAgB,GAAG,CAAC,mBAAmB,EAAE,YAAY,CAAU,CAAC;AACtE,MAAM,qBAAqB,GAAG,sCAAsC,CAAC;AACrE,sEAAsE;AACtE,MAAM,cAAc,GAAG,aAAa,CAAC;AAErC;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC,GAAG,CAAA;;;;;;;;CAQhD,CAAC;AAeF,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC7C,YAAY,OAAe;QAC1B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACnC,CAAC;CACD;AAED,SAAS,aAAa,CAAC,KAAc;IACpC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,MAAM,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC;AAC/E,CAAC;AAED,SAAS,YAAY,CAAC,SAAiB;IACtC,IAAI,SAAS,KAAK,EAAE,EAAE,CAAC;QACtB,MAAM,IAAI,mBAAmB,CAAC,wDAAwD,qBAAqB,EAAE,CAAC,CAAC;IAChH,CAAC;IACD,IAAI,KAAc,CAAC;IACnB,IAAI,CAAC;QACJ,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;IAC/B,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,IAAI,mBAAmB,CAC5B,qDAAqD,qBAAqB,KAAK,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KA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,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAChC,MAAM,SAAS,GAAG,KAAK,CAAC,SAAS,CAChC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,GAAG,CAAC,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC,UAAU,CAAC,uBAAuB,CAAC,CAClF,CAAC;IACF,IAAI,SAAS,KAAK,CAAC,CAAC,EAAE,CAAC;QACtB,MAAM,IAAI,mBAAmB,CAC5B,OAAO,uBAAuB,gEAAgE,SAAS,GAAG,CAAC,EAAE,CAC7G,CAAC;IACH,CAAC;IACD,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;IACpC,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;IAC9C,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, invalid options, and an options line that is not the\n * first line, which would otherwise be ignored without notice.\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 lines = input.split(\"\\n\");\n\tconst misplaced = lines.findIndex(\n\t\t(line, index) => index > 0 && line.trimStart().startsWith(CODEMODE_OPTIONS_PREFIX),\n\t);\n\tif (misplaced !== -1) {\n\t\tthrow new CodemodeSourceError(\n\t\t\t`The ${CODEMODE_OPTIONS_PREFIX} line must be the first line of the input; found one on line ${misplaced + 1}`,\n\t\t);\n\t}\n\tconst newline = input.indexOf(\"\\n\");\n\tconst firstLine = lines[0].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
CHANGED
|
@@ -61,11 +61,11 @@ export type CodemodeErrorKind =
|
|
|
61
61
|
/** The script threw or failed to parse. `name` and `stack` come from the script's error. */
|
|
62
62
|
"script"
|
|
63
63
|
/**
|
|
64
|
-
* The overall deadline expired, or a VM on the calling thread used up its interrupt budget.
|
|
65
|
-
* was
|
|
64
|
+
* The overall deadline expired, or a VM on the calling thread used up its interrupt budget.
|
|
65
|
+
* The execution ended and the VM was asked to stop; a worker or remote VM may still be computing.
|
|
66
66
|
*/
|
|
67
67
|
| "timeout"
|
|
68
|
-
/** The caller's signal fired or the sandbox was closed. The VM was
|
|
68
|
+
/** The caller's signal fired or the sandbox was closed. The execution ended and the VM was asked to stop. */
|
|
69
69
|
| "aborted"
|
|
70
70
|
/**
|
|
71
71
|
* The VM or its transport failed outside the script's control (for example a wasm trap, a missing
|
|
@@ -84,18 +84,24 @@ export interface CodemodeStoreWrites {
|
|
|
84
84
|
/** Keys stored as `undefined`. */
|
|
85
85
|
delete: string[];
|
|
86
86
|
}
|
|
87
|
-
/**
|
|
87
|
+
/**
|
|
88
|
+
* `output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`.
|
|
89
|
+
* `during`: in a {@link CodemodeSandboxBase.start} run that the script itself ended (it returned, threw, or exited),
|
|
90
|
+
* the result being processed when it did.
|
|
91
|
+
*/
|
|
88
92
|
export type CodemodeResult = {
|
|
89
93
|
ok: true;
|
|
90
94
|
value: unknown;
|
|
91
95
|
output: CodemodeOutputItem[];
|
|
92
96
|
calls: CodemodeCall[];
|
|
93
97
|
storeWrites: CodemodeStoreWrites;
|
|
98
|
+
during?: CodemodeDuring;
|
|
94
99
|
} | {
|
|
95
100
|
ok: false;
|
|
96
101
|
error: CodemodeError;
|
|
97
102
|
output: CodemodeOutputItem[];
|
|
98
103
|
calls: CodemodeCall[];
|
|
104
|
+
during?: CodemodeDuring;
|
|
99
105
|
};
|
|
100
106
|
/** Options every sandbox accepts, wherever its VM runs. */
|
|
101
107
|
export interface CodemodeSandboxBaseOptions {
|
|
@@ -134,6 +140,98 @@ export interface CodemodeSandboxOptions extends CodemodeSandboxBaseOptions {
|
|
|
134
140
|
* specifier of an embedded build entrypoint; other hosts usually use a URL.
|
|
135
141
|
*/
|
|
136
142
|
workerUrl?: string | URL;
|
|
143
|
+
/**
|
|
144
|
+
* Synchronously reserves capacity immediately before creating each worker, after loading wasm.
|
|
145
|
+
* Throw to deny admission without starting a worker. Return a release callback, called once if
|
|
146
|
+
* worker construction fails or when the worker actually exits, not when the result settles.
|
|
147
|
+
* The release callback must not throw. Reservations can be shared across sandbox instances.
|
|
148
|
+
*/
|
|
149
|
+
acquireWorker?(): () => void;
|
|
150
|
+
/**
|
|
151
|
+
* Called once for each worker started by execute() or start(). `exited` resolves when that worker
|
|
152
|
+
* actually exits, which may be after the result and close() settle: on Bun a non-interruptible
|
|
153
|
+
* built-in can delay termination. Use it to keep the worker counted against host concurrency
|
|
154
|
+
* limits until it exits. A thrown callback error fails the execution and requests worker termination.
|
|
155
|
+
*/
|
|
156
|
+
onWorkerStarted?(exited: Promise<void>): void;
|
|
157
|
+
}
|
|
158
|
+
/** A call the script made in a {@link CodemodeSandboxBase.start} run, answered with `CodemodeRun.deliver()`. */
|
|
159
|
+
export interface CodemodeHostCall {
|
|
160
|
+
/** The VM's own number for the call, `1`, `2`, ... in the order the script made its calls (tools and globals). */
|
|
161
|
+
id: number;
|
|
162
|
+
target: "tool" | "global";
|
|
163
|
+
name: string;
|
|
164
|
+
/** What the script passed, after a JSON round trip; for spread globals the argument list. */
|
|
165
|
+
args: unknown;
|
|
166
|
+
}
|
|
167
|
+
/** A tool as a {@link CodemodeSandboxBase.start} run's script sees it: `tools.<name>` and its `ALL_TOOLS` entry. */
|
|
168
|
+
export interface CodemodeDeclaredTool {
|
|
169
|
+
name: string;
|
|
170
|
+
/**
|
|
171
|
+
* The identifier the script uses, `tools.<jsName>`. Default: `toCodemodeIdentifier(name)`. A host that replays a run
|
|
172
|
+
* passes the one the run started with, so a changed mapping cannot rename a tool under a resumed script.
|
|
173
|
+
*/
|
|
174
|
+
jsName?: string;
|
|
175
|
+
description?: string;
|
|
176
|
+
}
|
|
177
|
+
/** A global as a {@link CodemodeSandboxBase.start} run's script sees it; the same names as `globals` allow. */
|
|
178
|
+
export interface CodemodeDeclaredGlobal {
|
|
179
|
+
name: string;
|
|
180
|
+
spread?: boolean;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* A call's answer. A rejection becomes an `Error` with `message` in the script, carrying the own properties of
|
|
184
|
+
* `properties` (JSON values; `name`, `message`, and `stack` are ignored), for example `{ structuredOutput }`.
|
|
185
|
+
*/
|
|
186
|
+
export type CodemodeOutcome = {
|
|
187
|
+
ok: true;
|
|
188
|
+
value: unknown;
|
|
189
|
+
} | {
|
|
190
|
+
ok: false;
|
|
191
|
+
message: string;
|
|
192
|
+
properties?: Record<string, unknown>;
|
|
193
|
+
};
|
|
194
|
+
/** In a {@link CodemodeSandboxBase.start} run: the result the VM was processing when the script finished, 0 for its first run, and the calls issued by then. */
|
|
195
|
+
export interface CodemodeDuring {
|
|
196
|
+
seq: number;
|
|
197
|
+
issued: number;
|
|
198
|
+
}
|
|
199
|
+
export interface CodemodeRunOptions {
|
|
200
|
+
/** The VM clock's start, in ms since the epoch: `Date.now()` until the first result arrives. */
|
|
201
|
+
startedAt: number;
|
|
202
|
+
/** Seeds `Math.random()` and the VM's other randomness. A 32-bit unsigned integer. */
|
|
203
|
+
seed: number;
|
|
204
|
+
tools?: CodemodeDeclaredTool[];
|
|
205
|
+
globals?: CodemodeDeclaredGlobal[];
|
|
206
|
+
store?: Readonly<Record<string, unknown>>;
|
|
207
|
+
signal?: AbortSignal;
|
|
208
|
+
/** Deadline of this run in ms. Default: none (not the sandbox's default). */
|
|
209
|
+
timeoutMs?: number;
|
|
210
|
+
/** The VM's fingerprint, before the script runs and before any of its calls. */
|
|
211
|
+
onStarted?(fingerprint: string): void;
|
|
212
|
+
/** The script made a call. Answer it with `CodemodeRun.deliver()`, now or later. */
|
|
213
|
+
onCall(call: CodemodeHostCall): void;
|
|
214
|
+
/**
|
|
215
|
+
* The VM processed result `seq` (`0`: the script's first run, before any result) and waits again, having issued
|
|
216
|
+
* `issued` calls in total.
|
|
217
|
+
*/
|
|
218
|
+
onIdle?(seq: number, issued: number): void;
|
|
219
|
+
}
|
|
220
|
+
/** A running {@link CodemodeSandboxBase.start} execution. */
|
|
221
|
+
export interface CodemodeRun {
|
|
222
|
+
readonly result: Promise<CodemodeResult>;
|
|
223
|
+
/**
|
|
224
|
+
* Whether the run has its outcome: the script ended, timed out, or failed, or the run was aborted. Set when that is
|
|
225
|
+
* decided, before `result` settles; calls can no longer be answered. It does not mean the VM has exited.
|
|
226
|
+
*/
|
|
227
|
+
readonly finished: boolean;
|
|
228
|
+
/**
|
|
229
|
+
* Answer call `id` as result number `seq`. Results are numbered 1, 2, ... without gaps, and the VM applies them
|
|
230
|
+
* strictly in that order, whatever order they arrive in: after a gap it waits for the missing number. While it
|
|
231
|
+
* processes this one, its clock reads `now` (ms since the epoch), or the previous value if `now` is earlier.
|
|
232
|
+
* Throws for a call that is not waiting for an answer, a `seq` used before, or a `now` that is not finite.
|
|
233
|
+
*/
|
|
234
|
+
deliver(seq: number, now: number, id: number, outcome: CodemodeOutcome): void;
|
|
137
235
|
}
|
|
138
236
|
export interface CodemodeExecuteOptions {
|
|
139
237
|
signal?: AbortSignal;
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +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,CAAC;CACjF;AAED;;;GAGG;AACH,MAAM,MAAM,kBAAkB,GAC3B;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,IAAI,CAAA;CAAE,GAC9C;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,CAAC;AAErD,MAAM,MAAM,kBAAkB,GAAG,IAAI,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M,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC1C"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +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, with `console: true` for `console.*`, and `image()` image items. `data` is base64.\n */\nexport type CodemodeOutputItem =\n\t| { type: \"text\"; text: string; console?: true }\n\t| { 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/**\n\t * The overall deadline expired, or a VM on the calling thread used up its interrupt budget. The VM\n\t * was stopped.\n\t */\n\t| \"timeout\"\n\t/** The caller's signal fired or the sandbox was closed. The VM was stopped. */\n\t| \"aborted\"\n\t/**\n\t * The VM or its transport failed outside the script's control (for example a wasm trap, a missing\n\t * worker file, or a remote sandbox that failed).\n\t */\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\n/** Options every sandbox accepts, wherever its VM runs. */\nexport interface CodemodeSandboxBaseOptions {\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}\n\n/** Options of `CodemodeSandbox`, which runs each VM in a Node or Bun worker thread. */\nexport interface CodemodeSandboxOptions extends CodemodeSandboxBaseOptions {\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 `@ny4n/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"]}
|
|
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, with `console: true` for `console.*`, and `image()` image items. `data` is base64.\n */\nexport type CodemodeOutputItem =\n\t| { type: \"text\"; text: string; console?: true }\n\t| { 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/**\n\t * The overall deadline expired, or a VM on the calling thread used up its interrupt budget.\n\t * The execution ended and the VM was asked to stop; a worker or remote VM may still be computing.\n\t */\n\t| \"timeout\"\n\t/** The caller's signal fired or the sandbox was closed. The execution ended and the VM was asked to stop. */\n\t| \"aborted\"\n\t/**\n\t * The VM or its transport failed outside the script's control (for example a wasm trap, a missing\n\t * worker file, or a remote sandbox that failed).\n\t */\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/**\n * `output` is kept for failed executions too, up to the failure. `exit()` completes with `value: undefined`.\n * `during`: in a {@link CodemodeSandboxBase.start} run that the script itself ended (it returned, threw, or exited),\n * the result being processed when it did.\n */\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\t\tduring?: CodemodeDuring;\n\t }\n\t| {\n\t\t\tok: false;\n\t\t\terror: CodemodeError;\n\t\t\toutput: CodemodeOutputItem[];\n\t\t\tcalls: CodemodeCall[];\n\t\t\tduring?: CodemodeDuring;\n\t };\n\n/** Options every sandbox accepts, wherever its VM runs. */\nexport interface CodemodeSandboxBaseOptions {\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}\n\n/** Options of `CodemodeSandbox`, which runs each VM in a Node or Bun worker thread. */\nexport interface CodemodeSandboxOptions extends CodemodeSandboxBaseOptions {\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 `@ny4n/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\t/**\n\t * Synchronously reserves capacity immediately before creating each worker, after loading wasm.\n\t * Throw to deny admission without starting a worker. Return a release callback, called once if\n\t * worker construction fails or when the worker actually exits, not when the result settles.\n\t * The release callback must not throw. Reservations can be shared across sandbox instances.\n\t */\n\tacquireWorker?(): () => void;\n\t/**\n\t * Called once for each worker started by execute() or start(). `exited` resolves when that worker\n\t * actually exits, which may be after the result and close() settle: on Bun a non-interruptible\n\t * built-in can delay termination. Use it to keep the worker counted against host concurrency\n\t * limits until it exits. A thrown callback error fails the execution and requests worker termination.\n\t */\n\tonWorkerStarted?(exited: Promise<void>): void;\n}\n\n/** A call the script made in a {@link CodemodeSandboxBase.start} run, answered with `CodemodeRun.deliver()`. */\nexport interface CodemodeHostCall {\n\t/** The VM's own number for the call, `1`, `2`, ... in the order the script made its calls (tools and globals). */\n\tid: number;\n\ttarget: \"tool\" | \"global\";\n\tname: string;\n\t/** What the script passed, after a JSON round trip; for spread globals the argument list. */\n\targs: unknown;\n}\n\n/** A tool as a {@link CodemodeSandboxBase.start} run's script sees it: `tools.<name>` and its `ALL_TOOLS` entry. */\nexport interface CodemodeDeclaredTool {\n\tname: string;\n\t/**\n\t * The identifier the script uses, `tools.<jsName>`. Default: `toCodemodeIdentifier(name)`. A host that replays a run\n\t * passes the one the run started with, so a changed mapping cannot rename a tool under a resumed script.\n\t */\n\tjsName?: string;\n\tdescription?: string;\n}\n\n/** A global as a {@link CodemodeSandboxBase.start} run's script sees it; the same names as `globals` allow. */\nexport interface CodemodeDeclaredGlobal {\n\tname: string;\n\tspread?: boolean;\n}\n\n/**\n * A call's answer. A rejection becomes an `Error` with `message` in the script, carrying the own properties of\n * `properties` (JSON values; `name`, `message`, and `stack` are ignored), for example `{ structuredOutput }`.\n */\nexport type CodemodeOutcome =\n\t| { ok: true; value: unknown }\n\t| { ok: false; message: string; properties?: Record<string, unknown> };\n\n/** In a {@link CodemodeSandboxBase.start} run: the result the VM was processing when the script finished, 0 for its first run, and the calls issued by then. */\nexport interface CodemodeDuring {\n\tseq: number;\n\tissued: number;\n}\n\nexport interface CodemodeRunOptions {\n\t/** The VM clock's start, in ms since the epoch: `Date.now()` until the first result arrives. */\n\tstartedAt: number;\n\t/** Seeds `Math.random()` and the VM's other randomness. A 32-bit unsigned integer. */\n\tseed: number;\n\ttools?: CodemodeDeclaredTool[];\n\tglobals?: CodemodeDeclaredGlobal[];\n\tstore?: Readonly<Record<string, unknown>>;\n\tsignal?: AbortSignal;\n\t/** Deadline of this run in ms. Default: none (not the sandbox's default). */\n\ttimeoutMs?: number;\n\t/** The VM's fingerprint, before the script runs and before any of its calls. */\n\tonStarted?(fingerprint: string): void;\n\t/** The script made a call. Answer it with `CodemodeRun.deliver()`, now or later. */\n\tonCall(call: CodemodeHostCall): void;\n\t/**\n\t * The VM processed result `seq` (`0`: the script's first run, before any result) and waits again, having issued\n\t * `issued` calls in total.\n\t */\n\tonIdle?(seq: number, issued: number): void;\n}\n\n/** A running {@link CodemodeSandboxBase.start} execution. */\nexport interface CodemodeRun {\n\treadonly result: Promise<CodemodeResult>;\n\t/**\n\t * Whether the run has its outcome: the script ended, timed out, or failed, or the run was aborted. Set when that is\n\t * decided, before `result` settles; calls can no longer be answered. It does not mean the VM has exited.\n\t */\n\treadonly finished: boolean;\n\t/**\n\t * Answer call `id` as result number `seq`. Results are numbered 1, 2, ... without gaps, and the VM applies them\n\t * strictly in that order, whatever order they arrive in: after a gap it waits for the missing number. While it\n\t * processes this one, its clock reads `now` (ms since the epoch), or the previous value if `now` is earlier.\n\t * Throws for a call that is not waiting for an answer, a `seq` used before, or a `now` that is not finite.\n\t */\n\tdeliver(seq: number, now: number, id: number, outcome: CodemodeOutcome): void;\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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ny4n/codemode",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "Sandboxed JavaScript execution where the only capability is calling injected tools",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -21,6 +21,11 @@
|
|
|
21
21
|
"types": "./dist/source.d.ts",
|
|
22
22
|
"import": "./dist/source.js"
|
|
23
23
|
},
|
|
24
|
+
"./search": {
|
|
25
|
+
"source": "./src/search.ts",
|
|
26
|
+
"types": "./dist/search.d.ts",
|
|
27
|
+
"import": "./dist/search.js"
|
|
28
|
+
},
|
|
24
29
|
"./portable": {
|
|
25
30
|
"source": "./src/portable.ts",
|
|
26
31
|
"types": "./dist/portable.d.ts",
|