@opencode-ai/codemode 0.0.0-beta-17492

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +168 -0
  2. package/dist/codemode.d.ts +148 -0
  3. package/dist/codemode.js +70 -0
  4. package/dist/index.d.ts +5 -0
  5. package/dist/index.js +5 -0
  6. package/dist/interpreter/errors.d.ts +9 -0
  7. package/dist/interpreter/errors.js +91 -0
  8. package/dist/interpreter/execute.d.ts +4 -0
  9. package/dist/interpreter/execute.js +178 -0
  10. package/dist/interpreter/iterator.d.ts +13 -0
  11. package/dist/interpreter/iterator.js +4 -0
  12. package/dist/interpreter/methods.d.ts +17 -0
  13. package/dist/interpreter/methods.js +1026 -0
  14. package/dist/interpreter/model.d.ts +151 -0
  15. package/dist/interpreter/model.js +186 -0
  16. package/dist/interpreter/promises.d.ts +29 -0
  17. package/dist/interpreter/promises.js +253 -0
  18. package/dist/interpreter/references.d.ts +6 -0
  19. package/dist/interpreter/references.js +114 -0
  20. package/dist/interpreter/runtime.d.ts +98 -0
  21. package/dist/interpreter/runtime.js +2351 -0
  22. package/dist/interpreter/scope.d.ts +15 -0
  23. package/dist/interpreter/scope.js +79 -0
  24. package/dist/interpreter/transpile.node.d.ts +5 -0
  25. package/dist/interpreter/transpile.node.js +19 -0
  26. package/dist/interpreter/transpile.workerd.d.ts +5 -0
  27. package/dist/interpreter/transpile.workerd.js +6 -0
  28. package/dist/openapi/index.d.ts +7 -0
  29. package/dist/openapi/index.js +101 -0
  30. package/dist/openapi/runtime.d.ts +4 -0
  31. package/dist/openapi/runtime.js +283 -0
  32. package/dist/openapi/spec.d.ts +20 -0
  33. package/dist/openapi/spec.js +588 -0
  34. package/dist/openapi/types.d.ts +122 -0
  35. package/dist/openapi/types.js +2 -0
  36. package/dist/stdlib/collections.d.ts +4 -0
  37. package/dist/stdlib/collections.js +57 -0
  38. package/dist/stdlib/console.d.ts +2 -0
  39. package/dist/stdlib/console.js +126 -0
  40. package/dist/stdlib/date.d.ts +7 -0
  41. package/dist/stdlib/date.js +186 -0
  42. package/dist/stdlib/json.d.ts +6 -0
  43. package/dist/stdlib/json.js +124 -0
  44. package/dist/stdlib/math.d.ts +12 -0
  45. package/dist/stdlib/math.js +157 -0
  46. package/dist/stdlib/number.d.ts +6 -0
  47. package/dist/stdlib/number.js +76 -0
  48. package/dist/stdlib/object.d.ts +7 -0
  49. package/dist/stdlib/object.js +100 -0
  50. package/dist/stdlib/promise.d.ts +2 -0
  51. package/dist/stdlib/promise.js +1 -0
  52. package/dist/stdlib/regexp.d.ts +11 -0
  53. package/dist/stdlib/regexp.js +106 -0
  54. package/dist/stdlib/string.d.ts +4 -0
  55. package/dist/stdlib/string.js +48 -0
  56. package/dist/stdlib/url.d.ts +12 -0
  57. package/dist/stdlib/url.js +84 -0
  58. package/dist/stdlib/value.d.ts +12 -0
  59. package/dist/stdlib/value.js +120 -0
  60. package/dist/tool-error.d.ts +11 -0
  61. package/dist/tool-error.js +9 -0
  62. package/dist/tool-runtime.d.ts +68 -0
  63. package/dist/tool-runtime.js +390 -0
  64. package/dist/tool-schema.d.ts +15 -0
  65. package/dist/tool-schema.js +213 -0
  66. package/dist/tool.d.ts +55 -0
  67. package/dist/tool.js +21 -0
  68. package/dist/tools.d.ts +4 -0
  69. package/dist/tools.js +1 -0
  70. package/dist/values.d.ts +31 -0
  71. package/dist/values.js +50 -0
  72. package/package.json +46 -0
package/README.md ADDED
@@ -0,0 +1,168 @@
1
+ # @opencode-ai/codemode
2
+
3
+ This is our take on code mode: a lightweight, pure interpreter for a JavaScript-like language built around calling
4
+ tools. It supports familiar JavaScript syntax with a few key differences and limitations. See the
5
+ [interpreter support checklist](./interpreter-support.md) for more details.
6
+
7
+ Rather than trying to sandbox arbitrary JavaScript, CodeMode only runs the language features we implement. Programs
8
+ cannot directly access the network, filesystem, processes, or application APIs. They can interact with the outside
9
+ world only through tools provided by the host, which can also limit execution time, tool calls, output size, and data.
10
+
11
+ The idea of code mode was originally introduced by Cloudflare. See
12
+ [their post](https://blog.cloudflare.com/code-mode/) to learn more about the concept and their isolate-based approach.
13
+
14
+ ## How it differs from JavaScript
15
+
16
+ - **Only supported APIs are available.** Programs can use the provided tools and supported JavaScript built-ins. APIs
17
+ such as `fetch`, timers, `process`, filesystem access, imports, and modules are unavailable.
18
+ - **Unfinished work is interrupted.** Tool calls and async functions start when called. When the program finishes,
19
+ anything still running is interrupted. Unhandled rejections from un-awaited promises are returned as warnings.
20
+ - **REPL-style results.** Without an explicit `return`, the final top-level expression becomes the result. `undefined`
21
+ becomes `null`.
22
+
23
+ Unsupported syntax returns an `UnsupportedSyntax` diagnostic with a source location. Current gaps are tracked in the
24
+ [interpreter support checklist](./interpreter-support.md).
25
+
26
+ ## Quick Start
27
+
28
+ ```ts
29
+ import { CodeMode, Tool } from "@opencode-ai/codemode"
30
+ import { Effect, Schema } from "effect"
31
+
32
+ const lookupOrder = Tool.make({
33
+ description: "Look up an order by ID",
34
+ input: Schema.Struct({ id: Schema.String }),
35
+ output: Schema.Struct({ id: Schema.String, status: Schema.String }),
36
+ execute: ({ id }) => Effect.succeed({ id, status: "open" }),
37
+ })
38
+
39
+ const runtime = CodeMode.make({
40
+ tools: { orders: { lookup: lookupOrder } },
41
+ })
42
+
43
+ const result = await Effect.runPromise(
44
+ runtime.execute(`
45
+ const order = await tools.orders.lookup({ id: "order_42" })
46
+ return { id: order.id, needsAttention: order.status !== "complete" }
47
+ `),
48
+ )
49
+ ```
50
+
51
+ `result` is always a [`CodeMode.Result`](#results).
52
+
53
+ ## API
54
+
55
+ ### `Tool.make`
56
+
57
+ `input` and `output` accept either an Effect Schema or a render-only JSON Schema document. Effect Schema input is
58
+ decoded before `execute`; Effect Schema output is decoded and safely copied before the program sees it. JSON Schemas
59
+ only shape the model-visible signature. Without `output`, the signature uses `Promise<void>`.
60
+
61
+ Descriptions and schemas are model-visible contracts. Authorization belongs in `execute`.
62
+
63
+ Dots in tool names create namespaces: `{ "issues.list": tool }` and `{ issues: { list: tool } }` both expose
64
+ `tools.issues.list(...)`. Other characters use bracket notation, such as
65
+ `tools.context7["resolve-library-id"](...)`.
66
+
67
+ ### `CodeMode.execute` and `CodeMode.make`
68
+
69
+ `CodeMode.execute({ ...options, code })` runs once. `CodeMode.make(options)` creates a reusable runtime:
70
+
71
+ ```ts
72
+ const runtime = CodeMode.make({ tools, limits: { timeoutMs: 30_000 } })
73
+
74
+ runtime.catalog() // structured tool descriptions
75
+ runtime.execute(source) // Effect<CodeMode.Result, never, ToolServices>
76
+ ```
77
+
78
+ The Effect environment is inferred from the supplied tools. `onToolCallStart` observes admitted calls with decoded
79
+ input; `onToolCallEnd` observes settled outcomes and duration. Both hooks return Effects and must not fail.
80
+
81
+ ### OpenAPI tools
82
+
83
+ `OpenAPI.fromSpec` converts an OpenAPI 3.x document into one tool per supported operation. Dotted `operationId` values
84
+ create namespaces:
85
+
86
+ ```ts
87
+ const api = OpenAPI.fromSpec({ spec, auth: { resolve } })
88
+ const runtime = CodeMode.make({ tools: { opencode: api.tools } })
89
+ ```
90
+
91
+ The synchronous result is `{ tools, skipped }`. Operations with unsupported parameter encodings, request bodies
92
+ without JSON content, WebSocket or SSE semantics, or binary responses are reported in `skipped`.
93
+
94
+ Authentication is resolved by the host and never shown to the model. Generated tools require `HttpClient.HttpClient`.
95
+ Request signatures omit `readOnly` properties; response signatures omit `writeOnly` properties. These JSON Schemas
96
+ shape model-visible signatures but do not filter runtime values: nested JSON body properties and decoded server
97
+ responses pass through unchanged. See `src/openapi/types.ts` for option details.
98
+
99
+ ## Results
100
+
101
+ Every execution returns:
102
+
103
+ ```ts
104
+ type Result =
105
+ | {
106
+ readonly ok: true
107
+ readonly value: CodeMode.DataValue
108
+ readonly warnings?: ReadonlyArray<CodeMode.Diagnostic>
109
+ readonly logs?: ReadonlyArray<string>
110
+ readonly truncated?: boolean
111
+ readonly toolCalls: ReadonlyArray<CodeMode.ToolCall>
112
+ }
113
+ | {
114
+ readonly ok: false
115
+ readonly error: CodeMode.Diagnostic
116
+ readonly logs?: ReadonlyArray<string>
117
+ readonly truncated?: boolean
118
+ readonly toolCalls: ReadonlyArray<CodeMode.ToolCall>
119
+ }
120
+ ```
121
+
122
+ `value` is JSON-safe. `warnings` are non-fatal diagnostics, `logs` contain program console output, and `truncated`
123
+ indicates that retained output was cut by `maxOutputBytes`. `toolCalls` retains admitted calls in order, including after
124
+ failure.
125
+
126
+ Diagnostic kinds:
127
+
128
+ | Kind | Meaning |
129
+ | ----------------------- | ---------------------------------------------------------------------------------------------- |
130
+ | `ParseError` | Source is empty or cannot be parsed. |
131
+ | `UnsupportedSyntax` | Parsed JavaScript is outside the supported subset. |
132
+ | `UnknownTool` | The program referenced an unavailable tool. |
133
+ | `InvalidToolInput` | Tool input failed schema decoding or safe-data copying. |
134
+ | `InvalidToolOutput` | Tool output failed schema decoding or safe-data copying. |
135
+ | `InvalidDataValue` | Program data violated the plain-data contract. |
136
+ | `ToolCallLimitExceeded` | The program exceeded `maxToolCalls`. |
137
+ | `TimeoutExceeded` | Execution timed out; as a warning, background work was interrupted after the program returned. |
138
+ | `ToolFailure` | A tool refused or failed. |
139
+ | `ExecutionFailure` | The program threw or another execution error occurred. |
140
+ | `Truncated` | Warning only: additional warnings were omitted by `maxOutputBytes`. |
141
+
142
+ Unknown host failures, defects, and invalid outputs are sanitized. `toolError("safe message")` explicitly exposes a
143
+ safe refusal to the model; its optional cause remains private.
144
+
145
+ ## Discovery
146
+
147
+ `runtime.catalog()` returns structured descriptors — exact path, description, and generated TypeScript signature — for
148
+ every visible tool. Hosts render their own model-facing instructions from these descriptors; `CodeMode.searchSignature`
149
+ and `CodeMode.toolExpression(path)` supply the exact callable forms.
150
+
151
+ The synchronous `search(...)` built-in is always available. It supports exact-path lookup, namespace-scoped search,
152
+ empty-query browsing, and pagination, and returns callable paths with full signatures. Search counts toward
153
+ `maxToolCalls`.
154
+
155
+ ## Execution Limits
156
+
157
+ | Limit | Default | Controls |
158
+ | ---------------- | --------- | ------------------------------- |
159
+ | `timeoutMs` | unlimited | Total execution time. |
160
+ | `maxToolCalls` | unlimited | Admitted tool calls. |
161
+ | `maxOutputBytes` | unlimited | Retained result value and logs. |
162
+
163
+ Execution limits have no default values.
164
+
165
+ Invalid limit configuration throws `RangeError`. Warnings receive a separate budget equal to `maxOutputBytes`.
166
+ Truncation does not fail execution; an oversized value becomes a string with an in-band marker. Timeouts interrupt
167
+ tool calls and busy loops, while a result returned before cleanup times out remains successful with a
168
+ `TimeoutExceeded` warning. Tool-call concurrency is unrestricted. Boundary data is limited to 32 nested levels.
@@ -0,0 +1,148 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { type Services, type ToolDescription, ToolRuntime } from "./tool-runtime.js";
3
+ import type { Tools } from "./tools.js";
4
+ /** A tool call admitted during an execution. */
5
+ export type { ToolCall, ToolCallEnded, ToolCallHooks, ToolCallStarted, ToolDescription } from "./tool-runtime.js";
6
+ /** Signature-construction helpers for host-owned catalog instructions. */
7
+ export { searchSignature, toolExpression } from "./tool-runtime.js";
8
+ /** Resource budgets enforced independently during each CodeMode program execution. */
9
+ export type ExecutionLimits = {
10
+ /**
11
+ * Wall-clock milliseconds before interruption. Result delivery waits for tool cleanup.
12
+ * No default: absent means no timeout.
13
+ */
14
+ readonly timeoutMs?: number;
15
+ /** Maximum number of tool calls admitted by the runtime. No default: absent means unlimited. */
16
+ readonly maxToolCalls?: number;
17
+ /**
18
+ * Maximum UTF-8 bytes retained from the result and logs. Warnings have a separate equal budget;
19
+ * truncation notices and host formatting are additional.
20
+ */
21
+ readonly maxOutputBytes?: number;
22
+ };
23
+ export type ResolvedExecutionLimits = {
24
+ readonly timeoutMs: number | undefined;
25
+ readonly maxToolCalls: number | undefined;
26
+ readonly maxOutputBytes: number | undefined;
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;
32
+ /** Explicit tools exposed to the program as `tools`. */
33
+ tools?: Provided & Tools<Services<Provided>>;
34
+ /** Per-execution overrides for the default resource limits. */
35
+ 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>>;
40
+ };
41
+ /** A JSON value that can cross the confined interpreter boundary. */
42
+ 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
+ /** Schema for a host tool input containing CodeMode source. */
46
+ export declare const Input: Schema.Struct<{
47
+ readonly code: Schema.String;
48
+ }>;
49
+ export type Input = typeof Input.Type;
50
+ export declare const DiagnosticKind: Schema.Literals<readonly ["ParseError", "UnsupportedSyntax", "UnknownTool", "InvalidToolInput", "InvalidToolOutput", "InvalidDataValue", "ToolCallLimitExceeded", "TimeoutExceeded", "ToolFailure", "ExecutionFailure", "Truncated"]>;
51
+ /** Stable categories produced by program, schema, tool, limit, and truncation diagnostics. */
52
+ export type DiagnosticKind = typeof DiagnosticKind.Type;
53
+ export declare const Diagnostic: Schema.Struct<{
54
+ readonly kind: Schema.Literals<readonly ["ParseError", "UnsupportedSyntax", "UnknownTool", "InvalidToolInput", "InvalidToolOutput", "InvalidDataValue", "ToolCallLimitExceeded", "TimeoutExceeded", "ToolFailure", "ExecutionFailure", "Truncated"]>;
55
+ readonly message: Schema.String;
56
+ readonly location: Schema.optionalKey<Schema.Struct<{
57
+ readonly line: Schema.Number;
58
+ readonly column: Schema.Number;
59
+ }>>;
60
+ readonly suggestions: Schema.optionalKey<Schema.$Array<Schema.String>>;
61
+ }>;
62
+ /** A normalized program diagnostic safe to return across an agent tool boundary. */
63
+ export type Diagnostic = typeof Diagnostic.Type;
64
+ export declare const Success: Schema.Struct<{
65
+ readonly ok: Schema.Literal<true>;
66
+ readonly value: Schema.Codec<Schema.Json, Schema.Json, never, never>;
67
+ readonly warnings: Schema.optionalKey<Schema.$Array<Schema.Struct<{
68
+ readonly kind: Schema.Literals<readonly ["ParseError", "UnsupportedSyntax", "UnknownTool", "InvalidToolInput", "InvalidToolOutput", "InvalidDataValue", "ToolCallLimitExceeded", "TimeoutExceeded", "ToolFailure", "ExecutionFailure", "Truncated"]>;
69
+ readonly message: Schema.String;
70
+ readonly location: Schema.optionalKey<Schema.Struct<{
71
+ readonly line: Schema.Number;
72
+ readonly column: Schema.Number;
73
+ }>>;
74
+ readonly suggestions: Schema.optionalKey<Schema.$Array<Schema.String>>;
75
+ }>>>;
76
+ readonly logs: Schema.optionalKey<Schema.$Array<Schema.String>>;
77
+ readonly truncated: Schema.optionalKey<Schema.Boolean>;
78
+ readonly toolCalls: Schema.$Array<Schema.Struct<{
79
+ readonly name: Schema.String;
80
+ }>>;
81
+ }>;
82
+ /** Successful execution after the result has crossed the plain-data boundary. */
83
+ export type Success = typeof Success.Type;
84
+ export declare const Failure: Schema.Struct<{
85
+ readonly ok: Schema.Literal<false>;
86
+ readonly error: Schema.Struct<{
87
+ readonly kind: Schema.Literals<readonly ["ParseError", "UnsupportedSyntax", "UnknownTool", "InvalidToolInput", "InvalidToolOutput", "InvalidDataValue", "ToolCallLimitExceeded", "TimeoutExceeded", "ToolFailure", "ExecutionFailure", "Truncated"]>;
88
+ readonly message: Schema.String;
89
+ readonly location: Schema.optionalKey<Schema.Struct<{
90
+ readonly line: Schema.Number;
91
+ readonly column: Schema.Number;
92
+ }>>;
93
+ readonly suggestions: Schema.optionalKey<Schema.$Array<Schema.String>>;
94
+ }>;
95
+ readonly logs: Schema.optionalKey<Schema.$Array<Schema.String>>;
96
+ readonly truncated: Schema.optionalKey<Schema.Boolean>;
97
+ readonly toolCalls: Schema.$Array<Schema.Struct<{
98
+ readonly name: Schema.String;
99
+ }>>;
100
+ }>;
101
+ /** Failed execution with calls admitted before the diagnostic was produced. */
102
+ export type Failure = typeof Failure.Type;
103
+ /** Schema for the structured success or diagnostic returned by CodeMode execution. */
104
+ export declare const Result: Schema.Union<readonly [Schema.Struct<{
105
+ readonly ok: Schema.Literal<true>;
106
+ readonly value: Schema.Codec<Schema.Json, Schema.Json, never, never>;
107
+ readonly warnings: Schema.optionalKey<Schema.$Array<Schema.Struct<{
108
+ readonly kind: Schema.Literals<readonly ["ParseError", "UnsupportedSyntax", "UnknownTool", "InvalidToolInput", "InvalidToolOutput", "InvalidDataValue", "ToolCallLimitExceeded", "TimeoutExceeded", "ToolFailure", "ExecutionFailure", "Truncated"]>;
109
+ readonly message: Schema.String;
110
+ readonly location: Schema.optionalKey<Schema.Struct<{
111
+ readonly line: Schema.Number;
112
+ readonly column: Schema.Number;
113
+ }>>;
114
+ readonly suggestions: Schema.optionalKey<Schema.$Array<Schema.String>>;
115
+ }>>>;
116
+ readonly logs: Schema.optionalKey<Schema.$Array<Schema.String>>;
117
+ readonly truncated: Schema.optionalKey<Schema.Boolean>;
118
+ readonly toolCalls: Schema.$Array<Schema.Struct<{
119
+ readonly name: Schema.String;
120
+ }>>;
121
+ }>, Schema.Struct<{
122
+ readonly ok: Schema.Literal<false>;
123
+ readonly error: Schema.Struct<{
124
+ readonly kind: Schema.Literals<readonly ["ParseError", "UnsupportedSyntax", "UnknownTool", "InvalidToolInput", "InvalidToolOutput", "InvalidDataValue", "ToolCallLimitExceeded", "TimeoutExceeded", "ToolFailure", "ExecutionFailure", "Truncated"]>;
125
+ readonly message: Schema.String;
126
+ readonly location: Schema.optionalKey<Schema.Struct<{
127
+ readonly line: Schema.Number;
128
+ readonly column: Schema.Number;
129
+ }>>;
130
+ readonly suggestions: Schema.optionalKey<Schema.$Array<Schema.String>>;
131
+ }>;
132
+ readonly logs: Schema.optionalKey<Schema.$Array<Schema.String>>;
133
+ readonly truncated: Schema.optionalKey<Schema.Boolean>;
134
+ readonly toolCalls: Schema.$Array<Schema.Struct<{
135
+ readonly name: Schema.String;
136
+ }>>;
137
+ }>]>;
138
+ /** Result of executing a CodeMode program. Program failures are data, not Effect failures. */
139
+ export type Result = typeof Result.Type;
140
+ /** Reusable confined runtime over explicit tools. */
141
+ export type Runtime<R = never> = {
142
+ readonly catalog: () => ReadonlyArray<ToolDescription>;
143
+ readonly execute: (code: string) => Effect.Effect<Result, never, R>;
144
+ };
145
+ /** Executes one Effect-native CodeMode program without constructing a reusable runtime. */
146
+ export declare const execute: <const Provided extends Record<string, unknown>>(options: ExecuteOptions<Provided>) => Effect.Effect<Result, never, Services<Provided>>;
147
+ /** Creates an Effect-native runtime over explicit, schema-described tools. */
148
+ export declare const make: <const Provided extends Record<string, unknown> = {}>(options?: Options<Provided>) => Runtime<Services<Provided>>;
@@ -0,0 +1,70 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { executeWithLimits } from "./interpreter/execute.js";
3
+ import { ToolRuntime } from "./tool-runtime.js";
4
+ /** Signature-construction helpers for host-owned catalog instructions. */
5
+ export { searchSignature, toolExpression } from "./tool-runtime.js";
6
+ /** Schema for a host tool input containing CodeMode source. */
7
+ export const Input = Schema.Struct({ code: Schema.String });
8
+ export const DiagnosticKind = Schema.Literals([
9
+ "ParseError",
10
+ "UnsupportedSyntax",
11
+ "UnknownTool",
12
+ "InvalidToolInput",
13
+ "InvalidToolOutput",
14
+ "InvalidDataValue",
15
+ "ToolCallLimitExceeded",
16
+ "TimeoutExceeded",
17
+ "ToolFailure",
18
+ "ExecutionFailure",
19
+ "Truncated",
20
+ ]);
21
+ export const Diagnostic = Schema.Struct({
22
+ kind: DiagnosticKind,
23
+ message: Schema.String,
24
+ location: Schema.optionalKey(Schema.Struct({ line: Schema.Number, column: Schema.Number })),
25
+ suggestions: Schema.optionalKey(Schema.Array(Schema.String)),
26
+ });
27
+ const ToolCallSchema = Schema.Struct({ name: Schema.String });
28
+ export const Success = Schema.Struct({
29
+ ok: Schema.Literal(true),
30
+ value: Schema.Json,
31
+ warnings: Schema.optionalKey(Schema.Array(Diagnostic)),
32
+ logs: Schema.optionalKey(Schema.Array(Schema.String)),
33
+ truncated: Schema.optionalKey(Schema.Boolean),
34
+ toolCalls: Schema.Array(ToolCallSchema),
35
+ });
36
+ export const Failure = Schema.Struct({
37
+ ok: Schema.Literal(false),
38
+ error: Diagnostic,
39
+ logs: Schema.optionalKey(Schema.Array(Schema.String)),
40
+ truncated: Schema.optionalKey(Schema.Boolean),
41
+ toolCalls: Schema.Array(ToolCallSchema),
42
+ });
43
+ /** Schema for the structured success or diagnostic returned by CodeMode execution. */
44
+ export const Result = Schema.Union([Success, Failure]);
45
+ const validateLimit = (name, value, minimum) => {
46
+ if (value !== undefined && (!Number.isSafeInteger(value) || value < minimum)) {
47
+ throw new RangeError(`${name} must be a safe integer greater than or equal to ${minimum}.`);
48
+ }
49
+ return value;
50
+ };
51
+ const resolveExecutionLimits = (limits) => ({
52
+ timeoutMs: validateLimit("timeoutMs", limits?.timeoutMs, 1),
53
+ maxToolCalls: validateLimit("maxToolCalls", limits?.maxToolCalls, 0),
54
+ maxOutputBytes: validateLimit("maxOutputBytes", limits?.maxOutputBytes, 0),
55
+ });
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
+ };
61
+ /** Creates an Effect-native runtime over explicit, schema-described tools. */
62
+ export const make = (options = {}) => {
63
+ const tools = (options.tools ?? {});
64
+ const limits = resolveExecutionLimits(options.limits);
65
+ const prepared = ToolRuntime.prepare(tools);
66
+ return {
67
+ catalog: () => prepared.catalog,
68
+ execute: (code) => executeWithLimits({ ...options, code }, limits, prepared.searchIndex),
69
+ };
70
+ };
@@ -0,0 +1,5 @@
1
+ export * as CodeMode from "./codemode.js";
2
+ export * as Tool from "./tool.js";
3
+ export * as OpenAPI from "./openapi/index.js";
4
+ export { searchSignature, toolExpression } from "./codemode.js";
5
+ export { ToolError, toolError } from "./tool-error.js";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export * as CodeMode from "./codemode.js";
2
+ export * as Tool from "./tool.js";
3
+ export * as OpenAPI from "./openapi/index.js";
4
+ export { searchSignature, toolExpression } from "./codemode.js";
5
+ export { ToolError, toolError } from "./tool-error.js";
@@ -0,0 +1,9 @@
1
+ import { Effect } from "effect";
2
+ import type { Diagnostic } from "../codemode.js";
3
+ import { type SafeObject } from "../tool-runtime.js";
4
+ import { type AstNode } from "./model.js";
5
+ import { type SyncIteratorRunner } from "./iterator.js";
6
+ export declare const normalizeError: (error: unknown) => Diagnostic;
7
+ export declare const caughtErrorValue: (thrown: unknown) => unknown;
8
+ export declare const constructErrorValue: (name: string, args: Array<unknown>) => SafeObject;
9
+ export declare const constructAggregateErrorValue: <R>(runner: SyncIteratorRunner<R>, args: Array<unknown>, node: AstNode) => Effect.Effect<SafeObject, unknown, R>;
@@ -0,0 +1,91 @@
1
+ import { Effect } from "effect";
2
+ import { ToolError } from "../tool-error.js";
3
+ import { copyOut, ToolRuntimeError } from "../tool-runtime.js";
4
+ import { formatLocation, InterpreterRuntimeError, ProgramThrow, sourceLocation } from "./model.js";
5
+ import { containsRuntimeReference } from "./references.js";
6
+ import {} from "./iterator.js";
7
+ import { coerceToString, createAggregateErrorValue, createErrorValue, errorConstructors } from "../stdlib/value.js";
8
+ export const normalizeError = (error) => {
9
+ if (error instanceof InterpreterRuntimeError) {
10
+ return {
11
+ kind: error.kind,
12
+ message: `${error.message}${formatLocation(error.node)}`,
13
+ ...(error.node?.loc ? { location: sourceLocation(error.node) } : {}),
14
+ ...(error.suggestions ? { suggestions: error.suggestions } : {}),
15
+ };
16
+ }
17
+ if (error instanceof ToolRuntimeError) {
18
+ return {
19
+ kind: error.kind,
20
+ message: error.message,
21
+ ...(error.suggestions.length > 0 ? { suggestions: error.suggestions } : {}),
22
+ };
23
+ }
24
+ if (error instanceof ToolError) {
25
+ return { kind: "ToolFailure", message: error.message };
26
+ }
27
+ if (error instanceof ProgramThrow) {
28
+ const value = error.value;
29
+ let message;
30
+ if (containsRuntimeReference(value)) {
31
+ // Never expose runtime reference internals through thrown values.
32
+ message = "a non-data value";
33
+ }
34
+ else if (typeof value === "string") {
35
+ message = value;
36
+ }
37
+ else if (value !== null &&
38
+ typeof value === "object" &&
39
+ typeof value.message === "string") {
40
+ message = value.message;
41
+ }
42
+ else {
43
+ try {
44
+ message = JSON.stringify(copyOut(value, "json")) ?? String(value);
45
+ }
46
+ catch {
47
+ message = String(value);
48
+ }
49
+ }
50
+ return { kind: "ExecutionFailure", message: `Uncaught: ${message}` };
51
+ }
52
+ if (error instanceof RangeError && /call stack|recursion/i.test(error.message)) {
53
+ return {
54
+ kind: "ExecutionFailure",
55
+ message: "Execution exceeded the maximum nesting depth.",
56
+ };
57
+ }
58
+ if (error instanceof Error) {
59
+ return {
60
+ kind: error.name === "SyntaxError" ? "ParseError" : "ExecutionFailure",
61
+ message: error.message,
62
+ };
63
+ }
64
+ return {
65
+ kind: "ExecutionFailure",
66
+ message: String(error),
67
+ };
68
+ };
69
+ export const caughtErrorValue = (thrown) => {
70
+ if (thrown instanceof ProgramThrow)
71
+ return thrown.value;
72
+ if (thrown instanceof InterpreterRuntimeError)
73
+ return createErrorValue(thrown.errorName, thrown.message);
74
+ const name = thrown instanceof Error && errorConstructors.has(thrown.name) ? thrown.name : "Error";
75
+ return createErrorValue(name, normalizeError(thrown).message);
76
+ };
77
+ export const constructErrorValue = (name, args) => createErrorValue(name, args[0] === undefined ? "" : coerceToString(args[0]));
78
+ export const constructAggregateErrorValue = (runner, args, node) => Effect.gen(function* () {
79
+ const cursor = yield* runner.syncIterator(args[0], node);
80
+ if (cursor === undefined) {
81
+ throw new InterpreterRuntimeError("new AggregateError(...) expects a synchronous iterable of errors.", node).as("TypeError");
82
+ }
83
+ const errors = [];
84
+ while (true) {
85
+ const step = yield* cursor.next;
86
+ if (step.done) {
87
+ return createAggregateErrorValue(errors, args[1] === undefined ? "" : coerceToString(args[1]));
88
+ }
89
+ errors.push(step.value);
90
+ }
91
+ });
@@ -0,0 +1,4 @@
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>>;