@opencode/codemode 2.1.4 → 2.2.1

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 (55) hide show
  1. package/README.md +33 -4
  2. package/dist/codemode.d.ts +9 -7
  3. package/dist/codemode.js +1 -1
  4. package/dist/data.d.ts +5 -4
  5. package/dist/data.js +7 -4
  6. package/dist/extension.d.ts +17 -4
  7. package/dist/extension.js +8 -0
  8. package/dist/interpreter/callback.d.ts +10 -10
  9. package/dist/interpreter/callback.js +43 -31
  10. package/dist/interpreter/errors.d.ts +1 -1
  11. package/dist/interpreter/errors.js +12 -15
  12. package/dist/interpreter/execute.js +59 -29
  13. package/dist/interpreter/extensions.d.ts +2 -2
  14. package/dist/interpreter/extensions.js +46 -18
  15. package/dist/interpreter/generators.js +162 -19
  16. package/dist/interpreter/globals.js +12 -9
  17. package/dist/interpreter/interpreter.d.ts +20 -13
  18. package/dist/interpreter/interpreter.js +1329 -1147
  19. package/dist/interpreter/intrinsics.js +1 -2
  20. package/dist/interpreter/model.d.ts +4 -7
  21. package/dist/interpreter/model.js +1 -11
  22. package/dist/interpreter/native.d.ts +7 -8
  23. package/dist/interpreter/native.js +4 -10
  24. package/dist/interpreter/objects.d.ts +47 -21
  25. package/dist/interpreter/objects.js +33 -12
  26. package/dist/interpreter/promises.d.ts +15 -53
  27. package/dist/interpreter/promises.js +226 -401
  28. package/dist/interpreter/runner.d.ts +188 -0
  29. package/dist/interpreter/runner.js +492 -0
  30. package/dist/stdlib/array.d.ts +3 -3
  31. package/dist/stdlib/array.js +106 -102
  32. package/dist/stdlib/bytes.d.ts +3 -3
  33. package/dist/stdlib/bytes.js +46 -41
  34. package/dist/stdlib/collections.d.ts +5 -5
  35. package/dist/stdlib/collections.js +160 -165
  36. package/dist/stdlib/date.d.ts +1 -1
  37. package/dist/stdlib/date.js +28 -20
  38. package/dist/stdlib/headers.d.ts +1 -1
  39. package/dist/stdlib/headers.js +14 -19
  40. package/dist/stdlib/iterator.d.ts +1 -1
  41. package/dist/stdlib/iterator.js +140 -122
  42. package/dist/stdlib/json.js +9 -12
  43. package/dist/stdlib/math.js +10 -10
  44. package/dist/stdlib/number.d.ts +2 -2
  45. package/dist/stdlib/object.d.ts +1 -1
  46. package/dist/stdlib/object.js +21 -22
  47. package/dist/stdlib/regexp.d.ts +1 -1
  48. package/dist/stdlib/regexp.js +2 -3
  49. package/dist/stdlib/string.d.ts +1 -1
  50. package/dist/stdlib/string.js +18 -20
  51. package/dist/stdlib/url.d.ts +5 -5
  52. package/dist/stdlib/url.js +32 -33
  53. package/dist/stdlib/value.d.ts +2 -2
  54. package/dist/stdlib/web.d.ts +2 -2
  55. package/package.json +2 -1
package/README.md CHANGED
@@ -91,8 +91,10 @@ runtime.execute(source) // Effect<CodeMode.Result, never, ToolServices>
91
91
  The Effect environment is inferred from the supplied tools. `hooks` surround every call the program makes into the
92
92
  host: `tool.before`/`tool.after` receive `{ name, input }` with decoded input, `extension.before`/`extension.after`
93
93
  receive `{ extension, name, args }`. An `after` hook also receives how the call ended (`success` with its value,
94
- `failure` with its error, or `interrupted`). A failing `before` hook denies the call, and the program catches the
95
- failure as a thrown error.
94
+ `failure` with its error, or `interrupted`). A `before` hook runs before the call reaches the host, and a failing one
95
+ denies it: the host function is never called, and the program catches the failure as a thrown error. A denied call
96
+ fails the way the call itself would: a tool call or asynchronous global rejects its promise, and a synchronous global
97
+ throws.
96
98
 
97
99
  ### `Extension.make`
98
100
 
@@ -100,10 +102,36 @@ Extensions are host functions a program calls directly as globals, such as `fetc
100
102
  catalog, not counted against `maxToolCalls`, and not described to the model; the host decides what they mean.
101
103
 
102
104
  ```ts
103
- const web = Extension.make({ name: "web", globals: { fetch: (url: string) => globalThis.fetch(url) } })
105
+ const web = Extension.make({ name: "web", globals: { fetch: async (url: string) => globalThis.fetch(url) } })
104
106
  const runtime = CodeMode.make({ tools, extensions: [web] })
105
107
  ```
106
108
 
109
+ A global is synchronous unless it is an `async` function or is marked with `Extension.async`. Mark a plain function
110
+ that returns a Promise or an Effect, so a denied call rejects its promise like any other failure:
111
+
112
+ ```ts
113
+ Extension.make({ name: "web", globals: { fetch: Extension.async((url: string) => globalThis.fetch(url)) } })
114
+ ```
115
+
116
+ A global may return a value, a Promise, or an Effect. An Effect's requirements join the runtime's environment the same
117
+ way a tool's do, so the host can provide per-execution services such as the calling session:
118
+
119
+ ```ts
120
+ const web = Extension.make({
121
+ name: "web",
122
+ globals: {
123
+ fetch: Extension.async((url: string) =>
124
+ Effect.gen(function* () {
125
+ const session = yield* Session
126
+ yield* session.authorize(url)
127
+ return yield* Effect.promise(() => globalThis.fetch(url))
128
+ }),
129
+ ),
130
+ },
131
+ })
132
+ const result = yield* CodeMode.make({ extensions: [web] }).execute(code).pipe(Effect.provideService(Session, session))
133
+ ```
134
+
107
135
  Every value crossing in either direction is converted, never shared: arguments come in as copies, results go out as
108
136
  copies, and a function inside a result is callable the same way. A global that shadows a built-in or another
109
137
  extension throws at `CodeMode.make`.
@@ -179,7 +207,8 @@ every visible tool. Hosts render their own model-facing instructions from these
179
207
  and `CodeMode.toolExpression(path)` supply the exact callable forms.
180
208
 
181
209
  The synchronous `search(...)` built-in is always available. It supports exact-path lookup, namespace-scoped search,
182
- empty-query browsing, and pagination, and returns callable paths with full signatures. Search counts toward
210
+ empty-query browsing, and pagination, and returns callable paths with full signatures. Its result can be used directly,
211
+ awaited, or chained with `then`, `catch`, and `finally`, so programs work whichever way they treat it. Search counts toward
183
212
  `maxToolCalls`. Search also matches descriptions from enclosing `Namespace` values.
184
213
 
185
214
  ## Execution Limits
@@ -27,18 +27,20 @@ export type ResolvedExecutionLimits = {
27
27
  readonly maxOutputBytes: number | undefined;
28
28
  };
29
29
  /** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */
30
- export type Options<Provided extends Record<string, unknown> = {}> = {
30
+ export type Options<Provided extends Record<string, unknown> = {}, Extensions extends ReadonlyArray<Extension> = []> = {
31
31
  /** Explicit tools exposed to the program as `tools`. */
32
32
  tools?: Provided & Tools<Services<Provided>>;
33
33
  /** Hooks around every tool and extension call the program makes; see `Hooks`. */
34
- hooks?: ToolRuntime.Hooks<Services<Provided>>;
34
+ hooks?: ToolRuntime.Hooks<Environment<Provided, Extensions>>;
35
35
  /** Host functions exposed as globals; see `Extension.make`. */
36
- extensions?: ReadonlyArray<Extension>;
36
+ extensions?: Extensions;
37
37
  /** Resource limits enforced on each execution. */
38
38
  limits?: ExecutionLimits;
39
39
  };
40
+ /** The Effect environment an execution needs: what the tools and the extensions' Effect globals require. */
41
+ export type Environment<Provided extends Record<string, unknown>, Extensions extends ReadonlyArray<Extension>> = Services<Provided> | Extension.Services<Extensions[number]>;
40
42
  /** Options for one CodeMode execution. */
41
- export type ExecuteOptions<Provided extends Record<string, unknown> = {}> = Options<Provided> & {
43
+ export type ExecuteOptions<Provided extends Record<string, unknown> = {}, Extensions extends ReadonlyArray<Extension> = []> = Options<Provided, Extensions> & {
42
44
  /** Source for one program in the supported JavaScript subset. */
43
45
  code: string;
44
46
  };
@@ -145,6 +147,6 @@ export type Runtime<R = never> = {
145
147
  readonly execute: (code: string) => Effect.Effect<Result, never, R>;
146
148
  };
147
149
  /** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
148
- export declare const execute: <const Provided extends Record<string, unknown>>(options: ExecuteOptions<Provided>) => Effect.Effect<Result, never, Services<Provided>>;
149
- /** Creates an Effect-native runtime over explicit, schema-described tools. */
150
- export declare const make: <const Provided extends Record<string, unknown> = {}>(options?: Options<Provided>) => Runtime<Services<Provided>>;
150
+ 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>>;
151
+ /** Creates an Effect-native runtime over explicit, schema-described tools and extensions. */
152
+ export declare const 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
@@ -57,7 +57,7 @@ const resolveExecutionLimits = (limits) => ({
57
57
  });
58
58
  /** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
59
59
  export const execute = (options) => make(options).execute(options.code);
60
- /** Creates an Effect-native runtime over explicit, schema-described tools. */
60
+ /** Creates an Effect-native runtime over explicit, schema-described tools and extensions. */
61
61
  export const make = (options = {}) => {
62
62
  const prepared = ToolRuntime.prepare((options.tools ?? {}));
63
63
  const limits = resolveExecutionLimits(options.limits);
package/dist/data.d.ts CHANGED
@@ -1,20 +1,21 @@
1
1
  export * as Data from "./data.js";
2
- import { Effect, type Schema } from "effect";
2
+ import type { Schema } from "effect";
3
3
  import type { Interpreter } from "./interpreter/interpreter.js";
4
4
  import { Obj, type Value } from "./interpreter/objects.js";
5
+ import { type Eval } from "./interpreter/runner.js";
5
6
  export type Json = Schema.Json;
6
- type Replacer<R> = (args: Array<Value>, holder: Obj) => Effect.Effect<Value, unknown, R>;
7
+ type Replacer = (args: Array<Value>, holder: Obj) => Eval<Value>;
7
8
  /**
8
9
  * What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and
9
10
  * `undefined` vanish, non-finite numbers become null, and everything else is copied. Two departures from JS
10
11
  * so a mistake is not a silent `{}`: an Error serializes as `{ name, message, ...own }`, and a promise throws.
11
12
  */
12
- export declare const toJson: <R>(ctx: Interpreter<R>, value: Value, replacer?: Replacer<R>) => Effect.Effect<Schema.Json | undefined, unknown, R>;
13
+ export declare const toJson: <R>(ctx: Interpreter<R>, value: Value, replacer?: Replacer) => Eval<Schema.Json | undefined>;
13
14
  /**
14
15
  * The host boundary: `toJson`, plus what a program most likely meant when a value cannot be JSON. A promise is
15
16
  * awaited, a Set crosses as an array, a URLSearchParams as its query string, a Uint8Array asks to be encoded as
16
17
  * text first, and a `__proto__` key is dropped so host code can never receive one.
17
18
  */
18
- export declare const toBoundary: <R>(ctx: Interpreter<R>, value: Value) => Effect.Effect<Schema.Json | undefined, unknown, R>;
19
+ export declare const toBoundary: <R>(ctx: Interpreter<R>, value: Value) => Eval<Schema.Json | undefined>;
19
20
  /** Host JSON as program values: objects and arrays are copied, primitives pass through. */
20
21
  export declare const fromJson: <R>(ctx: Interpreter<R>, value: Json | undefined) => Value;
package/dist/data.js CHANGED
@@ -1,9 +1,9 @@
1
1
  export * as Data from "./data.js";
2
- import { Effect } from "effect";
3
2
  import { MAX_VALUE_DEPTH } from "./interpreter/limits.js";
4
3
  import { invalidData, rangeError, typeError } from "./interpreter/model.js";
5
4
  import { Arr, Bytes, Callable, define, ErrorObj, get, keys, Obj, PromiseObj, record, SetObj, URLSearchParamsObj, HeadersObj, } from "./interpreter/objects.js";
6
5
  import { typeofValue } from "./interpreter/references.js";
6
+ import { Slice } from "./interpreter/runner.js";
7
7
  /**
8
8
  * What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and
9
9
  * `undefined` vanish, non-finite numbers become null, and everything else is copied. Two departures from JS
@@ -18,14 +18,17 @@ export const toJson = (ctx, value, replacer) => walk(ctx, value, replacer, false
18
18
  export const toBoundary = (ctx, value) => walk(ctx, value, undefined, true);
19
19
  const walk = (ctx, value, replacer, boundary) => {
20
20
  const stack = new Set();
21
- const visit = (holder, key, depth) => Effect.gen(function* () {
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;
22
25
  if (depth > MAX_VALUE_DEPTH)
23
26
  throw rangeError(`Value exceeds the maximum depth of ${MAX_VALUE_DEPTH}.`);
24
27
  const raw = get(holder, key);
25
28
  if (raw instanceof PromiseObj && !boundary) {
26
29
  throw invalidData("JSON.stringify received an un-awaited Promise; await it first - e.g. `const result = await tools.ns.tool(...)`.");
27
30
  }
28
- const settled = raw instanceof PromiseObj ? yield* ctx.await(raw) : raw;
31
+ const settled = raw instanceof PromiseObj ? yield* ctx.awaitValue(raw) : raw;
29
32
  const toJSON = settled instanceof Obj ? get(settled, "toJSON") : undefined;
30
33
  const own = toJSON instanceof Callable ? yield* ctx.call(toJSON, settled, [key]) : settled;
31
34
  const value = replacer === undefined ? own : yield* replacer([key, own], holder);
@@ -74,7 +77,7 @@ const walk = (ctx, value, replacer, boundary) => {
74
77
  }
75
78
  stack.delete(target);
76
79
  return copied;
77
- });
80
+ };
78
81
  return visit(record(ctx.builtins.Object, { "": value }), "", 0);
79
82
  };
80
83
  /** Host JSON as program values: objects and arrays are copied, primitives pass through. */
@@ -1,11 +1,24 @@
1
1
  export * as Extension from "./extension.js";
2
+ import type { Effect } from "effect";
2
3
  /**
3
4
  * Host functions a program calls directly as globals. Values crossing in either direction are converted, never
4
5
  * shared: arguments come in as copies, results go out as copies, and a function inside a result is callable the
5
- * same way. Extension calls are not tool calls.
6
+ * same way. Extension calls are not tool calls. A global may return a value, a Promise, or an Effect, and an
7
+ * Effect's requirements join the runtime's environment.
8
+ *
9
+ * A global is synchronous unless it is an `async` function or is marked with `async`. The `extension.before` hook
10
+ * runs before the call, so a denied call never reaches the host; it fails the way the global would, by rejecting the
11
+ * promise of an asynchronous global and by throwing from a synchronous one.
6
12
  */
7
- export type Extension = {
13
+ export type Extension<Globals extends Readonly<Record<string, Function>> = Readonly<Record<string, Function>>> = {
8
14
  readonly name: string;
9
- readonly globals: Readonly<Record<string, Function>>;
15
+ readonly globals: Globals;
10
16
  };
11
- export declare const make: (options: Extension) => Extension;
17
+ /** The Effect environment required by an extension's Effect-returning globals. */
18
+ export type Services<E> = E extends {
19
+ readonly globals: infer Globals;
20
+ } ? Globals[keyof Globals] extends infer Global ? Global extends (...args: never) => infer Result ? Effect.Services<Result> : never : never : never;
21
+ export declare const make: <const Globals extends Readonly<Record<string, Function>>>(options: Extension<Globals>) => Extension<Globals>;
22
+ /** Marks a global that returns a Promise or an Effect, so a denied call rejects its promise instead of throwing. */
23
+ export declare const async: <F extends Function>(global: F) => F;
24
+ export declare const isAsync: (global: Function) => boolean;
package/dist/extension.js CHANGED
@@ -7,3 +7,11 @@ export const make = (options) => {
7
7
  }
8
8
  return { name: options.name, globals: { ...options.globals } };
9
9
  };
10
+ const asyncGlobals = new WeakSet();
11
+ const AsyncFunction = (async () => { }).constructor;
12
+ /** Marks a global that returns a Promise or an Effect, so a denied call rejects its promise instead of throwing. */
13
+ export const async = (global) => {
14
+ asyncGlobals.add(global);
15
+ return global;
16
+ };
17
+ export const isAsync = (global) => global instanceof AsyncFunction || asyncGlobals.has(global);
@@ -1,24 +1,24 @@
1
- import { Effect } from "effect";
2
1
  import type { Interpreter } from "./interpreter.js";
3
- import { Callable, type Cursor, type Value } from "./objects.js";
2
+ import { Callable, type Cursor, type NativeResult, type Value } from "./objects.js";
3
+ import { type Eval } from "./runner.js";
4
4
  /** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
5
5
  * return() is a return completion, so a failing close wins over it, as after `break`. */
6
- export declare const preserveConsumerError: <A, R>(close: Cursor<R>["close"], effect: Effect.Effect<A, unknown, R>) => Effect.Effect<A, unknown, R>;
6
+ export declare function preserveConsumerError<A>(close: Cursor["close"], body: Eval<A>): Eval<A>;
7
7
  export type Hint = "number" | "string" | "default";
8
8
  /**
9
9
  * ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the
10
10
  * default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool
11
11
  * references) pass through unchanged so callers reject or describe them in their built-in form.
12
12
  */
13
- export declare const toPrimitive: <R>(ctx: Interpreter<R>, value: Value, hint: Hint) => Effect.Effect<Value, unknown, R>;
13
+ export declare function toPrimitive<R>(ctx: Interpreter<R>, value: Value, hint: Hint): Eval<Value>;
14
14
  /** Invoke(value, name): calls the method the value would find through its prototype. */
15
- export declare const invoke: <R>(ctx: Interpreter<R>, value: Value, name: string, label: string) => Effect.Effect<Value, unknown, R>;
16
- export declare const toPrimitiveString: <R>(ctx: Interpreter<R>, value: Value) => Effect.Effect<string, unknown, R>;
17
- export declare const toPrimitiveNumber: <R>(ctx: Interpreter<R>, value: Value) => Effect.Effect<number, unknown, R>;
15
+ export declare const invoke: <R>(ctx: Interpreter<R>, value: Value, name: string, label: string) => Eval<Value>;
16
+ export declare function toPrimitiveString<R>(ctx: Interpreter<R>, value: Value): Eval<string>;
17
+ export declare function toPrimitiveNumber<R>(ctx: Interpreter<R>, value: Value): Eval<number>;
18
18
  /**
19
19
  * Runs a native body on its arguments after ToPrimitive, in order, with one hint for all positions or one per
20
- * position. Primitive arguments skip the Effect entirely.
20
+ * position. Primitive arguments skip the conversion entirely.
21
21
  */
22
- export declare const withPrimitives: <R>(ctx: Interpreter<R>, hints: Hint | ReadonlyArray<Hint>, values: Array<Value>, body: (primitives: Array<Value>) => Value | Effect.Effect<Value, unknown, R>) => Value | Effect.Effect<Value, unknown, R>;
22
+ export declare const withPrimitives: <R>(ctx: Interpreter<R>, hints: Hint | ReadonlyArray<Hint>, values: Array<Value>, body: (primitives: Array<Value>) => NativeResult) => NativeResult;
23
23
  export declare const isSupportedCallback: (value: Value) => value is Callable;
24
- export declare const applyCollectionCallback: <R>(ctx: Interpreter<R>, callback: Value, name: string) => ((args: Array<Value>, thisValue?: Value) => Effect.Effect<Value, unknown, R>);
24
+ export declare const applyCollectionCallback: <R>(ctx: Interpreter<R>, callback: Value, name: string) => ((args: Array<Value>, thisValue?: Value) => Eval<Value>);
@@ -1,42 +1,46 @@
1
- import { Cause, Effect, Exit } from "effect";
2
1
  import { primitivePrototype } from "./intrinsics.js";
3
2
  import { GeneratorReturn, typeError } from "./model.js";
4
3
  import { Callable, get, Native, DateObj, Obj, coerceToNumber, coerceToString, } from "./objects.js";
5
4
  import { isOpaque, typeofValue } from "./references.js";
5
+ import { Interruption, isEval } from "./runner.js";
6
6
  /** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
7
7
  * return() is a return completion, so a failing close wins over it, as after `break`. */
8
- export const preserveConsumerError = (close, effect) => Effect.flatMap(Effect.exit(effect), (exit) => {
9
- if (Exit.isSuccess(exit))
10
- return Effect.succeed(exit.value);
11
- return Effect.flatMap(Effect.exit(close), (closed) => {
12
- if (!Exit.isSuccess(closed) && Cause.squash(exit.cause) instanceof GeneratorReturn) {
13
- return Effect.failCause(closed.cause);
8
+ export function* preserveConsumerError(close, body) {
9
+ try {
10
+ return yield* body;
11
+ }
12
+ catch (error) {
13
+ if (error instanceof Interruption)
14
+ throw error;
15
+ try {
16
+ yield* close();
17
+ }
18
+ catch (closed) {
19
+ if (error instanceof GeneratorReturn)
20
+ throw closed;
14
21
  }
15
- return Effect.failCause(exit.cause);
16
- });
17
- });
22
+ throw error;
23
+ }
24
+ }
18
25
  /**
19
26
  * ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the
20
27
  * default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool
21
28
  * references) pass through unchanged so callers reject or describe them in their built-in form.
22
29
  */
23
- export const toPrimitive = (ctx, value, hint) => {
30
+ export function* toPrimitive(ctx, value, hint) {
24
31
  if (!(value instanceof Obj) || isOpaque(value))
25
- return Effect.succeed(value);
32
+ return value;
26
33
  const asString = hint === "string" || (hint === "default" && value instanceof DateObj);
27
- const order = asString ? ["toString", "valueOf"] : ["valueOf", "toString"];
28
- return Effect.gen(function* () {
29
- for (const method of order) {
30
- const callable = get(value, method);
31
- if (!(callable instanceof Callable))
32
- continue;
33
- const result = yield* ctx.call(callable, value, []);
34
- if (result === null || (typeof result !== "object" && typeof result !== "function"))
35
- return result;
36
- }
37
- throw typeError("Cannot convert object to primitive value.");
38
- });
39
- };
34
+ for (const method of asString ? ["toString", "valueOf"] : ["valueOf", "toString"]) {
35
+ const callable = get(value, method);
36
+ if (!(callable instanceof Callable))
37
+ continue;
38
+ const result = yield* ctx.call(callable, value, []);
39
+ if (result === null || (typeof result !== "object" && typeof result !== "function"))
40
+ return result;
41
+ }
42
+ throw typeError("Cannot convert object to primitive value.");
43
+ }
40
44
  /** Invoke(value, name): calls the method the value would find through its prototype. */
41
45
  export const invoke = (ctx, value, name, label) => {
42
46
  const target = value instanceof Obj ? value : primitivePrototype(ctx.builtins, value);
@@ -44,19 +48,27 @@ export const invoke = (ctx, value, name, label) => {
44
48
  throw typeError(`${label} called on null or undefined.`);
45
49
  return ctx.call(get(target, name), value, []);
46
50
  };
47
- export const toPrimitiveString = (ctx, value) => Effect.map(toPrimitive(ctx, value, "string"), coerceToString);
48
- export const toPrimitiveNumber = (ctx, value) => Effect.map(toPrimitive(ctx, value, "number"), coerceToNumber);
51
+ export function* toPrimitiveString(ctx, value) {
52
+ return coerceToString(yield* toPrimitive(ctx, value, "string"));
53
+ }
54
+ export function* toPrimitiveNumber(ctx, value) {
55
+ return coerceToNumber(yield* toPrimitive(ctx, value, "number"));
56
+ }
49
57
  /**
50
58
  * Runs a native body on its arguments after ToPrimitive, in order, with one hint for all positions or one per
51
- * position. Primitive arguments skip the Effect entirely.
59
+ * position. Primitive arguments skip the conversion entirely.
52
60
  */
53
61
  export const withPrimitives = (ctx, hints, values, body) => {
54
62
  if (!values.some((value) => value instanceof Obj))
55
63
  return body(values);
56
- return Effect.flatMap(Effect.forEach(values, (value, index) => toPrimitive(ctx, value, typeof hints === "string" ? hints : hints[index])), (primitives) => {
64
+ return (function* () {
65
+ const primitives = [];
66
+ for (const [index, value] of values.entries()) {
67
+ primitives.push(yield* toPrimitive(ctx, value, typeof hints === "string" ? hints : hints[index]));
68
+ }
57
69
  const result = body(primitives);
58
- return Effect.isEffect(result) ? result : Effect.succeed(result);
59
- });
70
+ return isEval(result) ? yield* result : result;
71
+ })();
60
72
  };
61
73
  // The single acceptance list for callbacks: collections, sort, string replacers,
62
74
  // Array.from mappers, and promise reactions all admit exactly these callables.
@@ -13,4 +13,4 @@ export declare const locate: (error: unknown, node?: AstNode) => unknown;
13
13
  export declare const materialize: <R>(ctx: Interpreter<R>, thrown: unknown) => Value;
14
14
  export declare const createAggregateErrorValue: <R>(ctx: Interpreter<R>, errors: Array<Value>, message: string, proto?: Obj) => ErrorObj;
15
15
  /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
16
- export declare const errorGlobal: <R>(type: ErrorType, ctx: Interpreter<R>) => Native<R>;
16
+ export declare const errorGlobal: <R>(type: ErrorType, ctx: Interpreter<R>) => Native;
@@ -1,4 +1,3 @@
1
- import { Effect } from "effect";
2
1
  import { ToolError } from "../tool-error.js";
3
2
  import { ToolRuntimeError } from "../tool-runtime.js";
4
3
  import { formatLocation, PendingThrow, Throw, sourceLocation, typeError } from "./model.js";
@@ -10,10 +9,11 @@ import { toPrimitiveString } from "./callback.js";
10
9
  import { formatValue } from "../stdlib/console.js";
11
10
  export const normalizeError = (error) => {
12
11
  if (error instanceof PendingThrow) {
12
+ const location = error.node?.loc ? sourceLocation(error.node) : undefined;
13
13
  return {
14
14
  kind: error.kind,
15
- message: `${error.type}: ${error.message}${formatLocation(error.node)}`,
16
- ...(error.node?.loc ? { location: sourceLocation(error.node) } : {}),
15
+ message: `${error.type}: ${error.message}${formatLocation(location)}`,
16
+ ...(location ? { location } : {}),
17
17
  ...(error.suggestions ? { suggestions: error.suggestions } : {}),
18
18
  };
19
19
  }
@@ -109,36 +109,33 @@ export const createAggregateErrorValue = (ctx, errors, message, proto = ctx.buil
109
109
  define(value, "errors", new Arr(ctx.builtins.Array, errors), { ...hidden });
110
110
  return value;
111
111
  };
112
- const constructAggregateErrorValue = (ctx, args, proto) => Effect.gen(function* () {
112
+ function* constructAggregateErrorValue(ctx, args, proto) {
113
113
  const message = args[1] === undefined ? "" : yield* toPrimitiveString(ctx, args[1]);
114
114
  const cursor = yield* ctx.iterate(args[0]);
115
115
  if (cursor === undefined)
116
116
  throw typeError("new AggregateError(...) expects a synchronous iterable of errors.");
117
117
  const errors = [];
118
118
  while (true) {
119
- const step = yield* cursor.next;
119
+ const step = yield* cursor.next();
120
120
  if (step.done)
121
121
  return createAggregateErrorValue(ctx, errors, message, proto);
122
122
  errors.push(step.value);
123
123
  }
124
- });
124
+ }
125
125
  /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
126
126
  export const errorGlobal = (type, ctx) => {
127
127
  const builtins = ctx.builtins;
128
128
  const prototype = builtins[type];
129
- const construct = (args, newTarget) => {
129
+ const construct = function* (args, newTarget) {
130
130
  const proto = prototypeFrom(newTarget, prototype);
131
131
  const created = type === "AggregateError"
132
- ? constructAggregateErrorValue(ctx, args, proto)
133
- : Effect.map(args[0] === undefined ? Effect.undefined : toPrimitiveString(ctx, args[0]), (message) => createErrorValue(proto, message));
132
+ ? yield* constructAggregateErrorValue(ctx, args, proto)
133
+ : createErrorValue(proto, args[0] === undefined ? undefined : yield* toPrimitiveString(ctx, args[0]));
134
134
  // ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all.
135
135
  const options = args[type === "AggregateError" ? 2 : 1];
136
- if (!(options instanceof Obj) || !has(options, "cause"))
137
- return created;
138
- return Effect.map(created, (value) => {
139
- define(value, "cause", get(options, "cause"), hidden);
140
- return value;
141
- });
136
+ if (options instanceof Obj && has(options, "cause"))
137
+ define(created, "cause", get(options, "cause"), hidden);
138
+ return created;
142
139
  };
143
140
  const ctor = constructor(builtins, prototype, {
144
141
  name: type,
@@ -1,11 +1,10 @@
1
1
  import { parse } from "acorn";
2
- import { Cause, Effect, Scope } from "effect";
3
- import { toBoundary } from "../data.js";
2
+ import { Cause, Effect, Option, Schema } from "effect";
4
3
  import { ToolRuntime } from "../tool-runtime.js";
5
4
  import { normalizeError } from "./errors.js";
6
5
  import { createBuiltins } from "./intrinsics.js";
7
- import { Pending } from "./promises.js";
8
6
  import { Interpreter } from "./interpreter.js";
7
+ import { formatLocation } from "./model.js";
9
8
  export const executeProgram = (code, prepared, limits, hooks, globals) => {
10
9
  if (code.trim().length === 0) {
11
10
  return Effect.succeed({
@@ -22,24 +21,31 @@ export const executeProgram = (code, prepared, limits, hooks, globals) => {
22
21
  const logged = () => (logs.length > 0 ? { logs: [...logs] } : {});
23
22
  // Set only after copy-out so timeouts cannot report invalid values as completed.
24
23
  let returned;
25
- const base = Effect.acquireUseRelease(Scope.make("parallel"), (scope) => Effect.gen(function* () {
26
- const program = parseProgram(code);
27
- const pending = new Pending(scope, builtins.Promise);
28
- const ctx = new Interpreter({ tools, pending, builtins, logs, globals });
29
- // The main job holds the turn until leftover promise work is interrupted.
30
- return yield* pending.turn.hold(Effect.gen(function* () {
31
- const result = (yield* toBoundary(ctx, yield* ctx.run(program))) ?? null;
32
- returned = { value: result, pending };
33
- const warnings = yield* pending.interrupt();
34
- return {
35
- ok: true,
36
- value: result,
37
- ...(warnings.length > 0 ? { warnings } : {}),
38
- ...logged(),
39
- toolCalls: tools.calls,
40
- };
41
- }));
42
- }), (scope, exit) => Scope.close(scope, exit));
24
+ let runner;
25
+ const base = Effect.gen(function* () {
26
+ const parsed = parseProgram(code);
27
+ if (!parsed.ok)
28
+ return { ok: false, error: parsed.error, toolCalls: [] };
29
+ const services = yield* Effect.context();
30
+ const ctx = new Interpreter({ tools, services, builtins, logs, globals });
31
+ runner = ctx.runner;
32
+ const outcome = yield* runner.run(ctx.main(parsed.program));
33
+ if (!outcome.ok) {
34
+ return { ok: false, error: normalizeError(outcome.error), ...logged(), toolCalls: tools.calls };
35
+ }
36
+ const result = outcome.value ?? null;
37
+ returned = { value: result, runner };
38
+ // Host work the program left running is interrupted, not awaited.
39
+ yield* runner.interrupt();
40
+ const warnings = runner.diagnostics();
41
+ return {
42
+ ok: true,
43
+ value: result,
44
+ ...(warnings.length > 0 ? { warnings } : {}),
45
+ ...logged(),
46
+ toolCalls: tools.calls,
47
+ };
48
+ }).pipe(Effect.ensuring(Effect.suspend(() => runner?.interrupt() ?? Effect.void)));
43
49
  const timeoutMs = limits.timeoutMs;
44
50
  const operation = timeoutMs === undefined
45
51
  ? base
@@ -63,7 +69,7 @@ export const executeProgram = (code, prepared, limits, hooks, globals) => {
63
69
  kind: "TimeoutExceeded",
64
70
  message: `The program returned, but background work was still running at the ${timeoutMs}ms timeout and was interrupted. Await all started promises.`,
65
71
  },
66
- ...returned.pending.diagnostics(),
72
+ ...returned.runner.diagnostics(),
67
73
  ],
68
74
  ...logged(),
69
75
  toolCalls: tools.calls,
@@ -81,13 +87,37 @@ export const executeProgram = (code, prepared, limits, hooks, globals) => {
81
87
  });
82
88
  };
83
89
  const parseProgram = (code) => {
84
- return parse(code, {
85
- ecmaVersion: "latest",
86
- sourceType: "script",
87
- allowReturnOutsideFunction: true,
88
- allowAwaitOutsideFunction: true,
89
- locations: true,
90
- });
90
+ try {
91
+ const program = parse(code, {
92
+ ecmaVersion: "latest",
93
+ sourceType: "script",
94
+ allowReturnOutsideFunction: true,
95
+ allowAwaitOutsideFunction: true,
96
+ locations: true,
97
+ });
98
+ return { ok: true, program };
99
+ }
100
+ catch (error) {
101
+ // Only acorn's own syntax errors become a located ParseError; anything else keeps the generic failure path.
102
+ const acorn = error instanceof SyntaxError ? decodeAcornError(error) : Option.none();
103
+ if (Option.isNone(acorn))
104
+ throw error;
105
+ return { ok: false, error: parseDiagnostic(acorn.value) };
106
+ }
107
+ };
108
+ // Acorn appends ` (line:column)` to its messages; its lines are 1-based and its columns 0-based.
109
+ const AcornError = Schema.Struct({
110
+ message: Schema.String,
111
+ loc: Schema.Struct({ line: Schema.Number, column: Schema.Number }),
112
+ });
113
+ const decodeAcornError = Schema.decodeUnknownOption(AcornError);
114
+ const parseDiagnostic = (error) => {
115
+ const location = { line: error.loc.line, column: error.loc.column + 1 };
116
+ const reason = error.message.replace(/ \(\d+:\d+\)$/, "");
117
+ const text = reason === "'import' and 'export' may appear only with 'sourceType: module'"
118
+ ? "Imports and exports aren't available. Call tools through `tools` and use the built-in globals."
119
+ : `${reason.endsWith(".") ? reason : `${reason}.`} Code must be plain JavaScript written as a program body.`;
120
+ return { kind: "ParseError", message: `SyntaxError: ${text}${formatLocation(location)}`, location };
91
121
  };
92
122
  const utf8ByteLength = (value) => new TextEncoder().encode(value).byteLength;
93
123
  // Drop a replacement character produced by truncating inside a UTF-8 sequence.
@@ -1,9 +1,9 @@
1
- import type { Extension } from "../extension.js";
1
+ import { type Extension } from "../extension.js";
2
2
  import type { Interpreter } from "./interpreter.js";
3
3
  import { type Value } from "./objects.js";
4
4
  /**
5
5
  * The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and
6
6
  * built-in wrappers are copied, a host function becomes a program function whose calls cross the same way, and a
7
- * host Promise becomes a program promise.
7
+ * host Promise or Effect becomes a program promise.
8
8
  */
9
9
  export declare const extensionGlobals: <R>(ctx: Interpreter<R>, extensions: ReadonlyArray<Extension>) => ReadonlyArray<readonly [string, Value]>;