The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as RpcServer from "./RpcServer.ts"; |
| 3 | import { SESSION_ENV_PARAM } from "./RpcServerEnvironment.ts"; |
| 4 | import type { ServerRpcSession } from "./RpcServerSession.ts"; |
| 5 | |
| 6 | export const RpcServerBun = RpcServer.layerServer( |
| 7 | Effect.fn(function* ({ parentConnected, parentDisconnected, createRpcSession }) { |
| 8 | const server = yield* Effect.sync(() => |
| 9 | Bun.serve< |
| 10 | | { type: "session"; session: ServerRpcSession<any> } |
| 11 | | { type: "pending"; sessionEnv: string | undefined } |
| 12 | | { type: "parent" } |
| 13 | >({ |
| 14 | port: 0, |
| 15 | // Loopback only, as in RpcServerNode: with no hostname Bun listens on |
| 16 | // every interface. |
| 17 | hostname: "127.0.0.1", |
| 18 | fetch: (request, server) => { |
| 19 | const url = new URL(request.url); |
| 20 | if ( |
| 21 | server.upgrade(request, { |
| 22 | data: |
| 23 | url.pathname === "/parent" |
| 24 | ? { type: "parent" } |
| 25 | : { |
| 26 | type: "pending", |
| 27 | sessionEnv: url.searchParams.get(SESSION_ENV_PARAM) ?? undefined, |
| 28 | }, |
| 29 | }) |
| 30 | ) { |
| 31 | return; |
| 32 | } |
| 33 | return new Response("Upgrade failed", { status: 400 }); |
| 34 | }, |
| 35 | websocket: { |
| 36 | // Bun closes sockets idle for 120s by default. A session can wait |
| 37 | // minutes on one provider call, and losing the parent link tears |
| 38 | // the sidecar down; the parent also sends heartbeats on its link. |
| 39 | // A dead peer still closes the socket at the TCP level. |
| 40 | idleTimeout: 0, |
| 41 | open: (ws) => { |
| 42 | if (ws.data && ws.data.type === "parent") { |
| 43 | parentConnected(); |
| 44 | } else { |
| 45 | const sessionEnv = |
| 46 | ws.data && ws.data.type === "pending" ? ws.data.sessionEnv : undefined; |
| 47 | ws.data = { |
| 48 | type: "session", |
| 49 | session: createRpcSession(ws, sessionEnv), |
| 50 | }; |
| 51 | } |
| 52 | }, |
| 53 | message: (ws, message) => { |
| 54 | if (ws.data.type === "session") { |
| 55 | ws.data.session.dispatch.message(message); |
| 56 | } |
| 57 | }, |
| 58 | close: (ws, code, reason) => { |
| 59 | if (ws.data.type === "session") { |
| 60 | ws.data.session.dispatch.close(code, reason); |
| 61 | } else if (ws.data.type === "parent") { |
| 62 | parentDisconnected(`code ${code}${reason ? `, ${reason}` : ""}`); |
| 63 | } |
| 64 | }, |
| 65 | }, |
| 66 | }), |
| 67 | ); |
| 68 | // Fire and forget: awaiting `stop(true)` can outlive the process's own shutdown. |
| 69 | yield* Effect.addFinalizer(() => |
| 70 | Effect.sync(() => { |
| 71 | void server.stop(true); |
| 72 | }), |
| 73 | ); |
| 74 | return { |
| 75 | url: `ws://${server.hostname}:${server.port}`, |
| 76 | }; |
| 77 | }), |
| 78 | ); |