@opencode/codemode 0.0.0-dev-1302 → 0.0.0-dev-1303

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -223,8 +223,9 @@ that returns a Promise or an Effect, so a denied call rejects its promise like a
223
223
  Extension.make({ name: "web", globals: { fetch: Extension.async((url: string) => globalThis.fetch(url)) } })
224
224
  ```
225
225
 
226
- A global may return a value, a Promise, or an Effect. An Effect's requirements join the runtime's environment the same
227
- way a tool's do, so the host can provide per-execution services such as the calling session:
226
+ A global may return a value, a Promise, or an Effect. A synchronous global's Effect runs to completion before the call
227
+ returns, so the host can offer blocking calls such as `fs.readFileSync`. An Effect's requirements join the runtime's
228
+ environment the same way a tool's do, so the host can provide per-execution services such as the calling session:
228
229
 
229
230
  ```ts
230
231
  const web = Extension.make({
@@ -364,7 +365,8 @@ and `CodeMode.toolExpression(path)` supply the exact callable forms.
364
365
  The synchronous `search(...)` built-in is always available. It supports exact-path lookup, namespace-scoped search,
365
366
  empty-query browsing, and pagination, and returns callable paths with full signatures. Its result can be used directly,
366
367
  awaited, or chained with `then`, `catch`, and `finally`, so programs work whichever way they treat it. Search counts toward
367
- `maxToolCalls`. Search also matches descriptions from enclosing `Namespace` values.
368
+ `maxToolCalls`. Search also matches descriptions from enclosing `Namespace` values. A plain string is the query:
369
+ `search("issues")` is `search({ query: "issues" })`.
368
370
 
369
371
  ## Execution Limits
370
372
 
@@ -6,7 +6,9 @@ import type { Effect } from "effect";
6
6
  * function inside a result is callable the same way. Extension calls are not tool calls. A global may return a value,
7
7
  * a Promise, or an Effect, and an Effect's requirements join the runtime's environment.
8
8
  *
9
- * A global is synchronous unless it is an `async` function or is marked with `async`. The `extension.before` hook
9
+ * A global is synchronous unless it is an `async` function or is marked with `async`. A synchronous global that
10
+ * returns an Effect blocks the program until the Effect completes and returns its value, as `fs.readFileSync` does;
11
+ * an asynchronous one hands the program a promise. The `extension.before` hook
10
12
  * runs before the call, so a denied call never reaches the host; it fails the way the global would, by rejecting the
11
13
  * promise of an asynchronous global and by throwing from a synchronous one. Functions inside a global object are
12
14
  * called the same way, named by their path (`fs.readFile`).
@@ -30,11 +32,11 @@ export type Snapshot = {
30
32
  readonly encode: (value: unknown) => unknown;
31
33
  readonly decode: (data: unknown) => unknown;
32
34
  };
33
- /** The Effect environment required by an extension's Effect-returning functions, at the top level or one level in. */
35
+ /** The Effect environment required by an extension's Effect-returning functions, at any depth (`fs.promises.readFile`). */
34
36
  export type Services<E> = E extends {
35
37
  readonly globals: infer Globals;
36
38
  } ? GlobalServices<Globals[keyof Globals]> : never;
37
- type GlobalServices<Global> = Global extends (...args: never) => unknown ? Requirements<Global> : Global extends object ? Requirements<Global[keyof Global]> : never;
39
+ type GlobalServices<Global> = Global extends (...args: never) => unknown ? Requirements<Global> : Global extends object ? GlobalServices<Global[keyof Global]> : never;
38
40
  type Requirements<F> = F extends (...args: never) => infer Result ? Effect.Services<Result> : never;
39
41
  export declare const make: <const Globals extends Readonly<Record<string, unknown>>>(options: Extension<Globals>) => Extension<Globals>;
40
42
  /** A live fetch response whose I/O is owned by the host for the lifetime of the program. */
package/dist/host.d.ts CHANGED
@@ -96,8 +96,8 @@ export declare const callTool: (vm: HostVm, hosts: HostCalls, path: ReadonlyArra
96
96
  export declare const callSearch: (vm: HostVm, hosts: HostCalls, args: Array<Value>, site: AstNode | undefined) => HostResult;
97
97
  /**
98
98
  * A synchronous extension function's call, staged here so its host values never enter a frame: the `extension.before`
99
- * hook (blocking), then the host function; what it returns settles now (blocking) unless it is an Effect or a Promise,
100
- * which the program holds a promise for. The call is active, holding live host values, until its result is a program
99
+ * hook (blocking), then the host function; what it returns settles now (blocking, an Effect
100
+ * included) unless it is a Promise, which the program holds a promise for. The call is active, holding live host values, until its result is a program
101
101
  * value or its concurrent call is queued.
102
102
  */
103
103
  export declare const callExtension: (ctx: Interpreter<unknown>, hosts: HostCalls, slots: ReadonlyArray<unknown>, site: AstNode | undefined) => HostResult;
package/dist/host.js CHANGED
@@ -179,8 +179,8 @@ const arrayOf = (vm, values) => new Arr(vm.ctx.builtins.Array, [...values]);
179
179
  // --- Extension calls ---
180
180
  /**
181
181
  * A synchronous extension function's call, staged here so its host values never enter a frame: the `extension.before`
182
- * hook (blocking), then the host function; what it returns settles now (blocking) unless it is an Effect or a Promise,
183
- * which the program holds a promise for. The call is active, holding live host values, until its result is a program
182
+ * hook (blocking), then the host function; what it returns settles now (blocking, an Effect
183
+ * included) unless it is a Promise, which the program holds a promise for. The call is active, holding live host values, until its result is a program
184
184
  * value or its concurrent call is queued.
185
185
  */
186
186
  export const callExtension = (ctx, hosts, slots, site) => {
@@ -11,6 +11,7 @@ import type { ExtensionRequest } from "../scheduler.js";
11
11
  export declare const extensionGlobals: <R>(ctx: Interpreter<R>, extensions: ReadonlyArray<Extension>) => ReadonlyArray<readonly [string, Value]>;
12
12
  /**
13
13
  * Calls a synchronous extension function's host function, once its `extension.before` hook allowed it: a promise for
14
- * a result that settles later (an Effect or a Promise), or the request that settles what it returned or threw now.
14
+ * a returned Promise, or the request that settles what it returned or threw. A returned Effect settles through that
15
+ * request too, so the program blocks until it completes, as `fs.readFileSync` does.
15
16
  */
16
17
  export declare const startExtensionCall: <R>(ctx: Interpreter<R>, host: Function, args: ReadonlyArray<unknown>, call: Pick<ExtensionRequest, "label" | "extension" | "invocation">, site: AstNode | undefined) => PromiseObj | ExtensionRequest;
@@ -1,5 +1,6 @@
1
1
  import { Effect } from "effect";
2
2
  import { isAsync, StreamingResponse } from "../extension.js";
3
+ import { BufferObj } from "../stdlib/buffer.js";
3
4
  import { hooked } from "../tool-runtime.js";
4
5
  import { errorMessage, errorType } from "./errors.js";
5
6
  import { createErrorValue } from "./intrinsics.js";
@@ -111,6 +112,8 @@ export const extensionGlobals = (ctx, extensions) => {
111
112
  }
112
113
  if (value instanceof RegExp)
113
114
  return new RegExpObj(builtins.RegExp, value.source, value.flags);
115
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(value))
116
+ return new BufferObj(builtins.Buffer, new Uint8Array(value));
114
117
  if (value instanceof Uint8Array)
115
118
  return new Bytes(builtins.Uint8Array, new Uint8Array(value));
116
119
  if (value instanceof ArrayBuffer) {
@@ -287,12 +290,13 @@ const pending = (ctx, call, site) => {
287
290
  };
288
291
  /**
289
292
  * Calls a synchronous extension function's host function, once its `extension.before` hook allowed it: a promise for
290
- * a result that settles later (an Effect or a Promise), or the request that settles what it returned or threw now.
293
+ * a returned Promise, or the request that settles what it returned or threw. A returned Effect settles through that
294
+ * request too, so the program blocks until it completes, as `fs.readFileSync` does.
291
295
  */
292
296
  export const startExtensionCall = (ctx, host, args, call, site) => {
293
297
  const [result, threw] = callHost(host, args);
294
298
  const request = { stage: "settle", ...call, host: result, args, threw };
295
- if (!threw && (Effect.isEffect(result) || result instanceof Promise))
299
+ if (!threw && result instanceof Promise)
296
300
  return pending(ctx, request, site);
297
301
  return request;
298
302
  };
@@ -1,6 +1,7 @@
1
1
  import { Arr, BoundFn, Callable, coerceToInteger, get, Obj } from "./objects.js";
2
2
  import { arrayGlobal } from "../stdlib/array.js";
3
3
  import { textDecoderGlobal, textEncoderGlobal, uint8ArrayGlobal } from "../stdlib/bytes.js";
4
+ import { bufferGlobal } from "../stdlib/buffer.js";
4
5
  import { mapGlobal, setGlobal, weakMapGlobal, weakSetGlobal } from "../stdlib/collections.js";
5
6
  import { consoleGlobal } from "../stdlib/console.js";
6
7
  import { dateGlobal } from "../stdlib/date.js";
@@ -116,6 +117,8 @@ const table = {
116
117
  URLSearchParams: (ctx) => urlSearchParamsGlobal(ctx),
117
118
  Headers: (ctx) => headersGlobal(ctx),
118
119
  Uint8Array: (ctx) => uint8ArrayGlobal(ctx),
120
+ // Built on the host's Buffer, so only where there is one (Node and Bun, not browsers).
121
+ ...(typeof Buffer === "undefined" ? {} : { Buffer: (ctx) => bufferGlobal(ctx) }),
119
122
  TextEncoder: (ctx) => textEncoderGlobal(ctx),
120
123
  TextDecoder: (ctx) => textDecoderGlobal(ctx),
121
124
  encodeURI: (ctx) => uriGlobal(ctx, "encodeURI"),
@@ -2,7 +2,7 @@ import { ErrorObj, Obj, type Value } from "./objects.js";
2
2
  export declare const errorTypes: readonly ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError", "AggregateError"];
3
3
  export type ErrorType = (typeof errorTypes)[number];
4
4
  export declare const isErrorType: (name: string) => name is ErrorType;
5
- declare const builtins: readonly ["Object", "Function", "Array", "String", "Number", "Boolean", "Date", "RegExp", "Map", "Set", "WeakMap", "WeakSet", "URL", "URLSearchParams", "Headers", "Uint8Array", "TextEncoder", "TextDecoder", "Promise", "PromiseLike", "Iterator", "IteratorHelper", "AsyncIterator", "Generator", "AsyncGenerator", "AsyncFromSyncIterator"];
5
+ declare const builtins: readonly ["Object", "Function", "Array", "String", "Number", "Boolean", "Date", "RegExp", "Map", "Set", "WeakMap", "WeakSet", "URL", "URLSearchParams", "Headers", "Uint8Array", "Buffer", "TextEncoder", "TextDecoder", "Promise", "PromiseLike", "Iterator", "IteratorHelper", "AsyncIterator", "Generator", "AsyncGenerator", "AsyncFromSyncIterator"];
6
6
  /**
7
7
  * The built-in prototype objects of one runtime, allocated empty in dependency order. The globals populate them
8
8
  * and attach their constructors when the runtime is built.
@@ -27,6 +27,7 @@ const builtins = [
27
27
  "URLSearchParams",
28
28
  "Headers",
29
29
  "Uint8Array",
30
+ "Buffer",
30
31
  "TextEncoder",
31
32
  "TextDecoder",
32
33
  "Promise",
@@ -70,6 +71,7 @@ export const createBuiltins = () => {
70
71
  };
71
72
  const iterator = plain();
72
73
  const asyncIterator = plain();
74
+ const uint8Array = plain();
73
75
  return {
74
76
  Object: object,
75
77
  Function: fn,
@@ -86,7 +88,9 @@ export const createBuiltins = () => {
86
88
  URL: plain(),
87
89
  URLSearchParams: plain(),
88
90
  Headers: plain(),
89
- Uint8Array: plain(),
91
+ Uint8Array: uint8Array,
92
+ /** Node's Buffer: a Uint8Array whose text conversions default to UTF-8. */
93
+ Buffer: new Obj(uint8Array),
90
94
  TextEncoder: plain(),
91
95
  TextDecoder: plain(),
92
96
  Promise: plain(),
package/dist/scan.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Result } from "effect";
2
2
  import { parseProgram } from "./runtime/execute.js";
3
3
  import { formatLocation } from "./runtime/model.js";
4
+ import { moduleName } from "./runtime/modules.js";
4
5
  /**
5
6
  * Extracts every `tools.<path>` referenced by a Code Mode program, in first-seen order. Fails on syntax errors,
6
7
  * dynamic bracket access (`tools[name]`), or aliasing/passing `tools` rather than calling `tools.<path>(...)` directly.
@@ -37,6 +38,11 @@ export function scanTools(code) {
37
38
  found.add(chain.path);
38
39
  return undefined;
39
40
  }
41
+ // `import`/`require` of "tools" would reach tools the scan never sees.
42
+ const loaded = loadedModule(node);
43
+ if (loaded !== undefined && (loaded === null || moduleName(loaded) === "tools")) {
44
+ return fail(node, "Automation code must call tools directly as tools.<name>(...), not import or require them.");
45
+ }
40
46
  const pushedScope = enterNodeScope(node);
41
47
  if (pushedScope)
42
48
  scopes.push(pushedScope);
@@ -52,6 +58,17 @@ export function scanTools(code) {
52
58
  return Result.fail(diagnostic);
53
59
  return Result.succeed(Array.from(found));
54
60
  }
61
+ /** The module an `import` or `require(...)` loads, `null` when it is computed, or `undefined` for other nodes. */
62
+ function loadedModule(node) {
63
+ const specifier = node.type === "ImportDeclaration" || node.type === "ImportExpression"
64
+ ? node.source
65
+ : node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "require"
66
+ ? node.arguments[0]
67
+ : undefined;
68
+ if (specifier === undefined)
69
+ return undefined;
70
+ return specifier.type === "Literal" && typeof specifier.value === "string" ? specifier.value : null;
71
+ }
55
72
  function isReferencePosition(node, parent) {
56
73
  if (!parent)
57
74
  return true;
@@ -101,7 +118,7 @@ function readStaticToolCall(root, ancestors) {
101
118
  return {
102
119
  ok: false,
103
120
  node: parent.property,
104
- reason: "Schedule checks must reference tools statically (e.g. tools.slack.read_thread), not with dynamic bracket expressions.",
121
+ reason: "Automation code must reference tools statically (e.g. tools.slack.read_thread), not with dynamic bracket expressions.",
105
122
  };
106
123
  }
107
124
  const callParent = index >= 0 ? ancestors[index] : undefined;
@@ -109,7 +126,7 @@ function readStaticToolCall(root, ancestors) {
109
126
  return {
110
127
  ok: false,
111
128
  node: current,
112
- reason: "Schedule checks must call tools directly as tools.<name>(...), not alias or pass the tools object.",
129
+ reason: "Automation code must call tools directly as tools.<name>(...), not alias or pass the tools object.",
113
130
  };
114
131
  }
115
132
  return { ok: true, path: segments.join(".") };
@@ -5,6 +5,7 @@ import { Convert, Interruption, Invoke } from "../runtime/signals.js";
5
5
  import { deleted, OrderedTable } from "../runtime/table.js";
6
6
  import { AsyncFromSyncIterator } from "../generators.js";
7
7
  import { HostCall, Resolving } from "../scheduler.js";
8
+ import { BufferObj } from "../stdlib/buffer.js";
8
9
  import { TextDecoderObj } from "../stdlib/bytes.js";
9
10
  import { ToolError, toolError } from "../tool-error.js";
10
11
  import { ToolReference, ToolRuntimeError } from "../tool-runtime.js";
@@ -85,6 +86,7 @@ const builtinSpecs = () => [
85
86
  { name: "HeadersObj", ctor: HeadersObj, fields: ["headers"], obj: true, constants: { tag: "Headers" } },
86
87
  { name: "URLObj", ctor: URLObj, fields: ["searchParams", "url"], obj: true, constants: { tag: "URL" } },
87
88
  { name: "Bytes", ctor: Bytes, fields: ["bytes"], obj: true, constants: { tag: "Uint8Array" } },
89
+ { name: "BufferObj", ctor: BufferObj, fields: ["bytes"], obj: true, constants: { tag: "Uint8Array" } },
88
90
  {
89
91
  name: "TextDecoderObj",
90
92
  ctor: TextDecoderObj,
@@ -0,0 +1,9 @@
1
+ import type { Interpreter } from "../runtime/interpreter.js";
2
+ import { Bytes } from "../runtime/objects.js";
3
+ /** A Node Buffer: a Uint8Array whose text conversions default to UTF-8. */
4
+ export declare class BufferObj extends Bytes {
5
+ toString(): string;
6
+ toHost(): Buffer<ArrayBuffer>;
7
+ inspect(): string;
8
+ }
9
+ export declare const bufferGlobal: <R>(ctx: Interpreter<R>) => import("../runtime/objects.js").Native;
@@ -0,0 +1,285 @@
1
+ import { createErrorValue } from "../runtime/intrinsics.js";
2
+ import { Throw, typeError } from "../runtime/model.js";
3
+ import { constructor, methods, prototypeFrom, receiver } from "../runtime/native.js";
4
+ import { Arr, Bytes, define, get, hidden, Obj, coerceToNumber, coerceToString, record, } from "../runtime/objects.js";
5
+ import { describeValue } from "../runtime/references.js";
6
+ /** A Node Buffer: a Uint8Array whose text conversions default to UTF-8. */
7
+ export class BufferObj extends Bytes {
8
+ toString() {
9
+ return host(this.bytes).toString("utf8");
10
+ }
11
+ toHost() {
12
+ return Buffer.from(this.bytes);
13
+ }
14
+ inspect() {
15
+ const shown = Array.from(this.bytes.subarray(0, 50), (byte) => byte.toString(16).padStart(2, "0")).join(" ");
16
+ const more = this.bytes.length > 50 ? ` ... ${this.bytes.length - 50} more bytes` : "";
17
+ return `<Buffer${shown === "" ? "" : ` ${shown}`}${more}>`;
18
+ }
19
+ }
20
+ // The host Buffer over the same memory, so reads and writes through it are the program's bytes.
21
+ const host = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
22
+ const encodings = new Set([
23
+ "utf8",
24
+ "utf-8",
25
+ "hex",
26
+ "base64",
27
+ "base64url",
28
+ "latin1",
29
+ "binary",
30
+ "ascii",
31
+ "ucs2",
32
+ "ucs-2",
33
+ "utf16le",
34
+ "utf-16le",
35
+ ]);
36
+ const isEncoding = (value) => typeof value === "string" && encodings.has(value.toLowerCase());
37
+ // Read and write methods that take only numbers, delegated to the host Buffer as is.
38
+ const numeric = [
39
+ "readUInt8",
40
+ "readUint8",
41
+ "readInt8",
42
+ "readUInt16LE",
43
+ "readUint16LE",
44
+ "readUInt16BE",
45
+ "readUint16BE",
46
+ "readInt16LE",
47
+ "readInt16BE",
48
+ "readUInt32LE",
49
+ "readUint32LE",
50
+ "readUInt32BE",
51
+ "readUint32BE",
52
+ "readInt32LE",
53
+ "readInt32BE",
54
+ "readFloatLE",
55
+ "readFloatBE",
56
+ "readDoubleLE",
57
+ "readDoubleBE",
58
+ "readUIntLE",
59
+ "readUIntBE",
60
+ "readIntLE",
61
+ "readIntBE",
62
+ "writeUInt8",
63
+ "writeUint8",
64
+ "writeInt8",
65
+ "writeUInt16LE",
66
+ "writeUint16LE",
67
+ "writeUInt16BE",
68
+ "writeUint16BE",
69
+ "writeInt16LE",
70
+ "writeInt16BE",
71
+ "writeUInt32LE",
72
+ "writeUint32LE",
73
+ "writeUInt32BE",
74
+ "writeUint32BE",
75
+ "writeInt32LE",
76
+ "writeInt32BE",
77
+ "writeFloatLE",
78
+ "writeFloatBE",
79
+ "writeDoubleLE",
80
+ "writeDoubleBE",
81
+ "writeUIntLE",
82
+ "writeUIntBE",
83
+ "writeIntLE",
84
+ "writeIntBE",
85
+ "swap16",
86
+ "swap32",
87
+ "swap64",
88
+ ];
89
+ export const bufferGlobal = (ctx) => {
90
+ const builtins = ctx.builtins;
91
+ const proto = builtins.Buffer;
92
+ const wrap = (bytes) => new BufferObj(proto, bytes);
93
+ const self = (thisValue, name) => receiver(Bytes, thisValue, `Buffer.prototype.${name}`);
94
+ const fail = (type, message, code) => {
95
+ const value = createErrorValue(builtins[type], message);
96
+ if (code !== undefined)
97
+ define(value, "code", code);
98
+ return new Throw(value);
99
+ };
100
+ // Host Buffer errors carry Node's `code`; they cross as the program error of the same type.
101
+ const attempt = (run) => {
102
+ try {
103
+ return run();
104
+ }
105
+ catch (error) {
106
+ if (!(error instanceof Error))
107
+ throw error;
108
+ const code = error.code;
109
+ throw fail(error.name === "RangeError" || error.name === "TypeError" ? error.name : "Error", error.message, typeof code === "string" ? code : undefined);
110
+ }
111
+ };
112
+ const encoding = (value) => {
113
+ if (value === undefined)
114
+ return undefined;
115
+ if (isEncoding(value))
116
+ return coerceToString(value).toLowerCase();
117
+ throw fail("TypeError", `Unknown encoding: ${coerceToString(value)}`, "ERR_UNKNOWN_ENCODING");
118
+ };
119
+ const argument = (value) => {
120
+ if (value instanceof Bytes)
121
+ return host(value.bytes);
122
+ if (value === null || value === undefined || typeof value !== "object")
123
+ return value;
124
+ return coerceToNumber(value);
125
+ };
126
+ const bytesFrom = (value, second, third) => {
127
+ if (typeof value === "string")
128
+ return new Uint8Array(Buffer.from(value, encoding(second) ?? "utf8"));
129
+ if (value instanceof Bytes) {
130
+ const offset = second === undefined ? 0 : coerceToNumber(second);
131
+ const length = third === undefined ? undefined : coerceToNumber(third);
132
+ return value.bytes.slice(offset, length === undefined ? undefined : offset + length);
133
+ }
134
+ if (value instanceof Arr)
135
+ return Uint8Array.from(value.items, coerceToNumber);
136
+ if (value instanceof Obj) {
137
+ const data = get(value, "data");
138
+ if (get(value, "type") === "Buffer" && data instanceof Arr)
139
+ return Uint8Array.from(data.items, coerceToNumber);
140
+ const length = get(value, "length");
141
+ if (typeof length === "number")
142
+ return Uint8Array.from({ length }, (_, index) => coerceToNumber(get(value, String(index))));
143
+ }
144
+ throw fail("TypeError", `The first argument must be of type string or an instance of Buffer, Uint8Array, or Array or an Array-like Object. Received ${describeValue(value)}`, "ERR_INVALID_ARG_TYPE");
145
+ };
146
+ const size = (value) => {
147
+ const length = coerceToNumber(value);
148
+ if (!Number.isInteger(length) || length < 0) {
149
+ throw fail("RangeError", `The argument 'size' is invalid. Received ${coerceToString(value)}`, "ERR_OUT_OF_RANGE");
150
+ }
151
+ return length;
152
+ };
153
+ const buffer = constructor(builtins, proto, {
154
+ name: "Buffer",
155
+ length: 2,
156
+ call: (_, args) => wrap(bytesFrom(args[0], args[1], args[2])),
157
+ construct: (args, newTarget) => new BufferObj(prototypeFrom(newTarget, proto), bytesFrom(args[0], args[1], args[2])),
158
+ });
159
+ methods(builtins, buffer, [
160
+ ["from", 3, (_, args) => wrap(bytesFrom(args[0], args[1], args[2]))],
161
+ [
162
+ "alloc",
163
+ 3,
164
+ (_, args) => {
165
+ const bytes = new Uint8Array(size(args[0]));
166
+ const fill = args[1] === undefined ? undefined : argument(args[1]);
167
+ // Node reads an encoding only after a string fill; after a number it would be an offset.
168
+ if (typeof fill === "string")
169
+ attempt(() => host(bytes).fill(fill, encoding(args[2]) ?? "utf8"));
170
+ else if (fill !== undefined)
171
+ attempt(() => host(bytes).fill(fill));
172
+ return wrap(bytes);
173
+ },
174
+ ],
175
+ ["allocUnsafe", 1, (_, args) => wrap(new Uint8Array(size(args[0])))],
176
+ ["allocUnsafeSlow", 1, (_, args) => wrap(new Uint8Array(size(args[0])))],
177
+ [
178
+ "byteLength",
179
+ 2,
180
+ (_, args) => args[0] instanceof Bytes
181
+ ? args[0].bytes.byteLength
182
+ : Buffer.byteLength(coerceToString(args[0]), encoding(args[1])),
183
+ ],
184
+ [
185
+ "concat",
186
+ 2,
187
+ (_, args) => {
188
+ const list = args[0];
189
+ if (!(list instanceof Arr))
190
+ throw typeError(`Buffer.concat expects an array of Buffers, received ${describeValue(list)}.`);
191
+ const parts = list.items.map((item) => {
192
+ if (item instanceof Bytes)
193
+ return item.bytes;
194
+ throw typeError(`Buffer.concat expects an array of Buffers, received ${describeValue(item)} in it.`);
195
+ });
196
+ const total = args[1] === undefined ? parts.reduce((sum, part) => sum + part.length, 0) : size(args[1]);
197
+ const joined = new Uint8Array(total);
198
+ parts.reduce((offset, part) => {
199
+ if (offset < total)
200
+ joined.set(part.subarray(0, total - offset), offset);
201
+ return offset + part.length;
202
+ }, 0);
203
+ return wrap(joined);
204
+ },
205
+ ],
206
+ ["isBuffer", 1, (_, args) => args[0] instanceof BufferObj],
207
+ ["isEncoding", 1, (_, args) => isEncoding(args[0])],
208
+ [
209
+ "compare",
210
+ 2,
211
+ (_, args) => {
212
+ if (!(args[0] instanceof Bytes) || !(args[1] instanceof Bytes))
213
+ throw typeError("Buffer.compare expects two Buffers or Uint8Arrays.");
214
+ return Buffer.compare(args[0].bytes, args[1].bytes);
215
+ },
216
+ ],
217
+ ]);
218
+ define(buffer, "poolSize", 8192, hidden);
219
+ const view = (thisValue, name, args) => {
220
+ const bytes = self(thisValue, name).bytes;
221
+ const length = bytes.length;
222
+ const clamp = (value, fallback) => {
223
+ if (value === undefined)
224
+ return fallback;
225
+ const index = Math.trunc(coerceToNumber(value)) || 0;
226
+ return index < 0 ? Math.max(0, length + index) : Math.min(index, length);
227
+ };
228
+ return wrap(bytes.subarray(clamp(args[0], 0), clamp(args[1], length)));
229
+ };
230
+ const delegate = (name, length) => [
231
+ name,
232
+ length,
233
+ (thisValue, args) => {
234
+ const target = host(self(thisValue, name).bytes);
235
+ const method = target[name];
236
+ const result = attempt(() => method.apply(target, args.map(argument)));
237
+ if (result === target)
238
+ return thisValue;
239
+ if (typeof result === "number" || typeof result === "boolean" || typeof result === "string")
240
+ return result;
241
+ return undefined;
242
+ },
243
+ ];
244
+ methods(builtins, proto, [
245
+ [
246
+ "toString",
247
+ 3,
248
+ (thisValue, args) => {
249
+ const bytes = self(thisValue, "toString").bytes;
250
+ const start = args[1] === undefined ? 0 : Math.max(0, coerceToNumber(args[1]));
251
+ const end = args[2] === undefined ? bytes.length : Math.min(bytes.length, coerceToNumber(args[2]));
252
+ return host(bytes).toString(encoding(args[0]) ?? "utf8", start, end);
253
+ },
254
+ ],
255
+ [
256
+ "toJSON",
257
+ 0,
258
+ (thisValue) => record(builtins.Object, {
259
+ type: "Buffer",
260
+ data: new Arr(builtins.Array, [...self(thisValue, "toJSON").bytes]),
261
+ }),
262
+ ],
263
+ ["slice", 2, (thisValue, args) => view(thisValue, "slice", args)],
264
+ ["subarray", 2, (thisValue, args) => view(thisValue, "subarray", args)],
265
+ [
266
+ "equals",
267
+ 1,
268
+ (thisValue, args) => {
269
+ const other = args[0];
270
+ if (!(other instanceof Bytes))
271
+ throw typeError(`The "otherBuffer" argument must be an instance of Buffer or Uint8Array. Received ${describeValue(other)}`);
272
+ return Buffer.compare(self(thisValue, "equals").bytes, other.bytes) === 0;
273
+ },
274
+ ],
275
+ delegate("compare", 5),
276
+ delegate("indexOf", 3),
277
+ delegate("lastIndexOf", 3),
278
+ delegate("includes", 3),
279
+ delegate("write", 4),
280
+ delegate("fill", 4),
281
+ delegate("copy", 4),
282
+ ...numeric.map((name) => delegate(name, 2)),
283
+ ]);
284
+ return buffer;
285
+ };
@@ -339,7 +339,7 @@ const makeSearchTool = (searchIndex) => ({
339
339
  /** Exact callable signature of the built-in `search` function, for host-owned instructions. */
340
340
  export const searchSignature = (() => {
341
341
  const tool = makeSearchTool([]);
342
- return `search(${inputTypeScript(tool, true)}): ${outputTypeScript(tool, true)}`;
342
+ return `search(query: string | ${inputTypeScript(tool, true)}): ${outputTypeScript(tool, true)}`;
343
343
  })();
344
344
  const toSearchEntry = (visible, position) => {
345
345
  const segments = visible.path.split(".");
@@ -443,7 +443,11 @@ export const make = (prepared, maxToolCalls, hooks = {}) => {
443
443
  const field = typeof input === "string" ? stringParameter(tool)?.name : undefined;
444
444
  return yield* Effect.try({
445
445
  try: () => decodeToolInput(tool, field === undefined ? input : { [field]: input }),
446
- catch: (cause) => new ToolRuntimeError("InvalidToolInput", `Invalid input for tool '${name}': ${String(cause)}`, name === "search" ? [] : ["The signature may have changed. Use search to get the current signature."]),
446
+ catch: (cause) => new ToolRuntimeError("InvalidToolInput", `Invalid input for tool '${name}': ${String(cause)}`, name === "search"
447
+ ? [
448
+ 'Pass search a query string or an object, such as search("issues") or search({ namespace: "github" }).',
449
+ ]
450
+ : ["The signature may have changed. Use search to get the current signature."]),
447
451
  });
448
452
  });
449
453
  // A tool's own failure becomes a ToolError; interruption passes through.
@@ -475,6 +479,8 @@ export const make = (prepared, maxToolCalls, hooks = {}) => {
475
479
  return yield* output(name, tool, raw);
476
480
  }), options.detaching);
477
481
  });
482
+ // `search("notes")` is shorthand for `search({ query: "notes" })`.
483
+ const search = (args, options) => executeTool("search", makeSearchTool(prepared.searchIndex), typeof args[0] === "string" ? [{ query: args[0] }, ...args.slice(1)] : args, options);
478
484
  const durableTool = (path) => {
479
485
  const segments = canonicalSegments(path);
480
486
  const name = segments.join(".");
@@ -490,12 +496,12 @@ export const make = (prepared, maxToolCalls, hooks = {}) => {
490
496
  invocations,
491
497
  record: (name) => recordCall({ name }),
492
498
  keys: (path) => namespaceKeys(root, path),
493
- search: (args, options) => Effect.suspend(() => executeTool("search", makeSearchTool(prepared.searchIndex), args, options)),
499
+ search: (args, options) => Effect.suspend(() => search(args, options)),
494
500
  execute: (path, args, options) => Effect.suspend(() => {
495
501
  const segments = canonicalSegments(path);
496
502
  // Models often write `tools.search(...)` for the bare `search(...)`; honor it unless a tool owns that path.
497
503
  if (segments.length === 1 && segments[0] === "search" && lookup(root, segments) === undefined)
498
- return executeTool("search", makeSearchTool(prepared.searchIndex), args, options);
504
+ return search(args, options);
499
505
  return executeTool(segments.join("."), resolve(root, path, prepared.searchIndex), args, options);
500
506
  }),
501
507
  mode: (path) => {
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-1302",
4
+ "version": "0.0.0-dev-1303",
5
5
  "description": "Effect-native confined code execution over schema-described tools",
6
6
  "type": "module",
7
7
  "license": "MIT",