@opencode/codemode 0.0.0-dev-19355 → 0.0.0-dev-19358

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.
@@ -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-19355",
4
+ "version": "0.0.0-dev-19358",
5
5
  "description": "Effect-native confined code execution over schema-described tools",
6
6
  "type": "module",
7
7
  "license": "MIT",