@opencode/codemode 0.0.0-dev-19352 → 0.0.0-dev-19356

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.
@@ -25,23 +25,20 @@ export type ResolvedExecutionLimits = {
25
25
  readonly maxToolCalls: number | undefined;
26
26
  readonly maxOutputBytes: number | undefined;
27
27
  };
28
- /** Options for one CodeMode execution. */
29
- export type ExecuteOptions<Provided extends Record<string, unknown> = {}> = {
30
- /** Source for one program in the supported JavaScript subset. */
31
- code: string;
28
+ /** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */
29
+ export type Options<Provided extends Record<string, unknown> = {}> = ToolRuntime.ToolCallHooks<Services<Provided>> & {
32
30
  /** Explicit tools exposed to the program as `tools`. */
33
31
  tools?: Provided & Tools<Services<Provided>>;
34
- /** Per-execution overrides for the default resource limits. */
32
+ /** Resource limits enforced on each execution. */
35
33
  limits?: ExecutionLimits;
36
- /** Observes decoded tool input immediately before tool execution. */
37
- onToolCallStart?: (call: ToolRuntime.ToolCallStarted) => Effect.Effect<void, never, Services<Provided>>;
38
- /** Observes each admitted tool call as it succeeds, fails, or is interrupted. */
39
- onToolCallEnd?: (call: ToolRuntime.ToolCallEnded) => Effect.Effect<void, never, Services<Provided>>;
34
+ };
35
+ /** Options for one CodeMode execution. */
36
+ export type ExecuteOptions<Provided extends Record<string, unknown> = {}> = Options<Provided> & {
37
+ /** Source for one program in the supported JavaScript subset. */
38
+ code: string;
40
39
  };
41
40
  /** A JSON value that can cross the confined interpreter boundary. */
42
41
  export type DataValue = Schema.Json;
43
- /** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */
44
- export type Options<Provided extends Record<string, unknown> = {}> = Omit<ExecuteOptions<Provided>, "code">;
45
42
  /** Schema for a host tool input containing CodeMode source. */
46
43
  export declare const Input: Schema.Struct<{
47
44
  readonly code: Schema.String;
package/dist/codemode.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Effect, Schema } from "effect";
2
- import { executeWithLimits } from "./interpreter/execute.js";
2
+ import { executeProgram } from "./interpreter/execute.js";
3
3
  import { ToolRuntime } from "./tool-runtime.js";
4
4
  /** Signature-construction helpers for host-owned catalog instructions. */
5
5
  export { searchSignature, toolExpression } from "./tool-runtime.js";
@@ -54,17 +54,13 @@ const resolveExecutionLimits = (limits) => ({
54
54
  maxOutputBytes: validateLimit("maxOutputBytes", limits?.maxOutputBytes, 0),
55
55
  });
56
56
  /** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
57
- export const execute = (options) => {
58
- const tools = (options.tools ?? {});
59
- return executeWithLimits(options, resolveExecutionLimits(options.limits), ToolRuntime.searchIndex(tools));
60
- };
57
+ export const execute = (options) => make(options).execute(options.code);
61
58
  /** Creates an Effect-native runtime over explicit, schema-described tools. */
62
59
  export const make = (options = {}) => {
63
- const tools = (options.tools ?? {});
60
+ const prepared = ToolRuntime.prepare((options.tools ?? {}));
64
61
  const limits = resolveExecutionLimits(options.limits);
65
- const prepared = ToolRuntime.prepare(tools);
66
62
  return {
67
63
  catalog: () => prepared.catalog,
68
- execute: (code) => executeWithLimits({ ...options, code }, limits, prepared.searchIndex),
64
+ execute: (code) => executeProgram(code, prepared, limits, options),
69
65
  };
70
66
  };
package/dist/data.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ export * as Data from "./data.js";
2
+ import type { DiagnosticKind } from "./codemode.js";
3
+ /** A null-prototype object owned by the program. */
4
+ export type SafeObject = Record<string, unknown>;
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
+ }
10
+ export declare const isBlockedMember: (name: string) => boolean;
11
+ /**
12
+ * Brings a host-produced runtime value into the program: runtime values pass through, their host
13
+ * counterparts (Date, RegExp, Map, Set, URL, URLSearchParams) are wrapped, and objects become
14
+ * null-prototype copies. Arrays keep extra enumerable properties such as `index` and `groups`.
15
+ */
16
+ export declare const toProgram: (value: unknown, label: string) => unknown;
17
+ /**
18
+ * Brings host data into the program: Date and URL become strings, other host collections become
19
+ * empty objects, and objects become null-prototype copies. Used for tool results and parsed JSON.
20
+ */
21
+ export declare const fromData: (value: unknown, label: string) => unknown;
22
+ /**
23
+ * Takes a program value out as plain JSON: runtime values serialize like `JSON.stringify` would,
24
+ * non-finite numbers become null, and array holes become null. `undefined` object properties are
25
+ * dropped ("json") or become null ("result", for program results where the consumer must never see
26
+ * undefined); a bare `undefined` follows the same rule.
27
+ */
28
+ export declare const toData: (value: unknown, label: string, undefinedAs?: "json" | "result") => unknown;
package/dist/data.js ADDED
@@ -0,0 +1,130 @@
1
+ export * as Data from "./data.js";
2
+ import { Values } from "./values.js";
3
+ 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
+ }
14
+ const blockedMemberNames = new Set(["__proto__", "constructor", "prototype"]);
15
+ export const isBlockedMember = (name) => blockedMemberNames.has(name);
16
+ /**
17
+ * Brings a host-produced runtime value into the program: runtime values pass through, their host
18
+ * counterparts (Date, RegExp, Map, Set, URL, URLSearchParams) are wrapped, and objects become
19
+ * null-prototype copies. Arrays keep extra enumerable properties such as `index` and `groups`.
20
+ */
21
+ export const toProgram = (value, label) => copy(value, label, "program", 0, new Set());
22
+ /**
23
+ * Brings host data into the program: Date and URL become strings, other host collections become
24
+ * empty objects, and objects become null-prototype copies. Used for tool results and parsed JSON.
25
+ */
26
+ export const fromData = (value, label) => copy(value, label, "data", 0, new Set());
27
+ /**
28
+ * Takes a program value out as plain JSON: runtime values serialize like `JSON.stringify` would,
29
+ * non-finite numbers become null, and array holes become null. `undefined` object properties are
30
+ * dropped ("json") or become null ("result", for program results where the consumer must never see
31
+ * undefined); a bare `undefined` follows the same rule.
32
+ */
33
+ export const toData = (value, label, undefinedAs = "json") => copy(value, label, undefinedAs, 0, new Set());
34
+ const copy = (value, label, mode, depth, seen) => {
35
+ if (depth > MAX_VALUE_DEPTH) {
36
+ throw new ToolRuntimeError("InvalidDataValue", `${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
37
+ }
38
+ if (value === undefined)
39
+ return mode === "result" ? null : undefined;
40
+ if (typeof value === "number")
41
+ return (mode === "json" || mode === "result") && !Number.isFinite(value) ? null : value;
42
+ if (value === null || typeof value === "string" || typeof value === "boolean")
43
+ return value;
44
+ if (typeof value !== "object") {
45
+ throw new ToolRuntimeError("InvalidDataValue", `${label} must contain data only.`);
46
+ }
47
+ if (value instanceof Values.Promise) {
48
+ 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.`);
49
+ }
50
+ if (mode === "program") {
51
+ if (Values.isValue(value))
52
+ return value;
53
+ if (value instanceof Date)
54
+ return new Values.Date(value.getTime());
55
+ if (value instanceof RegExp)
56
+ return new Values.RegExp(value.source, value.flags);
57
+ if (value instanceof Map) {
58
+ const wrapped = new Values.Map();
59
+ for (const [key, item] of value.entries()) {
60
+ wrapped.map.set(copy(key, label, mode, depth + 1, seen), copy(item, label, mode, depth + 1, seen));
61
+ }
62
+ return wrapped;
63
+ }
64
+ if (value instanceof Set) {
65
+ const wrapped = new Values.Set();
66
+ for (const item of value.values())
67
+ wrapped.set.add(copy(item, label, mode, depth + 1, seen));
68
+ return wrapped;
69
+ }
70
+ if (value instanceof URL)
71
+ return new Values.URL(new URL(value.href));
72
+ if (value instanceof URLSearchParams)
73
+ return new Values.URLSearchParams(new URLSearchParams(value));
74
+ }
75
+ const plain = mode === "program" || mode === "data";
76
+ if (value instanceof Values.Date)
77
+ return Number.isFinite(value.time) ? new Date(value.time).toISOString() : null;
78
+ if (value instanceof Date)
79
+ return Number.isFinite(value.getTime()) ? value.toISOString() : null;
80
+ if (value instanceof Values.URL)
81
+ return value.url.href;
82
+ if (value instanceof URL)
83
+ return value.href;
84
+ // Remaining runtime values and their host counterparts serialize as empty objects, like JSON.stringify.
85
+ if (Values.isValue(value) ||
86
+ value instanceof RegExp ||
87
+ value instanceof Map ||
88
+ value instanceof Set ||
89
+ value instanceof URLSearchParams) {
90
+ return plain ? Object.create(null) : {};
91
+ }
92
+ if (seen.has(value)) {
93
+ throw new ToolRuntimeError("InvalidDataValue", `${label} contains a circular value.`);
94
+ }
95
+ seen.add(value);
96
+ if (Array.isArray(value)) {
97
+ // Host output densifies holes to null like JSON; program copies keep them.
98
+ const copied = plain
99
+ ? value.map((item) => copy(item, label, mode, depth + 1, seen))
100
+ : Array.from(value, (item) => copy(item, label, mode, depth + 1, seen) ?? null);
101
+ if (mode === "program") {
102
+ for (const [key, item] of Object.entries(value)) {
103
+ if (Object.hasOwn(copied, key))
104
+ continue;
105
+ if (isBlockedMember(key)) {
106
+ throw new ToolRuntimeError("InvalidDataValue", `${label} contains blocked property '${key}'.`);
107
+ }
108
+ Reflect.set(copied, key, copy(item, label, mode, depth + 1, seen));
109
+ }
110
+ }
111
+ seen.delete(value);
112
+ return copied;
113
+ }
114
+ const prototype = Object.getPrototypeOf(value);
115
+ if (prototype !== Object.prototype && prototype !== null) {
116
+ throw new ToolRuntimeError("InvalidDataValue", `${label} must contain plain objects only.`);
117
+ }
118
+ const copied = plain ? Object.create(null) : {};
119
+ for (const [key, item] of Object.entries(value)) {
120
+ if (isBlockedMember(key)) {
121
+ throw new ToolRuntimeError("InvalidDataValue", `${label} contains blocked property '${key}'.`);
122
+ }
123
+ const next = copy(item, label, mode, depth + 1, seen);
124
+ if (next === undefined && mode === "json")
125
+ continue;
126
+ copied[key] = next;
127
+ }
128
+ seen.delete(value);
129
+ return copied;
130
+ };
@@ -1,6 +1,6 @@
1
1
  import { Effect } from "effect";
2
2
  import type { Diagnostic } from "../codemode.js";
3
- import { type SafeObject } from "../tool-runtime.js";
3
+ import { type SafeObject } from "../data.js";
4
4
  import { type AstNode } from "./model.js";
5
5
  import { type SyncIteratorRunner } from "./iterator.js";
6
6
  export declare const normalizeError: (error: unknown) => Diagnostic;
@@ -1,6 +1,6 @@
1
1
  import { Effect } from "effect";
2
2
  import { ToolError } from "../tool-error.js";
3
- import { copyOut, ToolRuntimeError } from "../tool-runtime.js";
3
+ import { toData, ToolRuntimeError } from "../data.js";
4
4
  import { formatLocation, InterpreterRuntimeError, ProgramThrow, sourceLocation } from "./model.js";
5
5
  import { containsRuntimeReference } from "./references.js";
6
6
  import {} from "./iterator.js";
@@ -41,7 +41,7 @@ export const normalizeError = (error) => {
41
41
  }
42
42
  else {
43
43
  try {
44
- message = JSON.stringify(copyOut(value, "json")) ?? String(value);
44
+ message = JSON.stringify(toData(value, "Thrown value")) ?? String(value);
45
45
  }
46
46
  catch {
47
47
  message = String(value);
@@ -1,4 +1,4 @@
1
1
  import { Effect } from "effect";
2
- import type { ExecuteOptions, ResolvedExecutionLimits, Result } from "../codemode.js";
3
- import { ToolRuntime, type Services } from "../tool-runtime.js";
4
- export declare const executeWithLimits: <const Provided extends Record<string, unknown>>(options: ExecuteOptions<Provided>, limits: ResolvedExecutionLimits, searchIndex: ToolRuntime.DiscoveryPlan["searchIndex"]) => Effect.Effect<Result, never, Services<Provided>>;
2
+ import type { ResolvedExecutionLimits, Result } from "../codemode.js";
3
+ import { ToolRuntime } from "../tool-runtime.js";
4
+ export declare const executeProgram: <R>(code: string, prepared: ToolRuntime.Prepared<R>, limits: ResolvedExecutionLimits, hooks: ToolRuntime.ToolCallHooks<R>) => Effect.Effect<Result, never, R>;
@@ -3,13 +3,14 @@ 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 { copyIn, copyOut, ToolRuntime } from "../tool-runtime.js";
6
+ import { toData } from "../data.js";
7
+ import { ToolRuntime } from "../tool-runtime.js";
7
8
  import { normalizeError } from "./errors.js";
8
9
  import { InterpreterRuntimeError, isRecord } from "./model.js";
9
10
  import { PromiseRuntime } from "./promises.js";
10
11
  import { Interpreter } from "./runtime.js";
11
- export const executeWithLimits = (options, limits, searchIndex) => {
12
- if (options.code.trim().length === 0) {
12
+ export const executeProgram = (code, prepared, limits, hooks) => {
13
+ if (code.trim().length === 0) {
13
14
  return Effect.succeed({
14
15
  ok: false,
15
16
  error: { kind: "ParseError", message: "Code cannot be empty." },
@@ -18,20 +19,17 @@ export const executeWithLimits = (options, limits, searchIndex) => {
18
19
  }
19
20
  // Allocate execution state inside suspension so reused Effects never share it.
20
21
  return Effect.suspend(() => {
21
- const tools = ToolRuntime.make((options.tools ?? {}), limits.maxToolCalls, searchIndex, {
22
- onToolCallStart: options.onToolCallStart,
23
- onToolCallEnd: options.onToolCallEnd,
24
- });
22
+ const tools = ToolRuntime.make(prepared, limits.maxToolCalls, hooks);
25
23
  const logs = [];
26
24
  const logged = () => (logs.length > 0 ? { logs: [...logs] } : {});
27
25
  // Set only after copy-out so timeouts cannot report invalid values as completed.
28
26
  let returned;
29
27
  const base = Effect.acquireUseRelease(Scope.make("parallel"), (scope) => Effect.gen(function* () {
30
- const program = parseProgram(options.code);
28
+ const program = parseProgram(code);
31
29
  const promises = new PromiseRuntime(scope);
32
30
  const interpreter = new Interpreter(tools.execute, tools.search, tools.keys, promises, logs);
33
31
  const value = yield* interpreter.run(program);
34
- const result = copyOut(copyIn(value, "Execution result"), "nullify");
32
+ const result = toData(value, "Execution result", "result");
35
33
  returned = { value: result, promises };
36
34
  const warnings = yield* promises.interrupt();
37
35
  return {
@@ -1,7 +1,8 @@
1
1
  import { Effect } from "effect";
2
2
  import { CodeModeFunction, CodeModeGenerator, CoercionFunction, ErrorConstructorReference, GlobalMethodReference, GlobalNamespace, IntrinsicReference, InterpreterRuntimeError, JsonMethodReference, PromiseCapabilityFunction, PromiseNamespace, UriFunction, } from "./model.js";
3
3
  import { containsOpaqueReference, isRuntimeReference, rejectCircularInsertion, typeofValue } from "./references.js";
4
- import { compareText, isBlockedMember } from "../tool-runtime.js";
4
+ import { isBlockedMember, toProgram } from "../data.js";
5
+ import { compareText } from "../tool-runtime.js";
5
6
  import { Values } from "../values.js";
6
7
  import { dateSetterArgumentCount, invokeDateMethod, invokeDateStatic } from "../stdlib/date.js";
7
8
  import { invokeMathMethod } from "../stdlib/math.js";
@@ -10,7 +11,7 @@ import { invokeObjectMethod } from "../stdlib/object.js";
10
11
  import { invokeRegExpMethod, invokeRegExpStatic, matchToValue, toHostRegex } from "../stdlib/regexp.js";
11
12
  import { invokeStringStatic } from "../stdlib/string.js";
12
13
  import { invokeURLMethod, invokeURLStatic, uriArgument } from "../stdlib/url.js";
13
- import { boundedData, coerceToNumber, coerceToString, errorBrandName } from "../stdlib/value.js";
14
+ import { coerceToNumber, coerceToString, errorBrandName } from "../stdlib/value.js";
14
15
  import { preserveConsumerError } from "./iterator.js";
15
16
  export const isSupportedCallback = (value) => value instanceof CodeModeFunction ||
16
17
  value instanceof CoercionFunction ||
@@ -227,7 +228,7 @@ const invokeStringMethod = (value, name, args, node) => {
227
228
  return null;
228
229
  // Preserve the own `index` and `groups` properties on non-global matches.
229
230
  if (pattern.global)
230
- return boundedData(matched, "String.match result");
231
+ return toProgram(matched, "String.match result");
231
232
  return matchToValue(matched);
232
233
  }
233
234
  case "matchAll": {
@@ -279,7 +280,7 @@ const invokeStringMethod = (value, name, args, node) => {
279
280
  default:
280
281
  throw new InterpreterRuntimeError(`String method '${name}' is not available.`, node);
281
282
  }
282
- return boundedData(result, `String.${name} result`);
283
+ return toProgram(result, `String.${name} result`);
283
284
  };
284
285
  export const arrayStatics = new Set(["isArray", "of", "from"]);
285
286
  const invokeArrayStatic = (name, args, node) => {
@@ -436,16 +437,16 @@ const invokeStringReplacer = (runner, value, name, args, node) => {
436
437
  let end = 0;
437
438
  for (const match of matches) {
438
439
  const replacement = yield* apply(match.args);
439
- // Error values are branded plain objects; boundedData would strip the brand before coercion.
440
+ // Error values are branded plain objects; toProgram would strip the brand before coercion.
440
441
  output.push(value.slice(end, match.offset), replacement instanceof Values.Promise
441
442
  ? "[object Promise]"
442
443
  : errorBrandName(replacement)
443
444
  ? coerceToString(replacement)
444
- : coerceToString(boundedData(replacement, `String.${name} replacer result`)));
445
+ : coerceToString(toProgram(replacement, `String.${name} replacer result`)));
445
446
  end = match.offset + match.match.length;
446
447
  }
447
448
  output.push(value.slice(end));
448
- return boundedData(output.join(""), `String.${name} result`);
449
+ return toProgram(output.join(""), `String.${name} result`);
449
450
  });
450
451
  };
451
452
  export const applyCollectionCallback = (runner, callback, name, node) => {
@@ -737,7 +738,7 @@ const invokeArrayMethod = (runner, target, name, args, node) => {
737
738
  if (args.length > 1 || (args.length === 1 && typeof args[0] !== "string")) {
738
739
  throw new InterpreterRuntimeError("Array.join expects zero arguments or one string separator.", node);
739
740
  }
740
- const input = boundedData(target, "Array.join input");
741
+ const input = toProgram(target, "Array.join input");
741
742
  return Effect.succeed(input.map((item) => coerceToString(item ?? "")).join(args.length === 0 ? "," : args[0]));
742
743
  }
743
744
  case "includes":
@@ -1,6 +1,6 @@
1
1
  import type { Effect } from "effect";
2
2
  import type { DiagnosticKind } from "../codemode.js";
3
- import type { SafeObject } from "../tool-runtime.js";
3
+ import type { SafeObject } from "../data.js";
4
4
  import type { Values } from "../values.js";
5
5
  export type SourcePosition = {
6
6
  line: number;
@@ -1,5 +1,6 @@
1
1
  import { Cause, Deferred, Effect, Exit } from "effect";
2
- import { isBlockedMember, ToolReference, ToolRuntimeError } from "../tool-runtime.js";
2
+ import { isBlockedMember, ToolRuntimeError, toProgram } from "../data.js";
3
+ import { ToolReference } from "../tool-runtime.js";
3
4
  import { AsyncIteratorSymbol, asNode, CodeModeFunction, CodeModeGenerator, CoercionFunction, ComputedValue, ErrorConstructorReference, GlobalMethodReference, GlobalNamespace, GeneratorMethodReference, GeneratorReturn, getArray, getBoolean, getNode, getOptionalNode, getString, IntrinsicReference, InterpreterRuntimeError, isRecord, IteratorSymbol, IteratorSymbols, JsonMethodReference, OptionalShortCircuit, PromiseCapabilityFunction, PromiseInstanceMethodReference, PromiseMethodReference, PromiseNamespace, ProgramThrow, SearchFunction, SymbolNamespace, unsupportedSyntax, UriFunction, } from "./model.js";
4
5
  import { caughtErrorValue, constructAggregateErrorValue, constructErrorValue } from "./errors.js";
5
6
  import { arrayStatics, invokeArrayFrom, invokeGlobalMethod, invokeGroupBy, invokeIntrinsic, toPrimitive, } from "./methods.js";
@@ -18,7 +19,7 @@ import { promiseStatics } from "../stdlib/promise.js";
18
19
  import { escapeRegexHint, regexpMethods, regexpProperties, regexpStatics, regexFailureReason, } from "../stdlib/regexp.js";
19
20
  import { stringMethods, stringStatics } from "../stdlib/string.js";
20
21
  import { urlMethods, urlProperties, urlSearchParamsMethods, urlStatics, urlWritableProperties, invokeUriFunction, uriArgument, urlArgument, } from "../stdlib/url.js";
21
- import { boundedData, coerceToNumber, coerceToString, compoundOperators, errorBrandName, errorConstructors, invokeCoercion, valueConstructors, } from "../stdlib/value.js";
22
+ import { coerceToNumber, coerceToString, compoundOperators, errorBrandName, errorConstructors, invokeCoercion, valueConstructors, } from "../stdlib/value.js";
22
23
  import { Values } from "../values.js";
23
24
  const globalStaticMembers = {
24
25
  Object: objectStatics,
@@ -1043,7 +1044,7 @@ export class Interpreter {
1043
1044
  if (isRecord(regex) && typeof regex.pattern === "string") {
1044
1045
  return Effect.sync(() => this.constructRegExp([regex.pattern, typeof regex.flags === "string" ? regex.flags : ""], node));
1045
1046
  }
1046
- return Effect.sync(() => boundedData(node.value, "Literal"));
1047
+ return Effect.sync(() => toProgram(node.value, "Literal"));
1047
1048
  }
1048
1049
  case "Identifier":
1049
1050
  return Effect.sync(() => this.scopes.get(getString(node, "name"), node));
@@ -1278,7 +1279,7 @@ export class Interpreter {
1278
1279
  }
1279
1280
  if (Values.isValue(init))
1280
1281
  return new Values.URLSearchParams(new URLSearchParams());
1281
- const data = boundedData(init, "new URLSearchParams input");
1282
+ const data = toProgram(init, "new URLSearchParams input");
1282
1283
  if (data === null || typeof data !== "object") {
1283
1284
  throw new InterpreterRuntimeError("new URLSearchParams(...) expects a query string, data object, iterable pairs, or URLSearchParams.", node).as("TypeError");
1284
1285
  }
@@ -1309,7 +1310,7 @@ export class Interpreter {
1309
1310
  const rhs = yield* self.evaluateExpression(getNode(node, "right"));
1310
1311
  if (operator === "instanceof")
1311
1312
  return instanceofValue(lhs, rhs, node);
1312
- return boundedData(self.applyBinaryOperator(operator, lhs, rhs, node), "Binary expression result");
1313
+ return toProgram(self.applyBinaryOperator(operator, lhs, rhs, node), "Binary expression result");
1313
1314
  });
1314
1315
  }
1315
1316
  applyBinaryOperator(operator, lhs, rhs, node) {
@@ -1430,7 +1431,7 @@ export class Interpreter {
1430
1431
  default:
1431
1432
  throw new InterpreterRuntimeError(`Unsupported unary operator '${operator}'.`, node);
1432
1433
  }
1433
- return boundedData(result, "Unary expression result");
1434
+ return toProgram(result, "Unary expression result");
1434
1435
  });
1435
1436
  }
1436
1437
  evaluateAssignmentExpression(node) {
@@ -1451,7 +1452,7 @@ export class Interpreter {
1451
1452
  if (operator !== "=") {
1452
1453
  const current = self.scopes.get(name, left);
1453
1454
  const rightValue = yield* self.evaluateExpression(getNode(node, "right"));
1454
- const next = boundedData(self.applyCompoundAssignment(operator, current, rightValue, node), "Assignment result");
1455
+ const next = toProgram(self.applyCompoundAssignment(operator, current, rightValue, node), "Assignment result");
1455
1456
  return self.scopes.set(name, next, left);
1456
1457
  }
1457
1458
  const rightValue = yield* self.evaluateExpression(getNode(node, "right"));
@@ -1461,7 +1462,7 @@ export class Interpreter {
1461
1462
  return yield* self.modifyMember(left, (current) => Effect.map(self.evaluateExpression(getNode(node, "right")), (rightValue) => {
1462
1463
  if (operator === "=")
1463
1464
  return { write: true, next: rightValue, result: rightValue };
1464
- const next = boundedData(self.applyCompoundAssignment(operator, current, rightValue, node), "Assignment result");
1465
+ const next = toProgram(self.applyCompoundAssignment(operator, current, rightValue, node), "Assignment result");
1465
1466
  return { write: true, next, result: next };
1466
1467
  }));
1467
1468
  }
@@ -1590,13 +1591,13 @@ export class Interpreter {
1590
1591
  if (callable.namespace === "Array" && callable.name === "of") {
1591
1592
  return invokeGlobalMethod(callable, args, node);
1592
1593
  }
1593
- return boundedData(invokeGlobalMethod(callable, args, node), `${callable.namespace}.${callable.name} result`);
1594
+ return toProgram(invokeGlobalMethod(callable, args, node), `${callable.namespace}.${callable.name} result`);
1594
1595
  }
1595
1596
  if (callable instanceof JsonMethodReference) {
1596
1597
  return yield* invokeJsonMethod(self.runner, callable.name, args, node);
1597
1598
  }
1598
1599
  if (callable instanceof CoercionFunction) {
1599
- return boundedData(invokeCoercion(callable, args, node), `${callable.name} result`);
1600
+ return toProgram(invokeCoercion(callable, args, node), `${callable.name} result`);
1600
1601
  }
1601
1602
  if (callable instanceof UriFunction) {
1602
1603
  return invokeUriFunction(callable, args, node);
@@ -1644,7 +1645,7 @@ export class Interpreter {
1644
1645
  }
1645
1646
  invokeObjectMethodOnTools(name, ref, node) {
1646
1647
  if (name === "keys") {
1647
- return boundedData(this.enumerableKeys(ref), "Object.keys result");
1648
+ return toProgram(this.enumerableKeys(ref), "Object.keys result");
1648
1649
  }
1649
1650
  throw new InterpreterRuntimeError(`Object.${name}(...) cannot read tool references: they are not plain data. Use Object.keys(tools) for names, or search({ query }) for signatures.`, node, "InvalidDataValue");
1650
1651
  }
@@ -2015,7 +2016,7 @@ export class Interpreter {
2015
2016
  output += rawValue.cooked;
2016
2017
  if (index < expressions.length) {
2017
2018
  const raw = yield* self.evaluateExpression(asNode(expressions[index], "expressions"));
2018
- output += coerceToString(boundedData(raw, "Template interpolation"));
2019
+ output += coerceToString(toProgram(raw, "Template interpolation"));
2019
2020
  }
2020
2021
  }
2021
2022
  return output;
@@ -1,5 +1,5 @@
1
1
  import { fromSchemaOpenApi3_0, fromSchemaOpenApi3_1 } from "effect/JsonSchema";
2
- import { isBlockedMember } from "../tool-runtime.js";
2
+ import { isBlockedMember } from "../data.js";
3
3
  export const methods = new Set(["get", "put", "post", "delete", "options", "head", "patch", "trace"]);
4
4
  const parameterLocations = ["path", "query", "header"];
5
5
  const ignoredHeaderParameters = new Set(["accept", "content-type", "authorization"]);
@@ -1,7 +1,7 @@
1
+ import { toData, toProgram } from "../data.js";
1
2
  import { containsOpaqueReference, containsRuntimeReference, isRuntimeReference } from "../interpreter/references.js";
2
- import { copyIn, copyOut } from "../tool-runtime.js";
3
3
  import { Values } from "../values.js";
4
- import { boundedData, coerceToString } from "./value.js";
4
+ import { coerceToString } from "./value.js";
5
5
  export const consoleMethods = new Set(["log", "info", "debug", "warn", "error", "dir", "table"]);
6
6
  const MAX_CONSOLE_DEPTH = 32;
7
7
  export const formatConsoleMessage = (name, args) => {
@@ -81,7 +81,7 @@ const formatConsoleTable = (value, columnsArgument) => {
81
81
  return "undefined";
82
82
  if (containsOpaqueReference(value))
83
83
  return "[opaque reference]";
84
- const data = boundedData(value, "console.table argument");
84
+ const data = toProgram(value, "console.table argument");
85
85
  const columns = consoleTableColumns(columnsArgument);
86
86
  const rows = consoleTableRows(data, columns);
87
87
  const keys = columns ?? Array.from(new Set(rows.flatMap((row) => Object.keys(row.values))));
@@ -96,7 +96,7 @@ const consoleTableColumns = (value) => {
96
96
  return undefined;
97
97
  if (containsRuntimeReference(value))
98
98
  return undefined;
99
- const columns = copyOut(copyIn(value, "console.table columns"), "nullify");
99
+ const columns = toData(value, "console.table columns", "result");
100
100
  return Array.isArray(columns) ? columns.map((column) => String(column)) : undefined;
101
101
  };
102
102
  const consoleTableRows = (data, columns) => {
@@ -2,7 +2,7 @@ import { Effect } from "effect";
2
2
  import { applyCollectionCallback } from "../interpreter/methods.js";
3
3
  import { InterpreterRuntimeError } from "../interpreter/model.js";
4
4
  import { typeofValue } from "../interpreter/references.js";
5
- import { copyIn, copyOut } from "../tool-runtime.js";
5
+ import { fromData, toData, toProgram } from "../data.js";
6
6
  import { Values } from "../values.js";
7
7
  export const jsonStatics = new Set(["parse", "stringify"]);
8
8
  export const invokeJsonMethod = (runner, name, args, node) => {
@@ -14,7 +14,7 @@ const parse = (runner, args, node) => {
14
14
  throw new InterpreterRuntimeError("JSON.parse expects a string.", node);
15
15
  const parsed = (() => {
16
16
  try {
17
- return copyIn(JSON.parse(text), "JSON.parse result");
17
+ return fromData(JSON.parse(text), "JSON.parse result");
18
18
  }
19
19
  catch (error) {
20
20
  throw new InterpreterRuntimeError(`JSON.parse received invalid JSON: ${error instanceof Error ? error.message : String(error)}`, node).as("SyntaxError");
@@ -54,27 +54,25 @@ const stringify = (runner, args, node) => {
54
54
  const space = args[2];
55
55
  const indent = typeof space === "number" || typeof space === "string" ? space : undefined;
56
56
  const replacer = args[1];
57
- const callable = typeofValue(replacer) === "function";
58
- const checked = copyIn(args[0], "JSON.stringify value", callable);
59
- const input = callable ? args[0] : checked;
60
- if (Array.isArray(replacer)) {
61
- const properties = replacer
62
- .filter((item) => typeof item === "string" || typeof item === "number")
63
- .map(String);
64
- return Effect.succeed(JSON.stringify(copyOut(input, "json"), properties, indent));
65
- }
66
- if (!callable) {
67
- return Effect.succeed(JSON.stringify(copyOut(input, "json"), null, indent));
57
+ if (typeofValue(replacer) !== "function") {
58
+ const properties = Array.isArray(replacer)
59
+ ? replacer
60
+ .filter((item) => typeof item === "string" || typeof item === "number")
61
+ .map(String)
62
+ : null;
63
+ return Effect.succeed(JSON.stringify(toData(args[0], "JSON.stringify value"), properties, indent));
68
64
  }
65
+ // Validate up front; the replacer walk below reads the original value.
66
+ toProgram(args[0], "JSON.stringify value");
69
67
  const apply = applyCollectionCallback(runner, replacer, "JSON.stringify", node);
70
68
  const root = Object.create(null);
71
- root[""] = input;
69
+ root[""] = args[0];
72
70
  const stack = new Set();
73
71
  const visit = (holder, key) => Effect.gen(function* () {
74
72
  const value = yield* apply([key, toJSONValue(holder[key])]);
75
73
  if (value === undefined || typeofValue(value) === "function")
76
74
  return undefined;
77
- copyIn(value, "JSON.stringify replacer result", true);
75
+ toProgram(value, "JSON.stringify replacer result");
78
76
  if (typeof value === "number")
79
77
  return Number.isFinite(value) ? value : null;
80
78
  if (value === null || typeof value === "string" || typeof value === "boolean")
@@ -1,5 +1,6 @@
1
1
  import { InterpreterRuntimeError } from "../interpreter/model.js";
2
- import { boundedData, coerceToString } from "./value.js";
2
+ import { toProgram } from "../data.js";
3
+ import { coerceToString } from "./value.js";
3
4
  export const numberMethods = new Set(["toFixed", "toPrecision", "toExponential", "toString", "valueOf"]);
4
5
  export const numberConstants = new Set([
5
6
  "MAX_SAFE_INTEGER",
@@ -48,7 +49,7 @@ export const invokeNumberMethod = (value, name, args, node) => {
48
49
  default:
49
50
  throw new InterpreterRuntimeError(`Number method '${name}' is not available.`, node);
50
51
  }
51
- return boundedData(result, `Number.${name} result`);
52
+ return toProgram(result, `Number.${name} result`);
52
53
  };
53
54
  export const invokeNumberStatic = (name, args, node) => {
54
55
  const value = args[0];
@@ -1,9 +1,10 @@
1
1
  import { Effect } from "effect";
2
2
  import { AsyncIteratorSymbol, InterpreterRuntimeError, IteratorSymbol } from "../interpreter/model.js";
3
3
  import { containsOpaqueReference, rejectCircularInsertion } from "../interpreter/references.js";
4
- import { isBlockedMember } from "../tool-runtime.js";
4
+ import { isBlockedMember } from "../data.js";
5
5
  import { Values } from "../values.js";
6
- import { boundedData, coerceToString } from "./value.js";
6
+ import { toProgram } from "../data.js";
7
+ import { coerceToString } from "./value.js";
7
8
  import { preserveConsumerError } from "../interpreter/iterator.js";
8
9
  export const objectMethodsPreservingIdentity = new Set(["assign", "values", "entries", "fromEntries"]);
9
10
  export const objectStatics = new Set(["keys", "values", "entries", "hasOwn", "is", "assign", "fromEntries", "groupBy"]);
@@ -97,8 +98,8 @@ export const invokeObjectFromEntries = (runner, source, node) => {
97
98
  throw new InterpreterRuntimeError("Object.fromEntries expects [key, value] entry objects.", node).as("TypeError");
98
99
  }
99
100
  const entry = step.value;
100
- boundedData(entry[0], "Object.fromEntries key");
101
- boundedData(entry[1], "Object.fromEntries value");
101
+ toProgram(entry[0], "Object.fromEntries key");
102
+ toProgram(entry[1], "Object.fromEntries value");
102
103
  const key = coerceToString(entry[0]);
103
104
  if (isBlockedMember(key))
104
105
  throw new InterpreterRuntimeError(`Property '${key}' is not available.`, node);
@@ -1,5 +1,5 @@
1
1
  import { InterpreterRuntimeError } from "../interpreter/model.js";
2
- import { isBlockedMember } from "../tool-runtime.js";
2
+ import { isBlockedMember } from "../data.js";
3
3
  import { Values } from "../values.js";
4
4
  import { coerceToNumber, coerceToString } from "./value.js";
5
5
  export const regexpMethods = new Set(["test", "exec", "toString"]);
@@ -1,6 +1,7 @@
1
1
  import { InterpreterRuntimeError, UriFunction } from "../interpreter/model.js";
2
2
  import { Values } from "../values.js";
3
- import { boundedData, coerceToString } from "./value.js";
3
+ import { toProgram } from "../data.js";
4
+ import { coerceToString } from "./value.js";
4
5
  export const urlProperties = new Set([
5
6
  "href",
6
7
  "origin",
@@ -42,7 +43,7 @@ export const urlSearchParamsMethods = new Set([
42
43
  "entries",
43
44
  "toString",
44
45
  ]);
45
- export const uriArgument = (value, label) => coerceToString(boundedData(value, label));
46
+ export const uriArgument = (value, label) => coerceToString(toProgram(value, label));
46
47
  export const invokeUriFunction = (ref, args, node) => {
47
48
  const value = uriArgument(args[0], `${ref.name} input`);
48
49
  try {
@@ -1,12 +1,11 @@
1
1
  import { type AstNode, CoercionFunction } from "../interpreter/model.js";
2
- import { type SafeObject } from "../tool-runtime.js";
2
+ import { type SafeObject } from "../data.js";
3
3
  export declare const errorConstructors: Set<string>;
4
4
  export declare const valueConstructors: Set<string>;
5
5
  export declare const compoundOperators: Set<string>;
6
6
  export declare const createErrorValue: (name: string, message: string) => SafeObject;
7
7
  export declare const createAggregateErrorValue: (errors: Array<unknown>, message: string) => SafeObject;
8
8
  export declare const errorBrandName: (value: unknown) => string | undefined;
9
- export declare const boundedData: (value: unknown, label: string) => unknown;
10
9
  export declare const coerceToString: (value: unknown) => string;
11
10
  export declare const coerceToNumber: (value: unknown) => number;
12
11
  export declare const invokeCoercion: (ref: CoercionFunction, args: Array<unknown>, node: AstNode) => unknown;
@@ -1,5 +1,5 @@
1
1
  import { CoercionFunction, InterpreterRuntimeError } from "../interpreter/model.js";
2
- import { copyIn } from "../tool-runtime.js";
2
+ import { toProgram } from "../data.js";
3
3
  import { Values } from "../values.js";
4
4
  export const errorConstructors = new Set([
5
5
  "Error",
@@ -23,7 +23,6 @@ export const createAggregateErrorValue = (errors, message) => Object.assign(crea
23
23
  export const errorBrandName = (value) => value !== null && typeof value === "object"
24
24
  ? value[ErrorBrand]
25
25
  : undefined;
26
- export const boundedData = (value, label) => copyIn(value, label, true);
27
26
  export const coerceToString = (value) => {
28
27
  if (value === null)
29
28
  return "null";
@@ -80,7 +79,7 @@ export const invokeCoercion = (ref, args, node) => {
80
79
  return "";
81
80
  }
82
81
  const raw = args[0];
83
- // Error values are plain SafeObjects; the boundedData path below would strip their brand.
82
+ // Error values are plain SafeObjects; the toProgram path below would strip their brand.
84
83
  if (ref.name === "String" && errorBrandName(raw) !== undefined)
85
84
  return coerceToString(raw);
86
85
  if (Values.isValue(raw)) {
@@ -98,7 +97,7 @@ export const invokeCoercion = (ref, args, node) => {
98
97
  return parseInt(coerceToString(raw));
99
98
  return parseFloat(coerceToString(raw));
100
99
  }
101
- const value = boundedData(raw, `${ref.name} input`);
100
+ const value = toProgram(raw, `${ref.name} input`);
102
101
  if (ref.name === "Number")
103
102
  return coerceToNumber(value);
104
103
  if (ref.name === "Boolean")
@@ -1,5 +1,6 @@
1
1
  import { Effect } from "effect";
2
- import type { DiagnosticKind } from "./codemode.js";
2
+ import { type Namespace } from "./namespace.js";
3
+ import { type Tool } from "./tool.js";
3
4
  import type { Tools } from "./tools.js";
4
5
  export declare const compareText: (left: string, right: string) => 0 | 1 | -1;
5
6
  export type Services<T> = ServicesOf<T, []>;
@@ -24,7 +25,9 @@ export type ToolCallEnded = {
24
25
  readonly message?: string;
25
26
  };
26
27
  export type ToolCallHooks<R = never> = {
28
+ /** Observes decoded tool input immediately before tool execution. */
27
29
  readonly onToolCallStart?: ((call: ToolCallStarted) => Effect.Effect<void, never, R>) | undefined;
30
+ /** Observes each admitted tool call as it succeeds, fails, or is interrupted. */
28
31
  readonly onToolCallEnd?: ((call: ToolCallEnded) => Effect.Effect<void, never, R>) | undefined;
29
32
  };
30
33
  export type ToolDescription = {
@@ -32,22 +35,19 @@ export type ToolDescription = {
32
35
  readonly description: string;
33
36
  readonly signature: string;
34
37
  };
35
- export type SafeObject = Record<string, unknown>;
36
38
  export declare const toolExpression: (path: string) => string;
37
39
  export declare class ToolReference {
38
40
  readonly path: ReadonlyArray<string>;
39
41
  constructor(path: ReadonlyArray<string>);
40
42
  }
41
- export declare class ToolRuntimeError extends Error {
42
- readonly kind: Extract<DiagnosticKind, "UnknownTool" | "InvalidToolInput" | "InvalidToolOutput" | "InvalidDataValue" | "ToolCallLimitExceeded">;
43
- readonly suggestions: ReadonlyArray<string>;
44
- constructor(kind: Extract<DiagnosticKind, "UnknownTool" | "InvalidToolInput" | "InvalidToolOutput" | "InvalidDataValue" | "ToolCallLimitExceeded">, message: string, suggestions?: ReadonlyArray<string>);
45
- }
46
- export declare const isBlockedMember: (name: string) => boolean;
47
- export declare const copyIn: (value: unknown, label: string, preserveCodeModeValues?: boolean) => unknown;
48
- export type CopyOutMode = "json" | "nullify";
49
- export declare const copyOut: (value: unknown, mode: CopyOutMode) => unknown;
50
- export type DiscoveryPlan = {
43
+ type ToolNode<R> = {
44
+ tool?: Tool<R>;
45
+ namespace?: Namespace<R>;
46
+ readonly children: Map<string, ToolNode<R>>;
47
+ };
48
+ /** Tools indexed once per runtime: the lookup trie plus the model-facing catalog and search index. */
49
+ export type Prepared<R = never> = {
50
+ readonly root: ToolNode<R>;
51
51
  readonly catalog: ReadonlyArray<ToolDescription>;
52
52
  readonly searchIndex: ReadonlyArray<SearchEntry>;
53
53
  };
@@ -57,14 +57,13 @@ export type SearchEntry = {
57
57
  };
58
58
  /** Exact callable signature of the built-in `search` function, for host-owned instructions. */
59
59
  export declare const searchSignature: string;
60
- export declare const searchIndex: <R>(tools: Tools<R>) => ReadonlyArray<SearchEntry>;
61
- export declare const prepare: <R>(tools: Tools<R>) => DiscoveryPlan;
60
+ export declare const prepare: <R>(tools: Tools<R>) => Prepared<R>;
62
61
  export type ToolRuntime<R = never> = {
63
- readonly root: ToolReference;
64
62
  readonly calls: Array<ToolCall>;
65
63
  readonly execute: (path: ReadonlyArray<string>, args: Array<unknown>) => Effect.Effect<unknown, unknown, R>;
66
64
  readonly search: (args: Array<unknown>) => Effect.Effect<unknown, unknown, R>;
67
65
  readonly keys: (path: ReadonlyArray<string>) => ReadonlyArray<string>;
68
66
  };
69
- export declare const make: <R>(tools: Tools<R>, maxToolCalls: number | undefined, searchIndex: ReadonlyArray<SearchEntry>, hooks?: ToolCallHooks<R>) => ToolRuntime<R>;
67
+ /** Per-execution call state over tools prepared once for the runtime. */
68
+ export declare const make: <R>(prepared: Prepared<R>, maxToolCalls: number | undefined, hooks?: ToolCallHooks<R>) => ToolRuntime<R>;
70
69
  export * as ToolRuntime from "./tool-runtime.js";
@@ -1,9 +1,9 @@
1
1
  import { Cause, Effect, Exit, Formatter, Schema } from "effect";
2
+ import { fromData, toData, ToolRuntimeError } from "./data.js";
2
3
  import { toolError } from "./tool-error.js";
3
4
  import { decodeInput as decodeToolInput, decodeOutput as decodeToolOutput, identifierSegment, inputProperties, inputTypeScript, isEmptyInput, outputTypeScript, } from "./tool-schema.js";
4
5
  import { isNamespace } from "./namespace.js";
5
6
  import { isTool } from "./tool.js";
6
- import { Values } from "./values.js";
7
7
  export const compareText = (left, right) => (left < right ? -1 : left > right ? 1 : 0);
8
8
  const defaultSearchLimit = 10;
9
9
  const PositiveInt = Schema.Int.check(Schema.isGreaterThan(0));
@@ -35,135 +35,6 @@ export class ToolReference {
35
35
  this.path = path;
36
36
  }
37
37
  }
38
- const MAX_VALUE_DEPTH = 32;
39
- export class ToolRuntimeError extends Error {
40
- kind;
41
- suggestions;
42
- constructor(kind, message, suggestions = []) {
43
- super(message);
44
- this.kind = kind;
45
- this.suggestions = suggestions;
46
- this.name = "ToolRuntimeError";
47
- }
48
- }
49
- const blockedMemberNames = new Set(["__proto__", "constructor", "prototype"]);
50
- export const isBlockedMember = (name) => blockedMemberNames.has(name);
51
- // Checkpoint mode preserves CodeMode values; boundary mode JSON-normalizes them.
52
- export const copyIn = (value, label, preserveCodeModeValues = false) => copyBounded(value, label, 0, new Set(), preserveCodeModeValues);
53
- const copyBounded = (value, label, depth, seen, preserveCodeModeValues) => {
54
- if (depth > MAX_VALUE_DEPTH) {
55
- throw new ToolRuntimeError("InvalidDataValue", `${label} exceeds the maximum value depth of ${MAX_VALUE_DEPTH}.`);
56
- }
57
- if (value === null ||
58
- value === undefined ||
59
- typeof value === "string" ||
60
- typeof value === "boolean" ||
61
- typeof value === "number") {
62
- return value;
63
- }
64
- if (typeof value !== "object") {
65
- throw new ToolRuntimeError("InvalidDataValue", `${label} must contain data only.`);
66
- }
67
- if (value instanceof Values.Promise) {
68
- 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.`);
69
- }
70
- if (preserveCodeModeValues) {
71
- if (Values.isValue(value))
72
- return value;
73
- if (value instanceof Date)
74
- return new Values.Date(value.getTime());
75
- if (value instanceof RegExp)
76
- return new Values.RegExp(value.source, value.flags);
77
- if (value instanceof Map) {
78
- const wrapped = new Values.Map();
79
- for (const [key, item] of value.entries()) {
80
- wrapped.map.set(copyBounded(key, label, depth + 1, seen, true), copyBounded(item, label, depth + 1, seen, true));
81
- }
82
- return wrapped;
83
- }
84
- if (value instanceof Set) {
85
- const wrapped = new Values.Set();
86
- for (const item of value.values())
87
- wrapped.set.add(copyBounded(item, label, depth + 1, seen, true));
88
- return wrapped;
89
- }
90
- if (value instanceof URL)
91
- return new Values.URL(new URL(value.href));
92
- if (value instanceof URLSearchParams)
93
- return new Values.URLSearchParams(new URLSearchParams(value));
94
- }
95
- if (value instanceof Values.Date) {
96
- return Number.isFinite(value.time) ? new Date(value.time).toISOString() : null;
97
- }
98
- if (value instanceof Date) {
99
- return Number.isFinite(value.getTime()) ? value.toISOString() : null;
100
- }
101
- if (value instanceof Values.URL)
102
- return value.url.href;
103
- if (value instanceof URL)
104
- return value.href;
105
- // Remaining runtime values and their host counterparts serialize as empty objects, like JSON.stringify.
106
- if (Values.isValue(value) ||
107
- value instanceof RegExp ||
108
- value instanceof Map ||
109
- value instanceof Set ||
110
- value instanceof URLSearchParams) {
111
- return Object.create(null);
112
- }
113
- if (seen.has(value)) {
114
- throw new ToolRuntimeError("InvalidDataValue", `${label} contains a circular value.`);
115
- }
116
- seen.add(value);
117
- if (Array.isArray(value)) {
118
- const copied = value.map((item) => copyBounded(item, label, depth + 1, seen, preserveCodeModeValues));
119
- if (preserveCodeModeValues) {
120
- // Checkpoint copies retain array metadata that boundary copies omit.
121
- for (const [key, item] of Object.entries(value)) {
122
- if (Object.hasOwn(copied, key))
123
- continue;
124
- if (isBlockedMember(key)) {
125
- throw new ToolRuntimeError("InvalidDataValue", `${label} contains blocked property '${key}'.`);
126
- }
127
- Reflect.set(copied, key, copyBounded(item, label, depth + 1, seen, true));
128
- }
129
- }
130
- seen.delete(value);
131
- return copied;
132
- }
133
- const prototype = Object.getPrototypeOf(value);
134
- if (prototype !== Object.prototype && prototype !== null) {
135
- throw new ToolRuntimeError("InvalidDataValue", `${label} must contain plain objects only.`);
136
- }
137
- const copied = Object.create(null);
138
- for (const [key, item] of Object.entries(value)) {
139
- if (isBlockedMember(key)) {
140
- throw new ToolRuntimeError("InvalidDataValue", `${label} contains blocked property '${key}'.`);
141
- }
142
- copied[key] = copyBounded(item, label, depth + 1, seen, preserveCodeModeValues);
143
- }
144
- seen.delete(value);
145
- return copied;
146
- };
147
- export const copyOut = (value, mode) => {
148
- if (value === undefined && mode === "nullify")
149
- return null;
150
- if (typeof value === "number" && !Number.isFinite(value)) {
151
- return null;
152
- }
153
- if (Array.isArray(value)) {
154
- // Array.from densifies holes so sparse arrays normalize at the boundary like JSON does.
155
- return Array.from(value, (item) => {
156
- const copied = copyOut(item, mode);
157
- return copied === undefined && mode === "json" ? null : copied;
158
- });
159
- }
160
- if (value !== null && typeof value === "object" && !(value instanceof ToolReference)) {
161
- return Object.fromEntries(Object.entries(value)
162
- .map(([key, item]) => [key, copyOut(item, mode)])
163
- .filter(([, item]) => !(item === undefined && mode === "json")));
164
- }
165
- return value;
166
- };
167
38
  const toolTrie = (tools) => {
168
39
  const root = { children: new Map() };
169
40
  const insert = (node, group) => {
@@ -204,8 +75,6 @@ const describeTool = (visible) => ({
204
75
  ? `${toolExpression(visible.path)}(): Promise<${outputTypeScript(visible.tool, true)}>`
205
76
  : `${toolExpression(visible.path)}(input: ${inputTypeScript(visible.tool, true)}): Promise<${outputTypeScript(visible.tool, true)}>`,
206
77
  });
207
- // Discovery bytes are durable instructions, so order only after canonical-path collisions settle.
208
- const visibleTools = (tools) => flattenTools(toolTrie(tools)).sort((left, right) => compareText(left.path, right.path));
209
78
  const tokenize = (query) => query
210
79
  .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
211
80
  .toLowerCase()
@@ -282,10 +151,12 @@ const toSearchEntry = (visible) => ({
282
151
  .join("\n")
283
152
  .toLowerCase(),
284
153
  });
285
- export const searchIndex = (tools) => visibleTools(tools).map(toSearchEntry);
286
154
  export const prepare = (tools) => {
287
- const visible = visibleTools(tools);
155
+ const root = toolTrie(tools);
156
+ // Discovery bytes are durable instructions, so order only after canonical-path collisions settle.
157
+ const visible = flattenTools(root).sort((left, right) => compareText(left.path, right.path));
288
158
  return {
159
+ root,
289
160
  catalog: visible.map(describeTool),
290
161
  searchIndex: visible.map(toSearchEntry),
291
162
  };
@@ -312,10 +183,11 @@ const resolve = (root, path) => {
312
183
  }
313
184
  return node.tool;
314
185
  };
315
- export const make = (tools, maxToolCalls, searchIndex, hooks) => {
186
+ /** Per-execution call state over tools prepared once for the runtime. */
187
+ export const make = (prepared, maxToolCalls, hooks) => {
316
188
  const calls = [];
317
- const root = toolTrie(tools);
318
- const searchTool = makeSearchTool(searchIndex);
189
+ const root = prepared.root;
190
+ const searchTool = makeSearchTool(prepared.searchIndex);
319
191
  const observeEnd = (effect, call) => {
320
192
  const onEnd = hooks?.onToolCallEnd;
321
193
  if (onEnd === undefined)
@@ -362,19 +234,18 @@ export const make = (tools, maxToolCalls, searchIndex, hooks) => {
362
234
  .join("\n")));
363
235
  }));
364
236
  return yield* Effect.try({
365
- try: () => copyIn(decodeToolOutput(tool, raw), `Result from tool '${name}'`),
237
+ try: () => fromData(decodeToolOutput(tool, raw), `Result from tool '${name}'`),
366
238
  catch: (cause) => new ToolRuntimeError("InvalidToolOutput", `Invalid output from tool '${name}': ${cause}`),
367
239
  });
368
240
  }), call);
369
241
  });
370
242
  return {
371
- root: new ToolReference([]),
372
243
  calls,
373
244
  keys: (path) => namespaceKeys(root, path),
374
- search: (args) => Effect.suspend(() => executeTool("search", searchTool, args.map((arg) => copyOut(copyIn(arg, "Arguments for tool 'search'"), "json")))),
245
+ search: (args) => Effect.suspend(() => executeTool("search", searchTool, args.map((arg) => toData(arg, "Arguments for tool 'search'")))),
375
246
  execute: (path, args) => Effect.gen(function* () {
376
247
  const name = canonicalSegments(path).join(".");
377
- const externalArgs = args.map((arg) => copyOut(copyIn(arg, `Arguments for tool '${name}'`), "json"));
248
+ const externalArgs = args.map((arg) => toData(arg, `Arguments for tool '${name}'`));
378
249
  const tool = resolve(root, path);
379
250
  return yield* executeTool(name, tool, externalArgs);
380
251
  }),
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-19352",
4
+ "version": "0.0.0-dev-19356",
5
5
  "description": "Effect-native confined code execution over schema-described tools",
6
6
  "type": "module",
7
7
  "license": "MIT",