Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions packages/codemode/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,8 +223,9 @@ that returns a Promise or an Effect, so a denied call rejects its promise like a
Extension.make({ name: "web", globals: { fetch: Extension.async((url: string) => globalThis.fetch(url)) } })
```

A global may return a value, a Promise, or an Effect. An Effect's requirements join the runtime's environment the same
way a tool's do, so the host can provide per-execution services such as the calling session:
A global may return a value, a Promise, or an Effect. A synchronous global's Effect runs to completion before the call
returns, so the host can offer blocking calls such as `fs.readFileSync`. An Effect's requirements join the runtime's
environment the same way a tool's do, so the host can provide per-execution services such as the calling session:

```ts
const web = Extension.make({
Expand Down
3 changes: 3 additions & 0 deletions packages/codemode/interpreter-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -632,6 +632,9 @@ Nothing is exposed unless a host provides it; extension calls are not tool calls
`code`, `errno`, `syscall`, and `path` reach the program and `err.code === "ENOENT"` works. `stack` stays on its
own side, no field may shadow an Error method, and a field that cannot cross (a class instance, a function) is
left behind rather than replacing the error.
- [x] A synchronous global that returns an Effect blocks the program until the Effect completes and returns its
value or throws its error, as `fs.readFileSync` does. An `async` global (or one marked `Extension.async`) hands
the program a promise instead.
- [ ] Program functions as arguments to extension code (callbacks such as `forEach`).
- [ ] Host classes. Stateful host objects are expressed as closures; a declared method table would be the next
step if `new X()` in a program is ever needed.
Expand Down
8 changes: 5 additions & 3 deletions packages/codemode/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ import type { Effect } from "effect"
* function inside a result is callable the same way. Extension calls are not tool calls. A global may return a value,
* a Promise, or an Effect, and an Effect's requirements join the runtime's environment.
*
* A global is synchronous unless it is an `async` function or is marked with `async`. The `extension.before` hook
* A global is synchronous unless it is an `async` function or is marked with `async`. A synchronous global that
* returns an Effect blocks the program until the Effect completes and returns its value, as `fs.readFileSync` does;
* an asynchronous one hands the program a promise. The `extension.before` hook
* runs before the call, so a denied call never reaches the host; it fails the way the global would, by rejecting the
* promise of an asynchronous global and by throwing from a synchronous one. Functions inside a global object are
* called the same way, named by their path (`fs.readFile`).
Expand All @@ -34,13 +36,13 @@ export type Snapshot = {
readonly decode: (data: unknown) => unknown
}

/** The Effect environment required by an extension's Effect-returning functions, at the top level or one level in. */
/** The Effect environment required by an extension's Effect-returning functions, at any depth (`fs.promises.readFile`). */
export type Services<E> = E extends { readonly globals: infer Globals } ? GlobalServices<Globals[keyof Globals]> : never

type GlobalServices<Global> = Global extends (...args: never) => unknown
? Requirements<Global>
: Global extends object
? Requirements<Global[keyof Global]>
? GlobalServices<Global[keyof Global]>
: never

type Requirements<F> = F extends (...args: never) => infer Result ? Effect.Services<Result> : never
Expand Down
4 changes: 2 additions & 2 deletions packages/codemode/src/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,8 @@ const arrayOf = (vm: HostVm, values: Array<Value>) => new Arr(vm.ctx.builtins.Ar

/**
* A synchronous extension function's call, staged here so its host values never enter a frame: the `extension.before`
* hook (blocking), then the host function; what it returns settles now (blocking) unless it is an Effect or a Promise,
* which the program holds a promise for. The call is active, holding live host values, until its result is a program
* hook (blocking), then the host function; what it returns settles now (blocking, an Effect
* 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
* value or its concurrent call is queued.
*/
export const callExtension = (
Expand Down
5 changes: 3 additions & 2 deletions packages/codemode/src/runtime/extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -359,7 +359,8 @@ const pending = <R>(ctx: Interpreter<R>, call: ExtensionRequest, site: AstNode |

/**
* Calls a synchronous extension function's host function, once its `extension.before` hook allowed it: a promise for
* a result that settles later (an Effect or a Promise), or the request that settles what it returned or threw now.
* a returned Promise, or the request that settles what it returned or threw. A returned Effect settles through that
* request too, so the program blocks until it completes, as `fs.readFileSync` does.
*/
export const startExtensionCall = <R>(
ctx: Interpreter<R>,
Expand All @@ -370,7 +371,7 @@ export const startExtensionCall = <R>(
): PromiseObj | ExtensionRequest => {
const [result, threw] = callHost(host, args)
const request = { stage: "settle", ...call, host: result, args, threw } as const
if (!threw && (Effect.isEffect(result) || result instanceof Promise)) return pending(ctx, request, site)
if (!threw && result instanceof Promise) return pending(ctx, request, site)
return request
}

Expand Down
21 changes: 19 additions & 2 deletions packages/codemode/test/extensions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,13 +417,18 @@ describe("Effect globals", () => {
const web = Extension.make({
name: "web",
globals: {
fetch: (url: string) =>
fetch: Extension.async((url: string) =>
Effect.gen(function* () {
const session = yield* Session
sent.push(url)
return { url, session: session.id }
}),
fail: () => Effect.fail(new RangeError("denied")),
),
fail: Extension.async(() => Effect.fail(new RangeError("denied"))),
fs: {
readSync: (path: string) => Session.use((session) => Effect.succeed(`${session.id}:${path}`)),
failSync: () => Effect.fail(new RangeError("missing")),
},
},
})

Expand Down Expand Up @@ -458,6 +463,18 @@ describe("Effect globals", () => {
expect(result).toMatchObject({ ok: true, value: [true, "denied"] })
})

test("a synchronous Effect global returns its value, or throws, before the next statement", async () => {
const result = await Effect.runPromise(
CodeMode.make({ extensions: [web] })
.execute(
`const text = fs.readSync("a")
try { fs.failSync() } catch (e) { return [text, e instanceof RangeError, e.message] }`,
)
.pipe(Effect.provideService(Session, { id: "ses_1" })),
)
expect(result).toMatchObject({ ok: true, value: ["ses_1:a", true, "missing"] })
})

test("a denying before hook stops the Effect before it runs", async () => {
sent.length = 0
const runtime = CodeMode.make({
Expand Down
Loading