GeezerVison is showing github.com — feat(codemode): let extension globals return Effects (#59948) · anomalyco/opencode@a882cf9
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/codemode/README.md +19Lines changed: 19 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -104,6 +104,25 @@ const web = Extension.make({ name: "web", globals: { fetch: (url: string) => glo | 104 | 104 | const runtime = CodeMode.make({ tools, extensions: [web] }) | 105 | 105 | ``` | 106 | 106 |
| | 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: | | 110 | + | | 111 | +```ts | | 112 | +const web = Extension.make({ | | 113 | + name: "web", | | 114 | + globals: { | | 115 | + fetch: (url: string) => | | 116 | + Effect.gen(function* () { | | 117 | + const session = yield* Session | | 118 | + yield* session.authorize(url) | | 119 | + return yield* Effect.promise(() => globalThis.fetch(url)) | | 120 | + }), | | 121 | + }, | | 122 | +}) | | 123 | +const result = yield* CodeMode.make({ extensions: [web] }).execute(code).pipe(Effect.provideService(Session, session)) | | 124 | +``` | | 125 | + | 107 | 126 | Every value crossing in either direction is converted, never shared: arguments come in as copies, results go out as | 108 | 127 | copies, and a function inside a result is callable the same way. A global that shadows a built-in or another | 109 | 128 | extension throws at `CodeMode.make`. | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/codemode.ts +29-13Lines changed: 29 additions & 13 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -41,19 +41,27 @@ export type ResolvedExecutionLimits = { | 41 | 41 | } | 42 | 42 |
| 43 | 43 | /** Configuration shared by `CodeMode.make` and `CodeMode.execute`. */ | 44 | | -export type Options<Provided extends Record<string, unknown> = {}> = { | | 44 | +export type Options<Provided extends Record<string, unknown> = {}, Extensions extends ReadonlyArray<Extension> = []> = { | 45 | 45 | /** Explicit tools exposed to the program as `tools`. */ | 46 | 46 | tools?: Provided & Tools<Services<Provided>> | 47 | 47 | /** Hooks around every tool and extension call the program makes; see `Hooks`. */ | 48 | | - hooks?: ToolRuntime.Hooks<Services<Provided>> | | 48 | + hooks?: ToolRuntime.Hooks<Environment<Provided, Extensions>> | 49 | 49 | /** Host functions exposed as globals; see `Extension.make`. */ | 50 | | - extensions?: ReadonlyArray<Extension> | | 50 | + extensions?: Extensions | 51 | 51 | /** Resource limits enforced on each execution. */ | 52 | 52 | limits?: ExecutionLimits | 53 | 53 | } | 54 | 54 |
| | 55 | +/** The Effect environment an execution needs: what the tools and the extensions' Effect globals require. */ | | 56 | +export type Environment<Provided extends Record<string, unknown>, Extensions extends ReadonlyArray<Extension>> = | | 57 | + | Services<Provided> | | 58 | + | Extension.Services<Extensions[number]> | | 59 | + | 55 | 60 | /** Options for one CodeMode execution. */ | 56 | | -export type ExecuteOptions<Provided extends Record<string, unknown> = {}> = Options<Provided> & { | | 61 | +export type ExecuteOptions< | | 62 | + Provided extends Record<string, unknown> = {}, | | 63 | + Extensions extends ReadonlyArray<Extension> = [], | | 64 | +> = Options<Provided, Extensions> & { | 57 | 65 | /** Source for one program in the supported JavaScript subset. */ | 58 | 66 | code: string | 59 | 67 | } | @@ -137,15 +145,23 @@ const resolveExecutionLimits = (limits?: ExecutionLimits): ResolvedExecutionLimi | 137 | 145 | }) | 138 | 146 |
| 139 | 147 | /** Executes one Effect-native CodeMode program without constructing a reusable runtime. */ | 140 | | -export const execute = <const Provided extends Record<string, unknown>>( | 141 | | - options: ExecuteOptions<Provided>, | 142 | | -): Effect.Effect<Result, never, Services<Provided>> => make(options).execute(options.code) | 143 | | - | 144 | | -/** Creates an Effect-native runtime over explicit, schema-described tools. */ | 145 | | -export const make = <const Provided extends Record<string, unknown> = {}>( | 146 | | - options: Options<Provided> = {}, | 147 | | -): Runtime<Services<Provided>> => { | 148 | | - const prepared = ToolRuntime.prepare((options.tools ?? {}) as Tools<Services<Provided>>) | | 148 | +export const execute = < | | 149 | + const Provided extends Record<string, unknown>, | | 150 | + const Extensions extends ReadonlyArray<Extension> = [], | | 151 | +>( | | 152 | + options: ExecuteOptions<Provided, Extensions>, | | 153 | +): Effect.Effect<Result, never, Environment<Provided, Extensions>> => make(options).execute(options.code) | | 154 | + | | 155 | +/** Creates an Effect-native runtime over explicit, schema-described tools and extensions. */ | | 156 | +export const make = < | | 157 | + const Provided extends Record<string, unknown> = {}, | | 158 | + const Extensions extends ReadonlyArray<Extension> = [], | | 159 | +>( | | 160 | + options: Options<Provided, Extensions> = {}, | | 161 | +): Runtime<Environment<Provided, Extensions>> => { | | 162 | + const prepared = ToolRuntime.prepare<Environment<Provided, Extensions>>( | | 163 | + (options.tools ?? {}) as Tools<Services<Provided>>, | | 164 | + ) | 149 | 165 | const limits = resolveExecutionLimits(options.limits) | 150 | 166 | const extensions = options.extensions ?? [] | 151 | 167 | const bound = new Set(globalNames) | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/extension.ts +18-4Lines changed: 18 additions & 4 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | export * as Extension from "./extension.js" | 2 | 2 |
| | 3 | +import type { Effect } from "effect" | | 4 | + | 3 | 5 | /** | 4 | 6 | * Host functions a program calls directly as globals. Values crossing in either direction are converted, never | 5 | 7 | * 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. | | 8 | + * same way. Extension calls are not tool calls. A global may return a value, a Promise, or an Effect; an Effect runs | | 9 | + * only after the extension hooks admit the call, and its requirements join the runtime's environment. | 7 | 10 | */ | 8 | | -export type Extension = { | | 11 | +export type Extension<Globals extends Readonly<Record<string, Function>> = Readonly<Record<string, Function>>> = { | 9 | 12 | readonly name: string | 10 | | - readonly globals: Readonly<Record<string, Function>> | | 13 | + readonly globals: Globals | 11 | 14 | } | 12 | 15 |
| 13 | | -export const make = (options: Extension): Extension => { | | 16 | +/** The Effect environment required by an extension's Effect-returning globals. */ | | 17 | +export type Services<E> = E extends { readonly globals: infer Globals } | | 18 | + ? Globals[keyof Globals] extends infer Global | | 19 | + ? Global extends (...args: never) => infer Result | | 20 | + ? Effect.Services<Result> | | 21 | + : never | | 22 | + : never | | 23 | + : never | | 24 | + | | 25 | +export const make = <const Globals extends Readonly<Record<string, Function>>>( | | 26 | + options: Extension<Globals>, | | 27 | +): Extension<Globals> => { | 14 | 28 | for (const [name, value] of Object.entries(options.globals)) { | 15 | 29 | if (typeof value !== "function") { | 16 | 30 | throw new TypeError(`Extension "${options.name}" global "${name}" must be a function.`) | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/src/interpreter/extensions.ts +42-25Lines changed: 42 additions & 25 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -4,7 +4,7 @@ import { type ExtensionInvocation, hooked } from "../tool-runtime.js" | 4 | 4 | import type { Interpreter } from "./interpreter.js" | 5 | 5 | import { createErrorValue, isErrorType } from "./intrinsics.js" | 6 | 6 | import { MAX_VALUE_DEPTH } from "./limits.js" | 7 | | -import { PendingThrow, Throw, typeError } from "./model.js" | | 7 | +import { type AstNode, PendingThrow, Throw, typeError } from "./model.js" | 8 | 8 | import type { Host } from "./runner.js" | 9 | 9 | import { fn } from "./native.js" | 10 | 10 | import { | @@ -32,7 +32,7 @@ import { describeValue, isOpaque } from "./references.js" | 32 | 32 | /** | 33 | 33 | * The global bindings of one run's extensions. Everything crossing the boundary is converted: plain data and | 34 | 34 | * built-in wrappers are copied, a host function becomes a program function whose calls cross the same way, and a | 35 | | - * host Promise becomes a program promise. | | 35 | + * host Promise or Effect becomes a program promise. | 36 | 36 | */ | 37 | 37 | export const extensionGlobals = <R>( | 38 | 38 | ctx: Interpreter<R>, | @@ -140,40 +140,57 @@ export const extensionGlobals = <R>( | 140 | 140 | const wrap = (value: Function, label: string, describe?: (args: ReadonlyArray<unknown>) => ExtensionInvocation) => | 141 | 141 | fn(builtins, value.name, value.length, (_, values, site) => { | 142 | 142 | const args = values.map((item, index) => toHost(item, `Argument ${index + 1} to ${label}`)) | | 143 | + const call = callHost<R>(value, args) | 143 | 144 | const hooks = ctx.tools.hooks | 144 | | - const settle = (run: Effect.Effect<unknown, unknown, R>) => | 145 | | - (describe === undefined | 146 | | - ? run | 147 | | - : hooked(describe(args), hooks["extension.before"], hooks["extension.after"], run) | 148 | | - ).pipe( | 149 | | - Effect.mapError((reason) => new Throw(fromHost(reason, label))), | 150 | | - Effect.map((settled) => fromHost(settled, label)), | 151 | | - ) | 152 | | - let result: unknown | 153 | | - try { | 154 | | - result = value.apply(undefined, args) | 155 | | - } catch (reason) { | 156 | | - return blocking(ctx.runner.blocking(settle(Effect.fail(reason)))) | 157 | | - } | 158 | | - if (!(result instanceof Promise)) return blocking(ctx.runner.blocking(settle(Effect.succeed(result)))) | 159 | | - const runner = ctx.runner | 160 | | - const promise = runner.newPromise() | 161 | | - const resolving = runner.resolving(promise, site) | 162 | | - runner.host( | 163 | | - settle(Effect.tryPromise({ try: () => result, catch: (reason) => reason })), | 164 | | - (settled) => (settled.ok ? resolving.resolve(settled.value as Value) : resolving.reject(settled.error)), | 165 | | - site, | | 145 | + const work = ( | | 146 | + describe === undefined | | 147 | + ? call.effect | | 148 | + : hooked(describe(args), hooks["extension.before"], hooks["extension.after"], call.effect) | | 149 | + ).pipe( | | 150 | + Effect.mapBoth({ | | 151 | + onFailure: (reason) => new Throw(fromHost(reason, label)), | | 152 | + onSuccess: (result) => fromHost(result, label), | | 153 | + }), | 166 | 154 | ) | 167 | | - return promise | | 155 | + return call.async ? pending(work, site) : blocking(ctx.runner.blocking(work)) | 168 | 156 | }) | 169 | 157 |
| | 158 | + // An asynchronous host call: the program holds a promise that settles when the host's work does. | | 159 | + const pending = (work: Effect.Effect<Value, Throw, R>, site: AstNode | undefined) => { | | 160 | + const promise = ctx.runner.newPromise() | | 161 | + const resolving = ctx.runner.resolving(promise, site) | | 162 | + ctx.runner.host( | | 163 | + work, | | 164 | + (settled) => (settled.ok ? resolving.resolve(settled.value as Value) : resolving.reject(settled.error)), | | 165 | + site, | | 166 | + ) | | 167 | + return promise | | 168 | + } | | 169 | + | 170 | 170 | return extensions.flatMap((extension) => | 171 | 171 | Object.entries(extension.globals).map( | 172 | 172 | ([name, value]) => [name, wrap(value, name, (args) => ({ extension: extension.name, name, args }))] as const, | 173 | 173 | ), | 174 | 174 | ) | 175 | 175 | } | 176 | 176 |
| | 177 | +/** | | 178 | + * Calls a host function and describes what the program waits on. A returned Effect or Promise settles later; a | | 179 | + * returned value or a throw settles now. An Effect has not started yet, so it runs only once the hooks admit it. | | 180 | + */ | | 181 | +const callHost = <R>(value: Function, args: ReadonlyArray<unknown>) => { | | 182 | + try { | | 183 | + const result: unknown = value.apply(undefined, args) | | 184 | + // Extension.Services adds an Effect global's requirements to R. | | 185 | + if (Effect.isEffect(result)) return { async: true, effect: result as Effect.Effect<unknown, unknown, R> } | | 186 | + if (result instanceof Promise) | | 187 | + return { async: true, effect: Effect.tryPromise({ try: () => result, catch: (reason) => reason }) } | | 188 | + return { async: false, effect: Effect.succeed(result) } | | 189 | + } catch (reason) { | | 190 | + return { async: false, effect: Effect.fail(reason) } | | 191 | + } | | 192 | +} | | 193 | + | 177 | 194 | // A synchronous host call: its hooks run before any other job, as the call itself did. | 178 | 195 | function* blocking(host: Host) { | 179 | 196 | return (yield host) as Value | |
Collapse file Copy file name to clipboardExpand all lines: packages/codemode/test/extensions.test.ts +64-1Lines changed: 64 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
| 1 | 1 | import { describe, expect, test } from "bun:test" | 2 | | -import { Effect, Schema } from "effect" | | 2 | +import { Context, Effect, Schema } from "effect" | 3 | 3 | import { CodeMode, Extension, Tool } from "../src/index.js" | 4 | 4 |
| 5 | 5 | const held: Array<unknown> = [] | @@ -254,6 +254,69 @@ describe("values are converted at the boundary, never shared", () => { | 254 | 254 | }) | 255 | 255 | }) | 256 | 256 |
| | 257 | +describe("Effect globals", () => { | | 258 | + class Session extends Context.Service<Session, { readonly id: string }>()("test/Session") {} | | 259 | + const sent: Array<string> = [] | | 260 | + const web = Extension.make({ | | 261 | + name: "web", | | 262 | + globals: { | | 263 | + fetch: (url: string) => | | 264 | + Effect.gen(function* () { | | 265 | + const session = yield* Session | | 266 | + sent.push(url) | | 267 | + return { url, session: session.id } | | 268 | + }), | | 269 | + fail: () => Effect.fail(new RangeError("denied")), | | 270 | + }, | | 271 | + }) | | 272 | + | | 273 | + test("the runtime requires what the Effect globals require", () => { | | 274 | + const runtime = CodeMode.make({ extensions: [web] }) | | 275 | + const provided: CodeMode.Runtime<Session> = runtime | | 276 | + // @ts-expect-error Session must be provided | | 277 | + const missing: CodeMode.Runtime<never> = runtime | | 278 | + expect([provided, missing]).toEqual([runtime, runtime]) | | 279 | + // An explicit tools type argument must name the extensions too, so their requirements are never dropped. | | 280 | + // @ts-expect-error web is not in the default empty extensions list | | 281 | + expect(CodeMode.make<{}>({ extensions: [web] })).toBeDefined() | | 282 | + }) | | 283 | + | | 284 | + test("an Effect global is a promise that runs with the execution's services", async () => { | | 285 | + sent.length = 0 | | 286 | + const result = await Effect.runPromise( | | 287 | + CodeMode.make({ extensions: [web] }) | | 288 | + .execute(`const pending = fetch("https://a.test/"); return [pending instanceof Promise, await pending]`) | | 289 | + .pipe(Effect.provideService(Session, { id: "ses_1" })), | | 290 | + ) | | 291 | + expect(result).toMatchObject({ ok: true, value: [true, { url: "https://a.test/", session: "ses_1" }] }) | | 292 | + expect(sent).toEqual(["https://a.test/"]) | | 293 | + }) | | 294 | + | | 295 | + test("a failing Effect rejects with the host's error", async () => { | | 296 | + const result = await Effect.runPromise( | | 297 | + CodeMode.make({ extensions: [web] }) | | 298 | + .execute(`try { await fail() } catch (e) { return [e instanceof RangeError, e.message] }`) | | 299 | + .pipe(Effect.provideService(Session, { id: "ses_1" })), | | 300 | + ) | | 301 | + expect(result).toMatchObject({ ok: true, value: [true, "denied"] }) | | 302 | + }) | | 303 | + | | 304 | + test("a denying before hook stops the Effect before it runs", async () => { | | 305 | + sent.length = 0 | | 306 | + const runtime = CodeMode.make({ | | 307 | + extensions: [web], | | 308 | + hooks: { "extension.before": (call) => Effect.fail(new Error(`${call.name} is not allowed`)) }, | | 309 | + }) | | 310 | + const result = await Effect.runPromise( | | 311 | + runtime | | 312 | + .execute(`try { await fetch("https://a.test/") } catch (e) { return e.message }`) | | 313 | + .pipe(Effect.provideService(Session, { id: "ses_1" })), | | 314 | + ) | | 315 | + expect(result).toMatchObject({ ok: true, value: "fetch is not allowed" }) | | 316 | + expect(sent).toEqual([]) | | 317 | + }) | | 318 | +}) | | 319 | + | 257 | 320 | describe("host errors", () => { | 258 | 321 | test("a synchronous throw becomes the matching program error", async () => { | 259 | 322 | const target = CodeMode.make({ | |
Collapse file Copy file name to clipboardExpand all lines: packages/core/src/codemode/tool.ts +5-1Lines changed: 5 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -250,7 +250,11 @@ function runtime(inventory: Inventory) { | 250 | 250 | }) | 251 | 251 | } | 252 | 252 | const tools = renderTools(root) | 253 | | - const created = CodeMode.make<typeof tools>({ tools, extensions: [CodeModeWeb.extension], hooks: runHooks }) | | 253 | + const created = CodeMode.make<typeof tools, [typeof CodeModeWeb.extension]>({ | | 254 | + tools, | | 255 | + extensions: [CodeModeWeb.extension], | | 256 | + hooks: runHooks, | | 257 | + }) | 254 | 258 | runtimes.set(inventory, created) | 255 | 259 | return created | 256 | 260 | } | |
|