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

main
ts 138 lines 5.48 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Effect from "effect/Effect";
3 import * as FetchHttpClient from "effect/http/FetchHttpClient";
4 import * as HttpClient from "effect/http/HttpClient";
5 import * as HttpClientRequest from "effect/http/HttpClientRequest";
6 import * as HttpClientResponse from "effect/http/HttpClientResponse";
7 import * as Stream from "effect/Stream";
8
9 const EXIT_MARKER = "__EXIT__:";
10
11 /**
12 * The session's MicroVM coordinates: its endpoint host and the already-resolved
13 * auth header map (from `AWS.Lambda.microvmAuthHeaders`). The DO speaks only
14 * the VM's data plane — it never touches AWS credentials, so these plain
15 * strings are all it needs.
16 */
17 export interface MicrovmCoords {
18 readonly endpoint: string;
19 readonly headers: Record<string, string>;
20 }
21
22 /**
23 * One terminal session. The hosting Worker provisions the session's MicroVM
24 * (assume-role control plane) and hands the coordinates here via the `init`
25 * RPC; the same VM is reused for every command in the session (no re-boot per
26 * command).
27 *
28 * Each command received on the WebSocket is POSTed to the VM's streaming
29 * `/exec` route; the combined stdout/stderr is forwarded back to the browser
30 * chunk-by-chunk as the process produces it.
31 */
32 export default class ShellSession extends Cloudflare.DurableObject<ShellSession>()(
33 "ShellSession",
34 Effect.gen(function* () {
35 // The session's VM coordinates, set by the `init` RPC and reused for every
36 // command in the session. The closure copy is just a cache: workerd's
37 // hibernatable WebSockets SURVIVE DO eviction, so an idle session's next
38 // message wakes a fresh instance (empty closure) on the SAME socket — the
39 // browser never reconnects. The authoritative copy lives in DO storage and
40 // is rehydrated lazily.
41 let coords: MicrovmCoords | undefined;
42
43 return Effect.gen(function* () {
44 const send = (socket: Cloudflare.WebSocket, text: string) =>
45 socket.send(text).pipe(Effect.ignore);
46
47 const loadCoords = Effect.gen(function* () {
48 if (coords) return coords;
49 const state = yield* Cloudflare.DurableObjectState;
50 coords = yield* state.storage.get<MicrovmCoords>("coords");
51 return coords;
52 });
53
54 const runCommand = (socket: Cloudflare.WebSocket, command: string) =>
55 Effect.gen(function* () {
56 const current = yield* loadCoords;
57 if (!current) {
58 yield* send(socket, "[session has no microvm]\n");
59 return;
60 }
61 const { endpoint, headers } = current;
62 const client = yield* HttpClient.HttpClient;
63 const request = HttpClientRequest.post(`https://${endpoint}/exec`).pipe(
64 HttpClientRequest.setHeaders(headers),
65 HttpClientRequest.bodyJsonUnsafe({ command }),
66 );
67
68 // Render like a real shell: forward output verbatim, swallow the
69 // VM's `\n__EXIT__:<code>` trailer (including the separator newline
70 // the server adds before it), and only make sure the next prompt
71 // starts on a fresh line when the command's output didn't end with
72 // one — no exit-status chatter.
73 let endedWithNewline = true;
74 yield* HttpClientResponse.stream(client.execute(request)).pipe(
75 Stream.decodeText(),
76 Stream.runForEach((chunk) =>
77 Effect.gen(function* () {
78 const marker = chunk.indexOf(EXIT_MARKER);
79 if (marker === -1) {
80 if (chunk) {
81 endedWithNewline = chunk.endsWith("\n");
82 yield* send(socket, chunk);
83 }
84 return;
85 }
86 let before = chunk.slice(0, marker);
87 if (before.endsWith("\n")) {
88 before = before.slice(0, -1);
89 }
90 if (before) {
91 endedWithNewline = before.endsWith("\n");
92 yield* send(socket, before);
93 }
94 }),
95 ),
96 );
97 if (!endedWithNewline) {
98 yield* send(socket, "\n");
99 }
100 }).pipe(
101 Effect.catch((error) => send(socket, `[error] ${String(error)}\n`)),
102 Effect.provide(FetchHttpClient.layer),
103 );
104
105 return {
106 /** Pin this session to a provisioned MicroVM (called by the Worker). */
107 init: (next: MicrovmCoords) =>
108 Effect.gen(function* () {
109 coords = next;
110 // Persist so a hibernation wake (same socket, fresh instance)
111 // finds its VM again.
112 const state = yield* Cloudflare.DurableObjectState;
113 yield* state.storage.put("coords", next);
114 }),
115 fetch: Effect.gen(function* () {
116 const [response, socket] = yield* Cloudflare.upgrade();
117 yield* send(socket, "connected to microvm — type a command and press enter\n");
118 return response;
119 }),
120 webSocketMessage: Effect.fn(function* (
121 socket: Cloudflare.WebSocket,
122 message: string | ArrayBuffer,
123 ) {
124 const command = typeof message === "string" ? message : new TextDecoder().decode(message);
125 if (!command.trim()) return;
126 yield* runCommand(socket, command.trim());
127 }),
128 webSocketClose: Effect.fn(function* (
129 socket: Cloudflare.WebSocket,
130 code: number,
131 reason: string,
132 ) {
133 yield* socket.close(code, reason).pipe(Effect.ignore);
134 }),
135 };
136 });
137 }),
138 ) {}