@opencode/codemode 0.0.0-dev-187 → 0.0.0-dev-192

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
@@ -91,8 +91,10 @@ runtime.execute(source) // Effect<CodeMode.Result, never, ToolServices>
91
91
  The Effect environment is inferred from the supplied tools. `hooks` surround every call the program makes into the
92
92
  host: `tool.before`/`tool.after` receive `{ name, input }` with decoded input, `extension.before`/`extension.after`
93
93
  receive `{ extension, name, args }`. An `after` hook also receives how the call ended (`success` with its value,
94
- `failure` with its error, or `interrupted`). A failing `before` hook denies the call, and the program catches the
95
- failure as a thrown error.
94
+ `failure` with its error, or `interrupted`). A `before` hook runs before the call reaches the host, and a failing one
95
+ denies it: the host function is never called, and the program catches the failure as a thrown error. A denied call
96
+ fails the way the call itself would: a tool call or asynchronous global rejects its promise, and a synchronous global
97
+ throws.
96
98
 
97
99
  ### `Extension.make`
98
100
 
@@ -100,24 +102,31 @@ Extensions are host functions a program calls directly as globals, such as `fetc
100
102
  catalog, not counted against `maxToolCalls`, and not described to the model; the host decides what they mean.
101
103
 
102
104
  ```ts
103
- const web = Extension.make({ name: "web", globals: { fetch: (url: string) => globalThis.fetch(url) } })
105
+ const web = Extension.make({ name: "web", globals: { fetch: async (url: string) => globalThis.fetch(url) } })
104
106
  const runtime = CodeMode.make({ tools, extensions: [web] })
105
107
  ```
106
108
 
107
- A global may return a value, a Promise, or an Effect. An Effect starts only after the `extension.before` hook admits
108
- the call, and its requirements join the runtime's environment the same way a tool's do, so the host can provide
109
- per-execution services such as the calling session:
109
+ A global is synchronous unless it is an `async` function or is marked with `Extension.async`. Mark a plain function
110
+ that returns a Promise or an Effect, so a denied call rejects its promise like any other failure:
111
+
112
+ ```ts
113
+ Extension.make({ name: "web", globals: { fetch: Extension.async((url: string) => globalThis.fetch(url)) } })
114
+ ```
115
+
116
+ A global may return a value, a Promise, or an Effect. An Effect's requirements join the runtime's environment the same
117
+ way a tool's do, so the host can provide per-execution services such as the calling session:
110
118
 
111
119
  ```ts
112
120
  const web = Extension.make({
113
121
  name: "web",
114
122
  globals: {
115
- fetch: (url: string) =>
123
+ fetch: Extension.async((url: string) =>
116
124
  Effect.gen(function* () {
117
125
  const session = yield* Session
118
126
  yield* session.authorize(url)
119
127
  return yield* Effect.promise(() => globalThis.fetch(url))
120
128
  }),
129
+ ),
121
130
  },
122
131
  })
123
132
  const result = yield* CodeMode.make({ extensions: [web] }).execute(code).pipe(Effect.provideService(Session, session))
@@ -3,8 +3,12 @@ import type { Effect } from "effect";
3
3
  /**
4
4
  * Host functions a program calls directly as globals. Values crossing in either direction are converted, never
5
5
  * shared: arguments come in as copies, results go out as copies, and a function inside a result is callable the
6
- * same way. Extension calls are not tool calls. A global may return a value, a Promise, or an Effect; an Effect runs
7
- * only after the extension hooks admit the call, and its requirements join the runtime's environment.
6
+ * same way. Extension calls are not tool calls. A global may return a value, a Promise, or an Effect, and an
7
+ * Effect's requirements join the runtime's environment.
8
+ *
9
+ * A global is synchronous unless it is an `async` function or is marked with `async`. The `extension.before` hook
10
+ * runs before the call, so a denied call never reaches the host; it fails the way the global would, by rejecting the
11
+ * promise of an asynchronous global and by throwing from a synchronous one.
8
12
  */
9
13
  export type Extension<Globals extends Readonly<Record<string, Function>> = Readonly<Record<string, Function>>> = {
10
14
  readonly name: string;
@@ -15,3 +19,6 @@ export type Services<E> = E extends {
15
19
  readonly globals: infer Globals;
16
20
  } ? Globals[keyof Globals] extends infer Global ? Global extends (...args: never) => infer Result ? Effect.Services<Result> : never : never : never;
17
21
  export declare const make: <const Globals extends Readonly<Record<string, Function>>>(options: Extension<Globals>) => Extension<Globals>;
22
+ /** Marks a global that returns a Promise or an Effect, so a denied call rejects its promise instead of throwing. */
23
+ export declare const async: <F extends Function>(global: F) => F;
24
+ export declare const isAsync: (global: Function) => boolean;
package/dist/extension.js CHANGED
@@ -7,3 +7,11 @@ export const make = (options) => {
7
7
  }
8
8
  return { name: options.name, globals: { ...options.globals } };
9
9
  };
10
+ const asyncGlobals = new WeakSet();
11
+ const AsyncFunction = (async () => { }).constructor;
12
+ /** Marks a global that returns a Promise or an Effect, so a denied call rejects its promise instead of throwing. */
13
+ export const async = (global) => {
14
+ asyncGlobals.add(global);
15
+ return global;
16
+ };
17
+ export const isAsync = (global) => global instanceof AsyncFunction || asyncGlobals.has(global);
@@ -1,4 +1,4 @@
1
- import type { Extension } from "../extension.js";
1
+ import { type Extension } from "../extension.js";
2
2
  import type { Interpreter } from "./interpreter.js";
3
3
  import { type Value } from "./objects.js";
4
4
  /**
@@ -1,4 +1,5 @@
1
1
  import { Effect } from "effect";
2
+ import { isAsync } from "../extension.js";
2
3
  import { hooked } from "../tool-runtime.js";
3
4
  import { createErrorValue, isErrorType } from "./intrinsics.js";
4
5
  import { MAX_VALUE_DEPTH } from "./limits.js";
@@ -122,20 +123,27 @@ export const extensionGlobals = (ctx, extensions) => {
122
123
  }
123
124
  throw typeError(`${label} produced ${describeHost(value)}, which the program cannot hold.`);
124
125
  };
125
- // A host function as a program function. Arguments cross in; a global's call runs inside the host's extension
126
- // hooks, which see the host's own error on failure; then whatever came back, or was thrown, crosses out so the
127
- // program catches a copy. Functions inside results are part of a value's API and skip the hooks.
128
- const wrap = (value, label, describe) => fn(builtins, value.name, value.length, (_, values, site) => {
126
+ // A host function as a program function. Arguments cross in; for a global, the `extension.before` hook runs before
127
+ // the host function is called, so a call it denies never reaches the host. The host's result, or what it threw,
128
+ // crosses out so the program catches a copy, and `extension.after` sees how the call ended. Functions inside
129
+ // results are part of a value's API and skip the hooks.
130
+ const wrap = (value, label, describe) => fn(builtins, value.name, value.length, function* (_, values, site) {
129
131
  const args = values.map((item, index) => toHost(item, `Argument ${index + 1} to ${label}`));
130
- const call = callHost(value, args);
132
+ const cross = (reason) => new Throw(fromHost(reason, label));
133
+ const call = describe?.(args);
131
134
  const hooks = ctx.tools.hooks;
132
- const work = (describe === undefined
133
- ? call.effect
134
- : hooked(describe(args), hooks["extension.before"], hooks["extension.after"], call.effect)).pipe(Effect.mapBoth({
135
- onFailure: (reason) => new Throw(fromHost(reason, label)),
136
- onSuccess: (result) => fromHost(result, label),
137
- }));
138
- return call.async ? pending(work, site) : blocking(ctx.runner.blocking(work));
135
+ const before = call && hooks["extension.before"]?.(call).pipe(Effect.mapError(cross));
136
+ const after = call && hooks["extension.after"];
137
+ const settle = (effect) => (after ? hooked(call, undefined, after, effect) : effect).pipe(Effect.mapBoth({ onFailure: cross, onSuccess: (result) => fromHost(result, label) }));
138
+ // A denied call fails the way the global would: an async global rejects its promise, a sync one throws.
139
+ if (isAsync(value))
140
+ return pending(Effect.andThen(before ?? Effect.void, settle(Effect.suspend(() => callHost(value, args).effect))), site);
141
+ if (before)
142
+ yield ctx.runner.blocking(before);
143
+ const host = callHost(value, args);
144
+ if (host.async)
145
+ return pending(settle(host.effect), site);
146
+ return (yield ctx.runner.blocking(settle(host.effect)));
139
147
  });
140
148
  // An asynchronous host call: the program holds a promise that settles when the host's work does.
141
149
  const pending = (work, site) => {
@@ -148,7 +156,7 @@ export const extensionGlobals = (ctx, extensions) => {
148
156
  };
149
157
  /**
150
158
  * Calls a host function and describes what the program waits on. A returned Effect or Promise settles later; a
151
- * returned value or a throw settles now. An Effect has not started yet, so it runs only once the hooks admit it.
159
+ * returned value or a throw settles now.
152
160
  */
153
161
  const callHost = (value, args) => {
154
162
  try {
@@ -164,10 +172,6 @@ const callHost = (value, args) => {
164
172
  return { async: false, effect: Effect.fail(reason) };
165
173
  }
166
174
  };
167
- // A synchronous host call: its hooks run before any other job, as the call itself did.
168
- function* blocking(host) {
169
- return (yield host);
170
- }
171
175
  /**
172
176
  * An error crosses as its name, message, `cause`, and own enumerable fields, such as Node's `code`, `errno`,
173
177
  * `syscall`, and `path`. `stack` stays on its own side, and no field may shadow an Error method. A field that cannot
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-187",
4
+ "version": "0.0.0-dev-192",
5
5
  "description": "Effect-native confined code execution over schema-described tools",
6
6
  "type": "module",
7
7
  "license": "MIT",