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

main
ts 40 lines 1.49 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import * as RpcSerialization from "effect/rpc/RpcSerialization";
5 import * as RpcServer from "effect/rpc/RpcServer";
6 import * as Stream from "effect/Stream";
7 import ChatBackendRpc from "./ChatBackendRpc.ts";
8 import { ChatRpcs } from "./ChatRpcs.ts";
9
10 // Same role as `ChatPersistenceWorker` (host the chat DO, route by
11 // thread id) but the whole `fetch` surface is a typed Effect
12 // `RpcGroup`. Each procedure proxies straight through the typed
13 // `getByName(id)` client returned by `RpcDurableObject`.
14 export default class ChatPersistenceRpcWorker extends Cloudflare.RpcWorker<ChatPersistenceRpcWorker>()(
15 "ChatPersistenceRpcWorker",
16 {
17 main: import.meta.url,
18 schema: ChatRpcs,
19 },
20 Effect.gen(function* () {
21 // Yielding the inline DO hosts it on this Worker and hands back the
22 // typed namespace.
23 const chats = yield* ChatBackendRpc;
24
25 const handlers = ChatRpcs.toLayer({
26 send: ({ id, prompt }) =>
27 Effect.flatMap(chats.getByName(id), (client) => client.send({ prompt })).pipe(Effect.orDie),
28 streamMessage: ({ id, prompt }) =>
29 chats.getByName(id).pipe(
30 Effect.map((client) => client.streamMessage({ prompt })),
31 Stream.unwrap,
32 Stream.orDie,
33 ),
34 });
35
36 return RpcServer.toHttpEffect(ChatRpcs).pipe(
37 Effect.provide(Layer.mergeAll(handlers, RpcSerialization.layerNdjson)),
38 );
39 }),
40 ) {}