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

main
ts 68 lines 2.3 KB
Raw
1 /// <reference types="@cloudflare/workers-types" />
2
3 import * as Effect from "effect/Effect";
4 import * as Layer from "effect/Layer";
5 import { Worker, WorkerEnvironment } from "../Workers/Worker.ts";
6 import type { Gateway as GatewayResource } from "./Gateway.ts";
7 import { makeLanguageModelLayer } from "./LanguageModel.ts";
8 import { GatewayError, QueryGateway, type QueryGatewayClient } from "./QueryGateway.ts";
9
10 /**
11 * Runtime layer for {@link QueryGateway}.
12 */
13 export const QueryGatewayBinding = Layer.effect(
14 QueryGateway,
15 Effect.gen(function* () {
16 const env = yield* WorkerEnvironment;
17 const host = yield* Worker;
18
19 return Effect.fn(function* (gateway: GatewayResource) {
20 if (!globalThis.__ALCHEMY_RUNTIME__) {
21 yield* host.bind`${gateway}`({
22 bindings: [
23 {
24 type: "ai",
25 name: gateway.LogicalId,
26 },
27 ],
28 });
29 }
30
31 const gatewayIdAccessor = yield* gateway.gatewayId;
32 const ai = Effect.sync(() => (env as Record<string, Ai>)[gateway.LogicalId]!);
33 const runtimeGateway = yield* Effect.zip(ai, gatewayIdAccessor).pipe(
34 Effect.map(([ai, gatewayId]) => ai.gateway(gatewayId)),
35 Effect.cached,
36 );
37
38 const use = <T>(fn: (gateway: AiGateway) => Promise<T>): Effect.Effect<T, GatewayError> =>
39 runtimeGateway.pipe(Effect.flatMap((gateway) => tryPromise(() => fn(gateway))));
40
41 const self: QueryGatewayClient = {
42 raw: ai,
43 gateway: runtimeGateway,
44 id: gatewayIdAccessor,
45 patchLog: (logId, data) => use((gateway) => gateway.patchLog(logId, data)),
46 getLog: (logId) => use((gateway) => gateway.getLog(logId)),
47 getUrl: (provider) => use((gateway) => gateway.getUrl(provider)),
48 run: (data, options) => use((gateway) => gateway.run(data, options)),
49 model: (options) =>
50 makeLanguageModelLayer({
51 ...options,
52 client: self,
53 }),
54 } satisfies QueryGatewayClient;
55 return self;
56 });
57 }),
58 );
59
60 const tryPromise = <T>(fn: () => Promise<T>): Effect.Effect<T, GatewayError> =>
61 Effect.tryPromise({
62 try: fn,
63 catch: (error) =>
64 new GatewayError({
65 message: error instanceof Error ? error.message : "Unknown AI Gateway runtime error",
66 cause: error,
67 }),
68 });