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

main
ts 101 lines 3.63 KB
Raw
1 // @effect-diagnostics globalJsonInEffect:off
2 import * as Effect from "effect/Effect";
3 import * as Stream from "effect/Stream";
4
5 const SSE_EVENT_SEPARATOR = /(?:\r\n|\r(?!\n)|\n){2}/u;
6 // A separator is at most four characters, so one that a new chunk completes starts within the
7 // last three characters already read. Scanning only those plus the chunk keeps parsing linear.
8 const SEPARATOR_OVERLAP = 3;
9
10 function sseEventData(rawEvent: string): string {
11 return rawEvent
12 .split(/\r\n|\r|\n/u)
13 .filter((line) => line.startsWith("data:"))
14 .map((line) => line.slice("data:".length).trimStart())
15 .join("\n");
16 }
17
18 async function* sseDataLines(
19 reader: ReadableStreamDefaultReader<Uint8Array>,
20 ): AsyncGenerator<string> {
21 const decoder = new TextDecoder();
22 let eventParts: string[] = [];
23 let unscanned = "";
24 while (true) {
25 const { done, value } = await reader.read();
26 if (done) return;
27 let text = unscanned + decoder.decode(value, { stream: true });
28 let separator = SSE_EVENT_SEPARATOR.exec(text);
29 while (separator !== null) {
30 eventParts.push(text.slice(0, separator.index));
31 const data = sseEventData(eventParts.join(""));
32 eventParts = [];
33 text = text.slice(separator.index + separator[0].length);
34 if (data.length > 0) yield data;
35 separator = SSE_EVENT_SEPARATOR.exec(text);
36 }
37 const scannedLength = Math.max(0, text.length - SEPARATOR_OVERLAP);
38 eventParts.push(text.slice(0, scannedLength));
39 unscanned = text.slice(scannedLength);
40 }
41 }
42
43 async function readText(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<string> {
44 const decoder = new TextDecoder();
45 let text = "";
46 while (true) {
47 const { done, value } = await reader.read();
48 if (done) return text + decoder.decode();
49 text += decoder.decode(value, { stream: true });
50 }
51 }
52
53 // Interrupting a read cannot settle the promise parked on read(), so the reader is cancelled
54 // from a finalizer instead; that settles the read and closes the body.
55 const scopedReader = (body: ReadableStream<Uint8Array>) =>
56 Effect.acquireRelease(
57 Effect.sync(() => body.getReader()),
58 (reader) =>
59 Effect.promise(() =>
60 reader
61 .cancel()
62 .catch(() => undefined)
63 .then(() => reader.releaseLock()),
64 ),
65 );
66
67 export const discardResponseBody = (response: Response): Effect.Effect<void> =>
68 Effect.promise(() => response.body?.cancel().catch(() => undefined) ?? Promise.resolve());
69
70 export function responsePayloads<E>(
71 response: Response,
72 onError: (cause: unknown) => E,
73 ): Stream.Stream<unknown, E> {
74 if (response.status === 202 || response.status === 204) {
75 return Stream.unwrap(discardResponseBody(response).pipe(Effect.as(Stream.empty)));
76 }
77 const body = response.body;
78 if (body === null) return Stream.empty;
79 const mediaType = (response.headers.get("content-type") ?? "").split(";", 1)[0]!.trim();
80 if (mediaType.toLowerCase() === "text/event-stream") {
81 return Stream.unwrap(
82 scopedReader(body).pipe(
83 Effect.map((reader) => Stream.fromAsyncIterable(sseDataLines(reader), onError)),
84 ),
85 ).pipe(Stream.mapEffect((data) => Effect.try({ try: () => JSON.parse(data), catch: onError })));
86 }
87 return Stream.unwrap(
88 scopedReader(body).pipe(
89 Effect.flatMap((reader) =>
90 Effect.tryPromise({ try: () => readText(reader), catch: onError }),
91 ),
92 Effect.flatMap((text) =>
93 text.trim().length === 0
94 ? Effect.succeed(Stream.empty)
95 : Effect.try({ try: () => JSON.parse(text) as unknown, catch: onError }).pipe(
96 Effect.map((payload) => Stream.fromIterable([payload])),
97 ),
98 ),
99 ),
100 );
101 }