@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 423 lines 16.9 KB
Raw
1 import { BetterAuth } from "@alchemy.run/better-auth";
2 import { CloudflareD1 } from "@alchemy.run/better-auth/CloudflareD1";
3 import * as Cloudflare from "@alchemy.run/cloudflare";
4 import * as Effect from "effect/Effect";
5 import * as HttpBody from "effect/http/HttpBody";
6 import * as HttpClientRequest from "effect/http/HttpClientRequest";
7 import { HttpServerRequest } from "effect/http/HttpServerRequest";
8 import * as HttpServerResponse from "effect/http/HttpServerResponse";
9 import * as Layer from "effect/Layer";
10 import * as Stream from "effect/Stream";
11 import Agent from "./Agent.ts";
12 import { Gateway } from "./AiGateway.ts";
13 import { Bucket } from "./Bucket.ts";
14 import { KV } from "./KV.ts";
15 import NotifyWorkflow from "./NotifyWorkflow.ts";
16 import { Queue } from "./Queue.ts";
17 import { Repos } from "./Repos.ts";
18 import Room from "./Room.ts";
19
20 interface QueueMessageBody {
21 id: string;
22 text: string;
23 sentAt: number;
24 }
25
26 /** D1 database backing Better Auth (auto-migrated at deploy). */
27 export const AuthDb = Cloudflare.D1.Database("AuthDb");
28
29 export default class Api extends Cloudflare.Worker<Api>()(
30 "Api",
31 {
32 main: import.meta.url,
33 observability: {
34 enabled: true,
35 },
36 assets: "./assets",
37 build: {
38 bundleAnalyzer: true,
39 },
40 compatibility: {
41 date: "2026-08-31",
42 },
43 },
44 Effect.gen(function* () {
45 const auth = yield* BetterAuth({
46 basePath: "/auth",
47 emailAndPassword: { enabled: true },
48 });
49 const agents = yield* Agent;
50 const rooms = yield* Room;
51 const notifier = yield* NotifyWorkflow;
52 const loader = yield* Cloudflare.WorkerLoader("Loader");
53 const bucket = yield* Cloudflare.R2.ReadWriteBucket(Bucket);
54 const kv = yield* Cloudflare.KV.ReadWriteNamespace(KV);
55 const queueResource = yield* Queue;
56 const queue = yield* Cloudflare.Queues.WriteQueue(queueResource);
57 const repos = yield* Cloudflare.Artifacts.ReadWriteNamespace(Repos);
58 const aiGateway = yield* Cloudflare.AI.QueryGateway(Gateway);
59
60 // Effect-style queue consumer. Each batch is piped through the
61 // handler; success ack()s every message in the batch, failure
62 // retry()s. The persisted JSON at /queue/<id> on R2 lets the
63 // integ test verify the producer→consumer round-trip.
64 yield* Cloudflare.Queues.consumeQueueMessages<QueueMessageBody>(queueResource, (stream) =>
65 Stream.runForEach(stream, (msg) =>
66 bucket
67 .put(`/queue/${msg.body.id}`, JSON.stringify(msg.body), {
68 httpMetadata: { contentType: "application/json" },
69 })
70 .pipe(Effect.asVoid),
71 ),
72 );
73
74 return {
75 fetch: Effect.gen(function* () {
76 const request = yield* HttpServerRequest;
77
78 if (request.url.startsWith("/auth/")) {
79 return yield* auth.fetch;
80 } else if (request.url.startsWith("/kv/")) {
81 if (request.method === "GET") {
82 const key = request.url.split("/").pop()!;
83 return yield* kv.get(key).pipe(
84 Effect.map((value) =>
85 value ? HttpServerResponse.text(value) : HttpServerResponse.empty({ status: 404 }),
86 ),
87 Effect.catch(() => Effect.succeed(HttpServerResponse.empty({ status: 404 }))),
88 );
89 } else if (request.method === "POST") {
90 const key = request.url.split("/").pop()!;
91 const value = yield* request.text;
92 return yield* kv.put(key, value).pipe(
93 Effect.map(() => HttpServerResponse.empty({ status: 200 })),
94 Effect.catch(() => Effect.succeed(HttpServerResponse.empty({ status: 500 }))),
95 );
96 }
97 } else if (request.url.startsWith("/object/")) {
98 if (request.method === "GET") {
99 return yield* bucket.get(request.url.split("/").pop()!).pipe(
100 Effect.flatMap((object) =>
101 object === null
102 ? Effect.succeed(
103 HttpServerResponse.text("Object not found", {
104 status: 404,
105 }),
106 )
107 : object.text().pipe(
108 Effect.map((text) =>
109 HttpServerResponse.text(text, {
110 headers: { "content-type": "application/json" },
111 }),
112 ),
113 ),
114 ),
115 Effect.catchTag("R2Error", (error) =>
116 Effect.succeed(
117 HttpServerResponse.text(error.message, {
118 status: 500,
119 statusText: error.message,
120 }),
121 ),
122 ),
123 );
124 } else if (request.method === "POST" || request.method === "PUT") {
125 // const request = yield* Cloudflare.Workers.Request
126 const key = request.url.split("/").pop()!;
127 return yield* bucket
128 .put(key, request.stream, {
129 contentLength: Number(request.headers["content-length"] ?? 0),
130 })
131 .pipe(
132 Effect.map(() => HttpServerResponse.empty({ status: 201 })),
133 Effect.catch((err) =>
134 HttpServerResponse.json(
135 {
136 error: err.message,
137 headers: request.headers,
138 },
139 { status: 500 },
140 ),
141 ),
142 );
143 } else {
144 return HttpServerResponse.text("Method not allowed", {
145 status: 405,
146 });
147 }
148 } else if (request.url === "/sandbox/increment") {
149 const agent = agents.getByName("sandbox-test");
150 const body = yield* agent.increment().pipe(Effect.orDie);
151 const room = rooms.getByName("default");
152 yield* room.broadcast(`[container] ${body}`);
153 return HttpServerResponse.text(body, {
154 headers: { "content-type": "application/json" },
155 });
156 } else if (request.url.startsWith("/sandbox")) {
157 const agent = agents.getByName("sandbox-test");
158 const body = yield* agent.hello().pipe(Effect.orDie);
159 return HttpServerResponse.text(body);
160 } else if (request.url.startsWith("/workflow/start/")) {
161 const roomId = request.url.split("/workflow/start/")[1];
162 if (!roomId) {
163 return yield* HttpServerResponse.json({ error: "roomId is required" }, { status: 400 });
164 }
165 const instance = yield* notifier.create({
166 params: {
167 roomId,
168 message: "hello from workflow",
169 },
170 });
171 return yield* HttpServerResponse.json({ instanceId: instance.id });
172 } else if (request.url.startsWith("/workflow/status/")) {
173 const instanceId = request.url.split("/workflow/status/")[1];
174 if (!instanceId) {
175 return yield* HttpServerResponse.json(
176 { error: "instanceId is required" },
177 { status: 400 },
178 );
179 }
180 const instance = yield* notifier.get(instanceId);
181 const status = yield* instance.status();
182 return yield* HttpServerResponse.json(status);
183 } else if (request.url.startsWith("/eval")) {
184 if (request.method === "POST") {
185 const code = yield* request.text;
186 const worker = yield* loader.load({
187 compatibilityDate: "2026-08-31",
188 mainModule: "worker.js",
189 modules: {
190 "worker.js": `
191 export default {
192 async fetch(request) {
193 try {
194 const result = (0, eval)(${"`${await request.text()}`"});
195 return new Response(String(result), { status: 200 });
196 } catch (e) {
197 return new Response(e.message, { status: 500 });
198 }
199 }
200 }
201 `,
202 },
203 globalOutbound: null,
204 });
205 return yield* worker
206 .fetch(
207 HttpClientRequest.post("https://worker/").pipe(
208 HttpClientRequest.setBody(HttpBody.text(code)),
209 ),
210 )
211 .pipe(Effect.map(HttpServerResponse.fromClientResponse), Effect.orDie);
212 }
213 } else if (request.url.startsWith("/connect/")) {
214 const agentId = request.url.split("/").pop()!;
215 const agent = agents.getByName(agentId);
216 const response = yield* agent.fetch(request);
217 return response;
218 } else if (request.url.startsWith("/room/")) {
219 const upgradeHeader = request.headers.upgrade;
220 const roomId = request.url.split("/").pop()!;
221 if (!upgradeHeader || upgradeHeader !== "websocket") {
222 return HttpServerResponse.text("Worker expected Upgrade: websocket", { status: 426 });
223 } else if (request.method !== "GET") {
224 return HttpServerResponse.text("Method not allowed", {
225 status: 405,
226 });
227 }
228 const room = rooms.getByName(roomId);
229 const response = yield* room.fetch(request);
230 return response;
231 }
232 // Cloudflare Artifacts — Git-compatible versioned repos.
233 // Exercises Cloudflare.ArtifactsConnection by creating a repo,
234 // looking it up, and minting short-lived clone tokens.
235 if (request.url.startsWith("/repos/create") && request.method === "POST") {
236 const text = yield* request.text;
237 const body = JSON.parse(text || "{}") as {
238 name?: string;
239 description?: string;
240 };
241 const name = body.name?.trim();
242 if (!name) {
243 return yield* HttpServerResponse.json({ error: "name is required" }, { status: 400 });
244 }
245 return yield* repos
246 .create(name, {
247 description: body.description,
248 setDefaultBranch: "main",
249 })
250 .pipe(
251 Effect.flatMap((created) =>
252 HttpServerResponse.json({
253 id: created.id,
254 name: created.name,
255 remote: created.remote,
256 token: created.token,
257 tokenExpiresAt: created.tokenExpiresAt,
258 defaultBranch: created.defaultBranch,
259 }),
260 ),
261 Effect.catchTag("ArtifactsError", (err) =>
262 HttpServerResponse.json({ error: err.message }, { status: 409 }),
263 ),
264 );
265 }
266 if (request.url.startsWith("/repos/list") && request.method === "GET") {
267 return yield* repos.list({ limit: 50 }).pipe(
268 Effect.flatMap((res) => HttpServerResponse.json(res)),
269 Effect.catchTag("ArtifactsError", (err) =>
270 HttpServerResponse.json({ error: err.message }, { status: 500 }),
271 ),
272 );
273 }
274 if (request.url.startsWith("/repos/info") && request.method === "GET") {
275 const name = new URL(request.url, "http://x").searchParams.get("name");
276 if (!name) {
277 return yield* HttpServerResponse.json({ error: "name is required" }, { status: 400 });
278 }
279 return yield* repos.get(name).pipe(
280 Effect.flatMap((repo) => repo.info()),
281 Effect.flatMap((info) =>
282 HttpServerResponse.json({
283 id: info.id,
284 name: info.name,
285 description: info.description,
286 defaultBranch: info.defaultBranch,
287 remote: info.remote,
288 createdAt: info.createdAt,
289 updatedAt: info.updatedAt,
290 lastPushAt: info.lastPushAt,
291 readOnly: info.readOnly,
292 }),
293 ),
294 Effect.catchTag("ArtifactsError", (err) =>
295 HttpServerResponse.json(
296 { name, error: err.message },
297 { status: err.code === "NOT_FOUND" ? 404 : 500 },
298 ),
299 ),
300 );
301 }
302 if (request.url.startsWith("/repos/token") && request.method === "POST") {
303 const text = yield* request.text;
304 const body = JSON.parse(text || "{}") as {
305 name?: string;
306 scope?: "read" | "write";
307 ttl?: number;
308 };
309 const name = body.name?.trim();
310 if (!name) {
311 return yield* HttpServerResponse.json({ error: "name is required" }, { status: 400 });
312 }
313 return yield* repos.get(name).pipe(
314 Effect.flatMap((repo) => repo.createToken(body.scope ?? "read", body.ttl ?? 3600)),
315 Effect.flatMap((token) => HttpServerResponse.json({ name, ...token })),
316 Effect.catchTag("ArtifactsError", (err) =>
317 HttpServerResponse.json({ name, error: err.message }, { status: 404 }),
318 ),
319 );
320 }
321 // Queue producer + consumer smoke test.
322 //
323 // POST /queue/send sends a message with a generated id.
324 // GET /queue/result/:id reads the bucket entry the consumer
325 // wrote when it processed that message.
326 //
327 // Producer side: `Cloudflare.Queues.WriteQueue`. Consumer side:
328 // `Cloudflare.Queues.consumeQueueMessages(Queue, handler)` registered in
329 // the init phase (above), with `EventSourceLive` on the
330 // worker layer.
331 // AI Gateway smoke test — POST /ai with { prompt }.
332 //
333 // Routes a Workers AI inference call through the gateway resource so
334 // every request is observable in the Cloudflare.AI. Gateway UI and
335 // benefits from caching/rate limiting configured on the resource.
336 if (request.url.startsWith("/ai") && request.method === "POST") {
337 const text = yield* request.text;
338 const body = (() => {
339 try {
340 return JSON.parse(text || "{}") as { prompt?: string };
341 } catch {
342 return {} as { prompt?: string };
343 }
344 })();
345 const prompt = body.prompt?.trim() || "Say hello in one short sentence.";
346 const response = yield* aiGateway.run({
347 provider: "workers-ai",
348 endpoint: "@cf/meta/llama-3.1-8b-instruct",
349 headers: { "content-type": "application/json" },
350 query: { prompt },
351 });
352 return HttpServerResponse.fromWeb(response);
353 }
354 if (request.url === "/queue/send" && request.method === "POST") {
355 const text = yield* request.text;
356 const msg: QueueMessageBody = {
357 id: crypto.randomUUID(),
358 text,
359 sentAt: Date.now(),
360 };
361 yield* queue.send(msg).pipe(Effect.orDie);
362 return yield* HttpServerResponse.json({ sent: msg }, { status: 202 });
363 }
364 if (request.url.startsWith("/queue/result/")) {
365 const id = request.url.split("/queue/result/")[1];
366 if (!id) {
367 return HttpServerResponse.text("missing id", { status: 400 });
368 }
369 if (request.method === "GET") {
370 return yield* bucket.get(`/queue/${id}`).pipe(
371 Effect.flatMap((object) =>
372 object === null
373 ? Effect.succeed(HttpServerResponse.text("not yet", { status: 404 }))
374 : object.text().pipe(
375 Effect.map((body) =>
376 HttpServerResponse.text(body, {
377 headers: { "content-type": "application/json" },
378 }),
379 ),
380 ),
381 ),
382 Effect.catchTag("R2Error", (error) =>
383 Effect.succeed(HttpServerResponse.text(error.message, { status: 500 })),
384 ),
385 );
386 }
387 // DELETE — used by the integ test to clear consumed
388 // entries before stack.destroy(), so Bucket delete
389 // doesn't fail with "bucket not empty".
390 if (request.method === "DELETE") {
391 return yield* bucket.delete(`/queue/${id}`).pipe(
392 Effect.map(() => HttpServerResponse.empty({ status: 204 })),
393 Effect.catchTag("R2Error", (error) =>
394 Effect.succeed(HttpServerResponse.text(error.message, { status: 500 })),
395 ),
396 );
397 }
398 }
399 return HttpServerResponse.text("Not Found", { status: 404 });
400 }).pipe(
401 Effect.catch(() =>
402 Effect.succeed(
403 HttpServerResponse.text("Internal Server Error", {
404 status: 500,
405 }),
406 ),
407 ),
408 ),
409 };
410 }).pipe(
411 Effect.provide(
412 Layer.mergeAll(
413 CloudflareD1(AuthDb),
414 Cloudflare.R2.ReadWriteBucketBinding,
415 Cloudflare.KV.ReadWriteNamespaceBinding,
416 Cloudflare.Queues.WriteQueueBinding,
417 Cloudflare.Queues.EventSourceLive,
418 Cloudflare.Artifacts.ReadWriteNamespaceBinding,
419 Cloudflare.AI.QueryGatewayBinding,
420 ),
421 ),
422 ),
423 ) {}