198 lines · 8.7 KBRaw
| 1 | import { DurableObject } from "cloudflare:workers"; |
| 2 | import { now } from "./auth.ts"; |
| 3 | import { hinting, repoStream, type Hint } from "./events.ts"; |
| 4 | import { APPROVAL_WAIT_SECONDS, expirePermissions, type Verdict } from "./permissions.ts"; |
| 5 | |
| 6 | interface Machine { |
| 7 | userId: string; |
| 8 | name: string; |
| 9 | } |
| 10 | |
| 11 | /** A mention the daemon answers with a sub-agent run. */ |
| 12 | export interface RunMessage { |
| 13 | readonly type: "run"; |
| 14 | readonly parent: string; |
| 15 | readonly mention: string; |
| 16 | readonly repo: string; |
| 17 | readonly pull: number; |
| 18 | readonly title: string; |
| 19 | readonly body: string; |
| 20 | readonly assigned: boolean; |
| 21 | } |
| 22 | |
| 23 | /** A mention of an OpenCode session: the daemon starts a turn in that live session. */ |
| 24 | export interface WakeMessage { |
| 25 | readonly type: "wake"; |
| 26 | readonly session: string; |
| 27 | readonly mention: string; |
| 28 | readonly pull: number; |
| 29 | readonly title: string; |
| 30 | readonly by: string; |
| 31 | } |
| 32 | |
| 33 | type DaemonMessage = { type: "hello"; machine: string; runtimes: string[]; version: string } | { type: "ping" }; |
| 34 | |
| 35 | const NAME = /^[A-Za-z0-9._-]{1,64}$/; |
| 36 | |
| 37 | const PING = JSON.stringify({ type: "ping" }); |
| 38 | const PONG = JSON.stringify({ type: "pong" }); |
| 39 | |
| 40 | /** |
| 41 | * One per human. Holds the socket of every machine where that human runs the refs daemon, and is the |
| 42 | * authority on which of them are connected. The `machines` table is only a projection of it for |
| 43 | * listing pages: written on hello and on close, so it can lag a socket that died without closing. |
| 44 | */ |
| 45 | export class UserHub extends DurableObject<Env> { |
| 46 | constructor(ctx: DurableObjectState, env: Env) { |
| 47 | super(ctx, env); |
| 48 | ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair(PING, PONG)); |
| 49 | } |
| 50 | |
| 51 | async fetch(request: Request): Promise<Response> { |
| 52 | const userId = request.headers.get("x-refs-user"); |
| 53 | if (!userId || request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("Expected a daemon socket\n", { status: 400 }); |
| 54 | const [client, server] = Object.values(new WebSocketPair()); |
| 55 | this.ctx.acceptWebSocket(server); |
| 56 | server.serializeAttachment({ userId, name: "" } satisfies Machine); |
| 57 | return new Response(null, { status: 101, webSocket: client }); |
| 58 | } |
| 59 | |
| 60 | /** Hands a run or a wake to the named machine's daemon. False when that machine isn't connected. */ |
| 61 | async dispatch(machine: string, run: RunMessage | WakeMessage): Promise<boolean> { |
| 62 | const socket = this.ctx.getWebSockets().find((ws) => (ws.deserializeAttachment() as Machine).name === machine); |
| 63 | if (!socket) return false; |
| 64 | socket.send(JSON.stringify(run)); |
| 65 | return true; |
| 66 | } |
| 67 | |
| 68 | /** The names of this human's machines whose daemon socket is open right now. */ |
| 69 | async connected(): Promise<string[]> { |
| 70 | return [...new Set(this.ctx.getWebSockets().map((ws) => (ws.deserializeAttachment() as Machine).name))].filter(Boolean); |
| 71 | } |
| 72 | |
| 73 | async webSocketMessage(ws: WebSocket, raw: string | ArrayBuffer): Promise<void> { |
| 74 | let message: DaemonMessage; |
| 75 | try { |
| 76 | message = JSON.parse(typeof raw === "string" ? raw : new TextDecoder().decode(raw)); |
| 77 | } catch { |
| 78 | return ws.close(1008, "Malformed message"); |
| 79 | } |
| 80 | const machine = ws.deserializeAttachment() as Machine; |
| 81 | if (message.type === "hello") { |
| 82 | if (!NAME.test(message.machine)) return ws.close(1008, "Invalid machine name"); |
| 83 | const runtimes = Array.isArray(message.runtimes) ? message.runtimes.filter((runtime) => NAME.test(runtime)).slice(0, 10) : []; |
| 84 | ws.serializeAttachment({ ...machine, name: message.machine } satisfies Machine); |
| 85 | await this.env.DB.prepare( |
| 86 | "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", |
| 87 | ) |
| 88 | .bind(machine.userId, message.machine, JSON.stringify(runtimes), String(message.version ?? "").slice(0, 32), now()) |
| 89 | .run(); |
| 90 | ws.send(JSON.stringify({ type: "welcome", machine: message.machine })); |
| 91 | return; |
| 92 | } |
| 93 | if (message.type === "ping") ws.send(PONG); |
| 94 | } |
| 95 | |
| 96 | async webSocketClose(ws: WebSocket): Promise<void> { |
| 97 | const machine = ws.deserializeAttachment() as Machine; |
| 98 | if (!machine.name) return; |
| 99 | const stillOpen = this.ctx.getWebSockets().some((socket) => socket !== ws && (socket.deserializeAttachment() as Machine).name === machine.name); |
| 100 | if (stillOpen) return; |
| 101 | const pinged = this.ctx.getWebSocketAutoResponseTimestamp(ws); |
| 102 | await this.env.DB.prepare("UPDATE machines SET connected = 0, last_seen_at = max(last_seen_at, ?) WHERE user_id = ? AND name = ?") |
| 103 | .bind(pinged ? Math.floor(pinged.getTime() / 1000) : 0, machine.userId, machine.name) |
| 104 | .run(); |
| 105 | } |
| 106 | |
| 107 | async webSocketError(ws: WebSocket): Promise<void> { |
| 108 | await this.webSocketClose(ws); |
| 109 | } |
| 110 | } |
| 111 | |
| 112 | const CAP_GRACE_MS = 5000; |
| 113 | |
| 114 | |
| 115 | /** |
| 116 | * One per repository. Holds the browser sockets watching the repository and its tasks, and tells them when a |
| 117 | * stream they watch moves. D1 stays the record: a hint carries no data, and the page reloads through its loaders. |
| 118 | */ |
| 119 | export class RepoHub extends DurableObject<Env> { |
| 120 | private readonly waiting = new Map<string, ((verdict: Verdict) => void)[]>(); |
| 121 | |
| 122 | constructor(ctx: DurableObjectState, env: Env) { |
| 123 | super(ctx, env); |
| 124 | ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong")); |
| 125 | } |
| 126 | |
| 127 | async fetch(request: Request): Promise<Response> { |
| 128 | const tags = (request.headers.get("x-refs-watch") ?? "").split(" ").filter(Boolean); |
| 129 | if (!tags.length || request.headers.get("upgrade")?.toLowerCase() !== "websocket") return new Response("Expected a live socket\n", { status: 400 }); |
| 130 | const [client, server] = Object.values(new WebSocketPair()); |
| 131 | this.ctx.acceptWebSocket(server, tags); |
| 132 | return new Response(null, { status: 101, webSocket: client }); |
| 133 | } |
| 134 | |
| 135 | async notify(hint: Omit<Hint, "repoId">): Promise<void> { |
| 136 | const message = JSON.stringify(hint); |
| 137 | for (const socket of this.ctx.getWebSockets(hint.stream)) { |
| 138 | try { |
| 139 | socket.send(message); |
| 140 | } catch {} |
| 141 | } |
| 142 | } |
| 143 | |
| 144 | /** |
| 145 | * Waits for a human's answer to a tool approval recorded in D1. A verdict already stored is returned at once, so an |
| 146 | * agent that retries after its request dropped picks it up. Otherwise the call parks until `decide` or the expiry alarm. |
| 147 | */ |
| 148 | async awaitDecision(repoId: string, session: string, requestId: string): Promise<Verdict> { |
| 149 | await this.ctx.storage.put("repo", repoId); |
| 150 | const key = `${session} ${requestId}`; |
| 151 | const answer = new Promise<Verdict>((resolve) => this.waiting.set(key, [...(this.waiting.get(key) ?? []), resolve])); |
| 152 | const row = await this.env.DB.prepare("SELECT behavior, created_at FROM permission_requests WHERE session_id = ? AND request_id = ?") |
| 153 | .bind(session, requestId) |
| 154 | .first<{ behavior: Verdict | null; created_at: number }>(); |
| 155 | if (!row || row.behavior) { |
| 156 | this.settle(key, row?.behavior ?? "expired"); |
| 157 | return answer; |
| 158 | } |
| 159 | const deadline = (row.created_at + APPROVAL_WAIT_SECONDS) * 1000; |
| 160 | const alarm = await this.ctx.storage.getAlarm(); |
| 161 | if (alarm === null || alarm > deadline) await this.ctx.storage.setAlarm(deadline); |
| 162 | const cap = setTimeout(() => void this.alarm().catch(() => undefined).finally(() => this.settle(key, "expired")), Math.max(0, deadline - Date.now()) + CAP_GRACE_MS); |
| 163 | try { |
| 164 | return await answer; |
| 165 | } finally { |
| 166 | clearTimeout(cap); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | /** Hands a verdict already written to D1 to whoever is waiting on it. */ |
| 171 | async decide(session: string, requestId: string, verdict: Verdict): Promise<void> { |
| 172 | this.settle(`${session} ${requestId}`, verdict); |
| 173 | } |
| 174 | |
| 175 | async alarm(): Promise<void> { |
| 176 | const repoId = await this.ctx.storage.get<string>("repo"); |
| 177 | if (!repoId) return; |
| 178 | const { expired, next } = await expirePermissions(this.env.DB, repoId, now()); |
| 179 | for (const { session_id, request_id } of expired) this.settle(`${session_id} ${request_id}`, "expired"); |
| 180 | if (expired.length) await this.notify({ latestId: 0, stream: repoStream(repoId) }); |
| 181 | if (next !== null) await this.ctx.storage.setAlarm(next * 1000); |
| 182 | } |
| 183 | |
| 184 | private settle(key: string, verdict: Verdict): void { |
| 185 | for (const resolve of this.waiting.get(key) ?? []) resolve(verdict); |
| 186 | this.waiting.delete(key); |
| 187 | } |
| 188 | |
| 189 | /** Closes the sockets carrying a tag, such as every anonymous viewer once the repository goes private. */ |
| 190 | async disconnect(tag: string): Promise<void> { |
| 191 | for (const socket of this.ctx.getWebSockets(tag)) socket.close(4403, "Access changed"); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /** The request's bindings, with a database that hints each repository's hub after every event it commits. */ |
| 196 | export function withHints(env: Env, ctx: ExecutionContext): Env { |
| 197 | return { ...env, DB: hinting(env.DB, ({ repoId, ...hint }) => ctx.waitUntil(env.REPO_HUB.get(env.REPO_HUB.idFromName(repoId)).notify(hint).catch(() => undefined))) }; |
| 198 | } |