@opencode/codemode 2.2.6 → 2.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/README.md +115 -29
- package/dist/{vm/async.d.ts → async.d.ts} +1 -1
- package/dist/codemode.d.ts +13 -22
- package/dist/codemode.js +18 -39
- package/dist/data.d.ts +4 -19
- package/dist/data.js +1 -82
- package/dist/extension.d.ts +20 -1
- package/dist/extension.js +14 -1
- package/dist/{vm/host.d.ts → host.d.ts} +5 -2
- package/dist/{vm/host.js → host.js} +9 -4
- package/dist/index.d.ts +1 -1
- package/dist/{vm/opcodes.d.ts → opcodes.d.ts} +1 -1
- package/dist/{vm/prelude → prelude}/helpers.js +1 -1
- package/dist/{vm/runtime → runtime}/driver.d.ts +18 -8
- package/dist/{vm/runtime → runtime}/driver.js +90 -20
- package/dist/{vm/runtime → runtime}/errors.js +2 -2
- package/dist/{vm/runtime → runtime}/execute.d.ts +18 -9
- package/dist/{vm/runtime → runtime}/execute.js +45 -15
- package/dist/{vm/runtime → runtime}/extensions.d.ts +2 -2
- package/dist/{vm/runtime → runtime}/extensions.js +121 -19
- package/dist/{vm/runtime → runtime}/globals.js +1 -1
- package/dist/{vm/runtime → runtime}/interpreter.d.ts +4 -1
- package/dist/{vm/runtime → runtime}/interpreter.js +2 -0
- package/dist/{vm/runtime → runtime}/model.d.ts +1 -1
- package/dist/{vm/runtime → runtime}/objects.d.ts +1 -1
- package/dist/{vm/runtime → runtime}/objects.js +1 -1
- package/dist/{vm/runtime → runtime}/operations.d.ts +1 -1
- package/dist/{vm/runtime → runtime}/operations.js +1 -1
- package/dist/scan.js +2 -2
- package/dist/{vm/scheduler.d.ts → scheduler.d.ts} +16 -4
- package/dist/{vm/scheduler.js → scheduler.js} +13 -2
- package/dist/{vm/snapshot → snapshot}/codec.d.ts +37 -6
- package/dist/{vm/snapshot → snapshot}/codec.js +112 -8
- package/dist/{vm/snapshot → snapshot}/snapshot.d.ts +13 -6
- package/dist/{vm/snapshot → snapshot}/snapshot.js +19 -4
- package/dist/{vm/snapshot.js → snapshot.js} +5 -2
- package/dist/stdlib/array.d.ts +14 -9
- package/dist/stdlib/array.js +89 -276
- package/dist/stdlib/bytes.d.ts +11 -7
- package/dist/stdlib/bytes.js +112 -79
- package/dist/stdlib/collections.d.ts +7 -7
- package/dist/stdlib/collections.js +30 -339
- package/dist/stdlib/console.d.ts +2 -2
- package/dist/stdlib/console.js +3 -3
- package/dist/stdlib/date.d.ts +2 -2
- package/dist/stdlib/date.js +21 -30
- package/dist/stdlib/headers.d.ts +2 -2
- package/dist/stdlib/headers.js +15 -33
- package/dist/stdlib/iterator.d.ts +2 -2
- package/dist/stdlib/iterator.js +10 -303
- package/dist/stdlib/json.d.ts +2 -2
- package/dist/stdlib/json.js +15 -31
- package/dist/stdlib/math.d.ts +2 -7
- package/dist/stdlib/math.js +6 -30
- package/dist/stdlib/number.d.ts +3 -3
- package/dist/stdlib/number.js +8 -8
- package/dist/stdlib/object.d.ts +4 -4
- package/dist/stdlib/object.js +12 -30
- package/dist/stdlib/regexp.d.ts +6 -5
- package/dist/stdlib/regexp.js +18 -13
- package/dist/stdlib/string.d.ts +2 -2
- package/dist/stdlib/string.js +53 -53
- package/dist/stdlib/url.d.ts +21 -9
- package/dist/stdlib/url.js +55 -55
- package/dist/stdlib/value.d.ts +3 -4
- package/dist/stdlib/value.js +5 -6
- package/dist/stdlib/web.d.ts +4 -4
- package/dist/stdlib/web.js +7 -7
- package/dist/tool-runtime.d.ts +34 -12
- package/dist/tool-runtime.js +350 -68
- package/dist/tool-schema.d.ts +5 -0
- package/dist/tool-schema.js +36 -16
- package/dist/tool.d.ts +60 -2
- package/dist/tool.js +17 -1
- package/dist/{vm/vm.d.ts → vm.d.ts} +4 -3
- package/dist/{vm/vm.js → vm.js} +1 -1
- package/package.json +5 -7
- package/dist/interpreter/callback.d.ts +0 -24
- package/dist/interpreter/callback.js +0 -86
- package/dist/interpreter/errors.js +0 -173
- package/dist/interpreter/execute.d.ts +0 -14
- package/dist/interpreter/execute.js +0 -207
- package/dist/interpreter/extensions.d.ts +0 -9
- package/dist/interpreter/extensions.js +0 -248
- package/dist/interpreter/generators.d.ts +0 -3
- package/dist/interpreter/generators.js +0 -168
- package/dist/interpreter/globals.js +0 -144
- package/dist/interpreter/interpreter.d.ts +0 -48
- package/dist/interpreter/interpreter.js +0 -2253
- package/dist/interpreter/intrinsics.d.ts +0 -15
- package/dist/interpreter/intrinsics.js +0 -105
- package/dist/interpreter/model.d.ts +0 -68
- package/dist/interpreter/model.js +0 -54
- package/dist/interpreter/native.d.ts +0 -17
- package/dist/interpreter/native.js +0 -35
- package/dist/interpreter/objects.d.ts +0 -301
- package/dist/interpreter/objects.js +0 -592
- package/dist/interpreter/promises.d.ts +0 -18
- package/dist/interpreter/promises.js +0 -292
- package/dist/interpreter/runner.d.ts +0 -188
- package/dist/interpreter/runner.js +0 -492
- package/dist/interpreter/scope.d.ts +0 -16
- package/dist/interpreter/scope.js +0 -79
- package/dist/suspend-error.d.ts +0 -23
- package/dist/suspend-error.js +0 -25
- package/dist/vm/data.d.ts +0 -7
- package/dist/vm/data.js +0 -13
- package/dist/vm/index.d.ts +0 -6
- package/dist/vm/index.js +0 -6
- package/dist/vm/runtime/errors.d.ts +0 -23
- package/dist/vm/runtime/globals.d.ts +0 -6
- package/dist/vm/runtime/limits.d.ts +0 -10
- package/dist/vm/runtime/limits.js +0 -19
- package/dist/vm/runtime/modules.d.ts +0 -4
- package/dist/vm/runtime/modules.js +0 -33
- package/dist/vm/runtime/references.d.ts +0 -8
- package/dist/vm/runtime/references.js +0 -51
- package/dist/vm/stdlib/array.d.ts +0 -16
- package/dist/vm/stdlib/array.js +0 -311
- package/dist/vm/stdlib/bytes.d.ts +0 -11
- package/dist/vm/stdlib/bytes.js +0 -222
- package/dist/vm/stdlib/collections.d.ts +0 -7
- package/dist/vm/stdlib/collections.js +0 -188
- package/dist/vm/stdlib/console.d.ts +0 -6
- package/dist/vm/stdlib/console.js +0 -93
- package/dist/vm/stdlib/date.d.ts +0 -2
- package/dist/vm/stdlib/date.js +0 -123
- package/dist/vm/stdlib/headers.d.ts +0 -2
- package/dist/vm/stdlib/headers.js +0 -92
- package/dist/vm/stdlib/iterator.d.ts +0 -2
- package/dist/vm/stdlib/iterator.js +0 -30
- package/dist/vm/stdlib/json.d.ts +0 -3
- package/dist/vm/stdlib/json.js +0 -42
- package/dist/vm/stdlib/math.d.ts +0 -3
- package/dist/vm/stdlib/math.js +0 -73
- package/dist/vm/stdlib/number.d.ts +0 -3
- package/dist/vm/stdlib/number.js +0 -72
- package/dist/vm/stdlib/object.d.ts +0 -6
- package/dist/vm/stdlib/object.js +0 -201
- package/dist/vm/stdlib/regexp.d.ts +0 -8
- package/dist/vm/stdlib/regexp.js +0 -119
- package/dist/vm/stdlib/string.d.ts +0 -2
- package/dist/vm/stdlib/string.js +0 -272
- package/dist/vm/stdlib/url.d.ts +0 -25
- package/dist/vm/stdlib/url.js +0 -255
- package/dist/vm/stdlib/value.d.ts +0 -6
- package/dist/vm/stdlib/value.js +0 -32
- package/dist/vm/stdlib/web.d.ts +0 -5
- package/dist/vm/stdlib/web.js +0 -97
- /package/dist/{vm/async.js → async.js} +0 -0
- /package/dist/{vm/code.d.ts → code.d.ts} +0 -0
- /package/dist/{vm/code.js → code.js} +0 -0
- /package/dist/{vm/compiler → compiler}/compile.d.ts +0 -0
- /package/dist/{vm/compiler → compiler}/compile.js +0 -0
- /package/dist/{vm/compiler → compiler}/scope.d.ts +0 -0
- /package/dist/{vm/compiler → compiler}/scope.js +0 -0
- /package/dist/{vm/generators.d.ts → generators.d.ts} +0 -0
- /package/dist/{vm/generators.js → generators.js} +0 -0
- /package/dist/{vm/internal-prelude.d.ts → internal-prelude.d.ts} +0 -0
- /package/dist/{vm/internal-prelude.js → internal-prelude.js} +0 -0
- /package/dist/{vm/opcodes.js → opcodes.js} +0 -0
- /package/dist/{vm/prelude → prelude}/bytecode.d.ts +0 -0
- /package/dist/{vm/prelude → prelude}/bytecode.js +0 -0
- /package/dist/{vm/prelude → prelude}/bytecode.json +0 -0
- /package/dist/{vm/prelude → prelude}/helpers.d.ts +0 -0
- /package/dist/{vm/prelude → prelude}/prelude.d.ts +0 -0
- /package/dist/{vm/prelude → prelude}/prelude.js +0 -0
- /package/dist/{vm/prelude → prelude}/source.d.ts +0 -0
- /package/dist/{vm/prelude → prelude}/source.js +0 -0
- /package/dist/{vm/runtime → runtime}/callback.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/callback.js +0 -0
- /package/dist/{interpreter → runtime}/errors.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/generators.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/generators.js +0 -0
- /package/dist/{interpreter → runtime}/globals.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/intrinsic-names.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/intrinsic-names.js +0 -0
- /package/dist/{vm/runtime → runtime}/intrinsics.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/intrinsics.js +0 -0
- /package/dist/{interpreter → runtime}/limits.d.ts +0 -0
- /package/dist/{interpreter → runtime}/limits.js +0 -0
- /package/dist/{vm/runtime → runtime}/model.js +0 -0
- /package/dist/{interpreter → runtime}/modules.d.ts +0 -0
- /package/dist/{interpreter → runtime}/modules.js +0 -0
- /package/dist/{vm/runtime → runtime}/native.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/native.js +0 -0
- /package/dist/{vm/runtime → runtime}/promises.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/promises.js +0 -0
- /package/dist/{interpreter → runtime}/references.d.ts +0 -0
- /package/dist/{interpreter → runtime}/references.js +0 -0
- /package/dist/{vm/runtime → runtime}/signals.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/signals.js +0 -0
- /package/dist/{vm/runtime → runtime}/source.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/source.js +0 -0
- /package/dist/{vm/runtime → runtime}/table.d.ts +0 -0
- /package/dist/{vm/runtime → runtime}/table.js +0 -0
- /package/dist/{vm/snapshot.d.ts → snapshot.d.ts} +0 -0
package/README.md
CHANGED
|
@@ -61,6 +61,10 @@ only shape the model-visible signature. Without `output`, the signature uses `Pr
|
|
|
61
61
|
|
|
62
62
|
Descriptions and schemas are model-visible contracts. Authorization belongs in `execute`.
|
|
63
63
|
|
|
64
|
+
Set `freeform: true` on a tool whose input is one required string field to let programs pass that string directly. For
|
|
65
|
+
`{ patchText: string }`, the catalog shows `tools.patch(patchText: string)`, and `tools.patch("*** Begin Patch...")`
|
|
66
|
+
delivers `{ patchText: "*** Begin Patch..." }` to validation, hooks and the executor. The object form still works.
|
|
67
|
+
|
|
64
68
|
Nested records are the shorthand for ordinary namespaces. Use `Namespace.make` when a namespace needs a description:
|
|
65
69
|
|
|
66
70
|
```ts
|
|
@@ -90,22 +94,20 @@ runtime.execute(source) // Effect<CodeMode.Result, never, ToolServices>
|
|
|
90
94
|
```
|
|
91
95
|
|
|
92
96
|
The Effect environment is inferred from the supplied tools. `hooks` surround every call the program makes into the
|
|
93
|
-
host: `tool.before`/`tool.after` receive `{ name, input }` with decoded input
|
|
94
|
-
receive `{ extension, name, args }`. An `after` hook also
|
|
95
|
-
`failure` with its error, or `interrupted`). A `before` hook
|
|
96
|
-
denies it: the host function is never called, and the program
|
|
97
|
-
fails the way the call itself would: a tool call or asynchronous
|
|
98
|
-
throws.
|
|
99
|
-
|
|
100
|
-
### Bytecode VM and suspending/resuming a run (experimental, `engine: "vm"`)
|
|
97
|
+
host: `tool.before`/`tool.after` receive `{ name, input, key }` with decoded input and the call's `<runId>:<callId>`
|
|
98
|
+
idempotency key, and `extension.before`/`extension.after` receive `{ extension, name, args }`. An `after` hook also
|
|
99
|
+
receives how the call ended (`success` with its value, `failure` with its error, or `interrupted`). A `before` hook
|
|
100
|
+
runs before the call reaches the host, and a failing one denies it: the host function is never called, and the program
|
|
101
|
+
catches the failure as a thrown error. A denied call fails the way the call itself would: a tool call or asynchronous
|
|
102
|
+
global rejects its promise, and a synchronous global throws.
|
|
101
103
|
|
|
102
|
-
|
|
103
|
-
`"legacy"` AST interpreter. `runtime.execute(code, bindings?)` keeps the same `Effect<CodeMode.Result>` signature on
|
|
104
|
-
both engines.
|
|
104
|
+
### Suspending and resuming a run
|
|
105
105
|
|
|
106
|
-
|
|
107
|
-
`runtime.program(code, bindings?)` makes a `CodeMode.Program`, and nothing runs until `program.run()`.
|
|
108
|
-
|
|
106
|
+
`CodeMode.make` returns a `CodeMode.Runtime`, which can also run a program step by step:
|
|
107
|
+
`runtime.program(code, bindings?, { runId }?)` makes a `CodeMode.Program`, and nothing runs until `program.run()`. Every
|
|
108
|
+
host call gets a stable key `<runId>:<callId>` (using a generated UUID when `runId` is omitted), saved in the snapshot
|
|
109
|
+
and passed to tools as `execute(input, { key })` and to hooks as `call.key`. `run()` runs the program in the current
|
|
110
|
+
fiber until it ends or is suspended, and gives a `CodeMode.Outcome`: a `Result`, or:
|
|
109
111
|
|
|
110
112
|
```ts
|
|
111
113
|
type Suspended = {
|
|
@@ -113,13 +115,13 @@ type Suspended = {
|
|
|
113
115
|
state: CodeMode.Snapshot // JSON; CodeMode.toBytes / CodeMode.fromBytes convert it
|
|
114
116
|
}
|
|
115
117
|
|
|
116
|
-
const runtime = CodeMode.make({ tools
|
|
118
|
+
const runtime = CodeMode.make({ tools })
|
|
117
119
|
|
|
118
120
|
// inline
|
|
119
121
|
const outcome = yield* runtime.program(code).run()
|
|
120
122
|
|
|
121
123
|
// in the background, suspended from another fiber
|
|
122
|
-
const program = runtime.program(code)
|
|
124
|
+
const program = runtime.program(code, undefined, { runId: "run-1" })
|
|
123
125
|
const fiber = yield* Effect.forkChild(program.run())
|
|
124
126
|
const suspended = yield* program.suspend() // the same Suspended that run() returns
|
|
125
127
|
const outcome = yield* Fiber.join(fiber)
|
|
@@ -128,27 +130,80 @@ const outcome = yield* Fiber.join(fiber)
|
|
|
128
130
|
yield* runtime.resume(CodeMode.toBytes(suspended.state)).run()
|
|
129
131
|
```
|
|
130
132
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
133
|
+
A program runs once: running it again is a defect, so make another with `runtime.program` or
|
|
134
|
+
`runtime.resume`. `run()` owns the run's host calls: interrupting it interrupts the program and every call in progress
|
|
135
|
+
(and cancels any started durable tool work).
|
|
134
136
|
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
137
|
+
#### Idempotent and durable tools, and safe suspension
|
|
138
|
+
|
|
139
|
+
A tool's `execute` is either a plain function or wrapped with `Tool.idempotent` or `Tool.durable`:
|
|
140
|
+
|
|
141
|
+
```ts
|
|
142
|
+
// plain (default): a suspend is refused while it runs
|
|
143
|
+
Tool.make({
|
|
144
|
+
description: "...",
|
|
145
|
+
input: ...,
|
|
146
|
+
output: ...,
|
|
147
|
+
execute: (input, { key }) => compute(input),
|
|
148
|
+
})
|
|
149
|
+
|
|
150
|
+
// idempotent: safe to run again; interrupted on suspend, rerun on resume with the same key
|
|
151
|
+
Tool.make({
|
|
152
|
+
description: "...",
|
|
153
|
+
input: ...,
|
|
154
|
+
output: ...,
|
|
155
|
+
execute: Tool.idempotent((input, { key }) => Db.get(input.name)),
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
// durable: keeps running across a suspend, reconnected through its JSON data on resume
|
|
159
|
+
Tool.make({
|
|
160
|
+
description: "...",
|
|
161
|
+
input: ...,
|
|
162
|
+
output: ...,
|
|
163
|
+
execute: Tool.durable({
|
|
164
|
+
start: (input, { key }) => Jobs.submit(input, key).pipe(Effect.map((id) => ({ id }))),
|
|
165
|
+
wait: ({ id }, { key }) => Jobs.wait(id),
|
|
166
|
+
cancel: ({ id }) => Jobs.kill(id),
|
|
167
|
+
}),
|
|
168
|
+
})
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
- **Plain (`execute: (input, { key }) => ...`):** not durable. Suspend is refused while the call is running.
|
|
172
|
+
- **`Tool.idempotent(execute)`:** idempotent/read-only work safe to run again. If a suspend lands while the call is
|
|
173
|
+
running, the VM detaches and interrupts it without firing `tool.after`, saves the call in the snapshot as queued, and
|
|
174
|
+
re-runs it on resume with the same `key` without double-counting it against `maxToolCalls`.
|
|
175
|
+
- **`Tool.durable({ start, wait, cancel })`:** work that outlives a suspended run:
|
|
176
|
+
- `start(input, { key }) => Effect<Data /* Json */>` begins the work and returns JSON `data` (inferred into `wait`
|
|
177
|
+
and `cancel`);
|
|
178
|
+
- `wait(data, { key }) => Effect<Output>` connects to the running work and waits for its result;
|
|
179
|
+
- `cancel(data) => Effect<void>` stops the work when the run is interrupted for real or ends, never when it is
|
|
180
|
+
suspended.
|
|
181
|
+
|
|
182
|
+
While `start` is running, the call blocks suspend. Once `start` returns its JSON data, the call is in the `started`
|
|
183
|
+
state with its data saved in the snapshot, and suspend is allowed. `wait` is not tied to the program's JavaScript
|
|
184
|
+
`await`: the VM calls `wait(data)` right after `start` returns, and calls `wait(data)` again for every `started` call
|
|
185
|
+
right when `resume` starts, whatever the program does with the call's promise (whether it `await`s it immediately,
|
|
186
|
+
passes it to `Promise.all`, chains `.then`, or keeps the unawaited promise in a variable and awaits it later).
|
|
187
|
+
|
|
188
|
+
`program.suspend(options?)` saves the run's state and stops it at once, and `run()` returns the same `Suspended`.
|
|
189
|
+
Suspend is allowed only when every in-flight call is queued, `Tool.idempotent`, or `Tool.durable` in `started`. When
|
|
190
|
+
any other host call is in progress — a plain tool, a durable tool still in `start`, `search`, or an async or
|
|
191
|
+
synchronous extension call — `suspend` fails with a `CodeMode.SuspendError` naming each blocking call in `running` by
|
|
192
|
+
its `key` and `path` (`tools.x.y`, `search`, `fetch`), and the run goes on untouched. Tool calls queued but not started
|
|
193
|
+
don't block: they start on resume. Outcomes already waiting in the inbox are part of the state. A suspend after the run
|
|
194
|
+
ended gives its result; one issued before `run()` has started waits for it to start (and for ever if it never runs).
|
|
141
195
|
|
|
142
196
|
The suspend is immediate: the program shares the thread with the caller, so it is at a step boundary. Its checks, saving
|
|
143
197
|
the state, and checking it against `options.maxBytes` all happen before anything about the run changes, so a state that
|
|
144
198
|
can't be saved or is too large fails the suspend the same way.
|
|
145
199
|
|
|
146
200
|
A resumed run keeps the limits it was saved with: `timeoutMs` counts active time across every resume, and `maxToolCalls`
|
|
147
|
-
counts every call of the run. A state resumes only on the same build of this package and with the same
|
|
148
|
-
state is checked when the resumed program runs: its `run()`
|
|
149
|
-
resumed here or is malformed. Built-ins are saved by name and
|
|
201
|
+
counts every admitted call of the run. A state resumes only on the same build of this package and with the same
|
|
202
|
+
extensions (and the same extension `snapshot` hooks). The state is checked when the resumed program runs: its `run()`
|
|
203
|
+
fails with a `CodeMode.SnapshotError` when it can't be resumed here or is malformed. Built-ins are saved by name and
|
|
204
|
+
only their changes are copied.
|
|
150
205
|
|
|
151
|
-
Set `CODEMODE_ROUNDTRIP=1` (`bun run test:roundtrip`) to run the tests
|
|
206
|
+
Set `CODEMODE_ROUNDTRIP=1` (`bun run test:roundtrip`) to run the tests with every run saved to bytes and
|
|
152
207
|
restored into a brand-new runtime at every host call and every few steps.
|
|
153
208
|
|
|
154
209
|
### `Extension.make`
|
|
@@ -191,6 +246,37 @@ Every value crossing in either direction is converted, never shared: arguments c
|
|
|
191
246
|
copies, and a function inside a result is callable the same way. A global that shadows a built-in or another
|
|
192
247
|
extension throws at `CodeMode.make`.
|
|
193
248
|
|
|
249
|
+
Functions inside a result have no data form, so a suspended run loses them by default: after a resume, calling one
|
|
250
|
+
throws a `TypeError`. An extension can preserve them across suspend and resume with `snapshot` hooks. `encode` receives
|
|
251
|
+
a value one of the extension's functions returned, as the host function returned it, and returns plain data (JSON
|
|
252
|
+
values and `Uint8Array`s); on resume, `decode` receives that data once per value and returns a host value of the same
|
|
253
|
+
shape, whose functions the restored program copies call from then on:
|
|
254
|
+
|
|
255
|
+
```ts
|
|
256
|
+
const saved = Symbol("saved")
|
|
257
|
+
const makeResponse = (data: { url: string; body: Uint8Array }) => ({
|
|
258
|
+
[saved]: data,
|
|
259
|
+
url: data.url,
|
|
260
|
+
text: async () => new TextDecoder().decode(data.body),
|
|
261
|
+
bytes: async () => data.body,
|
|
262
|
+
})
|
|
263
|
+
const web = Extension.make({
|
|
264
|
+
name: "web",
|
|
265
|
+
globals: {
|
|
266
|
+
fetch: Extension.async(async (url: string) =>
|
|
267
|
+
makeResponse({ url, body: await (await globalThis.fetch(url)).bytes() }),
|
|
268
|
+
),
|
|
269
|
+
},
|
|
270
|
+
snapshot: {
|
|
271
|
+
encode: (value) => (value as { [saved]: { url: string; body: Uint8Array } })[saved],
|
|
272
|
+
decode: (data) => makeResponse(data as { url: string; body: Uint8Array }),
|
|
273
|
+
},
|
|
274
|
+
})
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
A suspend fails (and the run continues) when `encode` throws or returns non-plain data. A snapshot saved with an
|
|
278
|
+
extension's hooks resumes only in a runtime whose extension of the same name also provides `snapshot` hooks.
|
|
279
|
+
|
|
194
280
|
A global can also be an object of functions, such as `fs`. Every function reachable from it is an entry point like a
|
|
195
281
|
global, so calls fire the `extension` hooks with their path as the name (`fs.readFile`, `fs.promises.readFile`).
|
|
196
282
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Diagnostic } from "
|
|
1
|
+
import type { Diagnostic } from "./codemode.js";
|
|
2
2
|
import { type AstNode } from "./runtime/model.js";
|
|
3
3
|
import { type Callable, PromiseObj, type Value } from "./runtime/objects.js";
|
|
4
4
|
import { type Completion } from "./runtime/signals.js";
|
package/dist/codemode.d.ts
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { Effect, Schema } from "effect";
|
|
2
2
|
import type { Extension } from "./extension.js";
|
|
3
3
|
import { scanTools } from "./scan.js";
|
|
4
|
-
import { fromBytes, SnapshotError, SuspendError, toBytes } from "./suspend-error.js";
|
|
5
4
|
import { type Services, type ToolDescription, ToolRuntime } from "./tool-runtime.js";
|
|
6
5
|
import type { Tools } from "./tools.js";
|
|
7
|
-
import
|
|
6
|
+
import { SuspendError } from "./runtime/execute.js";
|
|
7
|
+
import { fromBytes, type Snapshot, SnapshotError, type SnapshotHeader, toBytes } from "./snapshot/snapshot.js";
|
|
8
8
|
export { fromBytes, scanTools, SnapshotError, SuspendError, toBytes };
|
|
9
|
-
export type
|
|
10
|
-
export type Snapshot = VmEngine.Snapshot;
|
|
9
|
+
export type { Snapshot, SnapshotHeader };
|
|
11
10
|
/** A tool call admitted during an execution. */
|
|
12
11
|
export type { CallResult, ExtensionInvocation, Hooks, ToolCall, ToolDescription, ToolInvocation, } from "./tool-runtime.js";
|
|
13
12
|
/** Signature-construction helpers for host-owned catalog instructions. */
|
|
@@ -32,9 +31,12 @@ export type ResolvedExecutionLimits = {
|
|
|
32
31
|
readonly maxToolCalls: number | undefined;
|
|
33
32
|
readonly maxOutputBytes: number | undefined;
|
|
34
33
|
};
|
|
35
|
-
/**
|
|
36
|
-
export type
|
|
37
|
-
/**
|
|
34
|
+
/** Options for `Runtime.program`. */
|
|
35
|
+
export type ProgramOptions = {
|
|
36
|
+
/** Names this run's host calls (`<runId>:<callId>`); a random UUID by default. */
|
|
37
|
+
readonly runId?: string;
|
|
38
|
+
};
|
|
39
|
+
/** How `program.suspend` saves a run's state. */
|
|
38
40
|
export type SuspendOptions = {
|
|
39
41
|
/** The most bytes a saved state may take; a larger one fails the suspend, and the run goes on. */
|
|
40
42
|
readonly maxBytes?: number;
|
|
@@ -49,11 +51,6 @@ export type Options<Provided extends Record<string, unknown> = {}, Extensions ex
|
|
|
49
51
|
extensions?: Extensions;
|
|
50
52
|
/** Resource limits enforced on each execution. Time counts active time only, across every resume of a run. */
|
|
51
53
|
limits?: ExecutionLimits;
|
|
52
|
-
/**
|
|
53
|
-
* Interpreter that runs programs. `"vm"` is the experimental bytecode VM, whose runtime (`VmRuntime`) can also
|
|
54
|
-
* suspend and resume runs; the default is `"legacy"`.
|
|
55
|
-
*/
|
|
56
|
-
engine?: Engine;
|
|
57
54
|
};
|
|
58
55
|
/** The Effect environment an execution needs: what the tools and the extensions' Effect globals require. */
|
|
59
56
|
export type Environment<Provided extends Record<string, unknown>, Extensions extends ReadonlyArray<Extension>> = Services<Provided> | Extension.Services<Extensions[number]>;
|
|
@@ -161,22 +158,19 @@ export declare const Result: Schema.Union<readonly [Schema.Struct<{
|
|
|
161
158
|
}>]>;
|
|
162
159
|
/** Result of executing a CodeMode program. Program failures are data, not Effect failures. */
|
|
163
160
|
export type Result = typeof Result.Type;
|
|
164
|
-
/** A run stopped by `program.suspend`: its whole state, to resume with `
|
|
161
|
+
/** A run stopped by `program.suspend`: its whole state, to resume with `Runtime.resume`. */
|
|
165
162
|
export type Suspended = {
|
|
166
163
|
readonly ok: "suspended";
|
|
167
164
|
readonly state: Snapshot;
|
|
168
165
|
};
|
|
169
166
|
/** How a run of a program ended: its result, or its saved state once suspended. */
|
|
170
167
|
export type Outcome = Result | Suspended;
|
|
171
|
-
/** Reusable confined runtime over explicit tools. */
|
|
168
|
+
/** Reusable confined runtime over explicit tools and extensions. */
|
|
172
169
|
export type Runtime<R = never> = {
|
|
173
170
|
readonly catalog: ReadonlyArray<ToolDescription>;
|
|
174
171
|
readonly execute: (code: string, bindings?: Readonly<Record<string, DataValue>>) => Effect.Effect<Result, never, R>;
|
|
175
|
-
};
|
|
176
|
-
/** A runtime on the bytecode VM (`engine: "vm"`, experimental): it can also suspend runs and resume them. */
|
|
177
|
-
export type VmRuntime<R = never> = Runtime<R> & {
|
|
178
172
|
/** A program ready to run once; nothing runs until `program.run()`. */
|
|
179
|
-
readonly program: (code: string, bindings?: Readonly<Record<string, DataValue
|
|
173
|
+
readonly program: (code: string, bindings?: Readonly<Record<string, DataValue>>, options?: ProgramOptions) => Program<R>;
|
|
180
174
|
/**
|
|
181
175
|
* A suspended run (its `state`, or that state as bytes) as a program to continue in this runtime, which must be the
|
|
182
176
|
* same build with the same extensions. The state is checked when it runs: `run()` fails with a `SnapshotError` when
|
|
@@ -185,7 +179,7 @@ export type VmRuntime<R = never> = Runtime<R> & {
|
|
|
185
179
|
readonly resume: (state: Snapshot | Uint8Array) => Program<R, SnapshotError>;
|
|
186
180
|
};
|
|
187
181
|
/**
|
|
188
|
-
* One run of a program
|
|
182
|
+
* One run of a program. `run()` runs it in the current fiber until it ends or is suspended, and owns its host
|
|
189
183
|
* calls: interrupting `run()` interrupts them. A program runs once: running it again is a defect.
|
|
190
184
|
*/
|
|
191
185
|
export type Program<R = never, E = never> = {
|
|
@@ -201,7 +195,4 @@ export type Program<R = never, E = never> = {
|
|
|
201
195
|
/** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
|
|
202
196
|
export declare const execute: <const Provided extends Record<string, unknown>, const Extensions extends ReadonlyArray<Extension> = []>(options: ExecuteOptions<Provided, Extensions>) => Effect.Effect<Result, never, Environment<Provided, Extensions>>;
|
|
203
197
|
/** Creates an Effect-native runtime over explicit, schema-described tools and extensions. */
|
|
204
|
-
export declare function make<const Provided extends Record<string, unknown> = {}, const Extensions extends ReadonlyArray<Extension> = []>(options: Options<Provided, Extensions> & {
|
|
205
|
-
engine: "vm";
|
|
206
|
-
}): VmRuntime<Environment<Provided, Extensions>>;
|
|
207
198
|
export declare function make<const Provided extends Record<string, unknown> = {}, const Extensions extends ReadonlyArray<Extension> = []>(options?: Options<Provided, Extensions>): Runtime<Environment<Provided, Extensions>>;
|
package/dist/codemode.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { Deferred, Effect, Exit, Schema } from "effect";
|
|
2
|
-
import { fromJson } from "./data.js";
|
|
3
|
-
import { executeProgram } from "./interpreter/execute.js";
|
|
4
|
-
import { extensionGlobals } from "./interpreter/extensions.js";
|
|
5
|
-
import { globalNames } from "./interpreter/globals.js";
|
|
6
2
|
import { scanTools } from "./scan.js";
|
|
7
|
-
import { fromBytes, SnapshotError, SuspendError, toBytes } from "./suspend-error.js";
|
|
8
3
|
import { ToolRuntime } from "./tool-runtime.js";
|
|
4
|
+
import { fromJson } from "./data.js";
|
|
5
|
+
import { finishExecution, resumeProgram, startProgram, SuspendError } from "./runtime/execute.js";
|
|
6
|
+
import { extensionGlobals } from "./runtime/extensions.js";
|
|
7
|
+
import { globalNames } from "./runtime/globals.js";
|
|
8
|
+
import { fromBytes, SnapshotError, toBytes } from "./snapshot/snapshot.js";
|
|
9
9
|
export { fromBytes, scanTools, SnapshotError, SuspendError, toBytes };
|
|
10
10
|
/** Signature-construction helpers for host-owned catalog instructions. */
|
|
11
11
|
export { searchSignature, toolExpression } from "./tool-runtime.js";
|
|
@@ -61,11 +61,11 @@ const resolveExecutionLimits = (limits) => ({
|
|
|
61
61
|
});
|
|
62
62
|
/** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
|
|
63
63
|
export const execute = (options) => make(options).execute(options.code, options.bindings);
|
|
64
|
+
/** Creates an Effect-native runtime over explicit, schema-described tools and extensions. */
|
|
64
65
|
export function make(options = {}) {
|
|
65
66
|
const prepared = ToolRuntime.prepare((options.tools ?? {}));
|
|
66
67
|
const limits = resolveExecutionLimits(options.limits);
|
|
67
68
|
const extensions = options.extensions ?? [];
|
|
68
|
-
// Both engines bind the same global names; test/engines.test.ts keeps them in step.
|
|
69
69
|
const bound = new Set(globalNames);
|
|
70
70
|
for (const extension of extensions) {
|
|
71
71
|
for (const name of Object.keys(extension.globals)) {
|
|
@@ -74,40 +74,28 @@ export function make(options = {}) {
|
|
|
74
74
|
bound.add(name);
|
|
75
75
|
}
|
|
76
76
|
}
|
|
77
|
-
|
|
78
|
-
return {
|
|
79
|
-
get catalog() {
|
|
80
|
-
return prepared.catalog;
|
|
81
|
-
},
|
|
82
|
-
execute: (code, bindings) => executeProgram(code, prepared, limits, options.hooks ?? {}, (ctx) => [
|
|
83
|
-
...Object.entries(bindings ?? {}).map(([name, value]) => [name, fromJson(ctx, value)]),
|
|
84
|
-
...extensionGlobals(ctx, extensions),
|
|
85
|
-
]),
|
|
86
|
-
};
|
|
87
|
-
}
|
|
88
|
-
let setup;
|
|
89
|
-
const getSetup = (vm) => (setup ??= {
|
|
77
|
+
const setup = {
|
|
90
78
|
prepared,
|
|
91
79
|
limits,
|
|
92
80
|
hooks: options.hooks ?? {},
|
|
93
|
-
globals: extensions.length === 0 ? undefined : (ctx) =>
|
|
94
|
-
lossy: extensions.
|
|
95
|
-
}
|
|
96
|
-
const data = (
|
|
81
|
+
globals: extensions.length === 0 ? undefined : (ctx) => extensionGlobals(ctx, extensions),
|
|
82
|
+
lossy: extensions.some((extension) => extension.snapshot === undefined),
|
|
83
|
+
};
|
|
84
|
+
const data = (bindings) => bindings === undefined
|
|
97
85
|
? undefined
|
|
98
|
-
: (ctx) => Object.entries(bindings).map(([name, value]) => [name,
|
|
99
|
-
const program = (code, bindings) =>
|
|
86
|
+
: (ctx) => Object.entries(bindings).map(([name, value]) => [name, fromJson(ctx, value)]);
|
|
87
|
+
const program = (code, bindings, programOptions) => makeProgram(() => Effect.succeed(startProgram(setup, code, data(bindings), programOptions?.runId)));
|
|
100
88
|
return {
|
|
101
89
|
get catalog() {
|
|
102
90
|
return prepared.catalog;
|
|
103
91
|
},
|
|
104
|
-
execute: (code, bindings) => Effect.
|
|
92
|
+
execute: (code, bindings) => Effect.suspend(() => finishExecution(program(code, bindings).run())),
|
|
105
93
|
program,
|
|
106
|
-
resume: (state) =>
|
|
94
|
+
resume: (state) => makeProgram(() => resumeProgram(setup, state)),
|
|
107
95
|
};
|
|
108
96
|
}
|
|
109
|
-
// A program's one run: `start` makes it
|
|
110
|
-
const
|
|
97
|
+
// A program's one run: `start` makes it when `run()` is called, and a suspend waits for it.
|
|
98
|
+
const makeProgram = (start) => {
|
|
111
99
|
let claimed = false;
|
|
112
100
|
const started = Deferred.makeUnsafe();
|
|
113
101
|
return {
|
|
@@ -116,7 +104,7 @@ const vmProgram = (start) => {
|
|
|
116
104
|
return Effect.die(new Error("A CodeMode program runs once; make another with runtime.program or runtime.resume."));
|
|
117
105
|
}
|
|
118
106
|
claimed = true;
|
|
119
|
-
return
|
|
107
|
+
return start().pipe(Effect.onExit((exit) => Exit.isSuccess(exit)
|
|
120
108
|
? Deferred.succeed(started, exit.value)
|
|
121
109
|
: Deferred.fail(started, new SuspendError({ message: "The program didn't start.", running: [] }))), Effect.flatMap((running) => running.run()));
|
|
122
110
|
}),
|
|
@@ -129,12 +117,3 @@ const vmProgram = (start) => {
|
|
|
129
117
|
},
|
|
130
118
|
};
|
|
131
119
|
};
|
|
132
|
-
// The VM is loaded on first use so the default engine pulls in none of its code.
|
|
133
|
-
let vmLoaded;
|
|
134
|
-
let vmEngine;
|
|
135
|
-
const loadVm = () => vmLoaded !== undefined
|
|
136
|
-
? Effect.succeed(vmLoaded)
|
|
137
|
-
: Effect.promise(() => (vmEngine ??= import("./vm/index.js").then((mod) => {
|
|
138
|
-
vmLoaded = mod;
|
|
139
|
-
return mod;
|
|
140
|
-
})));
|
package/dist/data.d.ts
CHANGED
|
@@ -1,21 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
import type {
|
|
3
|
-
import type
|
|
4
|
-
|
|
5
|
-
import { type Eval } from "./interpreter/runner.js";
|
|
6
|
-
export type Json = Schema.Json;
|
|
7
|
-
type Replacer = (args: Array<Value>, holder: Obj) => Eval<Value>;
|
|
8
|
-
/**
|
|
9
|
-
* What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and
|
|
10
|
-
* `undefined` vanish, non-finite numbers become null, and everything else is copied. Two departures from JS
|
|
11
|
-
* so a mistake is not a silent `{}`: an Error serializes as `{ name, message, ...own }`, and a promise throws.
|
|
12
|
-
*/
|
|
13
|
-
export declare const toJson: <R>(ctx: Interpreter<R>, value: Value, replacer?: Replacer) => Eval<Schema.Json | undefined>;
|
|
14
|
-
/**
|
|
15
|
-
* The host boundary: `toJson`, plus what a program most likely meant when a value cannot be JSON. A promise is
|
|
16
|
-
* awaited, a Set crosses as an array, a URLSearchParams as its query string, a Uint8Array asks to be encoded as
|
|
17
|
-
* text first, and a `__proto__` key is dropped so host code can never receive one.
|
|
18
|
-
*/
|
|
19
|
-
export declare const toBoundary: <R>(ctx: Interpreter<R>, value: Value) => Eval<Schema.Json | undefined>;
|
|
1
|
+
import type { Json } from "./snapshot/codec.js";
|
|
2
|
+
import type { Interpreter } from "./runtime/interpreter.js";
|
|
3
|
+
import { type Value } from "./runtime/objects.js";
|
|
4
|
+
export type { Json };
|
|
20
5
|
/** Host JSON as program values: objects and arrays are copied, primitives pass through. */
|
|
21
6
|
export declare const fromJson: <R>(ctx: Interpreter<R>, value: Json | undefined) => Value;
|
package/dist/data.js
CHANGED
|
@@ -1,85 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
import { MAX_VALUE_DEPTH } from "./interpreter/limits.js";
|
|
3
|
-
import { invalidData, rangeError, typeError } from "./interpreter/model.js";
|
|
4
|
-
import { Arr, Bytes, Callable, define, ErrorObj, get, keys, Obj, PromiseObj, record, SetObj, URLSearchParamsObj, HeadersObj, } from "./interpreter/objects.js";
|
|
5
|
-
import { typeofValue } from "./interpreter/references.js";
|
|
6
|
-
import { Slice } from "./interpreter/runner.js";
|
|
7
|
-
/**
|
|
8
|
-
* What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and
|
|
9
|
-
* `undefined` vanish, non-finite numbers become null, and everything else is copied. Two departures from JS
|
|
10
|
-
* so a mistake is not a silent `{}`: an Error serializes as `{ name, message, ...own }`, and a promise throws.
|
|
11
|
-
*/
|
|
12
|
-
export const toJson = (ctx, value, replacer) => walk(ctx, value, replacer, false);
|
|
13
|
-
/**
|
|
14
|
-
* The host boundary: `toJson`, plus what a program most likely meant when a value cannot be JSON. A promise is
|
|
15
|
-
* awaited, a Set crosses as an array, a URLSearchParams as its query string, a Uint8Array asks to be encoded as
|
|
16
|
-
* text first, and a `__proto__` key is dropped so host code can never receive one.
|
|
17
|
-
*/
|
|
18
|
-
export const toBoundary = (ctx, value) => walk(ctx, value, undefined, true);
|
|
19
|
-
const walk = (ctx, value, replacer, boundary) => {
|
|
20
|
-
const stack = new Set();
|
|
21
|
-
const visit = function* (holder, key, depth) {
|
|
22
|
-
// Shared references expand into a tree, so the work is not bounded by the value's size or depth.
|
|
23
|
-
if (ctx.runner.tick())
|
|
24
|
-
yield Slice;
|
|
25
|
-
if (depth > MAX_VALUE_DEPTH)
|
|
26
|
-
throw rangeError(`Value exceeds the maximum depth of ${MAX_VALUE_DEPTH}.`);
|
|
27
|
-
const raw = get(holder, key);
|
|
28
|
-
if (raw instanceof PromiseObj && !boundary) {
|
|
29
|
-
throw invalidData("JSON.stringify received an un-awaited Promise; await it first - e.g. `const result = await tools.ns.tool(...)`.");
|
|
30
|
-
}
|
|
31
|
-
const settled = raw instanceof PromiseObj ? yield* ctx.awaitValue(raw) : raw;
|
|
32
|
-
const toJSON = settled instanceof Obj ? get(settled, "toJSON") : undefined;
|
|
33
|
-
const own = toJSON instanceof Callable ? yield* ctx.call(toJSON, settled, [key]) : settled;
|
|
34
|
-
const value = replacer === undefined ? own : yield* replacer([key, own], holder);
|
|
35
|
-
if (value === undefined || typeofValue(value) === "function")
|
|
36
|
-
return undefined;
|
|
37
|
-
if (typeof value === "number")
|
|
38
|
-
return Number.isFinite(value) ? value : null;
|
|
39
|
-
if (value === null || typeof value === "string" || typeof value === "boolean")
|
|
40
|
-
return value;
|
|
41
|
-
if (!(value instanceof Obj))
|
|
42
|
-
return {};
|
|
43
|
-
if (boundary && value instanceof Bytes) {
|
|
44
|
-
throw invalidData("A Uint8Array cannot cross to the host; pass text instead, e.g. `new TextDecoder().decode(bytes)` or `bytes.toBase64()`.");
|
|
45
|
-
}
|
|
46
|
-
if (boundary && value instanceof URLSearchParamsObj)
|
|
47
|
-
return value.params.toString();
|
|
48
|
-
if (value instanceof HeadersObj)
|
|
49
|
-
return Object.fromEntries(value.headers);
|
|
50
|
-
const target = boundary && value instanceof SetObj ? new Arr(ctx.builtins.Array, [...value.set]) : value;
|
|
51
|
-
if (stack.has(target))
|
|
52
|
-
throw typeError("Converting circular structure to JSON.");
|
|
53
|
-
stack.add(target);
|
|
54
|
-
if (target instanceof Arr) {
|
|
55
|
-
const items = [];
|
|
56
|
-
for (let index = 0; index < target.items.length; index += 1) {
|
|
57
|
-
items.push((yield* visit(target, String(index), depth + 1)) ?? null);
|
|
58
|
-
}
|
|
59
|
-
stack.delete(target);
|
|
60
|
-
return items;
|
|
61
|
-
}
|
|
62
|
-
const copied = {};
|
|
63
|
-
// Own data property regardless of the key, so "__proto__" never reaches the Object.prototype setter.
|
|
64
|
-
const put = (name, item) => {
|
|
65
|
-
if (item !== undefined)
|
|
66
|
-
Object.defineProperty(copied, name, { value: item, enumerable: true, writable: true, configurable: true });
|
|
67
|
-
};
|
|
68
|
-
// Errors serialize as { name, message, ...own }: both may be inherited, and neither is enumerable in JS.
|
|
69
|
-
if (target instanceof ErrorObj) {
|
|
70
|
-
put("name", yield* visit(target, "name", depth + 1));
|
|
71
|
-
put("message", yield* visit(target, "message", depth + 1));
|
|
72
|
-
}
|
|
73
|
-
for (const name of keys(target)) {
|
|
74
|
-
if (boundary && name === "__proto__")
|
|
75
|
-
continue;
|
|
76
|
-
put(name, yield* visit(target, name, depth + 1));
|
|
77
|
-
}
|
|
78
|
-
stack.delete(target);
|
|
79
|
-
return copied;
|
|
80
|
-
};
|
|
81
|
-
return visit(record(ctx.builtins.Object, { "": value }), "", 0);
|
|
82
|
-
};
|
|
1
|
+
import { Arr, define, Obj } from "./runtime/objects.js";
|
|
83
2
|
/** Host JSON as program values: objects and arrays are copied, primitives pass through. */
|
|
84
3
|
export const fromJson = (ctx, value) => {
|
|
85
4
|
if (value === null || typeof value !== "object")
|
package/dist/extension.d.ts
CHANGED
|
@@ -11,11 +11,24 @@ import type { Effect } from "effect";
|
|
|
11
11
|
* promise of an asynchronous global and by throwing from a synchronous one. Functions inside a global object are
|
|
12
12
|
* called the same way, named by their path (`fs.readFile`).
|
|
13
13
|
*
|
|
14
|
-
* Programs can also `import` or `require` a global by its Node module name; see `
|
|
14
|
+
* Programs can also `import` or `require` a global by its Node module name; see `runtime/modules.ts`.
|
|
15
15
|
*/
|
|
16
16
|
export type Extension<Globals extends Readonly<Record<string, unknown>> = Readonly<Record<string, unknown>>> = {
|
|
17
17
|
readonly name: string;
|
|
18
18
|
readonly globals: Globals;
|
|
19
|
+
/** How a suspended run saves the values this extension's functions returned; see `Snapshot`. */
|
|
20
|
+
readonly snapshot?: Snapshot | undefined;
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* Lets a suspended run keep the functions inside values this extension's functions returned (a response's `text`,
|
|
24
|
+
* say). `encode` gets such a value, as the host function returned it, and gives plain data: JSON values and
|
|
25
|
+
* `Uint8Array`s. On resume, `decode` gets that data back, once per value, and gives a value of the same shape, whose
|
|
26
|
+
* functions the program's copies call from then on. Without it, those functions are lost on resume: calling one
|
|
27
|
+
* throws. A suspend fails, and the run goes on, when `encode` throws or gives anything else.
|
|
28
|
+
*/
|
|
29
|
+
export type Snapshot = {
|
|
30
|
+
readonly encode: (value: unknown) => unknown;
|
|
31
|
+
readonly decode: (data: unknown) => unknown;
|
|
19
32
|
};
|
|
20
33
|
/** The Effect environment required by an extension's Effect-returning functions, at the top level or one level in. */
|
|
21
34
|
export type Services<E> = E extends {
|
|
@@ -24,6 +37,12 @@ export type Services<E> = E extends {
|
|
|
24
37
|
type GlobalServices<Global> = Global extends (...args: never) => unknown ? Requirements<Global> : Global extends object ? Requirements<Global[keyof Global]> : never;
|
|
25
38
|
type Requirements<F> = F extends (...args: never) => infer Result ? Effect.Services<Result> : never;
|
|
26
39
|
export declare const make: <const Globals extends Readonly<Record<string, unknown>>>(options: Extension<Globals>) => Extension<Globals>;
|
|
40
|
+
/** A live fetch response whose I/O is owned by the host for the lifetime of the program. */
|
|
41
|
+
export declare class StreamingResponse {
|
|
42
|
+
readonly response: Response;
|
|
43
|
+
readonly redirected: boolean;
|
|
44
|
+
constructor(response: Response, redirected?: boolean);
|
|
45
|
+
}
|
|
27
46
|
/** Marks a global that returns a Promise or an Effect, so a denied call rejects its promise instead of throwing. */
|
|
28
47
|
export declare const async: <F extends Function>(global: F) => F;
|
|
29
48
|
export declare const isAsync: (global: Function) => boolean;
|
package/dist/extension.js
CHANGED
|
@@ -5,9 +5,22 @@ export const make = (options) => {
|
|
|
5
5
|
throw new TypeError(`Extension "${options.name}" global "${name}" must be a function or an object.`);
|
|
6
6
|
}
|
|
7
7
|
}
|
|
8
|
-
return {
|
|
8
|
+
return {
|
|
9
|
+
name: options.name,
|
|
10
|
+
globals: { ...options.globals },
|
|
11
|
+
...(options.snapshot === undefined ? {} : { snapshot: options.snapshot }),
|
|
12
|
+
};
|
|
9
13
|
};
|
|
10
14
|
const asyncGlobals = new WeakSet();
|
|
15
|
+
/** A live fetch response whose I/O is owned by the host for the lifetime of the program. */
|
|
16
|
+
export class StreamingResponse {
|
|
17
|
+
response;
|
|
18
|
+
redirected;
|
|
19
|
+
constructor(response, redirected = response.redirected) {
|
|
20
|
+
this.response = response;
|
|
21
|
+
this.redirected = redirected;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
11
24
|
const AsyncFunction = (async () => { }).constructor;
|
|
12
25
|
/** Marks a global that returns a Promise or an Effect, so a denied call rejects its promise instead of throwing. */
|
|
13
26
|
export const async = (global) => {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Diagnostic } from "
|
|
1
|
+
import type { Diagnostic } from "./codemode.js";
|
|
2
2
|
import { type Json } from "./data.js";
|
|
3
3
|
import type { Interpreter } from "./runtime/interpreter.js";
|
|
4
4
|
import { type AstNode } from "./runtime/model.js";
|
|
@@ -41,6 +41,8 @@ export declare const VISIT_BUDGET = 2048;
|
|
|
41
41
|
export declare class HostCalls {
|
|
42
42
|
private readonly ctx;
|
|
43
43
|
readonly promises: Promises;
|
|
44
|
+
/** Names this run's host calls (`<runId>:<callId>`). */
|
|
45
|
+
runId: string;
|
|
44
46
|
queued: Array<HostCall>;
|
|
45
47
|
readonly running: Map<number, HostCall>;
|
|
46
48
|
readonly inbox: Array<Delivery>;
|
|
@@ -52,8 +54,9 @@ export declare class HostCalls {
|
|
|
52
54
|
readonly call: HostCall;
|
|
53
55
|
readonly completion: Completion;
|
|
54
56
|
} | undefined;
|
|
55
|
-
/** The synchronous extension call the program is in the middle of: see `
|
|
57
|
+
/** The synchronous extension call the program is in the middle of: see `Vm.activeExtension`. */
|
|
56
58
|
extension: {
|
|
59
|
+
readonly key: string;
|
|
57
60
|
readonly path: string;
|
|
58
61
|
} | undefined;
|
|
59
62
|
extensionResume: ((completion: Completion) => HostResult) | undefined;
|