An open-source, faster Devin alternative
TypeScript
edge alignment
Brian Reardonf625d88460ad
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex bcc01400..95dc3f9c 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -19,6 +19,7 @@export { CreditAccount } from "../../shared/credit_account";import { handleDashboard, type DashboardEnv } from "./dashboard";import * as secretStores from "./secret_stores";+import * as snapshots from "./snapshots";import * as templates from "./templates";export interface Env extends DashboardEnv {@@ -334,96 +335,139 @@ async function handlePreviewURL(// ── route handlers ───────────────────────────────────────────────────────-async function createSandbox(req: Request, env: Env): Promise<Response> {- const caller = await authenticate(req, env);- if (!caller) return json({ error: "missing or invalid API key" }, 401);+// OrgPolicy is the subset of the D1 `orgs` row the create/fork paths gate on.+interface OrgPolicy {+ home_cell: string;+ plan: string;+ is_halted: number;+ max_concurrent_sandboxes: number;+ max_disk_mb: number;+}- const org = await env.OPENCOMPUTER_DB.prepare(- "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes FROM orgs WHERE id = ?1",+// loadOrgPolicy reads an org's routing + policy fields from D1. Returns null+// when the org doesn't exist (callers 401).+async function loadOrgPolicy(env: Env, orgID: string): Promise<OrgPolicy | null> {+ return await env.OPENCOMPUTER_DB.prepare(+ "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb FROM orgs WHERE id = ?1",)- .bind(caller.orgID)- .first<{ home_cell: string; plan: string; is_halted: number; max_concurrent_sandboxes: number }>();- if (!org) return json({ error: "org not found" }, 401);+ .bind(orgID)+ .first<OrgPolicy>();+}++// enforceCreatePolicy applies every org-level gate for creating or forking a+// sandbox, reading authoritative state from D1 (and the CreditAccount DO for+// free orgs). Returns an error Response to short-circuit, or null when allowed.+//+// This is the edge's job post-cutover: cells are interchangeable executors+// that don't know about each other, so org policy can only be enforced+// correctly here. The concurrent limit especially — it's a count across the+// global sandboxes_index, and a per-cell count would let an org exceed its+// limit once its sandboxes spread across cells.+//+// `sizes` carries the caller-requested cpu/mem/disk; 0 means "unspecified"+// (inherit the checkpoint's value or the default), so size gates skip it —+// the defaults are always within limits.+async function enforceCreatePolicy(+ env: Env,+ orgID: string,+ org: OrgPolicy,+ sizes: { cpuCount: number; memoryMB: number; diskMB: number },+): Promise<Response | null> {const plan = org.plan === "pro" ? "pro" : "free";- // Gate on billing state BEFORE picking a cell. Free orgs hit the DO- // /check for an authoritative balance read; pro orgs skip the round trip.- // is_halted is a D1 fast path — if it's 1, we don't even need to ask the DO.+ // Free-tier billing gate. is_halted is the D1 fast path; otherwise ask the+ // CreditAccount DO for an authoritative balance read. Pro orgs skip this.if (plan === "free") {if (org.is_halted === 1) {return json({ error: "free trial credits exhausted — upgrade to resume" }, 402);}- const doID = env.CREDIT_ACCOUNT.idFromName(caller.orgID);- const doStub = env.CREDIT_ACCOUNT.get(doID);- const checkResp = await doStub.fetch(`https://do/check?org_id=${encodeURIComponent(caller.orgID)}`, {- method: "POST",- });+ const doStub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(orgID));+ const checkResp = await doStub.fetch(`https://do/check?org_id=${encodeURIComponent(orgID)}`, { method: "POST" });if (checkResp.status !== 200) {- // DO failure shouldn't soft-fail open — credit gating exists for a reason.- // If the DO is genuinely down we get a 5xx; surface that.+ // Don't soft-fail open — credit gating exists for a reason. A genuinely+ // down DO surfaces as a 5xx.return json({ error: "credit check unavailable" }, 503);}const check = await checkResp.json<{ allowed: boolean; balance_cents: number }>();if (!check.allowed) {return json({ error: "free trial credits exhausted — upgrade to resume", balance_cents: check.balance_cents }, 402);}- }-- // Read body once — used for the hard-pin peek + forwarded to the CP verbatim.- const bodyText = await req.text();- let requestedCellID: string | null = null;- let bodyCpuCount = 0;- let bodyMemoryMB = 0;- try {- if (bodyText) {- const parsed = JSON.parse(bodyText) as { cellId?: unknown; cpuCount?: unknown; memoryMB?: unknown };- if (typeof parsed.cellId === "string") requestedCellID = parsed.cellId;- if (typeof parsed.cpuCount === "number") bodyCpuCount = parsed.cpuCount;- if (typeof parsed.memoryMB === "number") bodyMemoryMB = parsed.memoryMB;+ // Free-tier ceilings: 4GB / 1 vCPU, 20GB disk.+ if (sizes.memoryMB > 4096 || sizes.cpuCount > 1) {+ return json({ error: "upgrade to pro for larger instances" }, 402);+ }+ if (sizes.diskMB > 20480) {+ return json({ error: "upgrade to pro for larger disk sizes" }, 402);}- } catch {- /* malformed JSON — let the CP reject with a proper 400 */}- // Org-policy gates that used to live on the cell's public createSandbox- // handler but were dropped from the edge-first internalCreateSandbox path- // during cutover. Enforce them here in the edge — D1 has all the data- // (org plan + max_concurrent_sandboxes + the active sandboxes_index- // count) so we don't need a cell round-trip.- //- // Free-tier instance size: customers on the free plan can't request- // bigger than 4GB / 1 vCPU. Pre-fix the limit was silently ignored at- // the edge-first path; free users could spin up 64GB / 16 vCPU- // instances at no cost.- if (plan === "free" && (bodyMemoryMB > 4096 || bodyCpuCount > 1)) {- return json({ error: "upgrade to pro for larger instances" }, 402);+ // Per-org disk ceiling (all plans). 0 in D1 means "use the 20GB default".+ if (sizes.diskMB > 0) {+ const maxDisk = org.max_disk_mb > 0 ? org.max_disk_mb : 20480;+ if (sizes.diskMB > maxDisk) {+ return json({ error: `disk size ${sizes.diskMB}MB exceeds org limit of ${maxDisk}MB` }, 403);+ }}- // Concurrent sandbox limit: count `running` only, matching legacy- // CountActiveSandboxes semantics (internal/db/store.go). Pre-fix this- // gate counted `running` + `hibernated`, which 429'd a heavy-hibernation- // workload — Mysten Labs had 157 hibernated + 1 running and got- // "limit reached (158/20)" even though only 1 was actually consuming- // worker capacity. Hibernated sandboxes live in S3 and don't count- // against compute capacity, only restore-on-wake potential.+ // Concurrent-sandbox limit (all plans). Counts `running` only — hibernated+ // sandboxes live in S3 and don't consume worker capacity. The count spans+ // every cell via the global sandboxes_index, which is the whole reason it+ // must live at the edge and not on any single cell.const limit = org.max_concurrent_sandboxes ?? 5;const countRow = await env.OPENCOMPUTER_DB.prepare("SELECT COUNT(*) AS n FROM sandboxes_index WHERE org_id = ?1 AND status = 'running'",)- .bind(caller.orgID)+ .bind(orgID).first<{ n: number }>();const active = countRow?.n ?? 0;if (active >= limit) {return json(- {- error: `concurrent sandbox limit reached (${active}/${limit}) — hibernate or delete one before creating another`,- active,- limit,- },+ { error: `concurrent sandbox limit reached (${active}/${limit}) — hibernate or delete one before creating another`, active, limit },429,);}+ return null;+}++async function createSandbox(req: Request, env: Env): Promise<Response> {+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);++ const org = await loadOrgPolicy(env, caller.orgID);+ if (!org) return json({ error: "org not found" }, 401);+ const plan = org.plan === "pro" ? "pro" : "free";++ // Read body once — used for size-gating, the hard-pin cell peek, and the+ // verbatim forward to the CP.+ const bodyText = await req.text();+ let requestedCellID: string | null = null;+ let bodyCpuCount = 0;+ let bodyMemoryMB = 0;+ let bodyDiskMB = 0;+ try {+ if (bodyText) {+ const parsed = JSON.parse(bodyText) as { cellId?: unknown; cpuCount?: unknown; memoryMB?: unknown; diskMB?: unknown };+ if (typeof parsed.cellId === "string") requestedCellID = parsed.cellId;+ if (typeof parsed.cpuCount === "number") bodyCpuCount = parsed.cpuCount;+ if (typeof parsed.memoryMB === "number") bodyMemoryMB = parsed.memoryMB;+ if (typeof parsed.diskMB === "number") bodyDiskMB = parsed.diskMB;+ }+ } catch {+ /* malformed JSON — let the CP reject with a proper 400 */+ }++ // Every org-policy gate (billing, instance size, disk, concurrency) is+ // enforced here against D1. Cells trust the cap-token and no longer+ // re-check — see enforceCreatePolicy for why the concurrent limit in+ // particular can only be correct at the edge.+ const gate = await enforceCreatePolicy(env, caller.orgID, org, {+ cpuCount: bodyCpuCount,+ memoryMB: bodyMemoryMB,+ diskMB: bodyDiskMB,+ });+ if (gate) return gate;+const cell = await pickCell(env, org.home_cell, requestedCellID);if (!cell) {return json(@@ -435,6 +479,28 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {}const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, caller.userID);++ // SSE build streaming: image/snapshot creates can take minutes (apt installs,+ // etc.). When the client asks for an event stream, forward the Accept header+ // and stream the cell's SSE response straight through — build logs reach the+ // client live and the final `result` event is delivered intact. Buffering+ // with .text() (the non-SSE path below) collapsed the stream to one blob,+ // which broke the Python SDK ("No result received from build stream"). The+ // sandboxes_index row is populated by the cell's `created` event via the+ // events pipeline, so we don't need the inline INSERT on this path.+ const wantsSSE = req.headers.get("accept") === "text/event-stream";+ if (wantsSSE) {+ try {+ return await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {+ method: "POST",+ headers: { authorization: "Bearer " + capToken, "content-type": "application/json", accept: "text/event-stream" },+ body: bodyText || "{}",+ });+ } catch (e) {+ return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);+ }+ }+let cpResp: Response;try {cpResp = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {@@ -665,6 +731,60 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, calreturn resp;}+// proxyToCellAuthed forwards an authenticated SDK/CLI request to a cell with an+// edge-minted cap-token, replacing the caller's X-API-Key (which the cell can no+// longer validate — api_keys live in D1 post-cutover). The response is streamed+// through unbuffered, so SSE build-log streams (image/snapshot create) flow to+// the client frame-by-frame instead of being collapsed to a single JSON blob.+//+// Routing:+// - opts.cellId set → route to that specific cell (e.g. owner_cell_id of a+// snapshot being deleted; correct in a multi-cell world where the resource+// lives in one cell only).+// - opts.cellId unset → route to the org's home_cell (new-resource creates).+//+// This single helper is the backstop for every SDK route that doesn't have a+// dedicated D1-native handler: it gives correct auth + routing + streaming+// without the caller's key ever reaching the cell.+async function proxyToCellAuthed(+ req: Request,+ env: Env,+ caller: Caller,+ opts: { cellId?: string; pathOverride?: string } = {},+): Promise<Response> {+ const org = await env.OPENCOMPUTER_DB.prepare(+ "SELECT home_cell, plan FROM orgs WHERE id = ?1",+ ).bind(caller.orgID).first<{ home_cell: string; plan: string }>();+ if (!org) return json({ error: "org not found" }, 401);+ const plan = org.plan === "pro" ? "pro" : "free";++ const cell = opts.cellId+ ? await lookupCell(env, opts.cellId)+ : await pickCell(env, org.home_cell, null);+ if (!cell) return json({ error: "no cell available to serve request" }, 503);++ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, caller.userID);+ const url = new URL(req.url);+ const target = cell.base_url.replace(/\/$/, "") + (opts.pathOverride ?? url.pathname) + url.search;++ // Forward all headers except the ones the cell shouldn't see: the raw+ // X-API-Key (replaced by the cap-token), the browser cookie, and CF's+ // hop-by-hop headers. WebSocket upgrades pass through transparently.+ const headers = new Headers(req.headers);+ headers.delete("x-api-key");+ headers.delete("cookie");+ headers.set("authorization", "Bearer " + token);+ if (isWebSocketUpgrade(req)) {+ const fwd = new Request(target, req);+ fwd.headers.set("authorization", "Bearer " + token);+ fwd.headers.delete("x-api-key");+ return await fetch(fwd);+ }+ const init: RequestInit = { method: req.method, headers, redirect: "manual" };+ if (req.method !== "GET" && req.method !== "HEAD") init.body = req.body;+ return fetch(target, init);+}+// ── /internal/halt-list ─────────────────────────────────────────────────@@ -716,6 +836,42 @@ async function haltList(req: Request, env: Env): Promise<Response> {});}+// ── /internal/org-policy ──────────────────────────────────────────────────++// HMAC-auth'd endpoint the cell pulls for an org's authoritative billing+// policy from D1. The autoscaler loop runs in-process on the cell with no+// request or cap-token to ride, so it can't get a fresh plan the way the+// resize handlers do (they read it off the cap-token). D1 is the source of+// truth for plan post-cutover — the cell's create-time-stamped cell-PG copy+// goes stale on upgrade/downgrade — so the autoscaler asks here before+// growing a sandbox past the free-tier ceiling. Same HMAC scheme as haltList.+async function orgPolicy(req: Request, env: Env): Promise<Response> {+ const ts = req.headers.get("X-Timestamp") ?? "";+ const sig = req.headers.get("X-Signature") ?? "";+ if (!ts || !sig) return json({ error: "missing signature headers" }, 400);+ const tsNum = Number.parseInt(ts, 10);+ if (!Number.isFinite(tsNum)) return json({ error: "invalid timestamp" }, 400);+ const now = Math.floor(Date.now() / 1000);+ if (Math.abs(now - tsNum) > 5 * 60) return json({ error: "timestamp out of window" }, 401);++ const url = new URL(req.url);+ const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}`);+ if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);++ const orgID = url.searchParams.get("org_id") ?? "";+ if (!orgID) return json({ error: "missing org_id" }, 400);+ const row = await env.OPENCOMPUTER_DB.prepare(+ "SELECT plan, max_memory_gb FROM orgs WHERE id = ?1",+ )+ .bind(orgID)+ .first<{ plan: string; max_memory_gb: number }>();+ if (!row) return json({ error: "org not found" }, 404);+ return json({+ plan: row.plan === "pro" ? "pro" : "free",+ maxMemoryMb: (row.max_memory_gb ?? 0) * 1024,+ });+}+async function hmacHex(secret: string, data: string): Promise<string> {const key = await crypto.subtle.importKey("raw",@@ -1119,6 +1275,11 @@ export default {return haltList(req, env);}+ if (path === "/internal/org-policy") {+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);+ return orgPolicy(req, env);+ }+// /internal/admin/do-mark-free — operator-only escape hatch to flip a// CreditAccount DO's internal plan from "pro" back to "free" without// running a real Stripe subscription.deleted webhook. HMAC-auth'd with@@ -1209,6 +1370,44 @@ export default {}}+ // ── Snapshots + images (SDK/CLI, X-API-Key) ─────────────────────────+ // A snapshot is a named image; both are mirrored into D1 images_index.+ // Reads serve straight from D1 (no cell hop, multi-cell correct, survive+ // an owning-cell outage). Create routes to the org home_cell with SSE+ // build-log streaming. Delete routes to the cell that owns the bytes.+ if (path === "/api/snapshots") {+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ if (req.method === "GET") return snapshots.listSnapshots(env, caller);+ if (req.method === "POST") return proxyToCellAuthed(req, env, caller); // build → home_cell, SSE+ return json({ error: "method not allowed" }, 405);+ }+ {+ // /api/snapshots/:name and /api/snapshots/:name/patches[/:patchId]+ const m = path.match(/^\/api\/snapshots\/([^/]+)(\/patches(?:\/[^/]+)?)?$/);+ if (m) {+ const name = decodeURIComponent(m[1]);+ const isPatch = !!m[2];+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ // Patches + delete are cell-work — route to the cell that owns the+ // snapshot bytes (looked up from D1), not "any active cell".+ if (isPatch || req.method === "DELETE") {+ const ownerCell = await snapshots.ownerCellOfSnapshot(env, caller, name);+ if (!ownerCell) return json({ error: "snapshot not found" }, 404);+ return proxyToCellAuthed(req, env, caller, { cellId: ownerCell });+ }+ if (req.method === "GET") return snapshots.getSnapshot(env, caller, name);+ return json({ error: "method not allowed" }, 405);+ }+ }+ if (path === "/api/images") {+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ if (req.method === "GET") return snapshots.listImages(env, caller);+ return json({ error: "method not allowed" }, 405);+ }+// Auth flow (browser).if (path === "/auth/login") { if (req.method === "GET") return authLogin(req, env); }if (path === "/auth/callback") { if (req.method === "GET") return authCallback(req, env); }@@ -1253,24 +1452,32 @@ export default {if (cpRow.org_id !== caller.orgID) return json({ error: "checkpoint not in your org" }, 403);const cell = await lookupCell(env, cpRow.owner_cell_id);if (!cell) return json({ error: `cell ${cpRow.owner_cell_id} not registered` }, 503);- const orgRow = await env.OPENCOMPUTER_DB.prepare("SELECT plan FROM orgs WHERE id = ?1")- .bind(caller.orgID).first<{ plan: string }>();- const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, orgRow?.plan ?? "free", caller.userID);- // Read the body so we can both forward it and record cpu/mem, then+ const org = await loadOrgPolicy(env, caller.orgID);+ if (!org) return json({ error: "org not found" }, 401);+ // Read the body so we can size-gate, forward it, and record cpu/mem to// register the forked sandbox in sandboxes_index — same as createSandbox.- // Without this, forked sandboxes run on the cell but are invisible to the- // edge (exec/delete/get 404), since the row is otherwise only INSERTed on- // the POST /api/sandboxes create path.+ // Without the index row, forked sandboxes run on the cell but are+ // invisible to the edge (exec/delete/get 404).const fcBody = await req.text();let fcCpu = 0;let fcMem = 0;+ let fcDisk = 0;try {const b = JSON.parse(fcBody || "{}");if (typeof b.cpuCount === "number") fcCpu = b.cpuCount;if (typeof b.memoryMB === "number") fcMem = b.memoryMB;+ if (typeof b.diskMB === "number") fcDisk = b.diskMB;} catch {/* malformed JSON — let the CP reject */}+ // Edge-authoritative org-policy gate, same as createSandbox. Forks were+ // previously ungated at the edge and leaned on a cell-side concurrent+ // check that read stale cell PG and could only ever count one cell's+ // sandboxes — wrong once an org spans cells. Enforce from D1 here.+ const fcGate = await enforceCreatePolicy(env, caller.orgID, org, { cpuCount: fcCpu, memoryMB: fcMem, diskMB: fcDisk });+ if (fcGate) return fcGate;+ const plan = org.plan === "pro" ? "pro" : "free";+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, plan, caller.userID);const fcResp = await fetch(cell.base_url.replace(/\/$/, "") + path, {method: "POST",headers: { authorization: "Bearer " + token, "content-type": "application/json" },@@ -1333,28 +1540,18 @@ export default {return proxyToCellSDK(req, env, ctx, caller, id);}- // Generic /api/* fallback proxy — routes unmatched dashboard endpoints- // (/api/images, /api/sessions, /api/me, /api/workers, /api/checkpoints,- // /api/api-keys, /api/org*, /api/agents, /api/billing*, etc.) to the- // home cell's CP. These were served by the CP pre-cutover; the edge- // doesn't have native handlers for them yet. The CP does its own auth- // (X-API-Key or session JWT) — we just pass through.+ // Generic /api/* fallback for SDK/CLI routes without a dedicated D1-native+ // handler yet (/api/usage, /api/tags, /api/capacity/*, /api/workers,+ // /api/sessions, checkpoint patches, etc.). Authenticate against D1, mint a+ // cap-token, and route to the org's home_cell. Pre-fix this forwarded the+ // raw X-API-Key to "any active cell" — which 403'd because the cell can no+ // longer validate D1-only api_keys, and would mis-route in a multi-cell+ // world. proxyToCellAuthed streams the response (SSE-safe). This is a+ // backstop; prefer adding a native handler for high-traffic resources.if (path.startsWith("/api/")) {- const cellRow = await env.OPENCOMPUTER_DB.prepare(- `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at- FROM cells WHERE status = 'active' LIMIT 1`,- ).first<CellRow>();- if (!cellRow) return json({ error: "no active cell" }, 503);- const target = cellRow.base_url.replace(/\/$/, "") + url.pathname + url.search;- const proxyHeaders = new Headers(req.headers);- proxyHeaders.set("X-Forwarded-Host", url.host);- const proxyReq = new Request(target, {- method: req.method,- headers: proxyHeaders,- body: ["GET", "HEAD"].includes(req.method) ? null : req.body,- redirect: "manual",- });- return fetch(proxyReq);+ const caller = await authenticate(req, env);+ if (!caller) return json({ error: "missing or invalid API key" }, 401);+ return proxyToCellAuthed(req, env, caller);}// Anything not matched above is the dashboard SPA — delegate to thediff --git a/cloudflare-workers/api-edge/src/snapshots.ts b/cloudflare-workers/api-edge/src/snapshots.tsnew file mode 100644index 00000000..11a0ce75--- /dev/null+++ b/cloudflare-workers/api-edge/src/snapshots.ts@@ -0,0 +1,97 @@+// Edge-native snapshot + image reads. Snapshots and images are both backed by+// the cell's image_cache table, mirrored into D1's images_index by the+// events-ingest worker (image_cache_ready / image_cache_deleted events).+// A "snapshot" is just a *named* image. Because D1 is the global source of+// truth, the edge serves list/get directly — no cell round-trip, works across+// any number of cells, and survives an owning-cell outage.+//+// Create + delete are cell-work (build bytes / delete bytes) and route to a+// cell via proxyToCellAuthed in index.ts.++export interface SnapshotsEnv {+ OPENCOMPUTER_DB: D1Database;+}++interface Caller {+ orgID: string;+ userID: string | null;+}++interface ImageRow {+ id: string;+ org_id: string;+ owner_cell_id: string;+ content_hash: string;+ checkpoint_id: string | null;+ name: string | null;+ manifest: string | null;+ status: string;+ created_at: number;+ last_used_at: number;+}++function json(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });+}++// rowToJSON maps an images_index row to the shape the TS/Python SDKs unmarshal+// (SnapshotInfo / ImageCacheItem) — camelCase, ISO timestamps, parsed manifest.+function rowToJSON(r: ImageRow): Record<string, unknown> {+ let manifest: unknown = {};+ if (r.manifest) {+ try { manifest = JSON.parse(r.manifest); } catch { /* leave {} */ }+ }+ return {+ id: r.id,+ orgId: r.org_id,+ cellId: r.owner_cell_id,+ contentHash: r.content_hash,+ checkpointId: r.checkpoint_id ?? undefined,+ name: r.name ?? undefined,+ manifest,+ status: r.status,+ createdAt: new Date(r.created_at * 1000).toISOString(),+ lastUsedAt: new Date(r.last_used_at * 1000).toISOString(),+ };+}++const SELECT_COLS =+ "id, org_id, owner_cell_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at";++// GET /api/snapshots — named images only (a snapshot is a named image).+export async function listSnapshots(env: SnapshotsEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT ${SELECT_COLS} FROM images_index+ WHERE org_id = ?1 AND name IS NOT NULL AND name <> ''+ ORDER BY created_at DESC LIMIT 200`,+ ).bind(caller.orgID).all<ImageRow>();+ return json((results ?? []).map(rowToJSON));+}++// GET /api/snapshots/:name+export async function getSnapshot(env: SnapshotsEnv, caller: Caller, name: string): Promise<Response> {+ const row = await env.OPENCOMPUTER_DB.prepare(+ `SELECT ${SELECT_COLS} FROM images_index WHERE org_id = ?1 AND name = ?2 LIMIT 1`,+ ).bind(caller.orgID, name).first<ImageRow>();+ if (!row) return json({ error: "snapshot not found" }, 404);+ return json(rowToJSON(row));+}++// GET /api/images — all images for the org (named + auto-cached).+export async function listImages(env: SnapshotsEnv, caller: Caller): Promise<Response> {+ const { results } = await env.OPENCOMPUTER_DB.prepare(+ `SELECT ${SELECT_COLS} FROM images_index+ WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,+ ).bind(caller.orgID).all<ImageRow>();+ return json((results ?? []).map(rowToJSON));+}++// ownerCellOfSnapshot looks up which cell owns a named snapshot so a+// delete/patch can route to the cell holding the bytes. Returns null if the+// snapshot isn't in D1 (caller gets 404 upstream).+export async function ownerCellOfSnapshot(env: SnapshotsEnv, caller: Caller, name: string): Promise<string | null> {+ const row = await env.OPENCOMPUTER_DB.prepare(+ `SELECT owner_cell_id FROM images_index WHERE org_id = ?1 AND name = ?2 LIMIT 1`,+ ).bind(caller.orgID, name).first<{ owner_cell_id: string }>();+ return row?.owner_cell_id ?? null;+}diff --git a/internal/api/image_builder.go b/internal/api/image_builder.goindex 04f7c81c..af6e2b2b 100644--- a/internal/api/image_builder.go+++ b/internal/api/image_builder.go@@ -246,6 +246,12 @@ func (s *Server) resolveImageManifest(ctx context.Context, orgID uuid.UUID, manilog.Printf("image-builder: failed to set name %q on cache entry: %v", manifest.Name, err)} else {log.Printf("image-builder: named cache entry %s as %q", cached.ID, manifest.Name)+ // Mirror the new name to D1 images_index. SetImageCacheName+ // only touches cell PG; image_cache_ready is the sole writer+ // of the images_index name, so re-emit with the updated row.+ name := manifest.Name+ cached.Name = &name+ s.publishImageCacheReadyFrom(ctx, cached)}}log.Printf("image-builder: cache hit for hash %s (checkpoint=%s)", contentHash[:12], cached.CheckpointID)@@ -310,6 +316,15 @@ func (s *Server) resolveImageManifest(ctx context.Context, orgID uuid.UUID, maniManifest: manifestJSON,Status: "building",}+ // Persist the snapshot name so it propagates to D1 images_index via the+ // image_cache_ready event below. Without this, a named build lands in+ // images_index with name=null and is invisible to GET /api/snapshots+ // (the content hash deliberately excludes Name, so the name only lives+ // on the row, not the hash).+ if manifest.Name != "" {+ name := manifest.Name+ ic.Name = &name+ }if err := s.store.CreateImageCache(ctx, ic); err != nil {// Might conflict with concurrent insert — try to read existingcached, readErr := s.store.GetImageCacheByHash(ctx, orgID, contentHash)diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.goindex 64f0bb32..d2d3228c 100644--- a/internal/api/internal_sandbox.go+++ b/internal/api/internal_sandbox.go@@ -1,7 +1,6 @@package apiimport (- "fmt""net/http""strings"@@ -53,6 +52,7 @@ func (s *Server) capTokenMiddleware(next echo.HandlerFunc) echo.HandlerFunc {auth.SetUserID(c, uid)}}+ auth.SetPlan(c, claims.Plan)return next(c)}}@@ -125,32 +125,18 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})}- // Disk size validation. Pre-fix any value was accepted — customer could- // pass diskMB=1 (boot fails opaquely) or diskMB=10_000_000 (allocates- // 10TB of storage per sandbox). Mirrors internal/api/sandbox.go bounds.+ // Physical disk bounds. These are hardware/safety limits, not org policy:+ // diskMB=1 boots-fail opaquely, diskMB=10_000_000 would allocate 10TB per+ // sandbox. Per-org disk ceilings (free-tier cap, custom max_disk_mb) are+ // enforced at the edge against D1 — see enforceCreatePolicy in+ // cloudflare-workers/api-edge/src/index.ts. The cell trusts the cap-token+ // and only checks these physical bounds.if cfg.DiskMB < 20480 {return c.JSON(http.StatusBadRequest, map[string]string{"error": "diskMB must be at least 20480 (20GB)"})}if cfg.DiskMB > 262144 {return c.JSON(http.StatusBadRequest, map[string]string{"error": "diskMB cannot exceed 262144 (256GB)"})}- // Per-org disk gates: free-tier capped at 20GB, paid orgs may have a- // custom max_disk_mb. Look up the cell-local org (upserted at top of- // this handler from the cap-token claims).- if s.store != nil {- if org, oerr := s.store.GetOrg(c.Request().Context(), orgID); oerr == nil && org != nil {- if org.Plan == "free" && cfg.DiskMB > 20480 {- return c.JSON(http.StatusPaymentRequired, map[string]string{"error": "upgrade to pro for larger disk sizes"})- }- maxDisk := org.MaxDiskMB- if maxDisk == 0 {- maxDisk = 20480- }- if cfg.DiskMB > maxDisk {- return c.JSON(http.StatusForbidden, map[string]string{"error": fmt.Sprintf("disk size %dMB exceeds org limit of %dMB", cfg.DiskMB, maxDisk)})- }- }- }// Declarative image or named snapshot → resolve to a checkpoint and use// the createFromCheckpoint flow. Mirrors the public createSandbox handler@@ -162,6 +148,17 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {// reproducing with a `run` step that touched a marker file: file was// missing on the resulting sandbox.if len(cfg.ImageManifest) > 0 || cfg.Snapshot != "" {+ // SSE: when the client asks for an event stream (both SDKs do for+ // image/snapshot builds), delegate to createSandboxWithSSE so build+ // logs stream live and a final `result` event is emitted. The edge+ // streams this response straight through. Pre-fix this path always+ // returned a single JSON blob, so the Python SDK — which strictly+ // expects an SSE `result` event — failed with "No result received+ // from build stream" (the TS SDK happened to tolerate the JSON).+ if c.Request().Header.Get("Accept") == "text/event-stream" {+ return s.createSandboxWithSSE(c, c.Request().Context(), orgID, cfg)+ }+var checkpointID uuid.UUIDvar err errorif cfg.Snapshot != "" {diff --git a/internal/api/sandbox.go b/internal/api/sandbox.goindex 6ce8da5c..84db9b1b 100644--- a/internal/api/sandbox.go+++ b/internal/api/sandbox.go@@ -1168,6 +1168,23 @@ func (s *Server) migrateSandbox(c echo.Context) error {})}+// effectivePlan returns the org's billing plan for org-policy gates. It+// prefers the value the edge stamped into the cap-token (authoritative, fresh+// from D1) and falls back to the cell-local orgs row for legacy direct-to-cell+// callers that authenticate with a raw API key (no cap-token). Returns "" when+// neither source is available, in which case callers should not gate.+func (s *Server) effectivePlan(c echo.Context, orgID uuid.UUID) string {+ if plan, ok := auth.GetPlan(c); ok {+ return plan+ }+ if s.store != nil {+ if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil && org != nil {+ return org.Plan+ }+ }+ return ""+}+func (s *Server) setLimits(c echo.Context) error {id := c.Param("id")ctx := c.Request().Context()@@ -1193,14 +1210,13 @@ func (s *Server) setLimits(c echo.Context) error {}}- // Free tier: block scaling beyond 4GB / 1 vCPU- if orgID, hasOrg := auth.GetOrgID(c); hasOrg && s.store != nil {- if org, err := s.store.GetOrg(ctx, orgID); err == nil && org.Plan == "free" {- if req.MemoryMB > 4096 || req.CPUPercent > 100 {- return c.JSON(http.StatusPaymentRequired, map[string]string{- "error": "upgrade to pro for larger instances",- })- }+ // Free tier: block scaling beyond 4GB / 1 vCPU. Plan comes from the+ // cap-token (edge-authoritative) when present, else the cell-PG copy.+ if orgID, hasOrg := auth.GetOrgID(c); hasOrg {+ if s.effectivePlan(c, orgID) == "free" && (req.MemoryMB > 4096 || req.CPUPercent > 100) {+ return c.JSON(http.StatusPaymentRequired, map[string]string{+ "error": "upgrade to pro for larger instances",+ })}}@@ -1250,14 +1266,13 @@ func (s *Server) scaleSandbox(c echo.Context) error {return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})}- // Free tier: block scaling beyond 4GB / 1 vCPU- if orgID, hasOrg := auth.GetOrgID(c); hasOrg && s.store != nil {- if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil && org.Plan == "free" {- if req.MemoryMB > 4096 {- return c.JSON(http.StatusPaymentRequired, map[string]string{- "error": "upgrade to pro for larger instances",- })- }+ // Free tier: block scaling beyond 4GB. Plan comes from the cap-token+ // (edge-authoritative) when present, else the cell-PG copy.+ if orgID, hasOrg := auth.GetOrgID(c); hasOrg {+ if s.effectivePlan(c, orgID) == "free" && req.MemoryMB > 4096 {+ return c.JSON(http.StatusPaymentRequired, map[string]string{+ "error": "upgrade to pro for larger instances",+ })}}@@ -2414,21 +2429,12 @@ func (s *Server) createFromCheckpointCore(c echo.Context, userEnvs map[string]streturn nil, http.StatusUnauthorized, fmt.Errorf("org context required")}- // Enforce per-org concurrency limit on the fork path, mirroring the gate- // in the direct-create path at the top of CreateSandbox (around line 50).- // Without this, callers using POST /api/sandboxes/from-checkpoint/<id>- // (i.e. `oc checkpoint spawn` and equivalent SDK calls) can fork unbounded- // sandboxes past their plan's max_concurrent_sandboxes — every other- // per-plan gate (free-tier credits, machine size, disk size) is also- // missing on this path, but concurrency is the load-bearing one because- // it directly drives runaway billing.- //- // Fail-open on DB errors to match the existing direct-create behavior.- if org, gerr := s.store.GetOrg(ctx, orgID); gerr == nil {- if count, cerr := s.store.CountActiveSandboxes(ctx, orgID); cerr == nil && count >= org.MaxConcurrentSandboxes {- return nil, http.StatusTooManyRequests, fmt.Errorf("concurrent sandbox limit reached")- }- }+ // Org-policy gates (concurrency, plan tier, disk) are enforced at the edge+ // against D1 before this request is dispatched — see enforceCreatePolicy in+ // cloudflare-workers/api-edge/src/index.ts. A cell can only count its own+ // sandboxes, so a per-cell concurrency check is wrong once an org spans+ // cells; the edge counts the global sandboxes_index instead. This handler+ // trusts the cap-token and only validates physical bounds downstream.checkpointID, err := uuid.Parse(checkpointIDStr)if err != nil {diff --git a/internal/api/sandbox_autoscale.go b/internal/api/sandbox_autoscale.goindex 6a56b14e..038434e9 100644--- a/internal/api/sandbox_autoscale.go+++ b/internal/api/sandbox_autoscale.go@@ -68,13 +68,12 @@ func (s *Server) setAutoscale(c echo.Context) error {// Without this a free-tier user could PUT max=16GB and the// autoscaler would obediently scale them past their plan. Mirror the// same check we apply in scaleSandbox so the two paths can't diverge.+ // Plan comes from the cap-token (edge-authoritative) when present.if orgID, hasOrg := auth.GetOrgID(c); hasOrg {- if org, err := s.store.GetOrg(c.Request().Context(), orgID); err == nil && org.Plan == "free" {- if req.MaxMemoryMB > 4096 {- return c.JSON(http.StatusPaymentRequired, map[string]string{- "error": "free plan caps autoscale at 4096 MB — upgrade to pro for larger instances",- })- }+ if s.effectivePlan(c, orgID) == "free" && req.MaxMemoryMB > 4096 {+ return c.JSON(http.StatusPaymentRequired, map[string]string{+ "error": "free plan caps autoscale at 4096 MB — upgrade to pro for larger instances",+ })}}}@@ -153,12 +152,26 @@ func (a *AutoscalerSetter) SetSandboxMemoryMB(ctx context.Context, sandboxID strreturn nil}- // Defense in depth: re-check the org plan cap here in case the autoscale- // row was set before a downgrade or the cap was raised by another path.- // The PUT /autoscale handler already enforces this; this is the second- // gate so an obsolete row can't keep scaling past plan limits.- if org, err := a.server.store.GetOrg(ctx, session.OrgID); err == nil && org.Plan == "free" && memoryMB > 4096 {- return fmt.Errorf("plan cap: free plan limited to 4096 MB, refusing autoscale to %d", memoryMB)+ // Plan cap: the autoscaler runs in-process with no cap-token to read plan+ // from, so it asks the edge (D1 authority) before growing past the+ // free-tier ceiling. The cell-PG plan copy is stamped at create and goes+ // stale on upgrade/downgrade, so it can't be trusted here. Only >4GB+ // growth needs confirmation; staying within free tier is always allowed.+ // Fail closed: if we can't confirm the org is pro, don't grow — the+ // sandbox keeps its current size and the autoscaler retries next tick.+ if memoryMB > 4096 {+ if a.server.edge != nil {+ pol, err := a.server.edge.GetOrgPolicy(ctx, session.OrgID)+ if err != nil {+ return fmt.Errorf("autoscale plan check: edge org-policy unavailable: %w", err)+ }+ if pol.Plan == "free" {+ return fmt.Errorf("plan cap: free plan limited to 4096 MB, refusing autoscale to %d", memoryMB)+ }+ } else if org, err := a.server.store.GetOrg(ctx, session.OrgID); err == nil && org.Plan == "free" {+ // No edge client (legacy single-cell mode): fall back to cell PG.+ return fmt.Errorf("plan cap: free plan limited to 4096 MB, refusing autoscale to %d", memoryMB)+ }}client, err := a.server.workerRegistry.GetWorkerClient(session.WorkerID)diff --git a/internal/auth/middleware.go b/internal/auth/middleware.goindex 0a6166ef..6856da5a 100644--- a/internal/auth/middleware.go+++ b/internal/auth/middleware.go@@ -16,6 +16,10 @@ const (ContextKeyOrgID contextKey = "org_id"// ContextKeyUserID is the echo context key for the authenticated user ID.ContextKeyUserID contextKey = "user_id"+ // ContextKeyPlan is the echo context key for the org's billing plan, when+ // the request carried an edge-minted cap-token (which stamps the plan from+ // D1 at mint time). Absent for direct API-key auth.+ ContextKeyPlan contextKey = "plan")// SetOrgID stores the org ID in the echo context.@@ -38,6 +42,30 @@ func SetUserID(c echo.Context, userID uuid.UUID) {c.Set(string(ContextKeyUserID), userID)}+// SetPlan stores the org's billing plan (from an edge-minted cap-token) in the+// echo context. Empty strings are ignored so a later authoritative value isn't+// clobbered by an absent one.+func SetPlan(c echo.Context, plan string) {+ if plan != "" {+ c.Set(string(ContextKeyPlan), plan)+ }+}++// GetPlan retrieves the cap-token-supplied plan from the echo context. The+// bool is false when the request didn't carry a plan (e.g. direct API-key+// auth), so callers can fall back to a cell-PG lookup.+func GetPlan(c echo.Context) (string, bool) {+ v := c.Get(string(ContextKeyPlan))+ if v == nil {+ return "", false+ }+ p, ok := v.(string)+ if !ok || p == "" {+ return "", false+ }+ return p, true+}+// GetUserID retrieves the user ID from the echo context. Returns nil if not set.func GetUserID(c echo.Context) *uuid.UUID {v := c.Get(string(ContextKeyUserID))@@ -107,6 +135,12 @@ func PGAPIKeyMiddleware(store *db.Store, staticKey string, jwtIssuer *JWTIssuer,SetUserID(c, uid)}}+ // The cap-token carries the org's plan, stamped from D1+ // at mint time. Stash it so org-policy gates (resize,+ // autoscale) enforce against this authoritative value+ // instead of the cell-PG copy, which goes stale on+ // plan changes between sandbox creates.+ SetPlan(c, claims.Plan)return next(c)}}diff --git a/internal/edgeclient/client.go b/internal/edgeclient/client.goindex bab762f6..9f0abb96 100644--- a/internal/edgeclient/client.go+++ b/internal/edgeclient/client.go@@ -174,6 +174,37 @@ func (c *Client) LookupTemplate(ctx context.Context, orgID uuid.UUID, name strinreturn et.toDB()}+// ── Org policy ─────────────────────────────────────────────────────────++// OrgPolicy is an org's authoritative billing policy, read from D1 by the+// edge. The CP autoscaler pulls this before growing a sandbox past the+// free-tier ceiling — it runs in-process with no cap-token to read plan from,+// and the cell-PG plan copy (stamped at create) goes stale on plan changes.+type OrgPolicy struct {+ Plan string `json:"plan"` // "free" | "pro"+ MaxMemoryMB int `json:"maxMemoryMb"` // 0 = no custom cap+}++// GetOrgPolicy fetches an org's plan + memory cap from the edge.+func (c *Client) GetOrgPolicy(ctx context.Context, orgID uuid.UUID) (*OrgPolicy, error) {+ q := "/internal/org-policy?org_id=" + escapeQuery(orgID.String())+ body, status, err := c.do(ctx, "GET", q, nil)+ if err != nil {+ return nil, err+ }+ if status == 404 {+ return nil, ErrNotFound+ }+ if status != 200 {+ return nil, fmt.Errorf("edge status %d: %s", status, string(body))+ }+ var p OrgPolicy+ if err := json.Unmarshal(body, &p); err != nil {+ return nil, fmt.Errorf("decode org-policy: %w", err)+ }+ return &p, nil+}+// RegisterTemplate inserts a template row in D1. Called from the CP's "save// sandbox as template" flow after the rootfs + workspace are uploaded to// Tigris. The id field is honored if non-Nil (so the CP can reuse one it