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

main
ts 56 lines 1.96 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import * as Effect from "effect/Effect";
3 import * as HttpServerResponse from "effect/http/HttpServerResponse";
4 import * as Schema from "effect/Schema";
5 import * as Stream from "effect/Stream";
6
7 /** Streams, schemas, and route helpers shared by the K2 Worker fixtures. */
8
9 export const Order = Schema.Struct({
10 run: Schema.String,
11 index: Schema.Number,
12 });
13 export type Order = typeof Order.Type;
14
15 /** Worker-binding input only (the default), typed by `Order`. */
16 export const BindingOrders = Cloudflare.K2.Stream("K2BindingOrders", { schema: Order });
17
18 /** HTTP input enabled for the `*Http` producer layers, typed by `Order`. */
19 export const HttpOrders = Cloudflare.K2.Stream("K2HttpOrders", { http: true, schema: Order });
20
21 const params = (url: URL) => ({
22 run: url.searchParams.get("run") ?? "default",
23 count: Number(url.searchParams.get("count") ?? "1"),
24 });
25
26 const failed = (error: { _tag: string; message?: string }) =>
27 HttpServerResponse.json({ error: error._tag, message: error.message }, { status: 500 });
28
29 /**
30 * Producer routes over the stream's typed client and typed sink:
31 * `POST /typed|/sink?run=R&count=N`.
32 */
33 export const produceRoutes = (
34 url: URL,
35 clients: {
36 typed: Cloudflare.K2.WriteStreamClient<Order>;
37 sink: Cloudflare.K2.StreamSinkClient<Order>;
38 },
39 ) =>
40 Effect.gen(function* () {
41 const { run, count } = params(url);
42 const orders = Array.from({ length: count }, (_, index): Order => ({ run, index }));
43 const sent =
44 url.pathname === "/typed"
45 ? clients.typed.send(orders)
46 : url.pathname === "/sink"
47 ? Stream.fromIterable(orders).pipe(Stream.run(clients.sink))
48 : undefined;
49 if (sent === undefined) {
50 return HttpServerResponse.text("Not Found", { status: 404 });
51 }
52 return yield* sent.pipe(
53 Effect.flatMap(() => HttpServerResponse.json({ produced: count }, { status: 202 })),
54 Effect.catch((error) => failed(error)),
55 );
56 });