import { DurableObject } from "cloudflare:workers"; import { now } from "./auth.ts"; import { hinting, repoStream, type Hint } from "./events.ts"; import { APPROVAL_WAIT_SECONDS, expirePermissions, type Verdict } from "./permissions.ts"; interface Machine { userId: string; name: string; } /** A mention the daemon answers with a sub-agent run. */ export interface RunMessage { readonly type: "run"; readonly parent: string; readonly mention: string; readonly repo: string; readonly pull: number; readonly title: string; readonly body: string; readonly assigned: boolean; } /** A mention of an OpenCode session: the daemon starts a turn in that live session. */ export interface WakeMessage { readonly type: "wake"; readonly session: string; readonly mention: string; readonly pull: number; readonly title: string; readonly by: string; } type DaemonMessage = { type: "hello"; machine: string; runtimes: string[]; version: string } | { type: "ping" }; const NAME = /^[A-Za-z0-9._-]{1,64}$/; const PING = JSON.stringify({ type: "ping" }); const PONG = JSON.stringify({ type: "pong" }); /** * One per human. Holds the socket of every machine where that human runs the refs daemon, and is the * authority on which of them are connected. The `machines` table is only a projection of it for * listing pages: written on hello and on close, so it can lag a socket that died without closing. */ export class UserHub extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG)); } async fetch(request: Request): Promise { const userId = request.headers.get("x-refs-user"); if (!userId || request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("Expected a daemon socket\n", { status: 400 }); const [client, server] = Object.values(new WebSocketPair()); this.ctx.acceptWebSocket(server); server.serializeAttachment({ userId, name: "" } satisfies Machine); return new Response(null, { status: 101, webSocket: client }); } /** Hands a run or a wake to the named machine's daemon. False when that machine isn't connected. */ async dispatch(machine: string, run: RunMessage | WakeMessage): Promise { const socket = this.ctx.getWebSockets().find((ws) => (ws.deserializeAttachment() as Machine).name === machine); if (!socket) return false; socket.send(JSON.stringify(run)); return true; } /** The names of this human's machines whose daemon socket is open right now. */ async connected(): Promise { return [...new Set(this.ctx.getWebSockets().map((ws) => (ws.deserializeAttachment() as Machine).name))].filter(Boolean); } async webSocketMessage(ws: WebSocket, raw: string | ArrayBuffer): Promise { let message: DaemonMessage; try { message = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw)); } catch { return ws.close(1008, "Malformed message"); } const machine = ws.deserializeAttachment() as Machine; if (message.type === "hello") { if (!NAME.test(message.machine)) return ws.close(1008, "Invalid machine name"); const runtimes = Array.isArray(message.runtimes) ? message.runtimes.filter((runtime) => NAME.test(runtime)).slice(0, 10) : []; ws.serializeAttachment({ ...machine, name: message.machine } satisfies Machine); await this.env.DB.prepare( "INSERT INTO machines (user_id, name, runtimes, version, connected, last_seen_at) VALUES (?, ?, ?, ?, 1, ?) ON CONFLICT (user_id, name) DO UPDATE SET runtimes = excluded.runtimes, version = excluded.version, connected = 1, last_seen_at = excluded.last_seen_at", ) .bind(machine.userId, message.machine, JSON.stringify(runtimes), String(message.version ?? "").slice(0, 32), now()) .run(); ws.send(JSON.stringify({ type: "welcome", machine: message.machine })); return; } if (message.type === "ping") ws.send(PONG); } async webSocketClose(ws: WebSocket): Promise { const machine = ws.deserializeAttachment() as Machine; if (!machine.name) return; const stillOpen = this.ctx.getWebSockets().some((socket) => socket !== ws && (socket.deserializeAttachment() as Machine).name === machine.name); if (stillOpen) return; const pinged = this.ctx.getWebSocketAutoResponseTimestamp(ws); await this.env.DB.prepare("UPDATE machines SET connected = 0, last_seen_at = max(last_seen_at, ?) WHERE user_id = ? AND name = ?") .bind(pinged ? Math.floor(pinged.getTime() / 1000) : 0, machine.userId, machine.name) .run(); } async webSocketError(ws: WebSocket): Promise { await this.webSocketClose(ws); } } const CAP_GRACE_MS = 5000; /** * One per repository. Holds the browser sockets watching the repository and its tasks, and tells them when a * stream they watch moves. D1 stays the record: a hint carries no data, and the page reloads through its loaders. */ export class RepoHub extends DurableObject { private readonly waiting = new Map void)[]>(); constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong")); } async fetch(request: Request): Promise { const tags = (request.headers.get("x-refs-watch") ?? "").split(" ").filter(Boolean); if (!tags.length || request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("Expected a live socket\n", { status: 400 }); const [client, server] = Object.values(new WebSocketPair()); this.ctx.acceptWebSocket(server, tags); return new Response(null, { status: 101, webSocket: client }); } async notify(hint: Omit): Promise { const message = JSON.stringify(hint); for (const socket of this.ctx.getWebSockets(hint.stream)) { try { socket.send(message); } catch {} } } /** * Waits for a human's answer to a tool approval recorded in D1. A verdict already stored is returned at once, so an * agent that retries after its request dropped picks it up. Otherwise the call parks until `decide` or the expiry alarm. */ async awaitDecision(repoId: string, session: string, requestId: string): Promise { await this.ctx.storage.put("repo", repoId); const key = `${session} ${requestId}`; const answer = new Promise((resolve) => this.waiting.set(key, [...(this.waiting.get(key) ?? []), resolve])); const row = await this.env.DB.prepare("SELECT behavior, created_at FROM permission_requests WHERE session_id = ? AND request_id = ?") .bind(session, requestId) .first<{ behavior: Verdict | null; created_at: number }>(); if (!row || row.behavior) { this.settle(key, row?.behavior ?? "expired"); return answer; } const deadline = (row.created_at + APPROVAL_WAIT_SECONDS) * 1000; const alarm = await this.ctx.storage.getAlarm(); if (alarm === null || alarm > deadline) await this.ctx.storage.setAlarm(deadline); const cap = setTimeout(() => void this.alarm().catch(() => undefined).finally(() => this.settle(key, "expired")), Math.max(0, deadline - Date.now()) + CAP_GRACE_MS); try { return await answer; } finally { clearTimeout(cap); } } /** Hands a verdict already written to D1 to whoever is waiting on it. */ async decide(session: string, requestId: string, verdict: Verdict): Promise { this.settle(`${session} ${requestId}`, verdict); } async alarm(): Promise { const repoId = await this.ctx.storage.get("repo"); if (!repoId) return; const { expired, next } = await expirePermissions(this.env.DB, repoId, now()); for (const { session_id, request_id } of expired) this.settle(`${session_id} ${request_id}`, "expired"); if (expired.length) await this.notify({ latestId: 0, stream: repoStream(repoId) }); if (next !== null) await this.ctx.storage.setAlarm(next * 1000); } private settle(key: string, verdict: Verdict): void { for (const resolve of this.waiting.get(key) ?? []) resolve(verdict); this.waiting.delete(key); } /** Closes the sockets carrying a tag, such as every anonymous viewer once the repository goes private. */ async disconnect(tag: string): Promise { for (const socket of this.ctx.getWebSockets(tag)) socket.close(4403, "Access changed"); } } /** The request's bindings, with a database that hints each repository's hub after every event it commits. */ export function withHints(env: Env, ctx: ExecutionContext): Env { return { ...env, DB: hinting(env.DB, ({ repoId, ...hint }) => ctx.waitUntil(env.REPO_HUB.get(env.REPO_HUB.idFromName(repoId)).notify(hint).catch(() => undefined))) }; }