// rooms: a Cloudflare Worker with one Durable Object per chat room. // It runs unchanged on Cloudflare (wrangler dev/deploy) and on OpenOrange // (orange dev/serve). Bindings, from wrangler.jsonc: // ROOMS Durable Object class Room, one SQLite database per room // STATS KV namespace, written by the cron trigger // AI Workers AI, for /room//summary import { DurableObject } from "cloudflare:workers"; export class Room extends DurableObject { constructor(ctx, env) { super(ctx, env); ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, author TEXT NOT NULL, text TEXT NOT NULL, at INTEGER NOT NULL)`); } async post(author, text) { this.ctx.storage.sql.exec( "INSERT INTO messages (author, text, at) VALUES (?, ?, ?)", author, text, Date.now()); } async list() { return this.ctx.storage.sql .exec("SELECT author, text, at FROM messages ORDER BY id DESC LIMIT 50") .toArray() .reverse(); } async count() { return this.ctx.storage.sql.exec("SELECT count(*) AS n FROM messages").one().n; } } const esc = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); function page(room, messages, lastCron) { const items = messages .map((m) => `
  • ${esc(m.author)} ${esc(m.text)} ${new Date(m.at).toISOString().slice(0, 16).replace("T", " ")}
  • `) .join("\n"); return ` ${esc(room)}

    #${esc(room)}

    Summarize this room

    Last cron run: ${esc(lastCron ?? "not yet")}

    `; } export default { async fetch(request, env) { const url = new URL(request.url); if (url.pathname === "/") return Response.redirect(new URL("/room/lobby", url), 302); if (url.pathname === "/health") return new Response("ok\n"); const m = url.pathname.match(/^\/(api\/)?room\/([a-z0-9-]{1,40})(\/summary)?$/); if (!m) return new Response("not found\n", { status: 404 }); const [, api, name, summary] = m; // One Durable Object per room name, wherever this Worker runs. const room = env.ROOMS.getByName(name); if (request.method === "POST") { const form = await request.formData(); const text = String(form.get("text") ?? "").trim().slice(0, 500); // Behind the exe.dev proxy, signed-in visitors arrive with their email. const author = request.headers.get("X-ExeDev-Email") ?? "anonymous"; if (text) await room.post(author, text); return Response.redirect(url.href, 303); } const messages = await room.list(); if (summary) { const transcript = messages.map((x) => `${x.author}: ${x.text}`).join("\n"); const out = await env.AI.run("@cf/meta/llama-3.1-8b-instruct", { messages: [ { role: "system", content: "Summarize this chat in two sentences." }, { role: "user", content: transcript || "(empty room)" }, ], }); return new Response(out.response + "\n", { headers: { "content-type": "text/plain; charset=utf-8" } }); } if (api) return Response.json({ room: name, messages, count: await room.count() }); const lastCron = await env.STATS.get("last-cron"); return new Response(page(name, messages, lastCron), { headers: { "content-type": "text/html; charset=utf-8" }, }); }, // Cron Triggers: wrangler.jsonc runs this every five minutes. async scheduled(controller, env) { await env.STATS.put("last-cron", new Date(controller.scheduledTime).toISOString()); }, };