@opencode/codemode 2.2.5 → 2.2.7

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.
Files changed (142) hide show
  1. package/README.md +164 -7
  2. package/dist/codemode.d.ts +60 -4
  3. package/dist/codemode.js +63 -8
  4. package/dist/extension.d.ts +27 -9
  5. package/dist/extension.js +7 -3
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/interpreter/callback.d.ts +12 -1
  9. package/dist/interpreter/callback.js +13 -1
  10. package/dist/interpreter/execute.d.ts +1 -1
  11. package/dist/interpreter/execute.js +16 -4
  12. package/dist/interpreter/extensions.d.ts +3 -3
  13. package/dist/interpreter/extensions.js +17 -11
  14. package/dist/interpreter/globals.js +10 -0
  15. package/dist/interpreter/interpreter.d.ts +11 -1
  16. package/dist/interpreter/interpreter.js +88 -4
  17. package/dist/interpreter/modules.d.ts +4 -0
  18. package/dist/interpreter/modules.js +33 -0
  19. package/dist/interpreter/promises.js +2 -2
  20. package/dist/interpreter/runner.d.ts +1 -11
  21. package/dist/interpreter/runner.js +1 -13
  22. package/dist/stdlib/iterator.js +1 -2
  23. package/dist/suspend-error.d.ts +24 -0
  24. package/dist/suspend-error.js +25 -0
  25. package/dist/tool-runtime.d.ts +31 -7
  26. package/dist/tool-runtime.js +116 -26
  27. package/dist/tool.d.ts +45 -2
  28. package/dist/tool.js +30 -7
  29. package/dist/vm/async.d.ts +78 -0
  30. package/dist/vm/async.js +335 -0
  31. package/dist/vm/code.d.ts +122 -0
  32. package/dist/vm/code.js +407 -0
  33. package/dist/vm/compiler/compile.d.ts +13 -0
  34. package/dist/vm/compiler/compile.js +1477 -0
  35. package/dist/vm/compiler/scope.d.ts +74 -0
  36. package/dist/vm/compiler/scope.js +515 -0
  37. package/dist/vm/data.d.ts +7 -0
  38. package/dist/vm/data.js +13 -0
  39. package/dist/vm/generators.d.ts +42 -0
  40. package/dist/vm/generators.js +413 -0
  41. package/dist/vm/host.d.ts +106 -0
  42. package/dist/vm/host.js +231 -0
  43. package/dist/vm/index.d.ts +6 -0
  44. package/dist/vm/index.js +6 -0
  45. package/dist/vm/internal-prelude.d.ts +45 -0
  46. package/dist/vm/internal-prelude.js +534 -0
  47. package/dist/vm/opcodes.d.ts +222 -0
  48. package/dist/vm/opcodes.js +235 -0
  49. package/dist/vm/prelude/bytecode.d.ts +18 -0
  50. package/dist/vm/prelude/bytecode.js +31 -0
  51. package/dist/vm/prelude/bytecode.json +1 -0
  52. package/dist/vm/prelude/helpers.d.ts +8 -0
  53. package/dist/vm/prelude/helpers.js +258 -0
  54. package/dist/vm/prelude/prelude.d.ts +21 -0
  55. package/dist/vm/prelude/prelude.js +53 -0
  56. package/dist/vm/prelude/source.d.ts +1 -0
  57. package/dist/vm/prelude/source.js +652 -0
  58. package/dist/vm/runtime/callback.d.ts +25 -0
  59. package/dist/vm/runtime/callback.js +51 -0
  60. package/dist/vm/runtime/driver.d.ts +68 -0
  61. package/dist/vm/runtime/driver.js +254 -0
  62. package/dist/vm/runtime/errors.d.ts +23 -0
  63. package/dist/vm/runtime/errors.js +169 -0
  64. package/dist/vm/runtime/execute.d.ts +80 -0
  65. package/dist/vm/runtime/execute.js +442 -0
  66. package/dist/vm/runtime/extensions.d.ts +16 -0
  67. package/dist/vm/runtime/extensions.js +337 -0
  68. package/dist/vm/runtime/generators.d.ts +6 -0
  69. package/dist/vm/runtime/generators.js +44 -0
  70. package/dist/vm/runtime/globals.d.ts +6 -0
  71. package/dist/vm/runtime/globals.js +137 -0
  72. package/dist/vm/runtime/interpreter.d.ts +53 -0
  73. package/dist/vm/runtime/interpreter.js +96 -0
  74. package/dist/vm/runtime/intrinsic-names.d.ts +56 -0
  75. package/dist/vm/runtime/intrinsic-names.js +166 -0
  76. package/dist/vm/runtime/intrinsics.d.ts +15 -0
  77. package/dist/vm/runtime/intrinsics.js +111 -0
  78. package/dist/vm/runtime/limits.d.ts +10 -0
  79. package/dist/vm/runtime/limits.js +19 -0
  80. package/dist/vm/runtime/model.d.ts +58 -0
  81. package/dist/vm/runtime/model.js +57 -0
  82. package/dist/vm/runtime/modules.d.ts +4 -0
  83. package/dist/vm/runtime/modules.js +33 -0
  84. package/dist/vm/runtime/native.d.ts +19 -0
  85. package/dist/vm/runtime/native.js +41 -0
  86. package/dist/vm/runtime/objects.d.ts +403 -0
  87. package/dist/vm/runtime/objects.js +784 -0
  88. package/dist/vm/runtime/operations.d.ts +49 -0
  89. package/dist/vm/runtime/operations.js +288 -0
  90. package/dist/vm/runtime/promises.d.ts +55 -0
  91. package/dist/vm/runtime/promises.js +232 -0
  92. package/dist/vm/runtime/references.d.ts +8 -0
  93. package/dist/vm/runtime/references.js +51 -0
  94. package/dist/vm/runtime/signals.d.ts +69 -0
  95. package/dist/vm/runtime/signals.js +68 -0
  96. package/dist/vm/runtime/source.d.ts +29 -0
  97. package/dist/vm/runtime/source.js +63 -0
  98. package/dist/vm/runtime/table.d.ts +43 -0
  99. package/dist/vm/runtime/table.js +132 -0
  100. package/dist/vm/scheduler.d.ts +190 -0
  101. package/dist/vm/scheduler.js +74 -0
  102. package/dist/vm/snapshot/codec.d.ts +117 -0
  103. package/dist/vm/snapshot/codec.js +848 -0
  104. package/dist/vm/snapshot/snapshot.d.ts +53 -0
  105. package/dist/vm/snapshot/snapshot.js +74 -0
  106. package/dist/vm/snapshot.d.ts +32 -0
  107. package/dist/vm/snapshot.js +309 -0
  108. package/dist/vm/stdlib/array.d.ts +16 -0
  109. package/dist/vm/stdlib/array.js +311 -0
  110. package/dist/vm/stdlib/bytes.d.ts +11 -0
  111. package/dist/vm/stdlib/bytes.js +222 -0
  112. package/dist/vm/stdlib/collections.d.ts +7 -0
  113. package/dist/vm/stdlib/collections.js +188 -0
  114. package/dist/vm/stdlib/console.d.ts +6 -0
  115. package/dist/vm/stdlib/console.js +93 -0
  116. package/dist/vm/stdlib/date.d.ts +2 -0
  117. package/dist/vm/stdlib/date.js +123 -0
  118. package/dist/vm/stdlib/headers.d.ts +2 -0
  119. package/dist/vm/stdlib/headers.js +92 -0
  120. package/dist/vm/stdlib/iterator.d.ts +2 -0
  121. package/dist/vm/stdlib/iterator.js +30 -0
  122. package/dist/vm/stdlib/json.d.ts +3 -0
  123. package/dist/vm/stdlib/json.js +42 -0
  124. package/dist/vm/stdlib/math.d.ts +3 -0
  125. package/dist/vm/stdlib/math.js +73 -0
  126. package/dist/vm/stdlib/number.d.ts +3 -0
  127. package/dist/vm/stdlib/number.js +72 -0
  128. package/dist/vm/stdlib/object.d.ts +6 -0
  129. package/dist/vm/stdlib/object.js +201 -0
  130. package/dist/vm/stdlib/regexp.d.ts +8 -0
  131. package/dist/vm/stdlib/regexp.js +119 -0
  132. package/dist/vm/stdlib/string.d.ts +2 -0
  133. package/dist/vm/stdlib/string.js +272 -0
  134. package/dist/vm/stdlib/url.d.ts +25 -0
  135. package/dist/vm/stdlib/url.js +255 -0
  136. package/dist/vm/stdlib/value.d.ts +6 -0
  137. package/dist/vm/stdlib/value.js +32 -0
  138. package/dist/vm/stdlib/web.d.ts +5 -0
  139. package/dist/vm/stdlib/web.js +97 -0
  140. package/dist/vm/vm.d.ts +226 -0
  141. package/dist/vm/vm.js +2931 -0
  142. package/package.json +8 -5
@@ -0,0 +1,51 @@
1
+ import { primitivePrototype } from "./intrinsics.js";
2
+ import { typeError } from "./model.js";
3
+ import { Callable, get, Builtin, Obj } from "./objects.js";
4
+ import { typeofValue } from "./references.js";
5
+ import { Convert, Invoke } from "./signals.js";
6
+ /** Invoke(value, name), as the call to make: the method the value would find through its prototype. */
7
+ export const invokeMethod = (builtins, value, name, label) => {
8
+ const target = value instanceof Obj ? value : primitivePrototype(builtins, value);
9
+ if (target === undefined)
10
+ throw typeError(`${label} called on null or undefined.`);
11
+ return new Invoke(get(target, name), value, [], undefined);
12
+ };
13
+ /**
14
+ * The conversions a built-in received, while it runs again after them: by ordinal, the order its `withPrimitives`
15
+ * calls run in. The VM resets `count` before every built-in call.
16
+ */
17
+ export const conversions = {
18
+ count: 0,
19
+ replay: undefined,
20
+ };
21
+ /**
22
+ * Runs a native body on values after ToPrimitive, in order, with one hint for all positions or one per position.
23
+ * Primitive values skip the conversion entirely. Otherwise the built-in asks the VM for the conversions (they
24
+ * call program code, so they run as prelude code) and runs again from the start once they are done; this call then
25
+ * receives them. So everything a built-in does before its last conversion must be repeatable: it reads, checks, and
26
+ * throws, but changes nothing. State the body needs as it was before the conversions (a Date's time) goes in `values`.
27
+ * With `coerce`, each value is also converted to a number or string (by its hint) before the next one is.
28
+ */
29
+ export const withPrimitives = (hints, values, body, coerce = false) => {
30
+ const ordinal = conversions.count++;
31
+ const replayed = conversions.replay?.[ordinal];
32
+ if (replayed !== undefined)
33
+ return body(replayed);
34
+ if (!values.some((value) => value instanceof Obj))
35
+ return body(values);
36
+ return new Convert(hints, values, ordinal, coerce);
37
+ };
38
+ /** Checks a callback argument: the callable it is, or the TypeError for one a callback site does not admit. */
39
+ export const requireCallback = (callback, name) => {
40
+ if (isSupportedCallback(callback))
41
+ return callback;
42
+ if (typeofValue(callback) === "function") {
43
+ throw typeError(`${name} cannot use this callable as a callback; wrap it in an arrow function, e.g. (value) => tools.ns.tool(value).`);
44
+ }
45
+ throw typeError(`${name} expects a function callback.`);
46
+ };
47
+ // The single acceptance list for callbacks: collections, sort, string replacers,
48
+ // Array.from mappers, and promise reactions all admit exactly these callables.
49
+ // Admission means dispatchable, not necessarily invocable: new-requiring
50
+ // constructors pass the gate and throw a TypeError on call, like JS.
51
+ export const isSupportedCallback = (value) => value instanceof Callable && !(value instanceof Builtin && !value.callback);
@@ -0,0 +1,68 @@
1
+ import { type Context, Effect } from "effect";
2
+ import type { HostCall } from "../scheduler.js";
3
+ import { type ToolRuntime } from "../../tool-runtime.js";
4
+ import type { Vm } from "../vm.js";
5
+ import { type Completion } from "./signals.js";
6
+ /** What `Driver.run` returns once the run was suspended: its state is saved, and the VM stopped. */
7
+ export declare const SUSPENDED: unique symbol;
8
+ /**
9
+ * Runs the VM (see `Vm`) in Effect: the only place program execution meets the host. It calls `vm.run`
10
+ * until the program ends, and does what each stop asks: yields to the Effect scheduler for a slice, and starts the host
11
+ * calls the VM queued, as fibers with the caller's services, reporting each outcome back with `vm.complete`.
12
+ * Fibers live only here, by host call id, and never become part of the VM's state.
13
+ *
14
+ * A durable tool's call runs as two fibers, `start` then `wait`, so suspending can detach the second and keep the JSON
15
+ * data `start` gave. An idempotent tool's running fiber is detached and interrupted on suspend, and its call is saved
16
+ * as queued to run again on resume. The VM and tool bridge can be swapped for restored ones between stops (the
17
+ * round-trip test mode does); a fiber's outcome goes to whichever VM is current, by host call id.
18
+ */
19
+ export declare class Driver<R> {
20
+ vm: Vm;
21
+ tools: ToolRuntime<R>;
22
+ /** The services host work runs with: the caller's, so tools see its context, tracing, and clock. */
23
+ private readonly services;
24
+ private readonly fibers;
25
+ private readonly detached;
26
+ private wake;
27
+ private stopping;
28
+ private suspending;
29
+ private interrupted;
30
+ /** Called at every slice and host stop, before queued calls start: the round-trip test mode swaps the VM. */
31
+ checkpoint: Effect.Effect<void, unknown, R> | undefined;
32
+ constructor(vm: Vm, tools: ToolRuntime<R>,
33
+ /** The services host work runs with: the caller's, so tools see its context, tracing, and clock. */
34
+ services: Context.Context<R>);
35
+ /**
36
+ * Runs the VM until the program's body completes, then returns how it ended, or `SUSPENDED` once the run was
37
+ * suspended (see `detach`). Host work it started may still be running; `interrupt` stops it. Host work interrupted
38
+ * on its own that reaches the program's body, or blocking host work that is interrupted, interrupts the execution.
39
+ */
40
+ run(): Effect.Effect<Completion | typeof SUSPENDED, unknown, R>;
41
+ /**
42
+ * The host calls that block a suspend now: every call in progress except an idempotent tool call or a durable tool
43
+ * call in `started`, plus any queued or synchronous extension call the program is in the middle of, which holds live
44
+ * host values. A tool call queued but not started starts on resume.
45
+ */
46
+ blocking(): Array<{
47
+ readonly key: string;
48
+ readonly path: string;
49
+ }>;
50
+ /** Whether the run holds live host values: an extension call in progress. */
51
+ get holdsHostValues(): boolean;
52
+ /**
53
+ * Stops the run to suspend it, once its state is saved: `run` returns `SUSPENDED` at its next step, and running
54
+ * idempotent or durable calls' fibers are detached, so ending them reports nothing.
55
+ */
56
+ detach(): void;
57
+ /** Stops host work still running, waiting for its cleanup; a durable tool's work is cancelled unless detached. */
58
+ interrupt(): Effect.Effect<void>;
59
+ /** Starts tool calls that were queued (including idempotent calls) and waits on durable calls in `started`. */
60
+ resume(): void;
61
+ private admit;
62
+ private launch;
63
+ private wait;
64
+ private fork;
65
+ private get settled();
66
+ }
67
+ /** A host call as the program wrote it: `tools.x.y`, `search`, or an extension function's path. */
68
+ export declare const callPath: (call: HostCall) => string;
@@ -0,0 +1,254 @@
1
+ import { Cause, Effect, Exit, Fiber } from "effect";
2
+ import { toolExpression } from "../../tool-runtime.js";
3
+ import { locate } from "./errors.js";
4
+ import { PendingThrow } from "./model.js";
5
+ import { abrupt, Interruption, normal } from "./signals.js";
6
+ /** What `Driver.run` returns once the run was suspended: its state is saved, and the VM stopped. */
7
+ export const SUSPENDED = Symbol("codemode.suspended");
8
+ /**
9
+ * Runs the VM (see `Vm`) in Effect: the only place program execution meets the host. It calls `vm.run`
10
+ * until the program ends, and does what each stop asks: yields to the Effect scheduler for a slice, and starts the host
11
+ * calls the VM queued, as fibers with the caller's services, reporting each outcome back with `vm.complete`.
12
+ * Fibers live only here, by host call id, and never become part of the VM's state.
13
+ *
14
+ * A durable tool's call runs as two fibers, `start` then `wait`, so suspending can detach the second and keep the JSON
15
+ * data `start` gave. An idempotent tool's running fiber is detached and interrupted on suspend, and its call is saved
16
+ * as queued to run again on resume. The VM and tool bridge can be swapped for restored ones between stops (the
17
+ * round-trip test mode does); a fiber's outcome goes to whichever VM is current, by host call id.
18
+ */
19
+ export class Driver {
20
+ vm;
21
+ tools;
22
+ services;
23
+ fibers = new Map();
24
+ // Calls whose fibers were interrupted to suspend or end the run: their outcomes are not reported.
25
+ detached = new Set();
26
+ wake;
27
+ stopping = false;
28
+ suspending = false;
29
+ // Blocking host work interrupted on its own, which interrupts the execution.
30
+ interrupted;
31
+ /** Called at every slice and host stop, before queued calls start: the round-trip test mode swaps the VM. */
32
+ checkpoint;
33
+ constructor(vm, tools,
34
+ /** The services host work runs with: the caller's, so tools see its context, tracing, and clock. */
35
+ services) {
36
+ this.vm = vm;
37
+ this.tools = tools;
38
+ this.services = services;
39
+ }
40
+ /**
41
+ * Runs the VM until the program's body completes, then returns how it ended, or `SUSPENDED` once the run was
42
+ * suspended (see `detach`). Host work it started may still be running; `interrupt` stops it. Host work interrupted
43
+ * on its own that reaches the program's body, or blocking host work that is interrupted, interrupts the execution.
44
+ */
45
+ run() {
46
+ const self = this;
47
+ return Effect.gen(function* () {
48
+ while (true) {
49
+ if (self.interrupted !== undefined)
50
+ return yield* Effect.failCause(self.interrupted);
51
+ if (self.suspending)
52
+ return SUSPENDED;
53
+ const stop = self.vm.run();
54
+ if (stop.kind === "slice") {
55
+ if (self.checkpoint !== undefined)
56
+ yield* self.checkpoint;
57
+ yield* Effect.yieldNow;
58
+ continue;
59
+ }
60
+ if (stop.kind === "host") {
61
+ if (stop.calls.length === 0) {
62
+ yield* self.settled;
63
+ continue;
64
+ }
65
+ if (self.checkpoint !== undefined)
66
+ yield* self.checkpoint;
67
+ // Suspended now: the calls stay queued, and start on resume.
68
+ if (self.suspending)
69
+ continue;
70
+ for (const handed of stop.calls)
71
+ self.launch(self.vm.call(handed.id) ?? handed);
72
+ continue;
73
+ }
74
+ if (stop.kind === "stuck") {
75
+ return abrupt(new PendingThrow("Error", "The program is waiting on a promise that can never settle: nothing else is running, so nothing can resolve it. Code Mode has no timers or sleep, so don't wait or poll inside a program.", stop.node));
76
+ }
77
+ const outcome = stop.completion;
78
+ if (!outcome.ok && outcome.error instanceof Interruption)
79
+ return yield* Effect.failCause(outcome.error.cause);
80
+ return outcome;
81
+ }
82
+ });
83
+ }
84
+ /**
85
+ * The host calls that block a suspend now: every call in progress except an idempotent tool call or a durable tool
86
+ * call in `started`, plus any queued or synchronous extension call the program is in the middle of, which holds live
87
+ * host values. A tool call queued but not started starts on resume.
88
+ */
89
+ blocking() {
90
+ const vm = this.vm;
91
+ const calls = vm.calls().filter((call) => {
92
+ if (call.request.kind === "extension")
93
+ return true;
94
+ if (call.status === "queued" || call.status === "started")
95
+ return false;
96
+ if (call.request.kind === "tool" && this.tools.mode(call.request.path)?._tag === "CodeModeIdempotent")
97
+ return false;
98
+ return true;
99
+ });
100
+ const running = calls.map((call) => ({ key: call.key, path: callPath(call) }));
101
+ const active = vm.activeExtension;
102
+ if (active !== undefined && !calls.some((call) => call.blocking && call.request.kind === "extension")) {
103
+ running.push(active);
104
+ }
105
+ return running;
106
+ }
107
+ /** Whether the run holds live host values: an extension call in progress. */
108
+ get holdsHostValues() {
109
+ return this.vm.calls().some((call) => call.request.kind === "extension") || this.vm.activeExtension !== undefined;
110
+ }
111
+ /**
112
+ * Stops the run to suspend it, once its state is saved: `run` returns `SUSPENDED` at its next step, and running
113
+ * idempotent or durable calls' fibers are detached, so ending them reports nothing.
114
+ */
115
+ detach() {
116
+ this.suspending = true;
117
+ for (const id of this.fibers.keys())
118
+ this.detached.add(id);
119
+ this.wake?.();
120
+ }
121
+ /** Stops host work still running, waiting for its cleanup; a durable tool's work is cancelled unless detached. */
122
+ interrupt() {
123
+ const self = this;
124
+ return Effect.uninterruptible(Effect.gen(function* () {
125
+ self.stopping = true;
126
+ while (self.fibers.size > 0)
127
+ yield* Fiber.interruptAll([...self.fibers.values()]);
128
+ // A suspended run's durable work keeps running, to be waited on at resume.
129
+ if (self.suspending)
130
+ return;
131
+ for (const call of self.vm.calls()) {
132
+ const request = call.request;
133
+ if (call.status !== "started" || request.kind !== "tool")
134
+ continue;
135
+ call.status = "completed";
136
+ yield* Effect.ignore(self.tools.cancel(request.path, call.data)).pipe(Effect.provideContext(self.services));
137
+ }
138
+ }));
139
+ }
140
+ /** Starts tool calls that were queued (including idempotent calls) and waits on durable calls in `started`. */
141
+ resume() {
142
+ if (this.suspending)
143
+ return;
144
+ for (const call of this.vm.calls()) {
145
+ if (call.status === "queued")
146
+ this.launch(call);
147
+ else if (call.status === "started")
148
+ this.wait(call);
149
+ }
150
+ }
151
+ admit(id, name) {
152
+ const call = this.vm.call(id);
153
+ if (call?.admitted)
154
+ return;
155
+ this.tools.record(name);
156
+ if (call !== undefined)
157
+ call.admitted = true;
158
+ }
159
+ // Starts host work now; its outcome goes back to the VM: a blocking call's continues the job that made it, a
160
+ // concurrent call's waits in the inbox and settles its promise in a later job, in completion order.
161
+ launch(call) {
162
+ call.status = "running";
163
+ const request = call.request;
164
+ if (request.kind === "tool") {
165
+ if (this.tools.mode(request.path)?._tag === "CodeModeDurable") {
166
+ const started = this.tools.start(request.path, request.args, call.key, (name) => this.admit(call.id, name));
167
+ return this.fork(call.id, started, (data) => {
168
+ const current = this.vm.call(call.id);
169
+ if (current === undefined)
170
+ return;
171
+ current.status = "started";
172
+ current.data = data;
173
+ if (this.stopping || this.detached.has(call.id))
174
+ return;
175
+ this.wait(current);
176
+ });
177
+ }
178
+ return this.fork(call.id, this.tools.execute(request.path, request.args, {
179
+ key: call.key,
180
+ admit: (name) => this.admit(call.id, name),
181
+ detaching: () => this.suspending,
182
+ }));
183
+ }
184
+ if (request.kind === "search") {
185
+ return this.fork(call.id, this.tools.search(request.args, {
186
+ key: call.key,
187
+ admit: (name) => this.admit(call.id, name),
188
+ }));
189
+ }
190
+ // An extension's work, made by the extension bridge with the program's services in its requirements.
191
+ return this.fork(call.id, this.vm.ctx.extensionWork(request.call));
192
+ }
193
+ wait(call) {
194
+ const request = call.request;
195
+ if (request.kind !== "tool")
196
+ return;
197
+ this.fork(call.id, this.tools.wait(request.path, request.args, call.key, call.data, () => this.suspending));
198
+ }
199
+ // Forks `work` with the caller's services; it starts synchronously, so admission and hooks happen before the VM
200
+ // runs another job. A success goes to `next` when given, otherwise to the VM.
201
+ fork(id, work, next) {
202
+ const fiber = Effect.runForkWith(this.services)(work);
203
+ this.fibers.set(id, fiber);
204
+ fiber.addObserver((exit) => {
205
+ if (this.fibers.get(id) === fiber)
206
+ this.fibers.delete(id);
207
+ if (next !== undefined && Exit.isSuccess(exit))
208
+ return next(exit.value);
209
+ // Interrupted to end or suspend the run: nothing is left to settle.
210
+ if (this.stopping || this.detached.has(id))
211
+ return;
212
+ const call = this.vm.call(id);
213
+ if (call === undefined)
214
+ return;
215
+ if (call.blocking) {
216
+ // Blocking work interrupted on its own interrupts the execution.
217
+ if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause))
218
+ this.interrupted = exit.cause;
219
+ else
220
+ this.vm.complete(id, Exit.isSuccess(exit) ? normal(exit.value) : abrupt(Cause.squash(exit.cause)));
221
+ this.wake?.();
222
+ return;
223
+ }
224
+ this.vm.complete(id, Exit.isSuccess(exit)
225
+ ? normal(exit.value)
226
+ : abrupt(Cause.hasInterruptsOnly(exit.cause)
227
+ ? new Interruption(exit.cause)
228
+ : Cause.hasDies(exit.cause)
229
+ ? locate(Cause.squash(exit.cause), call.site)
230
+ : Cause.squash(exit.cause)));
231
+ this.wake?.();
232
+ });
233
+ }
234
+ get settled() {
235
+ return Effect.callback((resume) => {
236
+ if (this.vm.ready || this.suspending || this.interrupted !== undefined)
237
+ return resume(Effect.void);
238
+ this.wake = () => {
239
+ this.wake = undefined;
240
+ resume(Effect.void);
241
+ };
242
+ return Effect.sync(() => {
243
+ this.wake = undefined;
244
+ });
245
+ });
246
+ }
247
+ }
248
+ /** A host call as the program wrote it: `tools.x.y`, `search`, or an extension function's path. */
249
+ export const callPath = (call) => {
250
+ const request = call.request;
251
+ if (request.kind === "tool")
252
+ return toolExpression(request.path.flatMap((segment) => segment.split(".")).join("."));
253
+ return request.kind === "search" ? "search" : request.call.label;
254
+ };
@@ -0,0 +1,23 @@
1
+ import type { Diagnostic } from "../../codemode.js";
2
+ import { type AstNode } from "./model.js";
3
+ import { type ErrorType } from "./intrinsics.js";
4
+ import { type Native, ErrorObj, Obj, type Value } from "./objects.js";
5
+ import type { Interpreter } from "./interpreter.js";
6
+ /**
7
+ * A host error's message as text. A host can store anything there; an object must not cross as itself, and turning it
8
+ * into text would run its own methods.
9
+ */
10
+ export declare const errorMessage: (error: Error) => string;
11
+ /** A host error's name as a program error type, read once so a getter cannot pass the check and then change. */
12
+ export declare const errorType: (error: Error) => ErrorType;
13
+ export declare const normalizeError: (error: unknown) => Diagnostic;
14
+ /**
15
+ * Gives a failure the source location of the expression that raised it, keeping the first one attached. Host errors
16
+ * that escape a built-in become the equivalent program error here.
17
+ */
18
+ export declare const locate: (error: unknown, node?: AstNode) => unknown;
19
+ /** The program value a handler receives for a failure; one failure always yields the same value. */
20
+ export declare const materialize: <R>(ctx: Interpreter<R>, thrown: unknown) => Value;
21
+ export declare const createAggregateErrorValue: <R>(ctx: Interpreter<R>, errors: Array<Value>, message: string, proto?: Obj) => ErrorObj;
22
+ /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
23
+ export declare const errorGlobal: <R>(type: ErrorType, ctx: Interpreter<R>) => Native;
@@ -0,0 +1,169 @@
1
+ import { ToolError } from "../../tool-error.js";
2
+ import { ToolRuntimeError } from "../../tool-runtime.js";
3
+ import { formatLocation, PendingThrow, Throw, sourceLocation } from "./model.js";
4
+ import { containsRuntimeReference } from "./references.js";
5
+ import { createErrorValue, isErrorType } from "./intrinsics.js";
6
+ import { constructor, methods, prototypeFrom, receiver } from "./native.js";
7
+ import { define, get, has, hidden, Arr, ErrorObj, Obj, coerceToString, } from "./objects.js";
8
+ import { Invoke } from "./signals.js";
9
+ import { withPrimitives } from "./callback.js";
10
+ import { formatValue } from "../stdlib/console.js";
11
+ import { inPrelude } from "./source.js";
12
+ /**
13
+ * A host error's message as text. A host can store anything there; an object must not cross as itself, and turning it
14
+ * into text would run its own methods.
15
+ */
16
+ export const errorMessage = (error) => {
17
+ const message = error.message;
18
+ if (typeof message === "string")
19
+ return message;
20
+ if (message === undefined || typeof message === "function" || (typeof message === "object" && message !== null)) {
21
+ return "";
22
+ }
23
+ return String(message);
24
+ };
25
+ /** A host error's name as a program error type, read once so a getter cannot pass the check and then change. */
26
+ export const errorType = (error) => {
27
+ const name = error.name;
28
+ return typeof name === "string" && isErrorType(name) ? name : "Error";
29
+ };
30
+ export const normalizeError = (error) => {
31
+ if (error instanceof PendingThrow) {
32
+ const location = error.node?.loc ? sourceLocation(error.node) : undefined;
33
+ return {
34
+ kind: error.kind,
35
+ message: `${error.type}: ${error.message}${formatLocation(location)}`,
36
+ ...(location ? { location } : {}),
37
+ ...(error.suggestions ? { suggestions: error.suggestions } : {}),
38
+ };
39
+ }
40
+ if (error instanceof ToolRuntimeError) {
41
+ return {
42
+ kind: error.kind,
43
+ message: error.message,
44
+ ...(error.suggestions.length > 0 ? { suggestions: error.suggestions } : {}),
45
+ };
46
+ }
47
+ if (error instanceof ToolError) {
48
+ return { kind: "ToolFailure", message: error.message };
49
+ }
50
+ if (error instanceof Throw) {
51
+ const value = error.value;
52
+ if (value instanceof ErrorObj) {
53
+ return value.failure ? normalizeError(value.failure) : { kind: "ExecutionFailure", message: errorToString(value) };
54
+ }
55
+ let message;
56
+ if (containsRuntimeReference(value)) {
57
+ // Never expose runtime reference internals through thrown values.
58
+ message = "a non-data value";
59
+ }
60
+ else if (typeof value === "string") {
61
+ message = value;
62
+ }
63
+ else {
64
+ message = formatValue(value);
65
+ }
66
+ return { kind: "ExecutionFailure", message: `Uncaught: ${message}` };
67
+ }
68
+ if (error instanceof RangeError && /call stack|recursion/i.test(errorMessage(error))) {
69
+ return {
70
+ kind: "ExecutionFailure",
71
+ message: "Execution exceeded the maximum nesting depth.",
72
+ };
73
+ }
74
+ if (error instanceof Error) {
75
+ return {
76
+ kind: error.name === "SyntaxError" ? "ParseError" : "ExecutionFailure",
77
+ message: errorMessage(error),
78
+ };
79
+ }
80
+ return {
81
+ kind: "ExecutionFailure",
82
+ message: String(error),
83
+ };
84
+ };
85
+ /**
86
+ * Gives a failure the source location of the expression that raised it, keeping the first one attached. Host errors
87
+ * that escape a built-in become the equivalent program error here.
88
+ */
89
+ export const locate = (error, node) => {
90
+ if (error instanceof PendingThrow) {
91
+ if ((error.node === undefined || inPrelude(error.node)) && node)
92
+ error.node = node;
93
+ return error;
94
+ }
95
+ if (error instanceof Error && !(error instanceof ToolError) && !(error instanceof ToolRuntimeError)) {
96
+ return new PendingThrow(errorType(error), errorMessage(error), node);
97
+ }
98
+ return error;
99
+ };
100
+ /** The program value a handler receives for a failure; one failure always yields the same value. */
101
+ export const materialize = (ctx, thrown) => {
102
+ if (thrown instanceof Throw)
103
+ return thrown.value;
104
+ const builtins = ctx.builtins;
105
+ if (thrown instanceof PendingThrow) {
106
+ if (thrown.value === undefined) {
107
+ thrown.value = createErrorValue(builtins[thrown.type], thrown.message);
108
+ thrown.value.failure = thrown;
109
+ }
110
+ return thrown.value;
111
+ }
112
+ return createErrorValue(builtins[thrown instanceof Error ? errorType(thrown) : "Error"], normalizeError(thrown).message);
113
+ };
114
+ /** Error.prototype.toString: `name: message`, omitting whichever side is empty. */
115
+ const errorToString = (self) => {
116
+ const name = get(self, "name");
117
+ const message = get(self, "message");
118
+ const shownName = name === undefined ? "Error" : coerceToString(name);
119
+ const shownMessage = message === undefined ? "" : coerceToString(message);
120
+ if (shownMessage === "")
121
+ return shownName;
122
+ if (shownName === "")
123
+ return shownMessage;
124
+ return `${shownName}: ${shownMessage}`;
125
+ };
126
+ export const createAggregateErrorValue = (ctx, errors, message, proto = ctx.builtins.AggregateError) => {
127
+ const value = createErrorValue(proto, message);
128
+ define(value, "errors", new Arr(ctx.builtins.Array, errors), { ...hidden });
129
+ return value;
130
+ };
131
+ // ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all.
132
+ const withCause = (created, options) => {
133
+ if (options instanceof Obj && has(options, "cause"))
134
+ define(created, "cause", get(options, "cause"), hidden);
135
+ return created;
136
+ };
137
+ /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
138
+ export const errorGlobal = (type, ctx) => {
139
+ const builtins = ctx.builtins;
140
+ const prototype = builtins[type];
141
+ const construct = (args, newTarget) => {
142
+ const proto = prototypeFrom(newTarget, prototype);
143
+ if (type === "AggregateError") {
144
+ const message = args[1];
145
+ return withPrimitives("string", message === undefined ? [] : [message], ([text]) => {
146
+ const created = withCause(createErrorValue(proto, message === undefined ? "" : coerceToString(text)), args[2]);
147
+ return new Invoke(ctx.prelude.fn("aggregateError"), undefined, [created, args[0]], undefined);
148
+ }, true);
149
+ }
150
+ const message = args[0];
151
+ return withPrimitives("string", message === undefined ? [] : [message], ([text]) => withCause(createErrorValue(proto, message === undefined ? undefined : coerceToString(text)), args[1]), true);
152
+ };
153
+ const ctor = constructor(builtins, prototype, {
154
+ name: type,
155
+ length: type === "AggregateError" ? 2 : 1,
156
+ call: (_, args) => construct(args, ctor),
157
+ construct,
158
+ });
159
+ if (type === "Error") {
160
+ methods(builtins, prototype, [
161
+ ["toString", 0, (thisValue) => errorToString(receiver(Obj, thisValue, "Error.prototype.toString"))],
162
+ ]);
163
+ methods(builtins, ctor, [["isError", 1, (_, args) => args[0] instanceof ErrorObj]]);
164
+ return ctor;
165
+ }
166
+ // Derived constructors extend Error itself, so its statics are inherited. The globals table creates Error first.
167
+ ctor.proto = get(builtins.Error, "constructor");
168
+ return ctor;
169
+ };
@@ -0,0 +1,80 @@
1
+ import { type Program } from "acorn";
2
+ import { Effect } from "effect";
3
+ import type { DataValue, Diagnostic, Outcome, ResolvedExecutionLimits, Result } from "../../codemode.js";
4
+ import type { Extension } from "../../extension.js";
5
+ import { type Snapshot, SnapshotError } from "../snapshot/snapshot.js";
6
+ import { ToolRuntime } from "../../tool-runtime.js";
7
+ import { SuspendError } from "../../suspend-error.js";
8
+ import { Interpreter } from "./interpreter.js";
9
+ import type { Value } from "./objects.js";
10
+ import { Source } from "./source.js";
11
+ type Globals<R> = (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>;
12
+ /** How a runtime runs programs: its tools, limits, hooks, and host globals, shared by every run it starts. */
13
+ export type Setup<R> = {
14
+ readonly prepared: ToolRuntime.Prepared<R>;
15
+ readonly limits: ResolvedExecutionLimits;
16
+ readonly hooks: ToolRuntime.Hooks<R>;
17
+ /** The host's globals, made again for a restored run; see `Interpreter`. */
18
+ readonly globals?: Globals<R> | undefined;
19
+ /** Whether the host globals can hand the program values with no data form (extensions can). */
20
+ readonly lossy?: boolean;
21
+ };
22
+ /** Turns a suspended outcome into a failure, for callers that only run programs to their end. */
23
+ export declare const finishExecution: <E, R>(outcome: Effect.Effect<Outcome, E, R>) => Effect.Effect<Result, E, R>;
24
+ /** Runs a program on the VM with `CodeMode.make`'s extensions and JSON bindings. */
25
+ export declare const execute: <R>(code: string, prepared: ToolRuntime.Prepared<R>, limits: ResolvedExecutionLimits, hooks: ToolRuntime.Hooks<R>, extensions: ReadonlyArray<Extension>, bindings: Readonly<Record<string, DataValue>> | undefined) => Effect.Effect<Result, never, R>;
26
+ export declare const executeProgram: <R>(code: string, prepared: ToolRuntime.Prepared<R>, limits: ResolvedExecutionLimits, hooks: ToolRuntime.Hooks<R>, globals?: Globals<R>, bindings?: Globals<R>, lossy?: boolean) => Effect.Effect<Result, never, R>;
27
+ /** A program ready to run on the VM: nothing runs until `run`. */
28
+ export declare const startProgram: <R>(setup: Setup<R>, code: string, bindings?: Globals<R>, runId?: string) => Running<R>;
29
+ /**
30
+ * Restores a saved run into this runtime, under the limits it was saved with, ready to run as `startProgram`'s.
31
+ * Fails with a `SnapshotError` when the state can't be read or belongs to another build, other host globals, or other
32
+ * sources.
33
+ */
34
+ export declare const resumeProgram: <R>(setup: Setup<R>, saved: Snapshot | Uint8Array | unknown) => Effect.Effect<Running<R>, SnapshotError>;
35
+ export declare const setRoundTrip: (enabled: boolean) => void;
36
+ /** One run's state: the runtime it is in now (restoring swaps it), its driver, and how much active time it used. */
37
+ export declare class Running<R> {
38
+ private readonly setup;
39
+ /** Active milliseconds used before this run, by earlier ones of the same execution. */
40
+ private readonly activeBefore;
41
+ private readonly prepare;
42
+ private readonly resuming;
43
+ private ctx;
44
+ private driver;
45
+ private startedAt;
46
+ private finished;
47
+ private suspended;
48
+ private trips;
49
+ private skip;
50
+ private readonly started;
51
+ private readonly done;
52
+ constructor(setup: Setup<R>,
53
+ /** Active milliseconds used before this run, by earlier ones of the same execution. */
54
+ activeBefore: number, prepare: () => Interpreter<R> | Result, resuming?: boolean);
55
+ /** Makes the run's runtime and driver, then runs the program in the current fiber until it ends or is suspended. */
56
+ run(): Effect.Effect<Outcome, never, R>;
57
+ /**
58
+ * Saves the run's state and stops it, at once: `run` then returns the same `Suspended`. It fails with a
59
+ * `SuspendError`, leaving the run running, while a host call is in progress. A run that already ended gives its result.
60
+ * Before the run has started, it waits for it.
61
+ */
62
+ suspend(maxBytes: number | undefined): Effect.Effect<Outcome, SuspendError>;
63
+ private execute;
64
+ private stop;
65
+ /**
66
+ * Saves the run's state, with no effect on the run: the calls that block a suspend, or the state as it is now. The
67
+ * program shares this thread with the caller, so it is at a step boundary.
68
+ */
69
+ private save;
70
+ private trip;
71
+ }
72
+ export declare const parseProgram: (code: string) => {
73
+ ok: true;
74
+ program: Program;
75
+ source: Source;
76
+ } | {
77
+ ok: false;
78
+ error: Diagnostic;
79
+ };
80
+ export {};