@opencode/codemode 0.0.0-dev-19635 → 0.0.0-dev-19636

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/dist/data.d.ts CHANGED
@@ -1,32 +1,19 @@
1
1
  export * as Data from "./data.js";
2
- import type { DiagnosticKind } from "./codemode.js";
3
- import type { Builtins } from "./interpreter/intrinsics.js";
4
- export declare const MAX_VALUE_DEPTH = 32;
5
- export declare class ToolRuntimeError extends Error {
6
- readonly kind: Extract<DiagnosticKind, "UnknownTool" | "InvalidToolInput" | "InvalidToolOutput" | "InvalidDataValue" | "ToolCallLimitExceeded">;
7
- readonly suggestions: ReadonlyArray<string>;
8
- constructor(kind: Extract<DiagnosticKind, "UnknownTool" | "InvalidToolInput" | "InvalidToolOutput" | "InvalidDataValue" | "ToolCallLimitExceeded">, message: string, suggestions?: ReadonlyArray<string>);
9
- }
2
+ import { Effect, type Schema } from "effect";
3
+ import type { Interpreter } from "./interpreter/interpreter.js";
4
+ export type Json = Schema.Json;
5
+ type Replacer<R> = (args: Array<unknown>) => Effect.Effect<unknown, unknown, R>;
10
6
  /**
11
- * Brings a host-produced value into the program: program values pass through, host Date, RegExp,
12
- * Map, Set, URL, and URLSearchParams become their built-in wrappers, and host objects and arrays
13
- * are copied.
7
+ * What `JSON.stringify` would serialize for a program value, as host JSON: `toJSON` is honored, functions and
8
+ * `undefined` vanish, non-finite numbers become null, and everything else is copied. Two departures from JS
9
+ * so a mistake is not a silent `{}`: an Error serializes as `{ name, message, ...own }`, and a promise throws.
14
10
  */
15
- export declare const toProgram: (builtins: Builtins, value: unknown, label: string) => unknown;
11
+ export declare const toJson: <R>(ctx: Interpreter<R>, value: unknown, replacer?: Replacer<R>) => Effect.Effect<Schema.Json | undefined, unknown, R>;
16
12
  /**
17
- * Brings host data into the program: Date and URL become strings, other host collections become
18
- * empty objects, and objects become program copies. Used for tool results and parsed JSON.
13
+ * The host boundary: `toJson`, plus what a program most likely meant when a value cannot be JSON. A promise is
14
+ * awaited, a Set crosses as an array, a URLSearchParams as its query string, a Uint8Array asks to be encoded as
15
+ * text first, and a `__proto__` key is dropped so host code can never receive one.
19
16
  */
20
- export declare const fromData: (builtins: Builtins, value: unknown, label: string) => unknown;
21
- /**
22
- * Takes a program value out as plain JSON: runtime values serialize like `JSON.stringify` would,
23
- * non-finite numbers become null, and array holes become null. `undefined` object properties are
24
- * dropped ("json") or become null ("result", for program results where the consumer must never see
25
- * undefined); a bare `undefined` follows the same rule.
26
- *
27
- * At the host boundary (tool arguments and program results) `__proto__` keys are dropped and values
28
- * `JSON.stringify` would flatten to `{}` cross in a useful form instead: a Set as an array, a RegExp
29
- * and URLSearchParams as their strings. `JSON.stringify` itself passes `boundary: false` to keep JS
30
- * behavior.
31
- */
32
- export declare const toData: (value: unknown, label: string, undefinedAs?: "json" | "result", boundary?: boolean) => unknown;
17
+ export declare const toBoundary: <R>(ctx: Interpreter<R>, value: unknown) => Effect.Effect<Schema.Json | undefined, unknown, R>;
18
+ /** Host JSON as program values: objects and arrays are copied, primitives pass through. */
19
+ export declare const fromJson: <R>(ctx: Interpreter<R>, value: unknown) => unknown;
package/dist/data.js CHANGED
@@ -1,192 +1,88 @@
1
1
  export * as Data from "./data.js";
2
- import { Callable, define, entries, get, isWrapper, parseArrayIndex, Arr, Bytes, DateObj, ErrorObj, GeneratorObj, Handle, MapObj, Obj, PromiseObj, RegExpObj, SetObj, URLObj, URLSearchParamsObj, } from "./interpreter/objects.js";
3
- export const MAX_VALUE_DEPTH = 32;
4
- export class ToolRuntimeError extends Error {
5
- kind;
6
- suggestions;
7
- constructor(kind, message, suggestions = []) {
8
- super(message);
9
- this.kind = kind;
10
- this.suggestions = suggestions;
11
- this.name = "ToolRuntimeError";
12
- }
13
- }
2
+ import { Effect } from "effect";
3
+ import { MAX_VALUE_DEPTH } from "./interpreter/limits.js";
4
+ import { invalidData, rangeError, typeError } from "./interpreter/model.js";
5
+ import { Arr, Bytes, Callable, define, ErrorObj, get, keys, Obj, PromiseObj, record, SetObj, URLSearchParamsObj, } from "./interpreter/objects.js";
6
+ import { typeofValue } from "./interpreter/references.js";
14
7
  /**
15
- * Brings a host-produced value into the program: program values pass through, host Date, RegExp,
16
- * Map, Set, URL, and URLSearchParams become their built-in wrappers, and host objects and arrays
17
- * are copied.
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.
18
11
  */
19
- export const toProgram = (builtins, value, label) => copy(value, label, "program", 0, new Set(), builtins);
12
+ export const toJson = (ctx, value, replacer) => walk(ctx, value, replacer, false);
20
13
  /**
21
- * Brings host data into the program: Date and URL become strings, other host collections become
22
- * empty objects, and objects become program copies. Used for tool results and parsed JSON.
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.
23
17
  */
24
- export const fromData = (builtins, value, label) => copy(value, label, "data", 0, new Set(), builtins);
25
- /**
26
- * Takes a program value out as plain JSON: runtime values serialize like `JSON.stringify` would,
27
- * non-finite numbers become null, and array holes become null. `undefined` object properties are
28
- * dropped ("json") or become null ("result", for program results where the consumer must never see
29
- * undefined); a bare `undefined` follows the same rule.
30
- *
31
- * At the host boundary (tool arguments and program results) `__proto__` keys are dropped and values
32
- * `JSON.stringify` would flatten to `{}` cross in a useful form instead: a Set as an array, a RegExp
33
- * and URLSearchParams as their strings. `JSON.stringify` itself passes `boundary: false` to keep JS
34
- * behavior.
35
- */
36
- export const toData = (value, label, undefinedAs = "json", boundary = true) => copy(value, label, undefinedAs, 0, new Set(), undefined, boundary);
37
- const copy = (value, label, mode, depth, seen, builtins, boundary = true) => {
38
- const next = (item) => copy(item, label, mode, depth + 1, seen, builtins, boundary);
39
- if (depth > MAX_VALUE_DEPTH) {
40
- throw new ToolRuntimeError("InvalidDataValue", `${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
41
- }
42
- if (value === undefined)
43
- return mode === "result" ? null : undefined;
44
- if (typeof value === "number")
45
- return (mode === "json" || mode === "result") && !Number.isFinite(value) ? null : value;
46
- if (value === null || typeof value === "string" || typeof value === "boolean")
47
- return value;
48
- if (typeof value !== "object") {
49
- throw new ToolRuntimeError("InvalidDataValue", `${label} must contain data only.`);
50
- }
51
- if (value instanceof PromiseObj) {
52
- throw new ToolRuntimeError("InvalidDataValue", `${label} contains an un-awaited Promise; await tool calls (e.g. \`const result = await tools.ns.tool(...)\`) before using their results.`);
53
- }
54
- if ((value instanceof Callable || value instanceof GeneratorObj) && mode !== "program") {
55
- throw new ToolRuntimeError("InvalidDataValue", `${label} must contain data only.`);
56
- }
57
- if (value instanceof Handle && mode !== "program") {
58
- throw new ToolRuntimeError("InvalidDataValue", `${label} contains a ${value.instance.constructor.name}, which only extension functions accept.`);
59
- }
60
- // Host-produced input never holds program objects; one arriving here would come back as a host object.
61
- if (value instanceof Obj && mode === "data") {
62
- throw new ToolRuntimeError("InvalidDataValue", `${label} must be host data, not a program value.`);
63
- }
64
- if (builtins !== undefined && mode === "program") {
65
- if (value instanceof Obj)
66
- return value;
67
- if (value instanceof Date)
68
- return new DateObj(builtins.Date, value.getTime());
69
- if (value instanceof RegExp)
70
- return new RegExpObj(builtins.RegExp, value.source, value.flags);
71
- if (value instanceof Map) {
72
- const wrapped = new MapObj(builtins.Map);
73
- for (const [key, item] of value.entries())
74
- wrapped.map.set(next(key), next(item));
75
- return wrapped;
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 = (holder, key, depth) => Effect.gen(function* () {
22
+ if (depth > MAX_VALUE_DEPTH)
23
+ throw rangeError(`Value exceeds the maximum depth of ${MAX_VALUE_DEPTH}.`);
24
+ const raw = get(holder, key);
25
+ if (raw instanceof PromiseObj && !boundary) {
26
+ throw invalidData("JSON.stringify received an un-awaited Promise; await it first - e.g. `const result = await tools.ns.tool(...)`.");
76
27
  }
77
- if (value instanceof Set) {
78
- const wrapped = new SetObj(builtins.Set);
79
- for (const item of value.values())
80
- wrapped.set.add(next(item));
81
- return wrapped;
82
- }
83
- if (value instanceof URL)
84
- return new URLObj(builtins.URL, builtins.URLSearchParams, new URL(value.href));
85
- if (value instanceof URLSearchParams)
86
- return new URLSearchParamsObj(builtins.URLSearchParams, new URLSearchParams(value));
87
- }
88
- if (value instanceof DateObj)
89
- return Number.isFinite(value.time) ? new Date(value.time).toISOString() : null;
90
- if (value instanceof Date)
91
- return Number.isFinite(value.getTime()) ? value.toISOString() : null;
92
- if (value instanceof URLObj)
93
- return value.url.href;
94
- if (value instanceof URL)
95
- return value.href;
96
- if (value instanceof Bytes) {
97
- if (boundary) {
98
- throw new ToolRuntimeError("InvalidDataValue", `${label} contains a Uint8Array; pass text instead, e.g. \`new TextDecoder().decode(bytes)\` or \`bytes.toBase64()\`.`);
28
+ const settled = raw instanceof PromiseObj ? yield* ctx.await(raw) : raw;
29
+ const toJSON = settled instanceof Obj ? get(settled, "toJSON") : undefined;
30
+ const own = toJSON instanceof Callable ? yield* ctx.call(toJSON, settled, [key]) : settled;
31
+ const value = replacer === undefined ? own : yield* replacer([key, own]);
32
+ if (value === undefined || typeofValue(value) === "function")
33
+ return undefined;
34
+ if (typeof value === "number")
35
+ return Number.isFinite(value) ? value : null;
36
+ if (value === null || typeof value === "string" || typeof value === "boolean")
37
+ return value;
38
+ if (!(value instanceof Obj))
39
+ return {};
40
+ if (boundary && value instanceof Bytes) {
41
+ throw invalidData("A Uint8Array cannot cross to the host; pass text instead, e.g. `new TextDecoder().decode(bytes)` or `bytes.toBase64()`.");
99
42
  }
100
- return Object.fromEntries(value.bytes.entries());
101
- }
102
- if (boundary && builtins === undefined) {
103
- if (value instanceof RegExpObj)
104
- return String(value.regex);
105
- if (value instanceof URLSearchParamsObj)
43
+ if (boundary && value instanceof URLSearchParamsObj)
106
44
  return value.params.toString();
107
- if (value instanceof SetObj) {
108
- if (seen.has(value))
109
- throw new ToolRuntimeError("InvalidDataValue", `${label} contains a circular value.`);
110
- seen.add(value);
111
- const copied = Array.from(value.set, (item) => next(item) ?? null);
112
- seen.delete(value);
113
- return copied;
45
+ const target = boundary && value instanceof SetObj ? new Arr(ctx.builtins.Array, [...value.set]) : value;
46
+ if (stack.has(target))
47
+ throw typeError("Converting circular structure to JSON.");
48
+ stack.add(target);
49
+ if (target instanceof Arr) {
50
+ const items = [];
51
+ for (let index = 0; index < target.items.length; index += 1) {
52
+ items.push((yield* visit(target, String(index), depth + 1)) ?? null);
53
+ }
54
+ stack.delete(target);
55
+ return items;
114
56
  }
115
- }
116
- // Remaining wrappers and their host counterparts serialize as empty objects, like JSON.stringify.
117
- if (isWrapper(value) ||
118
- value instanceof RegExp ||
119
- value instanceof Map ||
120
- value instanceof Set ||
121
- value instanceof URLSearchParams) {
122
- return builtins !== undefined ? new Obj(builtins.Object) : {};
123
- }
124
- if (seen.has(value)) {
125
- throw new ToolRuntimeError("InvalidDataValue", `${label} contains a circular value.`);
126
- }
127
- seen.add(value);
128
- if (value instanceof Arr) {
129
- const copied = Array.from(value.items, (item) => next(item) ?? null);
130
- seen.delete(value);
131
- return copied;
132
- }
133
- if (value instanceof Obj) {
134
57
  const copied = {};
58
+ // Own data property regardless of the key, so "__proto__" never reaches the Object.prototype setter.
59
+ const put = (name, item) => {
60
+ if (item !== undefined)
61
+ Object.defineProperty(copied, name, { value: item, enumerable: true, writable: true, configurable: true });
62
+ };
135
63
  // Errors serialize as { name, message, ...own }: both may be inherited, and neither is enumerable in JS.
136
- if (value instanceof ErrorObj) {
137
- defineHost(copied, "name", next(get(value, "name")));
138
- defineHost(copied, "message", next(get(value, "message")));
64
+ if (target instanceof ErrorObj) {
65
+ put("name", yield* visit(target, "name", depth + 1));
66
+ put("message", yield* visit(target, "message", depth + 1));
139
67
  }
140
- for (const [key, item] of entries(value)) {
141
- if (boundary && key === "__proto__")
68
+ for (const name of keys(target)) {
69
+ if (boundary && name === "__proto__")
142
70
  continue;
143
- const copiedItem = next(item);
144
- if (copiedItem === undefined && mode === "json")
145
- continue;
146
- defineHost(copied, key, copiedItem);
147
- }
148
- seen.delete(value);
149
- return copied;
150
- }
151
- if (Array.isArray(value)) {
152
- if (builtins !== undefined) {
153
- const copied = new Arr(builtins.Array, value.map(next));
154
- for (const [key, item] of Object.entries(value)) {
155
- if (parseArrayIndex(key) === undefined)
156
- define(copied, key, next(item));
157
- }
158
- seen.delete(value);
159
- return copied;
71
+ put(name, yield* visit(target, name, depth + 1));
160
72
  }
161
- const copied = Array.from(value, (item) => next(item) ?? null);
162
- seen.delete(value);
73
+ stack.delete(target);
163
74
  return copied;
164
- }
165
- const prototype = Object.getPrototypeOf(value);
166
- if (prototype !== Object.prototype && prototype !== null) {
167
- throw new ToolRuntimeError("InvalidDataValue", `${label} must contain plain objects only.`);
168
- }
169
- if (builtins !== undefined) {
170
- const copied = new Obj(builtins.Object);
171
- for (const [key, item] of Object.entries(value))
172
- define(copied, key, next(item));
173
- seen.delete(value);
174
- return copied;
175
- }
176
- const copied = {};
177
- for (const [key, item] of Object.entries(value)) {
178
- if (boundary && key === "__proto__")
179
- continue;
180
- const copiedItem = next(item);
181
- if (copiedItem === undefined && mode === "json")
182
- continue;
183
- defineHost(copied, key, copiedItem);
184
- }
185
- seen.delete(value);
186
- return copied;
75
+ });
76
+ return visit(record(ctx.builtins.Object, { "": value }), "", 0);
187
77
  };
188
- // Own data property regardless of the target's prototype, so a "__proto__" key on a host object
189
- // never reaches the Object.prototype setter.
190
- const defineHost = (target, key, value) => {
191
- Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
78
+ /** Host JSON as program values: objects and arrays are copied, primitives pass through. */
79
+ export const fromJson = (ctx, value) => {
80
+ if (value === null || typeof value !== "object")
81
+ return value;
82
+ if (Array.isArray(value))
83
+ return new Arr(ctx.builtins.Array, value.map((item) => fromJson(ctx, item)));
84
+ const copied = new Obj(ctx.builtins.Object);
85
+ for (const [key, item] of Object.entries(value))
86
+ define(copied, key, fromJson(ctx, item));
87
+ return copied;
192
88
  };
@@ -1,11 +1,12 @@
1
1
  import { Effect } from "effect";
2
2
  import { ToolError } from "../tool-error.js";
3
- import { toData, ToolRuntimeError } from "../data.js";
3
+ import { ToolRuntimeError } from "../tool-runtime.js";
4
4
  import { formatLocation, PendingThrow, Throw, sourceLocation, typeError } from "./model.js";
5
5
  import { containsRuntimeReference } from "./references.js";
6
6
  import { createErrorValue, isErrorType } from "./intrinsics.js";
7
7
  import { constructor, methods, prototypeFrom, receiver } from "./native.js";
8
8
  import { define, get, hidden, Arr, ErrorObj, Obj } from "./objects.js";
9
+ import { formatValue } from "../stdlib/console.js";
9
10
  import { coerceToString } from "../stdlib/value.js";
10
11
  export const normalizeError = (error) => {
11
12
  if (error instanceof PendingThrow) {
@@ -40,12 +41,7 @@ export const normalizeError = (error) => {
40
41
  message = value;
41
42
  }
42
43
  else {
43
- try {
44
- message = JSON.stringify(toData(value, "Thrown value")) ?? String(value);
45
- }
46
- catch {
47
- message = String(value);
48
- }
44
+ message = formatValue(value);
49
45
  }
50
46
  return { kind: "ExecutionFailure", message: `Uncaught: ${message}` };
51
47
  }
@@ -3,7 +3,7 @@ import { Cause, Effect, Scope } from "effect";
3
3
  // #transpile: conditional import — full typescript on node/bun, an identity
4
4
  // pass-through on workerd (the compiler is ~11 MiB and can't init there).
5
5
  import { transpile } from "#transpile";
6
- import { toData } from "../data.js";
6
+ import { toBoundary } from "../data.js";
7
7
  import { ToolRuntime } from "../tool-runtime.js";
8
8
  import { normalizeError } from "./errors.js";
9
9
  import { createBuiltins } from "./intrinsics.js";
@@ -21,7 +21,7 @@ export const executeProgram = (code, prepared, limits, hooks, globals) => {
21
21
  // Allocate execution state inside suspension so reused Effects never share it.
22
22
  return Effect.suspend(() => {
23
23
  const builtins = createBuiltins();
24
- const tools = ToolRuntime.make(prepared, builtins, limits.maxToolCalls, hooks);
24
+ const tools = ToolRuntime.make(prepared, limits.maxToolCalls, hooks);
25
25
  const logs = [];
26
26
  const logged = () => (logs.length > 0 ? { logs: [...logs] } : {});
27
27
  // Set only after copy-out so timeouts cannot report invalid values as completed.
@@ -29,8 +29,8 @@ export const executeProgram = (code, prepared, limits, hooks, globals) => {
29
29
  const base = Effect.acquireUseRelease(Scope.make("parallel"), (scope) => Effect.gen(function* () {
30
30
  const program = parseProgram(code);
31
31
  const pending = new Pending(scope, builtins.Promise);
32
- const value = yield* new Interpreter({ tools, pending, builtins, logs, globals }).run(program);
33
- const result = toData(value, "Execution result", "result");
32
+ const ctx = new Interpreter({ tools, pending, builtins, logs, globals });
33
+ const result = (yield* toBoundary(ctx, yield* ctx.run(program))) ?? null;
34
34
  returned = { value: result, pending };
35
35
  const warnings = yield* pending.interrupt();
36
36
  return {
@@ -1,7 +1,7 @@
1
1
  import { Effect } from "effect";
2
- import { MAX_VALUE_DEPTH } from "../data.js";
3
2
  import { coerceToString } from "../stdlib/value.js";
4
3
  import { createErrorValue, isErrorType } from "./intrinsics.js";
4
+ import { MAX_VALUE_DEPTH } from "./limits.js";
5
5
  import { Throw, typeError } from "./model.js";
6
6
  import { constructor, fn } from "./native.js";
7
7
  import { Callable, define, defineAccessor, entries, get, hidden, Arr, Bytes, DateObj, ErrorObj, GeneratorObj, Handle, MapObj, Obj, PromiseObj, RegExpObj, SetObj, URLObj, URLSearchParamsObj, } from "./objects.js";
@@ -46,7 +46,7 @@ const symbolGlobal = (ctx) => {
46
46
  // A table rather than a list so the names are known before any runtime exists.
47
47
  const table = {
48
48
  tools: () => new ToolReference([]),
49
- search: (ctx) => native(ctx.builtins, { name: "search", call: (_, args) => ctx.tools.search(args), callback: false }),
49
+ search: (ctx) => native(ctx.builtins, { name: "search", call: (_, args) => ctx.tool(ctx.tools.search, args), callback: false }),
50
50
  undefined: () => undefined,
51
51
  NaN: () => NaN,
52
52
  Infinity: () => Infinity,
@@ -1,5 +1,6 @@
1
1
  import type { Program } from "acorn";
2
2
  import { Effect } from "effect";
3
+ import { type Json } from "../data.js";
3
4
  import { type ToolRuntime } from "../tool-runtime.js";
4
5
  import type { Builtins } from "./intrinsics.js";
5
6
  import { PromiseObj } from "./objects.js";
@@ -28,4 +29,6 @@ export declare class Interpreter<R> {
28
29
  }, unknown, R>;
29
30
  close: Effect.Effect<void, unknown, R>;
30
31
  } | undefined, unknown, R>;
32
+ /** Runs one host tool: arguments cross as JSON and the result comes back as program values. */
33
+ tool(run: (args: Array<Json | undefined>) => Effect.Effect<Json | undefined, unknown, R>, args: Array<unknown>): Effect.Effect<unknown, unknown, R>;
31
34
  }
@@ -1,5 +1,5 @@
1
1
  import { Cause, Deferred, Effect, Exit } from "effect";
2
- import { toProgram } from "../data.js";
2
+ import { fromJson, toBoundary } from "../data.js";
3
3
  import { ToolReference } from "../tool-runtime.js";
4
4
  import { AsyncIteratorSymbol, CallSite, GeneratorReturn, IteratorSymbol, OptionalShortCircuit, invalidData, Throw, rangeError, typeError, unsupportedSyntax, } from "./model.js";
5
5
  import { checkStringLength } from "./limits.js";
@@ -173,6 +173,14 @@ export class Interpreter {
173
173
  iterate(value) {
174
174
  return this.root.iterate(value);
175
175
  }
176
+ /** Runs one host tool: arguments cross as JSON and the result comes back as program values. */
177
+ tool(run, args) {
178
+ const ctx = this;
179
+ return Effect.gen(function* () {
180
+ const json = yield* Effect.forEach(args, (arg) => toBoundary(ctx, arg));
181
+ return fromJson(ctx, yield* run(json));
182
+ });
183
+ }
176
184
  }
177
185
  const MAX_CALL_DEPTH = 10_000;
178
186
  /** One activation: the top-level program or a single function call, evaluating against its own scope chain. */
@@ -219,7 +227,7 @@ class Frame {
219
227
  }
220
228
  // Fork at the call site so admission and hooks occur when the call is made.
221
229
  createToolCallPromise(path, args) {
222
- return this.ctx.pending.create(Effect.suspend(() => this.ctx.tools.execute(path, args)));
230
+ return this.ctx.pending.create(this.ctx.tool((json) => this.ctx.tools.execute(path, json), args));
223
231
  }
224
232
  // Fiber exits make settlement idempotent; yielding prevents inline continuation.
225
233
  await(promise) {
@@ -943,7 +951,9 @@ class Frame {
943
951
  const regex = node.regex;
944
952
  if (regex)
945
953
  return Effect.sync(() => constructRegExp(this.ctx.builtins, [regex.pattern, regex.flags]));
946
- return Effect.sync(() => toProgram(this.ctx.builtins, node.value, "Literal"));
954
+ if (typeof node.value === "bigint")
955
+ throw typeError("BigInt literals are not supported.", node);
956
+ return Effect.succeed(node.value);
947
957
  }
948
958
  case "Identifier":
949
959
  return Effect.sync(() => this.scopes.get(node.name, node));
@@ -1029,7 +1039,7 @@ class Frame {
1029
1039
  const rhs = yield* self.evaluateExpression(node.right);
1030
1040
  if (operator === "instanceof")
1031
1041
  return instanceofValue(lhs, rhs, node);
1032
- return toProgram(self.ctx.builtins, self.applyBinaryOperator(operator, lhs, rhs, node), "Binary expression result");
1042
+ return self.applyBinaryOperator(operator, lhs, rhs, node);
1033
1043
  });
1034
1044
  }
1035
1045
  applyBinaryOperator(operator, lhs, rhs, node) {
@@ -1154,7 +1164,7 @@ class Frame {
1154
1164
  default:
1155
1165
  throw typeError(`Unsupported unary operator '${operator}'.`, node);
1156
1166
  }
1157
- return toProgram(this.ctx.builtins, result, "Unary expression result");
1167
+ return result;
1158
1168
  });
1159
1169
  }
1160
1170
  evaluateAssignmentExpression(node) {
@@ -1175,8 +1185,7 @@ class Frame {
1175
1185
  if (operator !== "=") {
1176
1186
  const current = self.scopes.get(name, left);
1177
1187
  const rightValue = yield* self.evaluateExpression(node.right);
1178
- const next = toProgram(self.ctx.builtins, self.applyCompoundAssignment(operator, current, rightValue, node), "Assignment result");
1179
- return self.scopes.set(name, next, left);
1188
+ return self.scopes.set(name, self.applyCompoundAssignment(operator, current, rightValue, node), left);
1180
1189
  }
1181
1190
  const rightValue = yield* self.evaluateNamed(node.right, name);
1182
1191
  return self.scopes.set(name, rightValue, left);
@@ -1185,7 +1194,7 @@ class Frame {
1185
1194
  return yield* self.modifyMember(left, (current) => Effect.map(self.evaluateExpression(node.right), (rightValue) => {
1186
1195
  if (operator === "=")
1187
1196
  return { write: true, next: rightValue, result: rightValue };
1188
- const next = toProgram(self.ctx.builtins, self.applyCompoundAssignment(operator, current, rightValue, node), "Assignment result");
1197
+ const next = self.applyCompoundAssignment(operator, current, rightValue, node);
1189
1198
  return { write: true, next, result: next };
1190
1199
  }));
1191
1200
  }
@@ -1650,7 +1659,7 @@ class Frame {
1650
1659
  checkStringLength(output.length);
1651
1660
  if (index < expressions.length) {
1652
1661
  const raw = yield* self.evaluateExpression(expressions[index]);
1653
- output += coerceToString(toProgram(self.ctx.builtins, raw, "Template interpolation"));
1662
+ output += coerceToString(raw);
1654
1663
  checkStringLength(output.length);
1655
1664
  }
1656
1665
  }
@@ -4,5 +4,7 @@ export declare const MAX_STRING_LENGTH: number;
4
4
  export declare const MAX_ARRAY_LENGTH = 10000000;
5
5
  /** Most promises that may be pending at once. */
6
6
  export declare const MAX_PENDING_PROMISES = 10000;
7
+ /** Deepest nesting a value may have when it crosses to or from the host. */
8
+ export declare const MAX_VALUE_DEPTH = 32;
7
9
  export declare const checkStringLength: (length: number) => void;
8
10
  export declare const checkArrayLength: (length: number) => void;
@@ -7,6 +7,8 @@ export const MAX_STRING_LENGTH = 1 << 24;
7
7
  export const MAX_ARRAY_LENGTH = 10_000_000;
8
8
  /** Most promises that may be pending at once. */
9
9
  export const MAX_PENDING_PROMISES = 10_000;
10
+ /** Deepest nesting a value may have when it crosses to or from the host. */
11
+ export const MAX_VALUE_DEPTH = 32;
10
12
  export const checkStringLength = (length) => {
11
13
  if (length > MAX_STRING_LENGTH)
12
14
  throw rangeError("Invalid string length");
@@ -2,3 +2,5 @@ import { Obj } from "../interpreter/objects.js";
2
2
  import type { Interpreter } from "../interpreter/interpreter.js";
3
3
  /** Captured console: every method appends one formatted line to `logs`. */
4
4
  export declare const consoleGlobal: <R>(ctx: Interpreter<R>) => Obj;
5
+ /** One value as `console.log` shows it. */
6
+ export declare const formatValue: (value: unknown) => string;
@@ -1,7 +1,6 @@
1
- import { toData, toProgram } from "../data.js";
2
1
  import { methods } from "../interpreter/native.js";
3
2
  import { entries, get, Arr, Bytes, DateObj, MapObj, Obj, PromiseObj, RegExpObj, SetObj, URLObj, URLSearchParamsObj, } from "../interpreter/objects.js";
4
- import { containsOpaqueReference, containsRuntimeReference, isRuntimeReference } from "../interpreter/references.js";
3
+ import { containsOpaqueReference, isRuntimeReference } from "../interpreter/references.js";
5
4
  import { coerceToString } from "./value.js";
6
5
  const consoleMethods = ["log", "info", "debug", "warn", "error", "dir", "table"];
7
6
  /** Captured console: every method appends one formatted line to `logs`. */
@@ -12,22 +11,23 @@ export const consoleGlobal = (ctx) => {
12
11
  name,
13
12
  0,
14
13
  (_, args) => {
15
- ctx.logs.push(formatConsoleMessage(builtins, name, args));
14
+ ctx.logs.push(formatConsoleMessage(name, args));
16
15
  return undefined;
17
16
  },
18
17
  ]));
19
18
  return console;
20
19
  };
21
20
  const MAX_CONSOLE_DEPTH = 32;
22
- const formatConsoleMessage = (builtins, name, args) => {
21
+ const formatConsoleMessage = (name, args) => {
23
22
  if (name === "dir")
24
- return args.length === 0 ? "undefined" : formatConsoleArgument(args[0]);
23
+ return args.length === 0 ? "undefined" : formatValue(args[0]);
25
24
  if (name === "table")
26
- return formatConsoleTable(builtins, args[0], args[1]);
25
+ return formatConsoleTable(args[0], args[1]);
27
26
  const prefix = name === "warn" ? "[warn] " : name === "error" ? "[error] " : name === "debug" ? "[debug] " : "";
28
- return `${prefix}${args.map((arg) => formatConsoleArgument(arg)).join(" ")}`;
27
+ return `${prefix}${args.map((arg) => formatValue(arg)).join(" ")}`;
29
28
  };
30
- const formatConsoleArgument = (value) => {
29
+ /** One value as `console.log` shows it. */
30
+ export const formatValue = (value) => {
31
31
  if (value === undefined)
32
32
  return "undefined";
33
33
  if (typeof value === "string")
@@ -95,14 +95,13 @@ const formatConsoleValue = (value, seen, depth) => {
95
95
  }
96
96
  };
97
97
  const formatItems = (items, seen, depth) => items.map((item) => formatConsoleValue(item, seen, depth)).join(",");
98
- const formatConsoleTable = (builtins, value, columnsArgument) => {
98
+ const formatConsoleTable = (value, columnsArgument) => {
99
99
  if (value === undefined)
100
100
  return "undefined";
101
101
  if (containsOpaqueReference(value))
102
102
  return "[opaque reference]";
103
- const data = toProgram(builtins, value, "console.table argument");
104
- const columns = consoleTableColumns(columnsArgument);
105
- const rows = consoleTableRows(data, columns);
103
+ const columns = columnsArgument instanceof Arr ? columnsArgument.items.map(String) : undefined;
104
+ const rows = consoleTableRows(value, columns);
106
105
  const keys = columns ?? Array.from(new Set(rows.flatMap((row) => Object.keys(row.values))));
107
106
  const header = ["(index)", ...keys].join("\t");
108
107
  return [
@@ -110,14 +109,6 @@ const formatConsoleTable = (builtins, value, columnsArgument) => {
110
109
  ...rows.map((row) => [row.index, ...keys.map((key) => formatConsoleTableCell(row.values[key]))].join("\t")),
111
110
  ].join("\n");
112
111
  };
113
- const consoleTableColumns = (value) => {
114
- if (value === undefined)
115
- return undefined;
116
- if (containsRuntimeReference(value))
117
- return undefined;
118
- const columns = toData(value, "console.table columns", "result");
119
- return Array.isArray(columns) ? columns.map((column) => String(column)) : undefined;
120
- };
121
112
  const consoleTableRows = (data, columns) => {
122
113
  if (data instanceof Arr) {
123
114
  return data.items.map((item, index) => ({ index: String(index), values: consoleTableValues(item, columns) }));
@@ -4,8 +4,8 @@ import { applyCollectionCallback } from "../interpreter/callback.js";
4
4
  import { checkStringLength } from "../interpreter/limits.js";
5
5
  import { syntaxError, typeError } from "../interpreter/model.js";
6
6
  import { typeofValue } from "../interpreter/references.js";
7
- import { fromData, toData, toProgram } from "../data.js";
8
- import { Callable, get, keys, Arr, Obj, record, remove, set } from "../interpreter/objects.js";
7
+ import { fromJson, toJson } from "../data.js";
8
+ import { get, keys, Arr, Obj, record, remove, set } from "../interpreter/objects.js";
9
9
  export const jsonGlobal = (ctx) => {
10
10
  const json = new Obj(ctx.builtins.Object);
11
11
  methods(ctx.builtins, json, [
@@ -20,7 +20,7 @@ const parse = (ctx, args) => {
20
20
  throw typeError("JSON.parse expects a string.");
21
21
  const parsed = (() => {
22
22
  try {
23
- return fromData(ctx.builtins, JSON.parse(text), "JSON.parse result");
23
+ return fromJson(ctx, JSON.parse(text));
24
24
  }
25
25
  catch (error) {
26
26
  throw syntaxError(`JSON.parse received invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
@@ -48,59 +48,16 @@ const stringify = (ctx, args) => {
48
48
  const space = args[2];
49
49
  const indent = typeof space === "number" || typeof space === "string" ? space : undefined;
50
50
  const replacer = args[1];
51
- if (typeofValue(replacer) !== "function") {
52
- const properties = replacer instanceof Arr
53
- ? replacer.items
54
- .filter((item) => typeof item === "string" || typeof item === "number")
55
- .map(String)
56
- : null;
57
- // Not a host boundary: __proto__ stays and Set/RegExp/URLSearchParams serialize as {}, like JS.
58
- const text = JSON.stringify(toData(args[0], "JSON.stringify value", "json", false), properties, indent);
51
+ const properties = replacer instanceof Arr
52
+ ? replacer.items
53
+ .filter((item) => typeof item === "string" || typeof item === "number")
54
+ .map(String)
55
+ : null;
56
+ const callback = typeofValue(replacer) === "function" ? applyCollectionCallback(ctx, replacer, "JSON.stringify") : undefined;
57
+ return Effect.map(toJson(ctx, args[0], callback), (value) => {
58
+ const text = JSON.stringify(value, properties, indent);
59
59
  if (text !== undefined)
60
60
  checkStringLength(text.length);
61
- return Effect.succeed(text);
62
- }
63
- // Validate up front; the replacer walk below reads the original value.
64
- toProgram(ctx.builtins, args[0], "JSON.stringify value");
65
- const apply = applyCollectionCallback(ctx, replacer, "JSON.stringify");
66
- const stack = new Set();
67
- const visit = (holder, key) => Effect.gen(function* () {
68
- const value = yield* apply([key, yield* toJSONValue(ctx, get(holder, key), key)]);
69
- if (value === undefined || typeofValue(value) === "function")
70
- return undefined;
71
- toProgram(ctx.builtins, value, "JSON.stringify replacer result");
72
- if (typeof value === "number")
73
- return Number.isFinite(value) ? value : null;
74
- if (value === null || typeof value === "string" || typeof value === "boolean")
75
- return value;
76
- if (!(value instanceof Obj))
77
- return {};
78
- if (stack.has(value))
79
- throw typeError("Converting circular structure to JSON.");
80
- stack.add(value);
81
- if (value instanceof Arr) {
82
- const result = [];
83
- for (let index = 0; index < value.items.length; index += 1) {
84
- result.push((yield* visit(value, String(index))) ?? null);
85
- }
86
- stack.delete(value);
87
- return result;
88
- }
89
- const result = Object.create(null);
90
- for (const name of keys(value)) {
91
- const item = yield* visit(value, name);
92
- if (item !== undefined)
93
- result[name] = item;
94
- }
95
- stack.delete(value);
96
- return result;
61
+ return text;
97
62
  });
98
- return Effect.map(visit(record(ctx.builtins.Object, { "": args[0] }), ""), (value) => JSON.stringify(value, null, indent));
99
- };
100
- // SerializeJSONProperty step 2: a callable `toJSON` decides the value, as Date and URL define.
101
- const toJSONValue = (ctx, value, key) => {
102
- if (!(value instanceof Obj))
103
- return Effect.succeed(value);
104
- const toJSON = get(value, "toJSON");
105
- return toJSON instanceof Callable ? ctx.call(toJSON, value, [key]) : Effect.succeed(value);
106
63
  };
@@ -1,5 +1,4 @@
1
1
  import { Effect } from "effect";
2
- import { toProgram } from "../data.js";
3
2
  import { constructor, methods, receiver } from "../interpreter/native.js";
4
3
  import { AsyncIteratorSymbol, invalidData, IteratorSymbol, rangeError, typeError, } from "../interpreter/model.js";
5
4
  import { Callable, define, entries, enumerableKeys, getOwn, hasOwn, hasPrototype, hidden, keys, own, Arr, Bytes, DateObj, ErrorObj, Obj, PromiseObj, RegExpObj, set, } from "../interpreter/objects.js";
@@ -115,9 +114,9 @@ export const objectGlobal = (ctx) => {
115
114
  [
116
115
  "keys",
117
116
  1,
118
- (_, args) => toProgram(builtins, args[0] instanceof ToolReference
117
+ (_, args) => new Arr(builtins.Array, args[0] instanceof ToolReference
119
118
  ? [...ctx.tools.keys(args[0].path)]
120
- : keys(enumerableSource(ctx, "Object.keys(...)", args[0])), "Object.keys result"),
119
+ : keys(enumerableSource(ctx, "Object.keys(...)", args[0]))),
121
120
  ],
122
121
  [
123
122
  "values",
@@ -1,5 +1,4 @@
1
1
  import { Effect } from "effect";
2
- import { toProgram } from "../data.js";
3
2
  import { constructor, methods } from "../interpreter/native.js";
4
3
  import { checkArrayLength, checkStringLength } from "../interpreter/limits.js";
5
4
  import { invalidData, rangeError, typeError } from "../interpreter/model.js";
@@ -58,9 +57,7 @@ const replaceWithCallback = (ctx, value, name, args) => {
58
57
  let end = 0;
59
58
  for (const match of matches) {
60
59
  const replacement = yield* apply(match.args);
61
- output.push(value.slice(end, match.offset), replacement instanceof PromiseObj
62
- ? "[object Promise]"
63
- : coerceToString(toProgram(builtins, replacement, `String.${name} replacer result`)));
60
+ output.push(value.slice(end, match.offset), replacement instanceof PromiseObj ? "[object Promise]" : coerceToString(replacement));
64
61
  end = match.offset + match.match.length;
65
62
  }
66
63
  output.push(value.slice(end));
@@ -187,7 +184,7 @@ export const stringGlobal = (ctx) => {
187
184
  return null;
188
185
  // Preserve the own `index` and `groups` properties on non-global matches.
189
186
  if (pattern.global)
190
- return toProgram(builtins, matched, "String.match result");
187
+ return new Arr(builtins.Array, [...matched]);
191
188
  return matchToValue(builtins, matched);
192
189
  }),
193
190
  simple("matchAll", 1, (value, args) => {
@@ -1,6 +1,4 @@
1
- import type { Builtins } from "../interpreter/intrinsics.js";
2
1
  import type { Interpreter } from "../interpreter/interpreter.js";
3
- export declare const uriArgument: (builtins: Builtins, value: unknown, label: string) => string;
4
2
  type UriFunction = "encodeURI" | "encodeURIComponent" | "decodeURI" | "decodeURIComponent";
5
3
  export declare const uriGlobal: <R>(ctx: Interpreter<R>, name: UriFunction) => import("../interpreter/objects.js").Native<R>;
6
4
  export declare const urlGlobal: <R>(ctx: Interpreter<R>) => import("../interpreter/objects.js").Native<R>;
@@ -1,5 +1,4 @@
1
1
  import { Effect } from "effect";
2
- import { toProgram, ToolRuntimeError } from "../data.js";
3
2
  import { constructor, fn, methods, prototypeFrom, receiver, requiresNew } from "../interpreter/native.js";
4
3
  import { PendingThrow, typeError, uriError } from "../interpreter/model.js";
5
4
  import { defineAccessor, entries, isWrapper, Arr, Obj, URLObj, URLSearchParamsObj } from "../interpreter/objects.js";
@@ -19,7 +18,6 @@ const urlProperties = [
19
18
  "search",
20
19
  "hash",
21
20
  ];
22
- export const uriArgument = (builtins, value, label) => coerceToString(toProgram(builtins, value, label));
23
21
  const uriFunctions = {
24
22
  encodeURI,
25
23
  encodeURIComponent,
@@ -27,7 +25,7 @@ const uriFunctions = {
27
25
  decodeURIComponent,
28
26
  };
29
27
  export const uriGlobal = (ctx, name) => fn(ctx.builtins, name, 1, (_, args) => {
30
- const value = uriArgument(ctx.builtins, args[0], `${name} input`);
28
+ const value = coerceToString(args[0]);
31
29
  try {
32
30
  return uriFunctions[name](value);
33
31
  }
@@ -35,7 +33,7 @@ export const uriGlobal = (ctx, name) => fn(ctx.builtins, name, 1, (_, args) => {
35
33
  throw uriError(`${name} received malformed URI data: ${error instanceof Error ? error.message : String(error)}`);
36
34
  }
37
35
  });
38
- const urlArgument = (builtins, value, label) => value instanceof URLObj ? value.url.href : uriArgument(builtins, value, label);
36
+ const urlArgument = (value) => (value instanceof URLObj ? value.url.href : coerceToString(value));
39
37
  export const urlGlobal = (ctx) => {
40
38
  const builtins = ctx.builtins;
41
39
  const proto = builtins.URL;
@@ -43,8 +41,8 @@ export const urlGlobal = (ctx) => {
43
41
  if (args.length === 0) {
44
42
  throw typeError("new URL(...) requires a URL string and an optional base URL.");
45
43
  }
46
- const input = urlArgument(builtins, args[0], "new URL input");
47
- const base = args[1] === undefined ? undefined : urlArgument(builtins, args[1], "new URL base");
44
+ const input = urlArgument(args[0]);
45
+ const base = args[1] === undefined ? undefined : urlArgument(args[1]);
48
46
  try {
49
47
  return new URLObj(into, builtins.URLSearchParams, new URL(input, base));
50
48
  }
@@ -64,8 +62,8 @@ export const urlGlobal = (ctx) => {
64
62
  (_, args) => {
65
63
  if (args.length === 0)
66
64
  throw typeError(`URL.${name} requires a URL argument.`);
67
- const input = urlArgument(builtins, args[0], `URL.${name} input`);
68
- const base = args[1] === undefined ? undefined : urlArgument(builtins, args[1], `URL.${name} base`);
65
+ const input = urlArgument(args[0]);
66
+ const base = args[1] === undefined ? undefined : urlArgument(args[1]);
69
67
  try {
70
68
  const parsed = new URL(input, base);
71
69
  return name === "canParse" ? true : new URLObj(proto, builtins.URLSearchParams, parsed);
@@ -84,10 +82,10 @@ export const urlGlobal = (ctx) => {
84
82
  const target = self(thisValue, name);
85
83
  try {
86
84
  ;
87
- target.url[name] = uriArgument(builtins, value, `URL.${name} value`);
85
+ target.url[name] = coerceToString(value);
88
86
  }
89
87
  catch (error) {
90
- if (error instanceof PendingThrow || error instanceof ToolRuntimeError)
88
+ if (error instanceof PendingThrow)
91
89
  throw error;
92
90
  throw typeError(`URL.${name} received an invalid value.`);
93
91
  }
@@ -110,7 +108,7 @@ const readPair = (ctx, value) => Effect.gen(function* () {
110
108
  const step = yield* cursor.next;
111
109
  if (step.done)
112
110
  return items;
113
- items.push(yield* preserveConsumerError(cursor, Effect.sync(() => uriArgument(ctx.builtins, step.value, "URLSearchParams pair value"))));
111
+ items.push(yield* preserveConsumerError(cursor, Effect.sync(() => coerceToString(step.value))));
114
112
  }
115
113
  });
116
114
  const constructURLSearchParams = (ctx, init, proto) => {
@@ -160,7 +158,7 @@ export const urlSearchParamsGlobal = (ctx) => {
160
158
  });
161
159
  const self = (thisValue, name) => receiver(URLSearchParamsObj, thisValue, `URLSearchParams.prototype.${name}`);
162
160
  const wrap = (items) => new Arr(builtins.Array, items);
163
- const arg = (name, args, index) => uriArgument(builtins, args[index], `URLSearchParams.${name} argument ${index + 1}`);
161
+ const arg = (args, index) => coerceToString(args[index]);
164
162
  const requireArgs = (name, args, count) => {
165
163
  if (args.length < count) {
166
164
  throw typeError(`URLSearchParams.${name} requires ${count} argument${count === 1 ? "" : "s"}.`);
@@ -173,7 +171,7 @@ export const urlSearchParamsGlobal = (ctx) => {
173
171
  2,
174
172
  (thisValue, args) => {
175
173
  requireArgs("append", args, 2);
176
- self(thisValue, "append").params.append(arg("append", args, 0), arg("append", args, 1));
174
+ self(thisValue, "append").params.append(arg(args, 0), arg(args, 1));
177
175
  return undefined;
178
176
  },
179
177
  ],
@@ -184,9 +182,9 @@ export const urlSearchParamsGlobal = (ctx) => {
184
182
  requireArgs("delete", args, 1);
185
183
  const params = self(thisValue, "delete").params;
186
184
  if (args[1] !== undefined)
187
- params.delete(arg("delete", args, 0), arg("delete", args, 1));
185
+ params.delete(arg(args, 0), arg(args, 1));
188
186
  else
189
- params.delete(arg("delete", args, 0));
187
+ params.delete(arg(args, 0));
190
188
  return undefined;
191
189
  },
192
190
  ],
@@ -195,7 +193,7 @@ export const urlSearchParamsGlobal = (ctx) => {
195
193
  1,
196
194
  (thisValue, args) => {
197
195
  requireArgs("get", args, 1);
198
- return self(thisValue, "get").params.get(arg("get", args, 0));
196
+ return self(thisValue, "get").params.get(arg(args, 0));
199
197
  },
200
198
  ],
201
199
  [
@@ -203,7 +201,7 @@ export const urlSearchParamsGlobal = (ctx) => {
203
201
  1,
204
202
  (thisValue, args) => {
205
203
  requireArgs("getAll", args, 1);
206
- return wrap(self(thisValue, "getAll").params.getAll(arg("getAll", args, 0)));
204
+ return wrap(self(thisValue, "getAll").params.getAll(arg(args, 0)));
207
205
  },
208
206
  ],
209
207
  [
@@ -212,9 +210,7 @@ export const urlSearchParamsGlobal = (ctx) => {
212
210
  (thisValue, args) => {
213
211
  requireArgs("has", args, 1);
214
212
  const params = self(thisValue, "has").params;
215
- return args[1] !== undefined
216
- ? params.has(arg("has", args, 0), arg("has", args, 1))
217
- : params.has(arg("has", args, 0));
213
+ return args[1] !== undefined ? params.has(arg(args, 0), arg(args, 1)) : params.has(arg(args, 0));
218
214
  },
219
215
  ],
220
216
  [
@@ -222,7 +218,7 @@ export const urlSearchParamsGlobal = (ctx) => {
222
218
  2,
223
219
  (thisValue, args) => {
224
220
  requireArgs("set", args, 2);
225
- self(thisValue, "set").params.set(arg("set", args, 0), arg("set", args, 1));
221
+ self(thisValue, "set").params.set(arg(args, 0), arg(args, 1));
226
222
  return undefined;
227
223
  },
228
224
  ],
@@ -1,4 +1,3 @@
1
- import { toProgram } from "../data.js";
2
1
  import { fn } from "../interpreter/native.js";
3
2
  import { typeError } from "../interpreter/model.js";
4
3
  import { get, isWrapper, Arr, Bytes, DateObj, ErrorObj, MapObj, RegExpObj, SetObj, URLObj, URLSearchParamsObj, } from "../interpreter/objects.js";
@@ -78,25 +77,24 @@ const coerce = (ctx, name, args) => {
78
77
  return parseInt(coerceToString(raw));
79
78
  return parseFloat(coerceToString(raw));
80
79
  }
81
- const value = toProgram(ctx.builtins, raw, `${name} input`);
82
80
  if (name === "Number")
83
- return coerceToNumber(value);
81
+ return coerceToNumber(raw);
84
82
  if (name === "Boolean")
85
- return Boolean(value);
83
+ return Boolean(raw);
86
84
  if (name === "isFinite")
87
- return Number.isFinite(coerceToNumber(value));
85
+ return Number.isFinite(coerceToNumber(raw));
88
86
  if (name === "isNaN")
89
- return Number.isNaN(coerceToNumber(value));
87
+ return Number.isNaN(coerceToNumber(raw));
90
88
  if (name === "parseInt") {
91
89
  const radix = args[1];
92
90
  if (radix !== undefined && typeof radix !== "number") {
93
91
  throw typeError("parseInt expects a numeric radix.");
94
92
  }
95
- return parseInt(coerceToString(value), radix);
93
+ return parseInt(coerceToString(raw), radix);
96
94
  }
97
95
  if (name === "parseFloat")
98
- return parseFloat(coerceToString(value));
99
- return coerceToString(value);
96
+ return parseFloat(coerceToString(raw));
97
+ return coerceToString(raw);
100
98
  };
101
99
  /** A global coercion function such as `Number` or `parseInt`. */
102
- export const coercion = (ctx, name, length = 1) => fn(ctx.builtins, name, length, (_, args) => toProgram(ctx.builtins, coerce(ctx, name, args), `${name} result`));
100
+ export const coercion = (ctx, name, length = 1) => fn(ctx.builtins, name, length, (_, args) => coerce(ctx, name, args));
@@ -1,5 +1,6 @@
1
1
  import { Effect } from "effect";
2
- import type { Builtins } from "./interpreter/intrinsics.js";
2
+ import type { Json } from "./data.js";
3
+ import type { DiagnosticKind } from "./codemode.js";
3
4
  import { type Namespace } from "./namespace.js";
4
5
  import { type Tool } from "./tool.js";
5
6
  import type { Tools } from "./tools.js";
@@ -59,12 +60,18 @@ export type SearchEntry = {
59
60
  /** Exact callable signature of the built-in `search` function, for host-owned instructions. */
60
61
  export declare const searchSignature: string;
61
62
  export declare const prepare: <R>(tools: Tools<R>) => Prepared<R>;
63
+ export declare class ToolRuntimeError extends Error {
64
+ readonly kind: Extract<DiagnosticKind, "UnknownTool" | "InvalidToolInput" | "InvalidToolOutput" | "ToolCallLimitExceeded">;
65
+ readonly suggestions: ReadonlyArray<string>;
66
+ constructor(kind: Extract<DiagnosticKind, "UnknownTool" | "InvalidToolInput" | "InvalidToolOutput" | "ToolCallLimitExceeded">, message: string, suggestions?: ReadonlyArray<string>);
67
+ }
68
+ /** The tool bridge of one execution. Arguments arrive and results leave as JSON; program values never enter. */
62
69
  export type ToolRuntime<R = never> = {
63
70
  readonly calls: Array<ToolCall>;
64
- readonly execute: (path: ReadonlyArray<string>, args: Array<unknown>) => Effect.Effect<unknown, unknown, R>;
65
- readonly search: (args: Array<unknown>) => Effect.Effect<unknown, unknown, R>;
71
+ readonly execute: (path: ReadonlyArray<string>, args: Array<Json | undefined>) => Effect.Effect<Json | undefined, unknown, R>;
72
+ readonly search: (args: Array<Json | undefined>) => Effect.Effect<Json | undefined, unknown, R>;
66
73
  readonly keys: (path: ReadonlyArray<string>) => ReadonlyArray<string>;
67
74
  };
68
75
  /** Per-execution call state over tools prepared once for the runtime. */
69
- export declare const make: <R>(prepared: Prepared<R>, builtins: Builtins, maxToolCalls: number | undefined, hooks?: ToolCallHooks<R>) => ToolRuntime<R>;
76
+ export declare const make: <R>(prepared: Prepared<R>, maxToolCalls: number | undefined, hooks?: ToolCallHooks<R>) => ToolRuntime<R>;
70
77
  export * as ToolRuntime from "./tool-runtime.js";
@@ -1,5 +1,4 @@
1
1
  import { Cause, Effect, Exit, Formatter, Schema } from "effect";
2
- import { fromData, toData, ToolRuntimeError } from "./data.js";
3
2
  import { toolError } from "./tool-error.js";
4
3
  import { decodeInput as decodeToolInput, decodeOutput as decodeToolOutput, identifierSegment, inputProperties, inputTypeScript, isEmptyInput, outputTypeScript, } from "./tool-schema.js";
5
4
  import { isNamespace } from "./namespace.js";
@@ -183,8 +182,18 @@ const resolve = (root, path) => {
183
182
  }
184
183
  return node.tool;
185
184
  };
185
+ export class ToolRuntimeError extends Error {
186
+ kind;
187
+ suggestions;
188
+ constructor(kind, message, suggestions = []) {
189
+ super(message);
190
+ this.kind = kind;
191
+ this.suggestions = suggestions;
192
+ this.name = "ToolRuntimeError";
193
+ }
194
+ }
186
195
  /** Per-execution call state over tools prepared once for the runtime. */
187
- export const make = (prepared, builtins, maxToolCalls, hooks) => {
196
+ export const make = (prepared, maxToolCalls, hooks) => {
188
197
  const calls = [];
189
198
  const root = prepared.root;
190
199
  const searchTool = makeSearchTool(prepared.searchIndex);
@@ -210,8 +219,8 @@ export const make = (prepared, builtins, maxToolCalls, hooks) => {
210
219
  }
211
220
  calls.push(call);
212
221
  };
213
- const executeTool = (name, tool, externalArgs) => Effect.gen(function* () {
214
- const normalized = externalArgs.length === 0 ? [{}] : externalArgs;
222
+ const executeTool = (name, tool, args) => Effect.gen(function* () {
223
+ const normalized = args.length === 0 ? [{}] : args;
215
224
  if (normalized.length !== 1)
216
225
  throw new ToolRuntimeError("InvalidToolInput", `Tool '${name}' expects at most one input object.`);
217
226
  const input = yield* Effect.try({
@@ -233,8 +242,12 @@ export const make = (prepared, builtins, maxToolCalls, hooks) => {
233
242
  .map((error) => (error.cause ? Formatter.format(error) : error.message || error.name))
234
243
  .join("\n")));
235
244
  }));
245
+ // The same round trip a tool result would take through text: exact JSON.stringify semantics.
236
246
  return yield* Effect.try({
237
- try: () => fromData(builtins, decodeToolOutput(tool, raw), `Result from tool '${name}'`),
247
+ try: () => {
248
+ const text = JSON.stringify(decodeToolOutput(tool, raw));
249
+ return text === undefined ? undefined : JSON.parse(text);
250
+ },
238
251
  catch: (cause) => new ToolRuntimeError("InvalidToolOutput", `Invalid output from tool '${name}': ${cause}`),
239
252
  });
240
253
  }), call);
@@ -242,13 +255,8 @@ export const make = (prepared, builtins, maxToolCalls, hooks) => {
242
255
  return {
243
256
  calls,
244
257
  keys: (path) => namespaceKeys(root, path),
245
- search: (args) => Effect.suspend(() => executeTool("search", searchTool, args.map((arg) => toData(arg, "Arguments for tool 'search'")))),
246
- execute: (path, args) => Effect.gen(function* () {
247
- const name = canonicalSegments(path).join(".");
248
- const externalArgs = args.map((arg) => toData(arg, `Arguments for tool '${name}'`));
249
- const tool = resolve(root, path);
250
- return yield* executeTool(name, tool, externalArgs);
251
- }),
258
+ search: (args) => Effect.suspend(() => executeTool("search", searchTool, args)),
259
+ execute: (path, args) => Effect.suspend(() => executeTool(canonicalSegments(path).join("."), resolve(root, path), args)),
252
260
  };
253
261
  };
254
262
  export * as ToolRuntime from "./tool-runtime.js";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@opencode/codemode",
4
- "version": "0.0.0-dev-19635",
4
+ "version": "0.0.0-dev-19636",
5
5
  "description": "Effect-native confined code execution over schema-described tools",
6
6
  "type": "module",
7
7
  "license": "MIT",