@opencode/codemode 2.2.6 → 2.3.0

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 (197) hide show
  1. package/README.md +115 -29
  2. package/dist/{vm/async.d.ts → async.d.ts} +1 -1
  3. package/dist/codemode.d.ts +13 -22
  4. package/dist/codemode.js +18 -39
  5. package/dist/data.d.ts +4 -19
  6. package/dist/data.js +1 -82
  7. package/dist/extension.d.ts +20 -1
  8. package/dist/extension.js +14 -1
  9. package/dist/{vm/host.d.ts → host.d.ts} +5 -2
  10. package/dist/{vm/host.js → host.js} +9 -4
  11. package/dist/index.d.ts +1 -1
  12. package/dist/{vm/opcodes.d.ts → opcodes.d.ts} +1 -1
  13. package/dist/{vm/prelude → prelude}/helpers.js +1 -1
  14. package/dist/{vm/runtime → runtime}/driver.d.ts +18 -8
  15. package/dist/{vm/runtime → runtime}/driver.js +90 -20
  16. package/dist/{vm/runtime → runtime}/errors.js +2 -2
  17. package/dist/{vm/runtime → runtime}/execute.d.ts +18 -9
  18. package/dist/{vm/runtime → runtime}/execute.js +45 -15
  19. package/dist/{vm/runtime → runtime}/extensions.d.ts +2 -2
  20. package/dist/{vm/runtime → runtime}/extensions.js +121 -19
  21. package/dist/{vm/runtime → runtime}/globals.js +1 -1
  22. package/dist/{vm/runtime → runtime}/interpreter.d.ts +4 -1
  23. package/dist/{vm/runtime → runtime}/interpreter.js +2 -0
  24. package/dist/{vm/runtime → runtime}/model.d.ts +1 -1
  25. package/dist/{vm/runtime → runtime}/objects.d.ts +1 -1
  26. package/dist/{vm/runtime → runtime}/objects.js +1 -1
  27. package/dist/{vm/runtime → runtime}/operations.d.ts +1 -1
  28. package/dist/{vm/runtime → runtime}/operations.js +1 -1
  29. package/dist/scan.js +2 -2
  30. package/dist/{vm/scheduler.d.ts → scheduler.d.ts} +16 -4
  31. package/dist/{vm/scheduler.js → scheduler.js} +13 -2
  32. package/dist/{vm/snapshot → snapshot}/codec.d.ts +37 -6
  33. package/dist/{vm/snapshot → snapshot}/codec.js +112 -8
  34. package/dist/{vm/snapshot → snapshot}/snapshot.d.ts +13 -6
  35. package/dist/{vm/snapshot → snapshot}/snapshot.js +19 -4
  36. package/dist/{vm/snapshot.js → snapshot.js} +5 -2
  37. package/dist/stdlib/array.d.ts +14 -9
  38. package/dist/stdlib/array.js +89 -276
  39. package/dist/stdlib/bytes.d.ts +11 -7
  40. package/dist/stdlib/bytes.js +112 -79
  41. package/dist/stdlib/collections.d.ts +7 -7
  42. package/dist/stdlib/collections.js +30 -339
  43. package/dist/stdlib/console.d.ts +2 -2
  44. package/dist/stdlib/console.js +3 -3
  45. package/dist/stdlib/date.d.ts +2 -2
  46. package/dist/stdlib/date.js +21 -30
  47. package/dist/stdlib/headers.d.ts +2 -2
  48. package/dist/stdlib/headers.js +15 -33
  49. package/dist/stdlib/iterator.d.ts +2 -2
  50. package/dist/stdlib/iterator.js +10 -303
  51. package/dist/stdlib/json.d.ts +2 -2
  52. package/dist/stdlib/json.js +15 -31
  53. package/dist/stdlib/math.d.ts +2 -7
  54. package/dist/stdlib/math.js +6 -30
  55. package/dist/stdlib/number.d.ts +3 -3
  56. package/dist/stdlib/number.js +8 -8
  57. package/dist/stdlib/object.d.ts +4 -4
  58. package/dist/stdlib/object.js +12 -30
  59. package/dist/stdlib/regexp.d.ts +6 -5
  60. package/dist/stdlib/regexp.js +18 -13
  61. package/dist/stdlib/string.d.ts +2 -2
  62. package/dist/stdlib/string.js +53 -53
  63. package/dist/stdlib/url.d.ts +21 -9
  64. package/dist/stdlib/url.js +55 -55
  65. package/dist/stdlib/value.d.ts +3 -4
  66. package/dist/stdlib/value.js +5 -6
  67. package/dist/stdlib/web.d.ts +4 -4
  68. package/dist/stdlib/web.js +7 -7
  69. package/dist/tool-runtime.d.ts +34 -12
  70. package/dist/tool-runtime.js +350 -68
  71. package/dist/tool-schema.d.ts +5 -0
  72. package/dist/tool-schema.js +36 -16
  73. package/dist/tool.d.ts +60 -2
  74. package/dist/tool.js +17 -1
  75. package/dist/{vm/vm.d.ts → vm.d.ts} +4 -3
  76. package/dist/{vm/vm.js → vm.js} +1 -1
  77. package/package.json +5 -7
  78. package/dist/interpreter/callback.d.ts +0 -24
  79. package/dist/interpreter/callback.js +0 -86
  80. package/dist/interpreter/errors.js +0 -173
  81. package/dist/interpreter/execute.d.ts +0 -14
  82. package/dist/interpreter/execute.js +0 -207
  83. package/dist/interpreter/extensions.d.ts +0 -9
  84. package/dist/interpreter/extensions.js +0 -248
  85. package/dist/interpreter/generators.d.ts +0 -3
  86. package/dist/interpreter/generators.js +0 -168
  87. package/dist/interpreter/globals.js +0 -144
  88. package/dist/interpreter/interpreter.d.ts +0 -48
  89. package/dist/interpreter/interpreter.js +0 -2253
  90. package/dist/interpreter/intrinsics.d.ts +0 -15
  91. package/dist/interpreter/intrinsics.js +0 -105
  92. package/dist/interpreter/model.d.ts +0 -68
  93. package/dist/interpreter/model.js +0 -54
  94. package/dist/interpreter/native.d.ts +0 -17
  95. package/dist/interpreter/native.js +0 -35
  96. package/dist/interpreter/objects.d.ts +0 -301
  97. package/dist/interpreter/objects.js +0 -592
  98. package/dist/interpreter/promises.d.ts +0 -18
  99. package/dist/interpreter/promises.js +0 -292
  100. package/dist/interpreter/runner.d.ts +0 -188
  101. package/dist/interpreter/runner.js +0 -492
  102. package/dist/interpreter/scope.d.ts +0 -16
  103. package/dist/interpreter/scope.js +0 -79
  104. package/dist/suspend-error.d.ts +0 -23
  105. package/dist/suspend-error.js +0 -25
  106. package/dist/vm/data.d.ts +0 -7
  107. package/dist/vm/data.js +0 -13
  108. package/dist/vm/index.d.ts +0 -6
  109. package/dist/vm/index.js +0 -6
  110. package/dist/vm/runtime/errors.d.ts +0 -23
  111. package/dist/vm/runtime/globals.d.ts +0 -6
  112. package/dist/vm/runtime/limits.d.ts +0 -10
  113. package/dist/vm/runtime/limits.js +0 -19
  114. package/dist/vm/runtime/modules.d.ts +0 -4
  115. package/dist/vm/runtime/modules.js +0 -33
  116. package/dist/vm/runtime/references.d.ts +0 -8
  117. package/dist/vm/runtime/references.js +0 -51
  118. package/dist/vm/stdlib/array.d.ts +0 -16
  119. package/dist/vm/stdlib/array.js +0 -311
  120. package/dist/vm/stdlib/bytes.d.ts +0 -11
  121. package/dist/vm/stdlib/bytes.js +0 -222
  122. package/dist/vm/stdlib/collections.d.ts +0 -7
  123. package/dist/vm/stdlib/collections.js +0 -188
  124. package/dist/vm/stdlib/console.d.ts +0 -6
  125. package/dist/vm/stdlib/console.js +0 -93
  126. package/dist/vm/stdlib/date.d.ts +0 -2
  127. package/dist/vm/stdlib/date.js +0 -123
  128. package/dist/vm/stdlib/headers.d.ts +0 -2
  129. package/dist/vm/stdlib/headers.js +0 -92
  130. package/dist/vm/stdlib/iterator.d.ts +0 -2
  131. package/dist/vm/stdlib/iterator.js +0 -30
  132. package/dist/vm/stdlib/json.d.ts +0 -3
  133. package/dist/vm/stdlib/json.js +0 -42
  134. package/dist/vm/stdlib/math.d.ts +0 -3
  135. package/dist/vm/stdlib/math.js +0 -73
  136. package/dist/vm/stdlib/number.d.ts +0 -3
  137. package/dist/vm/stdlib/number.js +0 -72
  138. package/dist/vm/stdlib/object.d.ts +0 -6
  139. package/dist/vm/stdlib/object.js +0 -201
  140. package/dist/vm/stdlib/regexp.d.ts +0 -8
  141. package/dist/vm/stdlib/regexp.js +0 -119
  142. package/dist/vm/stdlib/string.d.ts +0 -2
  143. package/dist/vm/stdlib/string.js +0 -272
  144. package/dist/vm/stdlib/url.d.ts +0 -25
  145. package/dist/vm/stdlib/url.js +0 -255
  146. package/dist/vm/stdlib/value.d.ts +0 -6
  147. package/dist/vm/stdlib/value.js +0 -32
  148. package/dist/vm/stdlib/web.d.ts +0 -5
  149. package/dist/vm/stdlib/web.js +0 -97
  150. /package/dist/{vm/async.js → async.js} +0 -0
  151. /package/dist/{vm/code.d.ts → code.d.ts} +0 -0
  152. /package/dist/{vm/code.js → code.js} +0 -0
  153. /package/dist/{vm/compiler → compiler}/compile.d.ts +0 -0
  154. /package/dist/{vm/compiler → compiler}/compile.js +0 -0
  155. /package/dist/{vm/compiler → compiler}/scope.d.ts +0 -0
  156. /package/dist/{vm/compiler → compiler}/scope.js +0 -0
  157. /package/dist/{vm/generators.d.ts → generators.d.ts} +0 -0
  158. /package/dist/{vm/generators.js → generators.js} +0 -0
  159. /package/dist/{vm/internal-prelude.d.ts → internal-prelude.d.ts} +0 -0
  160. /package/dist/{vm/internal-prelude.js → internal-prelude.js} +0 -0
  161. /package/dist/{vm/opcodes.js → opcodes.js} +0 -0
  162. /package/dist/{vm/prelude → prelude}/bytecode.d.ts +0 -0
  163. /package/dist/{vm/prelude → prelude}/bytecode.js +0 -0
  164. /package/dist/{vm/prelude → prelude}/bytecode.json +0 -0
  165. /package/dist/{vm/prelude → prelude}/helpers.d.ts +0 -0
  166. /package/dist/{vm/prelude → prelude}/prelude.d.ts +0 -0
  167. /package/dist/{vm/prelude → prelude}/prelude.js +0 -0
  168. /package/dist/{vm/prelude → prelude}/source.d.ts +0 -0
  169. /package/dist/{vm/prelude → prelude}/source.js +0 -0
  170. /package/dist/{vm/runtime → runtime}/callback.d.ts +0 -0
  171. /package/dist/{vm/runtime → runtime}/callback.js +0 -0
  172. /package/dist/{interpreter → runtime}/errors.d.ts +0 -0
  173. /package/dist/{vm/runtime → runtime}/generators.d.ts +0 -0
  174. /package/dist/{vm/runtime → runtime}/generators.js +0 -0
  175. /package/dist/{interpreter → runtime}/globals.d.ts +0 -0
  176. /package/dist/{vm/runtime → runtime}/intrinsic-names.d.ts +0 -0
  177. /package/dist/{vm/runtime → runtime}/intrinsic-names.js +0 -0
  178. /package/dist/{vm/runtime → runtime}/intrinsics.d.ts +0 -0
  179. /package/dist/{vm/runtime → runtime}/intrinsics.js +0 -0
  180. /package/dist/{interpreter → runtime}/limits.d.ts +0 -0
  181. /package/dist/{interpreter → runtime}/limits.js +0 -0
  182. /package/dist/{vm/runtime → runtime}/model.js +0 -0
  183. /package/dist/{interpreter → runtime}/modules.d.ts +0 -0
  184. /package/dist/{interpreter → runtime}/modules.js +0 -0
  185. /package/dist/{vm/runtime → runtime}/native.d.ts +0 -0
  186. /package/dist/{vm/runtime → runtime}/native.js +0 -0
  187. /package/dist/{vm/runtime → runtime}/promises.d.ts +0 -0
  188. /package/dist/{vm/runtime → runtime}/promises.js +0 -0
  189. /package/dist/{interpreter → runtime}/references.d.ts +0 -0
  190. /package/dist/{interpreter → runtime}/references.js +0 -0
  191. /package/dist/{vm/runtime → runtime}/signals.d.ts +0 -0
  192. /package/dist/{vm/runtime → runtime}/signals.js +0 -0
  193. /package/dist/{vm/runtime → runtime}/source.d.ts +0 -0
  194. /package/dist/{vm/runtime → runtime}/source.js +0 -0
  195. /package/dist/{vm/runtime → runtime}/table.d.ts +0 -0
  196. /package/dist/{vm/runtime → runtime}/table.js +0 -0
  197. /package/dist/{vm/snapshot.d.ts → snapshot.d.ts} +0 -0
@@ -237,22 +237,9 @@ export const jsonSchemaToTypeScript = (schema, pretty = false) => {
237
237
  };
238
238
  export const inputProperties = (tool) => {
239
239
  try {
240
- const document = isEffectSchema(tool.input)
241
- ? Schema.toJsonSchemaDocument(tool.input, { onExcessProperty: "error" })
242
- : {
243
- schema: tool.input,
244
- definitions: { ...(tool.input.definitions ?? {}), ...(tool.input.$defs ?? {}) },
245
- };
246
- let schema = document.schema;
247
- if (schema.$ref !== undefined) {
248
- const name = definitionName(schema.$ref);
249
- const resolved = name === undefined ? undefined : document.definitions[name];
250
- if (resolved === undefined)
251
- return [];
252
- schema = resolved;
253
- }
254
- const required = new Set(schema.required ?? []);
255
- return Object.entries(schema.properties ?? {}).map(([name, value]) => ({
240
+ const schema = inputDocument(tool)?.schema;
241
+ const required = new Set(schema?.required ?? []);
242
+ return Object.entries(schema?.properties ?? {}).map(([name, value]) => ({
256
243
  name,
257
244
  description: typeof value.description === "string" ? value.description : undefined,
258
245
  required: required.has(name),
@@ -262,6 +249,39 @@ export const inputProperties = (tool) => {
262
249
  return [];
263
250
  }
264
251
  };
252
+ /** A freeform tool whose input is one required string field takes that string directly: `tools.patch(patchText: string)`. */
253
+ export const stringParameter = (tool) => {
254
+ if (!tool.freeform)
255
+ return undefined;
256
+ try {
257
+ const document = inputDocument(tool);
258
+ const fields = Object.entries(document?.schema.properties ?? {});
259
+ if (document === undefined || fields.length !== 1)
260
+ return undefined;
261
+ const [name, field] = fields[0];
262
+ if (field.type !== "string" || !document.schema.required?.includes(name))
263
+ return undefined;
264
+ const label = identifierSegment.test(name) ? name : "input";
265
+ const type = renderSchema(field, { definitions: document.definitions, pretty: false });
266
+ return { name, signature: `(${jsdoc(field, "").replace(/\n$/, " ")}${label}: ${type})` };
267
+ }
268
+ catch {
269
+ return undefined;
270
+ }
271
+ };
272
+ const inputDocument = (tool) => {
273
+ const document = isEffectSchema(tool.input)
274
+ ? Schema.toJsonSchemaDocument(tool.input, { onExcessProperty: "error" })
275
+ : {
276
+ schema: tool.input,
277
+ definitions: { ...(tool.input.definitions ?? {}), ...(tool.input.$defs ?? {}) },
278
+ };
279
+ if (document.schema.$ref === undefined)
280
+ return document;
281
+ const name = definitionName(document.schema.$ref);
282
+ const schema = name === undefined ? undefined : document.definitions[name];
283
+ return schema && { schema, definitions: document.definitions };
284
+ };
265
285
  export const inputTypeScript = (tool, pretty = false) => isEffectSchema(tool.input) ? toTypeScript(tool.input, false, pretty) : jsonSchemaToTypeScript(tool.input, pretty);
266
286
  // Effect inputs are empty only when their encoded root is Effect's empty-struct marker, which records and checked
267
287
  // structs never are. Raw JSON Schema inputs keep the `{}` rendering check, which treats `{ type: "object" }` as empty.
package/dist/tool.d.ts CHANGED
@@ -38,13 +38,59 @@ export type JsonSchema = {
38
38
  };
39
39
  /** Either a validating Effect Schema or a render-only JSON Schema document. */
40
40
  export type SchemaType = Schema.Decoder<unknown> | JsonSchema;
41
+ /** Context passed to a tool call: its stable idempotency key (`<runId>:<callId>`). */
42
+ export type ToolContext = {
43
+ readonly key: string;
44
+ };
45
+ export type ExecuteFn<Input = unknown, Output = unknown, R = never> = (input: Input, context: ToolContext) => Effect.Effect<Output, unknown, R>;
46
+ /**
47
+ * A tool execution wrapper for idempotent work that is safe to run again. If a suspend lands while the call is running,
48
+ * the VM interrupts it without firing `tool.after`, keeps the call queued in the snapshot, and re-runs it on resume
49
+ * with the same `key` without double-counting against `maxToolCalls`.
50
+ */
51
+ export type Idempotent<Input = unknown, Output = unknown, R = never> = {
52
+ readonly _tag: "CodeModeIdempotent";
53
+ readonly execute: ExecuteFn<Input, Output, R>;
54
+ };
55
+ /**
56
+ * Options for `Tool.durable`: `start` begins the work under `key` and returns JSON `data` saved in the snapshot;
57
+ * `wait` connects to the running work and waits for its output; `cancel` stops the work when the run is interrupted
58
+ * for real or ends, never when it is suspended. `wait` is not tied to the program's JS `await`: the VM calls `wait`
59
+ * right after `start` returns, and again for every `started` call right at resume, whatever the program does with the
60
+ * promise.
61
+ */
62
+ export type DurableOptions<Data extends Schema.Json, Input = unknown, Output = unknown, RStart = never, RWait = never, RCancel = never> = {
63
+ readonly start: (input: Input, context: ToolContext) => Effect.Effect<Data, unknown, RStart>;
64
+ readonly wait: (data: NoInfer<Data>, context: ToolContext) => Effect.Effect<Output, unknown, RWait>;
65
+ readonly cancel: (data: NoInfer<Data>) => Effect.Effect<void, unknown, RCancel>;
66
+ };
67
+ /** A tool execution wrapper for work that keeps running across a suspend and reconnects through its JSON data. */
68
+ export type Durable<Input = unknown, Output = unknown, R = never> = {
69
+ readonly _tag: "CodeModeDurable";
70
+ readonly start: (input: Input, context: ToolContext) => Effect.Effect<Schema.Json, unknown, R>;
71
+ readonly wait: (data: never, context: ToolContext) => Effect.Effect<Output, unknown, R>;
72
+ readonly cancel: (data: never) => Effect.Effect<void, unknown, R>;
73
+ };
74
+ type IdempotentOption<Input = unknown, Output = unknown, R = never> = {
75
+ (input: Input, context: ToolContext): Effect.Effect<Output, unknown, R>;
76
+ readonly _tag: "CodeModeIdempotent";
77
+ readonly execute: ExecuteFn<Input, Output, R>;
78
+ };
79
+ type DurableOption<Input = unknown, Output = unknown, R = never> = {
80
+ (input: Input, context: ToolContext): Effect.Effect<Output, unknown, R>;
81
+ readonly _tag: "CodeModeDurable";
82
+ readonly start: (input: Input, context: ToolContext) => Effect.Effect<Schema.Json, unknown, R>;
83
+ readonly wait: (data: never, context: ToolContext) => Effect.Effect<Output, unknown, R>;
84
+ readonly cancel: (data: never) => Effect.Effect<void, unknown, R>;
85
+ };
41
86
  /** Executable tool exposed through CodeMode's `tools` object. */
42
87
  export type Tool<R = never> = {
43
88
  readonly _tag: "CodeModeTool";
44
89
  readonly description: string;
45
90
  readonly input: SchemaType;
91
+ readonly freeform?: boolean;
46
92
  readonly output: SchemaType | undefined;
47
- readonly execute: (input: unknown) => Effect.Effect<unknown, unknown, R>;
93
+ readonly execute: ExecuteFn<unknown, unknown, R> | Idempotent<unknown, unknown, R> | Durable<unknown, unknown, R>;
48
94
  };
49
95
  type InputType<S> = S extends Schema.Decoder<unknown> ? S["Type"] : unknown;
50
96
  type ResultType<S> = S extends undefined ? void : S extends Schema.Decoder<unknown> ? S["Encoded"] : unknown;
@@ -52,10 +98,22 @@ type ResultType<S> = S extends undefined ? void : S extends Schema.Decoder<unkno
52
98
  export type Options<I extends SchemaType, O extends SchemaType | undefined, R = never> = {
53
99
  readonly description: string;
54
100
  readonly input: I;
101
+ /**
102
+ * The tool's input is one required string field that programs pass directly, as in `tools.patch("...")`.
103
+ * The object form still works, and the executor receives the object either way.
104
+ */
105
+ readonly freeform?: boolean;
55
106
  readonly output?: O;
56
- readonly execute: (input: InputType<I>) => Effect.Effect<ResultType<O>, unknown, R>;
107
+ readonly execute: ExecuteFn<InputType<I>, ResultType<O>, R> | IdempotentOption<InputType<I>, ResultType<O>, R> | DurableOption<InputType<I>, ResultType<O>, R>;
57
108
  };
58
109
  export declare const isTool: <R = never>(value: Tool<R> | Namespace<R> | Tools<R> | undefined) => value is Tool<R>;
110
+ /** Marks a tool's `execute` function as safe to interrupt on suspend and re-run on resume with the same key. */
111
+ export declare const idempotent: <Input, Output, R = never>(execute: ExecuteFn<Input, Output, R>) => IdempotentOption<Input, Output, R>;
112
+ /**
113
+ * Wraps a tool's execution as `start`, `wait`, and `cancel` so work started before a suspend keeps running and
114
+ * reconnects through its JSON data on resume.
115
+ */
116
+ export declare const durable: <Data extends Schema.Json, Input = unknown, Output = unknown, RStart = never, RWait = never, RCancel = never>(options: DurableOptions<Data, Input, Output, RStart, RWait, RCancel>) => DurableOption<Input, Output, RStart | RWait | RCancel>;
59
117
  /**
60
118
  * Declares one schema-described tool available to a CodeMode program through `tools.*`.
61
119
  *
package/dist/tool.js CHANGED
@@ -1,5 +1,20 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  export const isTool = (value) => value !== undefined && Object.hasOwn(value, "_tag") && value._tag === "CodeModeTool";
3
+ /** Marks a tool's `execute` function as safe to interrupt on suspend and re-run on resume with the same key. */
4
+ export const idempotent = (execute) => ({
5
+ _tag: "CodeModeIdempotent",
6
+ execute,
7
+ });
8
+ /**
9
+ * Wraps a tool's execution as `start`, `wait`, and `cancel` so work started before a suspend keeps running and
10
+ * reconnects through its JSON data on resume.
11
+ */
12
+ export const durable = (options) => ({
13
+ _tag: "CodeModeDurable",
14
+ start: options.start,
15
+ wait: options.wait,
16
+ cancel: options.cancel,
17
+ });
3
18
  /**
4
19
  * Declares one schema-described tool available to a CodeMode program through `tools.*`.
5
20
  *
@@ -11,6 +26,7 @@ export const make = (options) => ({
11
26
  _tag: "CodeModeTool",
12
27
  description: options.description,
13
28
  input: options.input,
29
+ ...(options.freeform && { freeform: true }),
14
30
  output: options.output,
15
- execute: (input) => options.execute(input),
31
+ execute: options.execute,
16
32
  });
@@ -1,4 +1,4 @@
1
- import type { Diagnostic } from "../codemode.js";
1
+ import type { Diagnostic } from "./codemode.js";
2
2
  import type { Interpreter } from "./runtime/interpreter.js";
3
3
  import { type AstNode } from "./runtime/model.js";
4
4
  import { Arr, Fn, Obj, type Value } from "./runtime/objects.js";
@@ -119,15 +119,16 @@ export declare class Vm {
119
119
  * program value or its concurrent call is running: it holds live host values.
120
120
  */
121
121
  get activeExtension(): {
122
+ readonly key: string;
122
123
  readonly path: string;
123
124
  } | undefined;
124
125
  /** Saves the run's state as it is now. */
125
126
  capture(options: CaptureOptions): {
126
- readonly snapshot: import("./index.js").Snapshot;
127
+ readonly snapshot: import("./codemode.js").Snapshot;
127
128
  readonly lost: ReadonlyArray<string>;
128
129
  };
129
130
  /** Restores a saved state into this fresh VM, after checking it belongs to this build and runtime. */
130
- restore(saved: unknown, options: RestoreOptions): import("./index.js").Snapshot;
131
+ restore(saved: unknown, options: RestoreOptions): import("./codemode.js").Snapshot;
131
132
  deliverAnswer(frame: Frame): void;
132
133
  acquire(code: Code): Frame;
133
134
  release(frame: Frame): void;
@@ -12,7 +12,7 @@ import { Source } from "./runtime/source.js";
12
12
  import { compiledPrelude } from "./prelude/prelude.js";
13
13
  import { constructRegExp } from "./stdlib/regexp.js";
14
14
  import { enumerableSource } from "./stdlib/object.js";
15
- import { ToolReference } from "../tool-runtime.js";
15
+ import { ToolReference } from "./tool-runtime.js";
16
16
  import { registerAsyncIntrinsics, VmScheduler } from "./async.js";
17
17
  import { captureVm, restoreVm } from "./snapshot.js";
18
18
  import { compileSource } from "./compiler/compile.js";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "@opencode/codemode",
4
- "version": "2.2.6",
4
+ "version": "2.3.0",
5
5
  "description": "Effect-native confined code execution over schema-described tools",
6
6
  "type": "module",
7
7
  "license": "MIT",
@@ -18,8 +18,8 @@
18
18
  ],
19
19
  "exports": {
20
20
  ".": {
21
- "import": "./dist/index.js",
22
- "types": "./dist/index.d.ts"
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
23
  }
24
24
  },
25
25
  "scripts": {
@@ -27,10 +27,8 @@
27
27
  "pack": "bun run script/pack.ts",
28
28
  "typecheck": "bun check --no-script",
29
29
  "typecheck:tsc": "tsc --noEmit",
30
- "test": "bun test && CODEMODE_ENGINE=vm bun test",
31
- "test:legacy": "bun test",
32
- "test:vm": "CODEMODE_ENGINE=vm bun test",
33
- "test:roundtrip": "CODEMODE_ENGINE=vm CODEMODE_ROUNDTRIP=1 bun test"
30
+ "test": "bun test",
31
+ "test:roundtrip": "CODEMODE_ROUNDTRIP=1 bun test"
34
32
  },
35
33
  "dependencies": {
36
34
  "acorn": "8.15.0",
@@ -1,24 +0,0 @@
1
- import type { Interpreter } from "./interpreter.js";
2
- import { Callable, type Cursor, type NativeResult, type Value } from "./objects.js";
3
- import { type Eval } from "./runner.js";
4
- /** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
5
- * return() is a return completion, so a failing close wins over it, as after `break`. */
6
- export declare function preserveConsumerError<A>(close: Cursor["close"], body: Eval<A>): Eval<A>;
7
- export type Hint = "number" | "string" | "default";
8
- /**
9
- * ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the
10
- * default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool
11
- * references) pass through unchanged so callers reject or describe them in their built-in form.
12
- */
13
- export declare function toPrimitive<R>(ctx: Interpreter<R>, value: Value, hint: Hint): Eval<Value>;
14
- /** Invoke(value, name): calls the method the value would find through its prototype. */
15
- export declare const invoke: <R>(ctx: Interpreter<R>, value: Value, name: string, label: string) => Eval<Value>;
16
- export declare function toPrimitiveString<R>(ctx: Interpreter<R>, value: Value): Eval<string>;
17
- export declare function toPrimitiveNumber<R>(ctx: Interpreter<R>, value: Value): Eval<number>;
18
- /**
19
- * Runs a native body on its arguments after ToPrimitive, in order, with one hint for all positions or one per
20
- * position. Primitive arguments skip the conversion entirely.
21
- */
22
- export declare const withPrimitives: <R>(ctx: Interpreter<R>, hints: Hint | ReadonlyArray<Hint>, values: Array<Value>, body: (primitives: Array<Value>) => NativeResult) => NativeResult;
23
- export declare const isSupportedCallback: (value: Value) => value is Callable;
24
- export declare const applyCollectionCallback: <R>(ctx: Interpreter<R>, callback: Value, name: string) => ((args: Array<Value>, thisValue?: Value) => Eval<Value>);
@@ -1,86 +0,0 @@
1
- import { primitivePrototype } from "./intrinsics.js";
2
- import { GeneratorReturn, typeError } from "./model.js";
3
- import { Callable, get, Native, DateObj, Obj, coerceToNumber, coerceToString, } from "./objects.js";
4
- import { isOpaque, typeofValue } from "./references.js";
5
- import { Interruption, isEval } from "./runner.js";
6
- /** IteratorClose: a consumer failure closes the iterator and wins over any close failure, except that a generator's
7
- * return() is a return completion, so a failing close wins over it, as after `break`. */
8
- export function* preserveConsumerError(close, body) {
9
- try {
10
- return yield* body;
11
- }
12
- catch (error) {
13
- if (error instanceof Interruption)
14
- throw error;
15
- try {
16
- yield* close();
17
- }
18
- catch (closed) {
19
- if (error instanceof GeneratorReturn)
20
- throw closed;
21
- }
22
- throw error;
23
- }
24
- }
25
- /**
26
- * ToPrimitive: calls `valueOf`/`toString` in hint order and returns the first primitive result. Dates treat the
27
- * default hint as "string", like their `Symbol.toPrimitive`. Opaque values (functions, promises, generators, tool
28
- * references) pass through unchanged so callers reject or describe them in their built-in form.
29
- */
30
- export function* toPrimitive(ctx, value, hint) {
31
- if (!(value instanceof Obj) || isOpaque(value))
32
- return value;
33
- const asString = hint === "string" || (hint === "default" && value instanceof DateObj);
34
- for (const method of asString ? ["toString", "valueOf"] : ["valueOf", "toString"]) {
35
- const callable = get(value, method);
36
- if (!(callable instanceof Callable))
37
- continue;
38
- const result = yield* ctx.call(callable, value, []);
39
- if (result === null || (typeof result !== "object" && typeof result !== "function"))
40
- return result;
41
- }
42
- throw typeError("Cannot convert object to primitive value.");
43
- }
44
- /** Invoke(value, name): calls the method the value would find through its prototype. */
45
- export const invoke = (ctx, value, name, label) => {
46
- const target = value instanceof Obj ? value : primitivePrototype(ctx.builtins, value);
47
- if (target === undefined)
48
- throw typeError(`${label} called on null or undefined.`);
49
- return ctx.call(get(target, name), value, []);
50
- };
51
- export function* toPrimitiveString(ctx, value) {
52
- return coerceToString(yield* toPrimitive(ctx, value, "string"));
53
- }
54
- export function* toPrimitiveNumber(ctx, value) {
55
- return coerceToNumber(yield* toPrimitive(ctx, value, "number"));
56
- }
57
- /**
58
- * Runs a native body on its arguments after ToPrimitive, in order, with one hint for all positions or one per
59
- * position. Primitive arguments skip the conversion entirely.
60
- */
61
- export const withPrimitives = (ctx, hints, values, body) => {
62
- if (!values.some((value) => value instanceof Obj))
63
- return body(values);
64
- return (function* () {
65
- const primitives = [];
66
- for (const [index, value] of values.entries()) {
67
- primitives.push(yield* toPrimitive(ctx, value, typeof hints === "string" ? hints : hints[index]));
68
- }
69
- const result = body(primitives);
70
- return isEval(result) ? yield* result : result;
71
- })();
72
- };
73
- // The single acceptance list for callbacks: collections, sort, string replacers,
74
- // Array.from mappers, and promise reactions all admit exactly these callables.
75
- // Admission means dispatchable, not necessarily invocable: new-requiring
76
- // constructors pass the gate and throw a TypeError on call, like JS.
77
- export const isSupportedCallback = (value) => value instanceof Callable && !(value instanceof Native && !value.callback);
78
- export const applyCollectionCallback = (ctx, callback, name) => {
79
- if (!isSupportedCallback(callback)) {
80
- if (typeofValue(callback) === "function") {
81
- throw typeError(`${name} cannot use this callable as a callback; wrap it in an arrow function, e.g. (value) => tools.ns.tool(value).`);
82
- }
83
- throw typeError(`${name} expects a function callback.`);
84
- }
85
- return (callbackArgs, thisValue) => ctx.call(callback, thisValue, callbackArgs);
86
- };
@@ -1,173 +0,0 @@
1
- import { ToolError } from "../tool-error.js";
2
- import { ToolRuntimeError } from "../tool-runtime.js";
3
- import { formatLocation, PendingThrow, Throw, sourceLocation, typeError } from "./model.js";
4
- import { containsRuntimeReference } from "./references.js";
5
- import { createErrorValue, isErrorType } from "./intrinsics.js";
6
- import { constructor, methods, prototypeFrom, receiver } from "./native.js";
7
- import { define, get, has, hidden, Arr, ErrorObj, Obj, coerceToString, } from "./objects.js";
8
- import { toPrimitiveString } from "./callback.js";
9
- import { formatValue } from "../stdlib/console.js";
10
- /**
11
- * A host error's message as text. A host can store anything there; an object must not cross as itself, and turning it
12
- * into text would run its own methods.
13
- */
14
- export const errorMessage = (error) => {
15
- const message = error.message;
16
- if (typeof message === "string")
17
- return message;
18
- if (message === undefined || typeof message === "function" || (typeof message === "object" && message !== null)) {
19
- return "";
20
- }
21
- return String(message);
22
- };
23
- /** A host error's name as a program error type, read once so a getter cannot pass the check and then change. */
24
- export const errorType = (error) => {
25
- const name = error.name;
26
- return typeof name === "string" && isErrorType(name) ? name : "Error";
27
- };
28
- export const normalizeError = (error) => {
29
- if (error instanceof PendingThrow) {
30
- const location = error.node?.loc ? sourceLocation(error.node) : undefined;
31
- return {
32
- kind: error.kind,
33
- message: `${error.type}: ${error.message}${formatLocation(location)}`,
34
- ...(location ? { location } : {}),
35
- ...(error.suggestions ? { suggestions: error.suggestions } : {}),
36
- };
37
- }
38
- if (error instanceof ToolRuntimeError) {
39
- return {
40
- kind: error.kind,
41
- message: error.message,
42
- ...(error.suggestions.length > 0 ? { suggestions: error.suggestions } : {}),
43
- };
44
- }
45
- if (error instanceof ToolError) {
46
- return { kind: "ToolFailure", message: error.message };
47
- }
48
- if (error instanceof Throw) {
49
- const value = error.value;
50
- if (value instanceof ErrorObj) {
51
- return value.host ? normalizeError(value.host) : { kind: "ExecutionFailure", message: errorToString(value) };
52
- }
53
- let message;
54
- if (containsRuntimeReference(value)) {
55
- // Never expose runtime reference internals through thrown values.
56
- message = "a non-data value";
57
- }
58
- else if (typeof value === "string") {
59
- message = value;
60
- }
61
- else {
62
- message = formatValue(value);
63
- }
64
- return { kind: "ExecutionFailure", message: `Uncaught: ${message}` };
65
- }
66
- if (error instanceof RangeError && /call stack|recursion/i.test(errorMessage(error))) {
67
- return {
68
- kind: "ExecutionFailure",
69
- message: "Execution exceeded the maximum nesting depth.",
70
- };
71
- }
72
- if (error instanceof Error) {
73
- return {
74
- kind: error.name === "SyntaxError" ? "ParseError" : "ExecutionFailure",
75
- message: errorMessage(error),
76
- };
77
- }
78
- return {
79
- kind: "ExecutionFailure",
80
- message: String(error),
81
- };
82
- };
83
- /**
84
- * Gives a failure the source location of the expression that raised it, keeping the first one attached. Host errors
85
- * that escape a built-in become the equivalent program error here.
86
- */
87
- export const locate = (error, node) => {
88
- if (error instanceof PendingThrow) {
89
- if (error.node === undefined && node)
90
- error.node = node;
91
- return error;
92
- }
93
- if (error instanceof Error && !(error instanceof ToolError) && !(error instanceof ToolRuntimeError)) {
94
- return new PendingThrow(errorType(error), errorMessage(error), node);
95
- }
96
- return error;
97
- };
98
- /** The program value a handler receives for a failure; one failure always yields the same value. */
99
- export const materialize = (ctx, thrown) => {
100
- if (thrown instanceof Throw)
101
- return thrown.value;
102
- const builtins = ctx.builtins;
103
- if (thrown instanceof PendingThrow) {
104
- if (thrown.value === undefined) {
105
- thrown.value = createErrorValue(builtins[thrown.type], thrown.message);
106
- thrown.value.host = thrown;
107
- }
108
- return thrown.value;
109
- }
110
- return createErrorValue(builtins[thrown instanceof Error ? errorType(thrown) : "Error"], normalizeError(thrown).message);
111
- };
112
- /** Error.prototype.toString: `name: message`, omitting whichever side is empty. */
113
- const errorToString = (self) => {
114
- const name = get(self, "name");
115
- const message = get(self, "message");
116
- const shownName = name === undefined ? "Error" : coerceToString(name);
117
- const shownMessage = message === undefined ? "" : coerceToString(message);
118
- if (shownMessage === "")
119
- return shownName;
120
- if (shownName === "")
121
- return shownMessage;
122
- return `${shownName}: ${shownMessage}`;
123
- };
124
- export const createAggregateErrorValue = (ctx, errors, message, proto = ctx.builtins.AggregateError) => {
125
- const value = createErrorValue(proto, message);
126
- define(value, "errors", new Arr(ctx.builtins.Array, errors), { ...hidden });
127
- return value;
128
- };
129
- function* constructAggregateErrorValue(ctx, args, proto) {
130
- const message = args[1] === undefined ? "" : yield* toPrimitiveString(ctx, args[1]);
131
- const cursor = yield* ctx.iterate(args[0]);
132
- if (cursor === undefined)
133
- throw typeError("new AggregateError(...) expects a synchronous iterable of errors.");
134
- const errors = [];
135
- while (true) {
136
- const step = yield* cursor.next();
137
- if (step.done)
138
- return createAggregateErrorValue(ctx, errors, message, proto);
139
- errors.push(step.value);
140
- }
141
- }
142
- /** An error constructor such as `Error` or `TypeError`; callable with or without `new`, like JS. */
143
- export const errorGlobal = (type, ctx) => {
144
- const builtins = ctx.builtins;
145
- const prototype = builtins[type];
146
- const construct = function* (args, newTarget) {
147
- const proto = prototypeFrom(newTarget, prototype);
148
- const created = type === "AggregateError"
149
- ? yield* constructAggregateErrorValue(ctx, args, proto)
150
- : createErrorValue(proto, args[0] === undefined ? undefined : yield* toPrimitiveString(ctx, args[0]));
151
- // ES2022 `new Error(message, { cause })`: installed only when the options object has the property at all.
152
- const options = args[type === "AggregateError" ? 2 : 1];
153
- if (options instanceof Obj && has(options, "cause"))
154
- define(created, "cause", get(options, "cause"), hidden);
155
- return created;
156
- };
157
- const ctor = constructor(builtins, prototype, {
158
- name: type,
159
- length: type === "AggregateError" ? 2 : 1,
160
- call: (_, args) => construct(args, ctor),
161
- construct,
162
- });
163
- if (type === "Error") {
164
- methods(builtins, prototype, [
165
- ["toString", 0, (thisValue) => errorToString(receiver(Obj, thisValue, "Error.prototype.toString"))],
166
- ]);
167
- methods(builtins, ctor, [["isError", 1, (_, args) => args[0] instanceof ErrorObj]]);
168
- return ctor;
169
- }
170
- // Derived constructors extend Error itself, so its statics are inherited. The globals table creates Error first.
171
- ctor.proto = get(builtins.Error, "constructor");
172
- return ctor;
173
- };
@@ -1,14 +0,0 @@
1
- import { type Program } from "acorn";
2
- import { Effect } from "effect";
3
- import type { Diagnostic, ResolvedExecutionLimits, Result } from "../codemode.js";
4
- import { ToolRuntime } from "../tool-runtime.js";
5
- import { Interpreter } from "./interpreter.js";
6
- import type { Value } from "./objects.js";
7
- export declare const executeProgram: <R>(code: string, prepared: ToolRuntime.Prepared<R>, limits: ResolvedExecutionLimits, hooks: ToolRuntime.Hooks<R>, globals?: (ctx: Interpreter<R>) => ReadonlyArray<readonly [string, Value]>) => Effect.Effect<Result, never, R>;
8
- export declare const parseProgram: (code: string) => {
9
- ok: true;
10
- program: Program;
11
- } | {
12
- ok: false;
13
- error: Diagnostic;
14
- };