The best way to control Claude Code, Codex and more from any computer or phone

main
ts 48 lines 2.1 KB
Raw
1 import * as CoreBinding from "alchemy/Binding";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import type { Binding } from "./Binding.ts";
6 import { isWorker, WorkerEnvironment } from "./Worker.ts";
7
8 /**
9 * Native runtime layer for a Worker-only {@link Binding}. Registers the native
10 * binding on the host Worker at deploy time (via `binding.toWorkerBinding()`)
11 * and builds the Effect-native client from the lazy `env[name]` accessor.
12 *
13 * Factored out of `Binding.ts` (which must stay free of `Worker.ts` to avoid an
14 * import cycle through the contract files). Each binding's layer is a one-liner:
15 * `export const XBinding = makeBindingLayer(X, makeXClient)`.
16 */
17 export const makeBindingLayer = <Self, Runtime, Client>(
18 tag: Self,
19 makeClient: (
20 raw: Effect.Effect<Runtime, never, RuntimeContext>,
21 binding: Binding<string, Client, Self>,
22 ) => Client,
23 ): Layer.Layer<Self, never, WorkerEnvironment> =>
24 Layer.effect(
25 tag as never,
26 Effect.gen(function* () {
27 const env = yield* WorkerEnvironment;
28 return Effect.fn(function* (binding: Binding<string, Client>) {
29 // Deploy-time only: register the native binding on the host Worker.
30 if (!globalThis.__ALCHEMY_RUNTIME__) {
31 const host = yield* CoreBinding.Host;
32 if (isWorker(host)) {
33 yield* host.bind(binding.name, {
34 bindings: [binding.toWorkerBinding()],
35 // Dev-only local-emulation opt-out, contributed as a parallel
36 // channel (like `hyperdrives`) so the wire binding stays pure.
37 ...(binding.devRemote ? { devRemote: { [binding.name]: true } } : {}),
38 });
39 }
40 }
41 // Lazy: `WorkerEnvironment` is only populated at exec phase.
42 const raw = Effect.sync(
43 () => (env as Record<string, Runtime>)[binding.name]!,
44 ) as Effect.Effect<Runtime, never, RuntimeContext>;
45 return makeClient(raw, binding as Binding<string, Client, Self>);
46 });
47 }),
48 ) as Layer.Layer<Self, never, WorkerEnvironment>;