Skip to content

An open-source, faster Devin alternative

TypeScript

Add Autumn prepaid billing

Brian Reardon53d662f85e33
diff --git a/cloudflare-workers/api-edge/assets b/cloudflare-workers/api-edge/assets
deleted file mode 120000
index 31e65a1d..00000000
--- a/cloudflare-workers/api-edge/assets
+++ /dev/null
@@ -1 +0,0 @@
-/Users/brian/development/opencomputer/web/dist
\ No newline at end of file
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.ts
new file mode 100644
index 00000000..72c7c972
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts
@@ -0,0 +1,497 @@
+// Autumn (useautumn.com) webhook handler — the edge projection of Autumn's
+// authoritative billing state into D1, replacing the CreditAccount DO.
+//
+// Delivery is Svix. We verify the Svix signature, then follow the locked
+// "re-check, not payload" design: the ONLY field we read from the body is
+// data.customer_id (= our org id). We then GET the customer from Autumn and
+// project the *authoritative* balance + plans into D1:
+// - orgs.is_halted / halted_at (credits balance <= 0)
+// - orgs.max_concurrent_sandboxes (highest active concurrency plan)
+// On a halt/resume transition we dispatch /admin/halt-org or /admin/resume-org
+// to the cells running the org's sandboxes (same HMAC scheme the DO used).
+//
+// Event catalog (Svix): billing.updated, billing.auto_topup_succeeded,
+// balances.limit_reached, balances.usage_alert_triggered. customer.products.updated
+// is Deprecated and ignored. Because we always re-check, every event is handled
+// uniformly — the type only decides whether we bother projecting at all.
+
+// AutumnApiEnv is the minimal binding set for calling Autumn's REST API
+// (GetCustomer / checkout). The dashboard handlers satisfy this without the
+// webhook/dispatch secrets.
+export interface AutumnApiEnv {
+ AUTUMN_SECRET_KEY: string;
+ AUTUMN_BASE_URL?: string;
+}
+
+// AutumnSyncEnv adds D1 — enough to project Autumn state without dispatching.
+export interface AutumnSyncEnv extends AutumnApiEnv {
+ OPENCOMPUTER_DB: D1Database;
+}
+
+// AutumnEnv adds the secrets needed to dispatch halt to cells + verify webhooks.
+export interface AutumnEnv extends AutumnSyncEnv {
+ CF_ADMIN_SECRET: string;
+ EVENT_SECRET: string;
+ AUTUMN_WEBHOOK_SECRET: string;
+}
+
+const DEFAULT_BASE_URL = "https://api.useautumn.com/v1";
+const CREDITS_FEATURE_ID = "credits";
+const SVIX_TOLERANCE_SEC = 300;
+
+// Mirror of internal/billing/autumn.ConcurrencyByPlan — keep in sync.
+const CONCURRENCY_BY_PLAN: Record<string, number> = {
+ base: 5,
+ concurrency_pro: 100,
+ concurrency_pro_plus: 600,
+ concurrency_pro_plus_plus: 1000,
+};
+const DEFAULT_CONCURRENCY = 5;
+
+const HANDLED_EVENTS = new Set([
+ "billing.updated",
+ "billing.auto_topup_succeeded",
+ "balances.limit_reached",
+ "balances.usage_alert_triggered",
+]);
+
+export interface AutumnSubscription {
+ plan_id: string;
+ add_on: boolean;
+ status: string;
+}
+export interface AutumnAutoTopup {
+ feature_id: string;
+ enabled: boolean;
+ threshold: number;
+ quantity: number;
+}
+export interface AutumnCustomer {
+ id: string;
+ subscriptions?: AutumnSubscription[];
+ balances?: Record<string, { remaining?: number }>;
+ billing_controls?: { auto_topups?: AutumnAutoTopup[] };
+}
+
+function json(body: unknown, status = 200): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { "content-type": "application/json" },
+ });
+}
+
+export async function autumnWebhook(req: Request, env: AutumnEnv): Promise<Response> {
+ const rawBody = await req.text();
+
+ if (!env.AUTUMN_WEBHOOK_SECRET) {
+ console.error("autumn-webhook: AUTUMN_WEBHOOK_SECRET unset — rejecting");
+ return json({ error: "webhook not configured" }, 503);
+ }
+ if (!(await verifySvix(env.AUTUMN_WEBHOOK_SECRET, req.headers, rawBody))) {
+ return json({ error: "signature mismatch" }, 401);
+ }
+
+ let evt: { type?: string; data?: { customer_id?: string } };
+ try {
+ evt = JSON.parse(rawBody);
+ } catch {
+ return json({ error: "bad json" }, 400);
+ }
+
+ const type = evt.type ?? "";
+ const orgID = evt.data?.customer_id;
+ // Ack-and-ignore unknown/deprecated events so Svix doesn't retry them.
+ if (!HANDLED_EVENTS.has(type) || !orgID) {
+ return json({ ok: true, ignored: type });
+ }
+
+ try {
+ await projectOrg(env, orgID);
+ } catch (err) {
+ // 5xx → Svix retries with backoff (the Go reconciler is the longer backstop).
+ console.error(`autumn-webhook: project ${orgID} (${type}) failed`, err);
+ return json({ error: "projection failed" }, 502);
+ }
+ return json({ ok: true, type, org_id: orgID });
+}
+
+// autumnProjectInternal is the cell/reconciler-facing trigger for the SAME
+// re-check+project logic, behind the in-house EVENT_SECRET HMAC ({ts}.{body}).
+// The cell's inline halt (off track()) and the Go reconciler POST this so they
+// can drive the D1 projection without owning Autumn reads or D1 writes —
+// keeping all of that at the edge, exactly as the Svix path does.
+export async function autumnProjectInternal(req: Request, env: AutumnEnv): Promise<Response> {
+ const rawBody = await req.text();
+ 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 = parseInt(ts, 10);
+ if (!Number.isFinite(tsNum) || Math.abs(Date.now() / 1000 - tsNum) > SVIX_TOLERANCE_SEC) {
+ return json({ error: "timestamp out of window" }, 401);
+ }
+ // POST signs {ts}.{path}{query}.{body} — matches edgeclient.sign + templates.ts.
+ const url = new URL(req.url);
+ const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}.${rawBody}`);
+ if (!timingSafeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
+
+ let payload: { org_id?: string };
+ try {
+ payload = JSON.parse(rawBody);
+ } catch {
+ return json({ error: "bad json" }, 400);
+ }
+ if (!payload.org_id) return json({ error: "org_id required" }, 400);
+
+ try {
+ await projectOrg(env, payload.org_id);
+ } catch (err) {
+ console.error(`autumn-webhook: internal project ${payload.org_id} failed`, err);
+ return json({ error: "projection failed" }, 502);
+ }
+ return json({ ok: true, org_id: payload.org_id });
+}
+
+// ── self-healing gate ──────────────────────────────────────────────────────
+
+// Negative cache so a broke org retrying in a loop can't hammer Autumn: at most
+// one re-check per org per cooldown. Per-isolate + ephemeral, which is exactly
+// the best-effort rate-limit we want (Workers recycle isolates frequently).
+const lastHealCheck = new Map<string, number>();
+const HEAL_COOLDOWN_MS = 10_000;
+const HEAL_CACHE_CAP = 10_000;
+
+// selfHealHalt is the 4th resume trigger: when a halted org actually hits a
+// create/wake gate, re-check Autumn's authoritative balance (cooldown-gated)
+// and re-project D1, so a user who just topped up isn't stuck behind a lagging
+// webhook/reconciler. Returns whether the org is STILL halted afterward — the
+// caller 402s on true, proceeds on false.
+export async function selfHealHalt(env: AutumnEnv, orgID: string): Promise<boolean> {
+ const now = Date.now();
+ const last = lastHealCheck.get(orgID) ?? 0;
+ if (now - last >= HEAL_COOLDOWN_MS) {
+ if (lastHealCheck.size > HEAL_CACHE_CAP) lastHealCheck.clear();
+ lastHealCheck.set(orgID, now);
+ try {
+ await projectOrg(env, orgID);
+ } catch (err) {
+ // Re-check failed — fall through and trust whatever D1 already holds
+ // (fail closed: a still-halted projection keeps the org gated).
+ console.error(`autumn: self-heal project ${orgID} failed`, err);
+ }
+ }
+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT is_halted FROM orgs WHERE id = ?1")
+ .bind(orgID)
+ .first<{ is_halted: number }>();
+ return row?.is_halted === 1;
+}
+
+// syncAutumnToD1 reads Autumn's authoritative balance/plans and writes the D1
+// projection (is_halted / max_concurrent) WITHOUT any cell dispatch. Returns the
+// halt transition so callers can decide whether to actively hibernate. Reusable
+// by the dashboard (checkout-return) since it needs no dispatch secrets.
+export interface AutumnSyncResult {
+ customer: AutumnCustomer;
+ creditsRemaining: number; // dollars
+ maxConcurrent: number;
+ halted: boolean;
+ wasHalted: boolean;
+}
+
+export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise<AutumnSyncResult | null> {
+ const cust = await getAutumnCustomer(env, orgID);
+ if (!cust) {
+ console.error(`autumn: customer ${orgID} not found in Autumn`);
+ return null;
+ }
+
+ const creditsRemaining = cust.balances?.[CREDITS_FEATURE_ID]?.remaining ?? 0;
+ const halted = creditsRemaining <= 0;
+ const maxConcurrent = maxConcurrency(cust.subscriptions ?? []);
+ const nowSec = Math.floor(Date.now() / 1000);
+
+ const prevRow = await env.OPENCOMPUTER_DB.prepare("SELECT is_halted FROM orgs WHERE id = ?1")
+ .bind(orgID)
+ .first<{ is_halted: number }>();
+ const wasHalted = prevRow?.is_halted === 1;
+
+ await env.OPENCOMPUTER_DB.prepare(
+ `UPDATE orgs SET is_halted = ?1, halted_at = ?2, max_concurrent_sandboxes = ?3, updated_at = ?4 WHERE id = ?5`,
+ )
+ .bind(halted ? 1 : 0, halted ? nowSec : null, maxConcurrent, nowSec, orgID)
+ .run();
+
+ return { customer: cust, creditsRemaining, maxConcurrent, halted, wasHalted };
+}
+
+// autumnSetProviderInternal flips D1 orgs.billing_provider for one org (the
+// migrate tool's D1 half; cell-PG is flipped by the Go cmd). EVENT_SECRET HMAC.
+// On →autumn it also projects (is_halted/max_concurrent from Autumn) so the
+// edge gates are correct the instant the flag flips. Body: {org_id, provider}.
+export async function autumnSetProviderInternal(req: Request, env: AutumnEnv): Promise<Response> {
+ const rawBody = await req.text();
+ 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 = parseInt(ts, 10);
+ if (!Number.isFinite(tsNum) || Math.abs(Date.now() / 1000 - tsNum) > SVIX_TOLERANCE_SEC) {
+ 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}.${rawBody}`);
+ if (!timingSafeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
+
+ let p: { org_id?: string; provider?: string };
+ try {
+ p = JSON.parse(rawBody);
+ } catch {
+ return json({ error: "bad json" }, 400);
+ }
+ if (!p.org_id || (p.provider !== "autumn" && p.provider !== "legacy")) {
+ return json({ error: "org_id + provider ('autumn'|'legacy') required" }, 400);
+ }
+ try {
+ await env.OPENCOMPUTER_DB.prepare("UPDATE orgs SET billing_provider = ?1, updated_at = ?2 WHERE id = ?3")
+ .bind(p.provider, Math.floor(Date.now() / 1000), p.org_id)
+ .run();
+ if (p.provider === "autumn") await projectOrg(env, p.org_id);
+ } catch (err) {
+ console.error(`autumn-set-provider ${p.org_id} → ${p.provider} failed`, err);
+ return json({ error: "set provider failed" }, 502);
+ }
+ return json({ ok: true, org_id: p.org_id, provider: p.provider });
+}
+
+// projectOrg = syncAutumnToD1 + actively hibernate on a fresh halt.
+//
+// On halt we dispatch /admin/halt-org to hibernate running boxes. On RESUME we
+// do NOT dispatch — D1.is_halted is already cleared, which unblocks the gates;
+// hibernated boxes wake lazily on the next request. This is the locked "no
+// auto-wake for prepaid" decision: a top-up unblocks but never force-wakes.
+async function projectOrg(env: AutumnEnv, orgID: string): Promise<void> {
+ const r = await syncAutumnToD1(env, orgID);
+ if (!r || !r.halted) return;
+ // Dispatch halt on the fresh transition, OR whenever a halted org STILL has
+ // running sandboxes — so a halt is eventually complete even if a single
+ // hibernation flaked on the first dispatch. The reconciler calls projectOrg
+ // every 60s, so this is the straggler safety net (mirrors the legacy
+ // halt_reconciler, which re-issues HaltOrg for every halted org each sweep).
+ if (!r.wasHalted || (await hasRunningSandboxes(env, orgID))) {
+ await dispatchToCells(env, orgID, "/admin/halt-org", { org_id: orgID, reason: "credits_exhausted" });
+ }
+}
+
+// hasRunningSandboxes — does this org have any sandbox still running (across all
+// cells)? Cheap indexed lookup; gates the straggler re-dispatch so a fully
+// hibernated halted org costs no dispatch.
+async function hasRunningSandboxes(env: AutumnSyncEnv, orgID: string): Promise<boolean> {
+ const row = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT 1 AS one FROM sandboxes_index WHERE org_id = ?1 AND status = 'running' LIMIT 1",
+ )
+ .bind(orgID)
+ .first<{ one: number }>();
+ return row != null;
+}
+
+function maxConcurrency(subs: AutumnSubscription[]): number {
+ let limit = DEFAULT_CONCURRENCY;
+ for (const s of subs) {
+ if (s.status && s.status !== "active") continue;
+ const v = CONCURRENCY_BY_PLAN[s.plan_id];
+ if (v !== undefined && v > limit) limit = v;
+ }
+ return limit;
+}
+
+// createAutumnCustomer provisions an Autumn customer (id = our org UUID) →
+// Autumn auto-attaches the `base` plan + grants the $5 signup credit. POSTing an
+// existing id returns the existing customer, so it's idempotent/retry-safe.
+export async function createAutumnCustomer(
+ env: AutumnApiEnv,
+ p: { id: string; name: string; email: string },
+): Promise<void> {
+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;
+ const resp = await fetch(`${base}/customers`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${env.AUTUMN_SECRET_KEY}`, "content-type": "application/json" },
+ body: JSON.stringify({ id: p.id, name: p.name, email: p.email }),
+ });
+ if (!resp.ok) throw new Error(`autumn create customer ${resp.status}: ${await resp.text()}`);
+}
+
+export async function getAutumnCustomer(env: AutumnApiEnv, customerID: string): Promise<AutumnCustomer | null> {
+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;
+ const resp = await fetch(`${base}/customers/${encodeURIComponent(customerID)}`, {
+ headers: { Authorization: `Bearer ${env.AUTUMN_SECRET_KEY}` },
+ });
+ if (resp.status === 404) return null;
+ if (!resp.ok) throw new Error(`autumn GET customer ${resp.status}: ${await resp.text()}`);
+ return (await resp.json()) as AutumnCustomer;
+}
+
+// CheckoutOption sets a quantity for a priced feature in the product (e.g. the
+// number of $1 credits in a top-up).
+export interface AutumnCheckoutOption {
+ feature_id: string;
+ quantity: number;
+}
+
+export interface AutumnCheckoutResult {
+ url: string;
+ total?: number;
+ currency?: string;
+}
+
+// autumnCheckout creates an Autumn (Stripe-backed) checkout — a one-off credit
+// top-up (product_id="top_up", options=[{feature_id:"credits", quantity:N}]) or
+// a concurrency plan subscription (product_id="concurrency_pro" etc.). Shape
+// confirmed live against the Autumn sandbox.
+export async function autumnCheckout(
+ env: AutumnApiEnv,
+ params: { customerId: string; productId: string; options?: AutumnCheckoutOption[]; successUrl: string },
+): Promise<AutumnCheckoutResult> {
+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;
+ const body: Record<string, unknown> = {
+ customer_id: params.customerId,
+ product_id: params.productId,
+ success_url: params.successUrl,
+ };
+ if (params.options && params.options.length > 0) body.options = params.options;
+ const resp = await fetch(`${base}/checkout`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${env.AUTUMN_SECRET_KEY}`, "content-type": "application/json" },
+ body: JSON.stringify(body),
+ });
+ if (!resp.ok) throw new Error(`autumn checkout ${resp.status}: ${await resp.text()}`);
+ return (await resp.json()) as AutumnCheckoutResult;
+}
+
+// autumnSetAutoTopup configures (or disables) automatic credit top-up for the
+// `credits` feature. POST /customers/{id} with billing_controls.auto_topups —
+// confirmed live: after every track() Autumn checks the balance and, if below
+// `threshold`, charges the saved card for `quantity` credits (30s cooldown).
+// Requires a payment method on file to actually charge (config persists either way).
+export async function autumnSetAutoTopup(
+ env: AutumnApiEnv,
+ customerID: string,
+ cfg: { enabled: boolean; threshold: number; quantity: number },
+): Promise<void> {
+ const base = env.AUTUMN_BASE_URL || DEFAULT_BASE_URL;
+ const resp = await fetch(`${base}/customers/${encodeURIComponent(customerID)}`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${env.AUTUMN_SECRET_KEY}`, "content-type": "application/json" },
+ body: JSON.stringify({
+ billing_controls: {
+ auto_topups: [
+ { feature_id: CREDITS_FEATURE_ID, enabled: cfg.enabled, threshold: cfg.threshold, quantity: cfg.quantity },
+ ],
+ },
+ }),
+ });
+ if (!resp.ok) throw new Error(`autumn set auto-topup ${resp.status}: ${await resp.text()}`);
+}
+
+// ── cell dispatch (mirrors the DO's halt/resume fan-out) ───────────────────
+
+interface CellRow {
+ cell_id: string;
+ base_url: string;
+}
+const DISPATCH_BACKOFFS_MS = [200, 1000, 3000];
+
+async function dispatchToCells(env: AutumnEnv, orgID: string, path: string, payload: unknown): Promise<void> {
+ const { results } = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT DISTINCT c.cell_id, c.base_url
+ FROM sandboxes_index s
+ JOIN cells c ON s.cell_id = c.cell_id
+ WHERE s.org_id = ?1 AND s.status IN ('running', 'hibernated', 'migrating')`,
+ )
+ .bind(orgID)
+ .all<CellRow>();
+ const cells = results ?? [];
+ if (cells.length === 0) return;
+
+ const body = JSON.stringify(payload);
+ await Promise.all(cells.map((c) => postWithRetry(env, c, path, body)));
+}
+
+async function postWithRetry(env: AutumnEnv, cell: CellRow, path: string, body: string): Promise<void> {
+ const ts = Math.floor(Date.now() / 1000).toString();
+ const sig = await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${body}`);
+ const url = cell.base_url.replace(/\/$/, "") + path;
+
+ for (let attempt = 0; attempt <= DISPATCH_BACKOFFS_MS.length; attempt++) {
+ try {
+ const resp = await fetch(url, {
+ method: "POST",
+ headers: { "content-type": "application/json", "X-Timestamp": ts, "X-Signature": sig },
+ body,
+ });
+ if (resp.status >= 200 && resp.status < 300) return;
+ console.error(`autumn-webhook: dispatch ${path} → ${cell.cell_id} status=${resp.status} attempt=${attempt}`);
+ } catch (err) {
+ console.error(`autumn-webhook: dispatch ${path} → ${cell.cell_id} error=${(err as Error).message}`);
+ }
+ if (attempt < DISPATCH_BACKOFFS_MS.length) {
+ await new Promise((r) => setTimeout(r, DISPATCH_BACKOFFS_MS[attempt]));
+ }
+ }
+}
+
+// ── crypto ─────────────────────────────────────────────────────────────────
+
+// Svix signature: base64( HMAC_SHA256( "{id}.{ts}.{body}", base64decode(secret) ) ),
+// matched against any "v1,<sig>" entry in the space-separated svix-signature header.
+async function verifySvix(secret: string, headers: Headers, body: string): Promise<boolean> {
+ const id = headers.get("svix-id");
+ const ts = headers.get("svix-timestamp");
+ const sigHeader = headers.get("svix-signature");
+ if (!id || !ts || !sigHeader) return false;
+
+ const tsNum = parseInt(ts, 10);
+ if (!Number.isFinite(tsNum) || Math.abs(Date.now() / 1000 - tsNum) > SVIX_TOLERANCE_SEC) return false;
+
+ const rawSecret = secret.startsWith("whsec_") ? secret.slice(6) : secret;
+ const keyBytes = base64ToBytes(rawSecret);
+ const key = await crypto.subtle.importKey("raw", keyBytes, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
+ const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${id}.${ts}.${body}`));
+ const expected = bytesToBase64(new Uint8Array(mac));
+
+ for (const part of sigHeader.split(" ")) {
+ const comma = part.indexOf(",");
+ const sig = comma >= 0 ? part.slice(comma + 1) : part;
+ if (sig && timingSafeEqual(sig, expected)) return true;
+ }
+ return false;
+}
+
+async function hmacHex(secret: string, data: string): Promise<string> {
+ const key = await crypto.subtle.importKey(
+ "raw",
+ new TextEncoder().encode(secret),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));
+ return [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+function base64ToBytes(b64: string): Uint8Array {
+ const bin = atob(b64);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+ return out;
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let bin = "";
+ for (const b of bytes) bin += String.fromCharCode(b);
+ return btoa(bin);
+}
+
+function timingSafeEqual(a: string, b: string): boolean {
+ if (a.length !== b.length) return false;
+ let diff = 0;
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
+ return diff === 0;
+}
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 53ba5214..978a5fb8 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -17,6 +17,8 @@
// 3. Fetch the cell's /internal/dashboard/{path} with Authorization: Bearer.
// 4. Stream the response (or WebSocket pair) back to the browser.
+import { getAutumnCustomer, autumnCheckout, syncAutumnToD1, autumnSetAutoTopup } from "./autumn_webhook";
+
export interface DashboardEnv {
OPENCOMPUTER_DB: D1Database;
SESSIONS_KV: KVNamespace;
@@ -26,6 +28,13 @@ export interface DashboardEnv {
WORKOS_CLIENT_ID: string;
STRIPE_API_KEY: string;
WORKER_ENV: string;
+ // Autumn billing — read customer state + create top-up/concurrency checkouts.
+ // Empty on deployments not yet on Autumn.
+ AUTUMN_SECRET_KEY: string;
+ AUTUMN_BASE_URL?: string;
+ // "true" → new signups are provisioned on Autumn (Stage 2 switch). Default
+ // off keeps merge dormant; existing orgs are never auto-migrated by this.
+ AUTUMN_NEW_ORGS?: string;
// CF Custom Hostnames API token + zone (for /org/custom-domain). Optional —
// if unset the custom-domain endpoints return 503 (feature disabled).
CF_API_TOKEN?: string;
@@ -872,12 +881,12 @@ export async function handleDashboard(
// dashboard renders instead of 404-erroring on a missing route.
if (sub === "/billing" && method === "GET") {
const org = await env.OPENCOMPUTER_DB.prepare(
- `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted, max_concurrent_sandboxes
+ `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted, max_concurrent_sandboxes, billing_provider
FROM orgs WHERE id = ?1`,
).bind(caller.orgID).first<{
plan: string; stripe_customer_id: string | null; stripe_subscription_id: string | null;
free_credits_remaining_cents: number; credit_balance_cents: number; is_halted: number;
- max_concurrent_sandboxes: number;
+ max_concurrent_sandboxes: number; billing_provider: string;
}>();
if (!org) return json({ error: "org not found" }, 404);
// Cross-check against the live DO state — the D1 mirror gets written by
@@ -910,6 +919,7 @@ export async function handleDashboard(
creditBalanceCents: org.credit_balance_cents,
isHalted: !!org.is_halted,
maxConcurrentSandboxes: org.max_concurrent_sandboxes,
+ billingProvider: org.billing_provider,
// Upcoming-invoice + meters would come from Stripe API on demand;
// surface stubs for now so the UI has stable keys to render against.
upcomingInvoice: null,
@@ -935,6 +945,21 @@ export async function handleDashboard(
if (sub === "/billing/invoices" && method === "GET") {
return handleBillingInvoices(req, env, caller);
}
+ if (sub === "/usage/sandboxes" && method === "GET") {
+ return handleSandboxUsage(req, env, caller);
+ }
+ if (sub === "/billing/autumn" && method === "GET") {
+ return handleAutumnBilling(req, env, caller);
+ }
+ if (sub === "/billing/autumn/topup" && method === "POST") {
+ return handleAutumnTopup(req, env, caller);
+ }
+ if (sub === "/billing/autumn/concurrency" && method === "POST") {
+ return handleAutumnConcurrency(req, env, caller);
+ }
+ if (sub === "/billing/autumn/auto-topup" && method === "POST") {
+ return handleAutumnAutoTopup(req, env, caller);
+ }
return json({ error: `not found: ${method} ${sub}` }, 404);
}
@@ -1066,6 +1091,201 @@ async function handleBillingPortal(req: Request, env: DashboardEnv, caller: { or
}
}
+// ── Per-sandbox usage breakdown ──────────────────────────────────────────
+
+// Compute $/sec per memory tier. MUST stay in sync with
+// internal/billing/pricing.go TierPricePerSecond (and the Autumn credit
+// schema, which mirrors the same rates).
+const TIER_RATE_PER_SEC: Record<number, number> = {
+ 1024: 0.000001080246914,
+ 4096: 0.000005787037037,
+ 8192: 0.00001350308642,
+ 16384: 0.00002700617284,
+ 32768: 0.0001929012346,
+ 65536: 0.0005401234568,
+};
+
+// GET /api/dashboard/usage/sandboxes?days=N — per-sandbox compute cost over a
+// recent window, for billing transparency. Sourced from D1 usage_samples
+// (global across cells); disk overage is excluded (samples carry no disk size),
+// so this is compute cost only. usage_samples is short-lived, hence the window.
+async function handleSandboxUsage(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ const url = new URL(req.url);
+ let days = Number.parseInt(url.searchParams.get("days") ?? "30", 10);
+ if (!Number.isFinite(days) || days < 1) days = 30;
+ if (days > 90) days = 90;
+ const cutoffMs = (Math.floor(Date.now() / 1000) - days * 86400) * 1000;
+
+ const rows = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT u.sandbox_id AS sandbox_id, u.memory_mb AS memory_mb, SUM(u.interval_s) AS secs,
+ MAX(si.status) AS status, MAX(si.created_at) AS created_at
+ FROM usage_samples u
+ LEFT JOIN sandboxes_index si ON si.id = u.sandbox_id
+ WHERE u.org_id = ?1 AND u.ts >= ?2
+ GROUP BY u.sandbox_id, u.memory_mb`,
+ )
+ .bind(caller.orgID, cutoffMs)
+ .all<{ sandbox_id: string; memory_mb: number; secs: number; status: string | null; created_at: number | null }>();
+
+ // Fold per-(sandbox, tier) rows into per-sandbox totals.
+ const bySandbox = new Map<string, { costCents: number; seconds: number; status: string | null; createdAt: number | null }>();
+ for (const r of rows.results ?? []) {
+ const rate = TIER_RATE_PER_SEC[r.memory_mb] ?? 0;
+ const secs = r.secs ?? 0;
+ const cur = bySandbox.get(r.sandbox_id) ?? { costCents: 0, seconds: 0, status: r.status, createdAt: r.created_at };
+ cur.costCents += secs * rate * 100;
+ cur.seconds += secs;
+ if (cur.status == null) cur.status = r.status;
+ if (cur.createdAt == null) cur.createdAt = r.created_at;
+ bySandbox.set(r.sandbox_id, cur);
+ }
+
+ const sandboxes = [...bySandbox.entries()]
+ .map(([sandboxId, v]) => ({
+ sandboxId,
+ status: v.status ?? "deleted",
+ createdAt: v.createdAt ?? undefined,
+ seconds: Math.round(v.seconds),
+ costCents: Math.round(v.costCents),
+ }))
+ .sort((a, b) => b.costCents - a.costCents);
+
+ const totalCents = sandboxes.reduce((s, x) => s + x.costCents, 0);
+ return json({ windowDays: days, totalCents, sandboxes });
+}
+
+// ── Autumn prepaid billing ───────────────────────────────────────────────
+
+// Concurrency plans the user can self-serve subscribe to. Mirrors
+// autumn.ConcurrencyByPlan (the "base" tier is the free default, not purchasable).
+const AUTUMN_CONCURRENCY_PRODUCTS: Record<string, number> = {
+ concurrency_pro: 100,
+ concurrency_pro_plus: 600,
+ concurrency_pro_plus_plus: 1000,
+};
+
+// GET /api/dashboard/billing/autumn — prepaid credit balance + concurrency plan.
+// Re-syncs Autumn → D1 on the way (this is the checkout-return / page-view resume
+// trigger: a just-topped-up user's is_halted clears here even if the webhook lagged).
+async function handleAutumnBilling(_req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ if (!env.AUTUMN_SECRET_KEY) return json({ error: "autumn billing not configured" }, 503);
+ let r;
+ try {
+ r = await syncAutumnToD1(env, caller.orgID);
+ } catch (e) {
+ console.error("billing/autumn sync:", e);
+ return json({ error: "autumn unavailable" }, 502);
+ }
+ if (!r) return json({ error: "no autumn customer for org" }, 404);
+
+ // The active concurrency plan = the highest non-base plan the customer holds.
+ let concurrencyPlan = "base";
+ let best = 0;
+ for (const s of r.customer.subscriptions ?? []) {
+ if (s.status && s.status !== "active") continue;
+ const v = AUTUMN_CONCURRENCY_PRODUCTS[s.plan_id];
+ if (v !== undefined && v > best) {
+ best = v;
+ concurrencyPlan = s.plan_id;
+ }
+ }
+
+ const at = r.customer.billing_controls?.auto_topups?.find((a) => a.feature_id === "credits");
+
+ return json({
+ creditsRemainingCents: Math.round(r.creditsRemaining * 100),
+ maxConcurrentSandboxes: r.maxConcurrent,
+ concurrencyPlan,
+ isHalted: r.halted,
+ autoTopup: at ? { enabled: at.enabled, threshold: at.threshold, quantity: at.quantity } : null,
+ });
+}
+
+// POST /api/dashboard/billing/autumn/auto-topup { enabled, threshold, quantity }
+// — configure automatic credit recharge. threshold/quantity are in credits ($1
+// each). A saved payment method is required for the charge to succeed; the
+// config itself persists regardless.
+async function handleAutumnAutoTopup(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ if (!env.AUTUMN_SECRET_KEY) return json({ error: "autumn billing not configured" }, 503);
+ let body: { enabled?: boolean; threshold?: number; quantity?: number };
+ try {
+ body = await req.json();
+ } catch {
+ return json({ error: "bad json" }, 400);
+ }
+ const enabled = !!body.enabled;
+ const threshold = Math.floor(body.threshold ?? 0);
+ const quantity = Math.floor(body.quantity ?? 0);
+ if (enabled && (threshold < 0 || quantity < 1)) {
+ return json({ error: "threshold ≥ 0 and quantity ≥ 1 required when enabling" }, 400);
+ }
+ try {
+ await autumnSetAutoTopup(env, caller.orgID, { enabled, threshold, quantity });
+ return json({ ok: true });
+ } catch (e) {
+ console.error("billing/autumn auto-topup:", e);
+ return json({ error: (e as Error).message }, 502);
+ }
+}
+
+// POST /api/dashboard/billing/autumn/topup { credits } — one-off prepaid credit
+// purchase. Returns a Stripe checkout URL; success returns to the billing page
+// where handleAutumnBilling re-syncs the new balance.
+async function handleAutumnTopup(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ if (!env.AUTUMN_SECRET_KEY) return json({ error: "autumn billing not configured" }, 503);
+ let body: { credits?: number };
+ try {
+ body = await req.json();
+ } catch {
+ return json({ error: "bad json" }, 400);
+ }
+ const credits = Math.floor(body.credits ?? 0);
+ if (!Number.isFinite(credits) || credits < 1) {
+ return json({ error: "credits must be a positive integer" }, 400);
+ }
+ const origin = new URL(req.url).origin;
+ try {
+ const co = await autumnCheckout(env, {
+ customerId: caller.orgID,
+ productId: "top_up",
+ options: [{ feature_id: "credits", quantity: credits }],
+ successUrl: `${origin}/dashboard/billing?topup=success`,
+ });
+ return json({ url: co.url });
+ } catch (e) {
+ console.error("billing/autumn topup:", e);
+ return json({ error: (e as Error).message }, 502);
+ }
+}
+
+// POST /api/dashboard/billing/autumn/concurrency { plan } — subscribe/upgrade a
+// monthly concurrency tier. Returns a Stripe subscription checkout URL.
+async function handleAutumnConcurrency(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
+ if (!env.AUTUMN_SECRET_KEY) return json({ error: "autumn billing not configured" }, 503);
+ let body: { plan?: string };
+ try {
+ body = await req.json();
+ } catch {
+ return json({ error: "bad json" }, 400);
+ }
+ const plan = body.plan ?? "";
+ if (!(plan in AUTUMN_CONCURRENCY_PRODUCTS)) {
+ return json({ error: `unknown concurrency plan '${plan}'` }, 400);
+ }
+ const origin = new URL(req.url).origin;
+ try {
+ const co = await autumnCheckout(env, {
+ customerId: caller.orgID,
+ productId: plan,
+ successUrl: `${origin}/dashboard/billing?plan=success`,
+ });
+ return json({ url: co.url });
+ } catch (e) {
+ console.error("billing/autumn concurrency:", e);
+ return json({ error: (e as Error).message }, 502);
+ }
+}
+
async function handleBillingSetup(req: Request, env: DashboardEnv, caller: { orgID: string }): Promise<Response> {
const org = await loadOrgStripe(env, caller.orgID);
if (!org) return json({ error: "org not found" }, 404);
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 63d800ad..0b4b401d 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -18,6 +18,13 @@
export { CreditAccount } from "../../shared/credit_account";
import { handleDashboard, type DashboardEnv } from "./dashboard";
+import {
+ autumnWebhook,
+ autumnProjectInternal,
+ autumnSetProviderInternal,
+ selfHealHalt,
+ createAutumnCustomer,
+} from "./autumn_webhook";
import * as secretStores from "./secret_stores";
import * as snapshots from "./snapshots";
import * as templates from "./templates";
@@ -26,6 +33,10 @@ export interface Env extends DashboardEnv {
CF_ADMIN_SECRET: string;
STRIPE_WEBHOOK_SECRET: string;
EVENT_SECRET: string;
+ // Autumn (useautumn.com) billing. AUTUMN_WEBHOOK_SECRET is the Svix signing
+ // secret (whsec_…) for /webhooks/autumn. AUTUMN_SECRET_KEY / AUTUMN_BASE_URL
+ // are inherited from DashboardEnv. Unset on deployments not yet on Autumn.
+ AUTUMN_WEBHOOK_SECRET: string;
// Shared with every CP via Infisical /shared/ → per-cell KV/SM. Used for
// envelope encryption of secret_store_entries.encrypted_value. Matches
// internal/crypto.Encryptor key format (hex-encoded 32 bytes).
@@ -69,6 +80,7 @@ async function mintCapToken(
orgID: string,
cellID: string,
plan: string,
+ billingProvider: string,
userID: string | null,
): Promise<string> {
const now = Math.floor(Date.now() / 1000);
@@ -82,6 +94,9 @@ async function mintCapToken(
cell_id: cellID,
plan,
};
+ // Only set when known; empty lets the cell keep its existing cell-PG value
+ // (so a wake/preview token never clobbers an autumn flag set at create time).
+ if (billingProvider) payload.billing_provider = billingProvider;
if (userID) payload.user_id = userID;
const enc = new TextEncoder();
const signingInput =
@@ -352,13 +367,14 @@ interface OrgPolicy {
is_halted: number;
max_concurrent_sandboxes: number;
max_disk_mb: number;
+ billing_provider: string;
}
// 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",
+ "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider FROM orgs WHERE id = ?1",
)
.bind(orgID)
.first<OrgPolicy>();
@@ -385,9 +401,17 @@ async function enforceCreatePolicy(
): Promise<Response | null> {
const plan = org.plan === "pro" ? "pro" : "free";
- // 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") {
+ // Autumn orgs: Autumn owns the balance, so the credit gate is purely the
+ // is_halted projection — no CreditAccount DO. On a halt, self-heal (re-check
+ // Autumn) so a just-topped-up user isn't stuck behind a lagging webhook. The
+ // free-tier size ceilings below still apply by plan.
+ if (org.billing_provider === "autumn") {
+ if (org.is_halted === 1 && (await selfHealHalt(env, orgID))) {
+ return json({ error: "credits exhausted — top up to resume" }, 402);
+ }
+ } else if (plan === "free") {
+ // Legacy free-tier gate. is_halted is the D1 fast path; otherwise ask the
+ // CreditAccount DO for an authoritative balance read. Pro orgs skip this.
if (org.is_halted === 1) {
return json({ error: "free trial credits exhausted — upgrade to resume" }, 402);
}
@@ -402,7 +426,10 @@ async function enforceCreatePolicy(
if (!check.allowed) {
return json({ error: "free trial credits exhausted — upgrade to resume", balance_cents: check.balance_cents }, 402);
}
- // Free-tier ceilings: 4GB / 1 vCPU, 20GB disk.
+ }
+
+ // Free-tier ceilings: 4GB / 1 vCPU, 20GB disk.
+ if (plan === "free") {
if (sizes.memoryMB > 4096 || sizes.cpuCount > 1) {
return json({ error: "upgrade to pro for larger instances" }, 402);
}
@@ -614,7 +641,7 @@ 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);
+ const capToken = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, caller.userID);
// SSE build streaming: image/snapshot creates can take minutes (apt installs,
// etc.). Preserve live streaming, but index the final `result` event inline
@@ -766,7 +793,7 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// tokens and API keys), so the same handler chain that runs for SDK
// X-API-Key auth runs here. cell_id in the token guards against replay
// against a different cell.
- const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, row.cell_id, orgRow?.plan ?? "free", caller.userID);
+ const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, row.cell_id, orgRow?.plan ?? "free", "", caller.userID);
const headers = new Headers();
for (const [k, v] of req.headers.entries()) {
@@ -798,15 +825,22 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, cal
// silently fell through, letting halted orgs wake. Mirror the create
// flow's halt check here so wake gets the same treatment.
const haltRow = await env.OPENCOMPUTER_DB.prepare(
- "SELECT is_halted FROM orgs WHERE id = ?1",
+ "SELECT is_halted, billing_provider FROM orgs WHERE id = ?1",
)
.bind(caller.orgID)
- .first<{ is_halted: number }>();
+ .first<{ is_halted: number; billing_provider: string }>();
if (haltRow?.is_halted === 1) {
- return json(
- { error: "org is halted — upgrade to pro or wait for credit refill" },
- 402,
- );
+ // Autumn orgs self-heal: re-check the authoritative balance before
+ // blocking a wake, so a just-topped-up user resumes without waiting for
+ // the webhook/reconciler. Legacy orgs stay hard-gated on the D1 flag.
+ const stillHalted =
+ haltRow.billing_provider === "autumn" ? await selfHealHalt(env, caller.orgID) : true;
+ if (stillHalted) {
+ return json(
+ { error: "org is halted — upgrade to pro or wait for credit refill" },
+ 402,
+ );
+ }
}
}
@@ -878,7 +912,7 @@ async function proxyToCellAuthed(
: 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 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;
@@ -1168,11 +1202,25 @@ async function authCallback(req: Request, env: Env): Promise<Response> {
orgID = crypto.randomUUID();
const homeCell = await pickHomeCell(env, req);
orgPlan = "free";
+ // Stage 2: new signups go to Autumn when AUTUMN_NEW_ORGS is on. Create the
+ // Autumn customer first (it grants the $5 signup credit); only flag the org
+ // 'autumn' if that succeeds, so a transient Autumn failure falls back to the
+ // legacy trial rather than breaking signup. Existing orgs are untouched —
+ // they migrate later via cmd/migrate-to-autumn after notification.
+ let provider = "legacy";
+ if (env.AUTUMN_NEW_ORGS === "true" && env.AUTUMN_SECRET_KEY) {
+ try {
+ await createAutumnCustomer(env, { id: orgID, name: `${profile.email}'s workspace`, email: profile.email });
+ provider = "autumn";
+ } catch (e) {
+ console.error(`signup: autumn customer create failed for ${orgID}, falling back to legacy`, e);
+ }
+ }
await env.OPENCOMPUTER_DB.prepare(
- `INSERT INTO orgs (id, name, slug, plan, home_cell, is_personal, owner_user_id, created_at, updated_at)
- VALUES (?1, ?2, ?3, 'free', ?4, 1, ?5, ?6, ?6)`,
+ `INSERT INTO orgs (id, name, slug, plan, home_cell, is_personal, owner_user_id, billing_provider, created_at, updated_at)
+ VALUES (?1, ?2, ?3, 'free', ?4, 1, ?5, ?7, ?6, ?6)`,
)
- .bind(orgID, `${profile.email}'s workspace`, slugify(profile.email + "-" + orgID.slice(0, 6)), homeCell, userID, nowSec)
+ .bind(orgID, `${profile.email}'s workspace`, slugify(profile.email + "-" + orgID.slice(0, 6)), homeCell, userID, nowSec, provider)
.run();
await env.OPENCOMPUTER_DB.prepare(
`INSERT INTO org_memberships (org_id, user_id, role, created_at) VALUES (?1, ?2, 'owner', ?3)`,
@@ -1547,6 +1595,17 @@ export default {
return haltList(req, env);
}
+ // Cell/reconciler trigger for the Autumn re-check+project (EVENT_SECRET HMAC).
+ if (path === "/internal/autumn-project") {
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
+ return autumnProjectInternal(req, env);
+ }
+ // Migrate tool: flip D1 billing_provider for one org (EVENT_SECRET HMAC).
+ if (path === "/internal/autumn-set-provider") {
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
+ return autumnSetProviderInternal(req, env);
+ }
+
if (path === "/internal/org-policy") {
if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
return orgPolicy(req, env);
@@ -1694,6 +1753,10 @@ export default {
// Stripe webhook (test mode in app2, live in app).
if (path === "/webhooks/stripe" && req.method === "POST") return stripeWebhook(req, env);
+ // Autumn (useautumn.com) webhook — Svix-signed; projects authoritative
+ // balance/plans into D1 (is_halted, max_concurrent) + dispatches to cells.
+ if (path === "/webhooks/autumn" && req.method === "POST") return autumnWebhook(req, env);
+
// Dashboard API — everything under /api/dashboard/*. Edge-native handlers
// back D1 reads/writes; sandbox-runtime calls proxy to the sandbox's cell.
// Auth via the oc_session cookie minted at /auth/callback.
@@ -1754,7 +1817,7 @@ export default {
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 token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, plan, org.billing_provider, caller.userID);
const fcResp = await fetch(cell.base_url.replace(/\/$/, "") + path, {
method: "POST",
headers: { authorization: "Bearer " + token, "content-type": "application/json" },
diff --git a/cloudflare-workers/events-ingest/src/index.ts b/cloudflare-workers/events-ingest/src/index.ts
index 6710cfc3..b05a3046 100644
--- a/cloudflare-workers/events-ingest/src/index.ts
+++ b/cloudflare-workers/events-ingest/src/index.ts
@@ -358,7 +358,11 @@ export default {
];
const planLookup = await resolvePlans(env, tickOrgIds);
const planFor = (e: SandboxEventEnvelope): string | undefined =>
- planLookup.ok ? (e.org_id ? planLookup.byOrg.get(e.org_id) : undefined) : e.plan;
+ planLookup.ok ? (e.org_id ? planLookup.byOrg.get(e.org_id)?.plan : undefined) : e.plan;
+ // billing_provider has no envelope fallback; on a D1-lookup failure this is
+ // undefined → treated as legacy (fail-open, matching planFor's philosophy).
+ const providerFor = (e: SandboxEventEnvelope): string | undefined =>
+ e.org_id ? planLookup.byOrg.get(e.org_id)?.provider : undefined;
// Pro-tier usage samples: land each pro `usage_tick`'s resource dimensions
// into usage_samples for the rollup cron (the edge analog of the cell's
@@ -460,7 +464,12 @@ export default {
// Plan comes from the authoritative D1 lookup (planFor), not the stale
// envelope value — so a free→pro upgrade stops debiting immediately and a
// pro→free downgrade resumes it, with no dependency on cell-PG freshness.
- const debitTargets = fresh.filter((e) => e.type === "usage_tick" && planFor(e) === "free" && e.org_id);
+ // Autumn orgs are excluded: their credit ledger + halt live in Autumn, so a
+ // legacy DO debit would touch an ignored balance and could even wrongly halt
+ // them via the DO's debit→0 path.
+ const debitTargets = fresh.filter(
+ (e) => e.type === "usage_tick" && planFor(e) === "free" && providerFor(e) !== "autumn" && e.org_id,
+ );
if (debitTargets.length > 0) {
ctx.waitUntil(fanoutDebits(env, debitTargets));
}
@@ -535,17 +544,17 @@ async function resolveSandboxOwners(
async function resolvePlans(
env: Env,
orgIds: string[],
-): Promise<{ ok: boolean; byOrg: Map<string, string> }> {
- const byOrg = new Map<string, string>();
+): Promise<{ ok: boolean; byOrg: Map<string, { plan: string; provider: string }> }> {
+ const byOrg = new Map<string, { plan: string; provider: string }>();
if (orgIds.length === 0) return { ok: true, byOrg };
const placeholders = orgIds.map((_, i) => `?${i + 1}`).join(",");
try {
const res = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, plan FROM orgs WHERE id IN (${placeholders})`,
+ `SELECT id, plan, billing_provider FROM orgs WHERE id IN (${placeholders})`,
)
.bind(...orgIds)
- .all<{ id: string; plan: string }>();
- for (const r of res.results ?? []) byOrg.set(r.id, r.plan);
+ .all<{ id: string; plan: string; billing_provider: string }>();
+ for (const r of res.results ?? []) byOrg.set(r.id, { plan: r.plan, provider: r.billing_provider });
return { ok: true, byOrg };
} catch (err) {
console.error("events-ingest: org plan lookup failed — falling back to envelope plan", err);
diff --git a/cloudflare-workers/schema_phase6.sql b/cloudflare-workers/schema_phase6.sql
new file mode 100644
index 00000000..3d871af3
--- /dev/null
+++ b/cloudflare-workers/schema_phase6.sql
@@ -0,0 +1,29 @@
+-- Phase 6: Autumn billing — per-org billing_provider selector on D1.
+--
+-- The edge is authoritative for billing_provider: signup sets it, the cutover
+-- backfill flips existing orgs, and the cap-token carries it to each cell's
+-- Postgres mirror (like `plan`). The create/wake gates + the dashboard billing
+-- read it directly from D1, so this column MUST exist before the new api-edge
+-- code is deployed.
+--
+-- Apply with:
+-- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase6.sql
+--
+-- SQLite/D1 has no `ADD COLUMN IF NOT EXISTS`, so this is one-shot like the
+-- earlier phases.
+--
+-- ROLLOUT ORDER MATTERS. Run this migration BEFORE deploying the new api-edge
+-- code: loadOrgPolicy + GET /api/dashboard/billing now SELECT billing_provider
+-- for every org, and a missing column makes those reads error for ALL orgs
+-- (not just Autumn ones).
+--
+-- 'legacy' — in-house pipeline (CreditAccount DO / usage_reporter).
+-- 'autumn' — Autumn owns the credit ledger, metering, top-ups, concurrency.
+--
+-- Defaults to 'legacy' so every existing org is unaffected until explicitly
+-- flipped. Mirrors internal/db/migrations/047 on the cell.
+ALTER TABLE orgs ADD COLUMN billing_provider TEXT NOT NULL DEFAULT 'legacy';
+
+-- Cutover backfill / dashboard reads filter on it; partial index keeps the
+-- "which orgs are on Autumn" sweep tight while almost everyone is still legacy.
+CREATE INDEX IF NOT EXISTS idx_orgs_billing_provider ON orgs(billing_provider) WHERE billing_provider = 'autumn';
diff --git a/cmd/migrate-to-autumn/main.go b/cmd/migrate-to-autumn/main.go
new file mode 100644
index 00000000..180db7d0
--- /dev/null
+++ b/cmd/migrate-to-autumn/main.go
@@ -0,0 +1,163 @@
+// Command migrate-to-autumn moves a legacy org onto Autumn billing.
+//
+// Per org it: creates the Autumn customer (id = org UUID → base plan + $5),
+// carries the org's current legacy balance over to Autumn, flips
+// billing_provider to 'autumn' in BOTH D1 (edge) and cell-PG, and projects
+// is_halted/max_concurrent. It NEVER enables auto top-up — auto-recharge is
+// opt-in only (ROSCA, 15 U.S.C. § 8403: express informed consent required).
+//
+// Flip ordering avoids ever having both billers live for one org:
+// →autumn: D1 first (stops the legacy edge DO debit), then cell-PG (starts the
+// Autumn reporter). During the gap only the legacy cell deduction
+// runs — never a double-charge.
+// →legacy: cell-PG first (stops the Autumn reporter), then D1. Symmetric.
+//
+// Defaults to free orgs only and --dry-run. PRO orgs hold an active Stripe
+// subscription + saved card — moving them to prepaid requires canceling that
+// subscription, confirming card re-use, and customer notification; do those
+// deliberately, not in a bulk sweep (gated behind --include-pro).
+//
+// Run (single org):
+//
+// OPENSANDBOX_DATABASE_URL=... AUTUMN_SECRET_KEY=... \
+// OPENSANDBOX_CF_EDGE_BASE_URL=... OPENSANDBOX_CF_EVENT_SECRET=... \
+// go run ./cmd/migrate-to-autumn --org <uuid> --live
+package main
+
+import (
+ "context"
+ "flag"
+ "log"
+ "os"
+
+ "github.com/google/uuid"
+
+ "github.com/opensandbox/opensandbox/internal/billing/autumn"
+ "github.com/opensandbox/opensandbox/internal/db"
+ "github.com/opensandbox/opensandbox/internal/edgeclient"
+)
+
+func main() {
+ orgFlag := flag.String("org", "", "org UUID to migrate (required)")
+ revert := flag.Bool("revert", false, "flip back to legacy instead of migrating to autumn")
+ live := flag.Bool("live", false, "actually mutate; without it the run is a dry-run")
+ includePro := flag.Bool("include-pro", false, "allow migrating pro orgs (they have Stripe subs — handle their subscription + card + notice separately)")
+ minGrant := flag.Float64("min-grant", 0, "floor the carried-over Autumn balance at this many dollars")
+ flag.Parse()
+
+ if *orgFlag == "" {
+ log.Fatal("--org is required")
+ }
+ orgID, err := uuid.Parse(*orgFlag)
+ if err != nil {
+ log.Fatalf("bad --org: %v", err)
+ }
+ dryRun := !*live
+
+ dbURL := mustEnv("OPENSANDBOX_DATABASE_URL")
+ autumnKey := mustEnv("AUTUMN_SECRET_KEY")
+ edgeURL := mustEnv("OPENSANDBOX_CF_EDGE_BASE_URL")
+ edgeSecret := mustEnv("OPENSANDBOX_CF_EVENT_SECRET")
+
+ ctx := context.Background()
+ store, err := db.NewStore(ctx, dbURL)
+ if err != nil {
+ log.Fatalf("connect db: %v", err)
+ }
+ defer store.Close()
+
+ var aut autumn.Client = autumn.New(autumnKey)
+ if base := os.Getenv("AUTUMN_BASE_URL"); base != "" {
+ aut = autumn.New(autumnKey, autumn.WithBaseURL(base))
+ }
+ edge := edgeclient.New(edgeURL, edgeSecret)
+
+ org, err := store.GetOrg(ctx, orgID)
+ if err != nil {
+ log.Fatalf("get org %s: %v", orgID, err)
+ }
+
+ if *revert {
+ revertOrg(ctx, store, edge, org, dryRun)
+ return
+ }
+ migrateOrg(ctx, store, aut, edge, org, *includePro, *minGrant, dryRun)
+}
+
+func migrateOrg(ctx context.Context, store *db.Store, aut autumn.Client, edge *edgeclient.Client, org *db.Org, includePro bool, minGrant float64, dryRun bool) {
+ if org.BillingProvider == "autumn" {
+ log.Printf("org %s already on autumn — nothing to do", org.ID)
+ return
+ }
+ if org.Plan == "pro" && !includePro {
+ log.Fatalf("org %s is pro (has a Stripe subscription) — migrate it deliberately with --include-pro after handling the subscription + card + notice", org.ID)
+ }
+
+ balance := float64(org.FreeCreditsRemainingCents) / 100.0
+ if balance < minGrant {
+ balance = minGrant
+ }
+ log.Printf("MIGRATE org=%s plan=%s carry_balance=$%.2f max_concurrent=%d (dry_run=%v)",
+ org.ID, org.Plan, balance, org.MaxConcurrentSandboxes, dryRun)
+ if org.MaxConcurrentSandboxes > autumn.DefaultConcurrency {
+ log.Printf(" ⚠ org has max_concurrent=%d (> base %d) — attach the matching Autumn concurrency plan as a comp MANUALLY; this tool does not (comp API unconfirmed)",
+ org.MaxConcurrentSandboxes, autumn.DefaultConcurrency)
+ }
+
+ if dryRun {
+ log.Printf(" [dry-run] would: create customer, set balance $%.2f, flip D1→autumn (+project), flip cell-PG→autumn. auto-topup left OFF.", balance)
+ return
+ }
+
+ // 1. Autumn customer (idempotent) + carry balance over. Auto top-up left OFF.
+ // Link the existing Stripe customer (if any) so a card-on-file org keeps
+ // its saved payment method — confirmed live that POST /customers adopts
+ // an existing stripe_id.
+ cp := autumn.CreateCustomerParams{ID: org.ID.String(), Name: org.Name}
+ if org.StripeCustomerID != nil {
+ cp.StripeID = *org.StripeCustomerID
+ }
+ if _, err := aut.CreateCustomer(ctx, cp); err != nil {
+ log.Fatalf(" create customer: %v", err)
+ }
+ if err := aut.SetCreditBalance(ctx, org.ID.String(), balance); err != nil {
+ log.Fatalf(" set balance: %v", err)
+ }
+ // 2. Flip D1 first (stops legacy edge DO debit + projects is_halted/max_concurrent).
+ if err := edge.SetAutumnProvider(ctx, org.ID, "autumn"); err != nil {
+ log.Fatalf(" flip D1: %v", err)
+ }
+ // 3. Flip cell-PG (starts the Autumn reporter; stops the legacy cell deduction).
+ if err := store.SetBillingProvider(ctx, org.ID, "autumn"); err != nil {
+ log.Fatalf(" flip cell-PG: %v", err)
+ }
+ log.Printf(" ✓ migrated org %s to autumn (balance $%.2f, auto-topup OFF)", org.ID, balance)
+}
+
+func revertOrg(ctx context.Context, store *db.Store, edge *edgeclient.Client, org *db.Org, dryRun bool) {
+ if org.BillingProvider != "autumn" {
+ log.Printf("org %s is not on autumn — nothing to revert", org.ID)
+ return
+ }
+ log.Printf("REVERT org=%s → legacy (dry_run=%v)", org.ID, dryRun)
+ if dryRun {
+ log.Printf(" [dry-run] would: flip cell-PG→legacy, then D1→legacy")
+ return
+ }
+ // cell-PG first (stops the Autumn reporter before the legacy edge debit resumes).
+ if err := store.SetBillingProvider(ctx, org.ID, "legacy"); err != nil {
+ log.Fatalf(" flip cell-PG: %v", err)
+ }
+ if err := edge.SetAutumnProvider(ctx, org.ID, "legacy"); err != nil {
+ log.Fatalf(" flip D1: %v", err)
+ }
+ log.Printf(" ✓ reverted org %s to legacy", org.ID)
+}
+
+func mustEnv(k string) string {
+ v := os.Getenv(k)
+ if v == "" {
+ log.Fatalf("%s is required", k)
+ }
+ return v
+}
diff --git a/cmd/server/main.go b/cmd/server/main.go
index 7cad69e3..2e80291b 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -19,6 +19,7 @@ import (
"github.com/opensandbox/opensandbox/internal/api"
"github.com/opensandbox/opensandbox/internal/auth"
"github.com/opensandbox/opensandbox/internal/billing"
+ "github.com/opensandbox/opensandbox/internal/billing/autumn"
"github.com/opensandbox/opensandbox/internal/cloudflare"
"github.com/opensandbox/opensandbox/internal/compute"
"github.com/opensandbox/opensandbox/internal/config"
@@ -775,6 +776,51 @@ func main() {
log.Println("opensandbox: usage reporter started (interval=5m)")
}
+ // Start Autumn usage reporter (Phase 2: SHADOW). Ships per-org compute/disk
+ // usage to Autumn via track() for orgs flagged billing_provider='autumn',
+ // building the real ledger and logging a parity line against our local cost
+ // math — but never halting yet. Inert unless an Autumn API key is set.
+ if opts.Store != nil && cfg.AutumnSecretKey != "" {
+ var autumnOpts []autumn.Option
+ if cfg.AutumnBaseURL != "" {
+ autumnOpts = append(autumnOpts, autumn.WithBaseURL(cfg.AutumnBaseURL))
+ }
+ autumnClient := autumn.New(cfg.AutumnSecretKey, autumnOpts...)
+ autumnReporter := billing.NewAutumnReporter(opts.Store, autumnClient)
+
+ // Edge client for D1 projection (halt enforce + reconciler). Nil in
+ // combined dev mode where there's no separate edge.
+ var autumnEdge *edgeclient.Client
+ if cfg.CFEdgeBaseURL != "" && cfg.CFEventSecret != "" {
+ autumnEdge = edgeclient.New(cfg.CFEdgeBaseURL, cfg.CFEventSecret)
+ }
+
+ // Enforce mode (off by default): on balance exhaustion, hibernate the
+ // org's sandboxes on this cell AND ask the edge to re-check Autumn and
+ // project is_halted into D1 so create/wake gates reject it everywhere.
+ if cfg.AutumnEnforce {
+ var workers billing.WorkerClientSource
+ if redisRegistry != nil {
+ workers = redisRegistry
+ }
+ autumnReporter.SetEnforce(true)
+ autumnReporter.SetHaltFunc(func(ctx context.Context, orgID uuid.UUID) error {
+ if _, err := billing.EnforceCreditExhaustion(ctx, opts.Store, workers, orgID); err != nil {
+ log.Printf("autumn: local hibernate for %s: %v", orgID, err)
+ }
+ if autumnEdge != nil {
+ return autumnEdge.ProjectAutumnOrg(ctx, orgID)
+ }
+ return nil
+ })
+ log.Println("opensandbox: autumn usage reporter ENFORCING (halt on exhaustion)")
+ }
+
+ autumnReporter.Start()
+ defer autumnReporter.Stop()
+ log.Println("opensandbox: autumn usage reporter started (interval=5m)")
+ }
+
// Halt reconciler — safety net for missed CF halt webhooks. Pulls the
// authoritative halt-list from api-edge every 60s and re-issues halts
// for anything that should be halted but isn't. Inert unless
diff --git a/internal/api/internal_sandbox.go b/internal/api/internal_sandbox.go
index 407e2314..dfb69755 100644
--- a/internal/api/internal_sandbox.go
+++ b/internal/api/internal_sandbox.go
@@ -84,7 +84,7 @@ func (s *Server) internalCreateSandbox(c echo.Context) error {
// and lazily materialize the row here. Plan comes from the cap-token so
// the worker's event resolver can tag usage_tick events correctly.
if s.store != nil {
- if upErr := s.store.UpsertOrgFromCapToken(c.Request().Context(), orgID, claims.Plan); upErr != nil {
+ if upErr := s.store.UpsertOrgFromCapToken(c.Request().Context(), orgID, claims.Plan, claims.BillingProvider); upErr != nil {
// Non-fatal — the create may still succeed; downstream gates fall through
// when the row is missing. Logged so ops can investigate persistent failures.
c.Logger().Errorf("upsert org from cap-token: %v", upErr)
diff --git a/internal/auth/jwt.go b/internal/auth/jwt.go
index c7d29981..8e823a5c 100644
--- a/internal/auth/jwt.go
+++ b/internal/auth/jwt.go
@@ -144,6 +144,11 @@ type CapabilityClaims struct {
// idempotent, and the DO knows the current plan from D1 so it no-ops
// debits for a now-pro org.
Plan string `json:"plan,omitempty"`
+ // BillingProvider mirrors orgs.billing_provider ("legacy" | "autumn") from
+ // D1 → cell-PG via UpsertOrgFromCapToken, so the cell's AutumnReporter sees
+ // which orgs it owns without a separate sync. Empty on older tokens / paths
+ // that don't carry it — the cell then leaves the existing value untouched.
+ BillingProvider string `json:"billing_provider,omitempty"`
}
// CapabilityIssuer is the Issuer string on capability tokens — lets the CP
@@ -155,7 +160,7 @@ const CapabilityIssuer = "opensandbox-edge"
// be empty when the caller doesn't have it handy — the cell will then
// fall back to a PG lookup, which is a small performance hit but never
// incorrect.
-func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID, plan string, userID *string, ttl time.Duration) (string, error) {
+func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID, plan, billingProvider string, userID *string, ttl time.Duration) (string, error) {
now := time.Now()
claims := CapabilityClaims{
RegisteredClaims: jwt.RegisteredClaims{
@@ -164,10 +169,11 @@ func (j *JWTIssuer) IssueCapabilityToken(orgID, cellID, plan string, userID *str
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
Issuer: CapabilityIssuer,
},
- OrgID: orgID,
- CellID: cellID,
- UserID: userID,
- Plan: plan,
+ OrgID: orgID,
+ CellID: cellID,
+ UserID: userID,
+ Plan: plan,
+ BillingProvider: billingProvider,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(j.secret)
diff --git a/internal/billing/autumn/autumn.go b/internal/billing/autumn/autumn.go
new file mode 100644
index 00000000..816c7a79
--- /dev/null
+++ b/internal/billing/autumn/autumn.go
@@ -0,0 +1,195 @@
+// Package autumn is a thin Go client for the Autumn billing API
+// (useautumn.com). Autumn is the source of truth for credit balances and the
+// customer's active plans; this package is how the cell creates customers,
+// reports usage (track), reads balances/plans, and starts checkouts.
+//
+// The shapes here were validated against the live sandbox API:
+//
+// POST /v1/customers {id,name,email} -> Customer
+// GET /v1/customers/{id} -> Customer
+// POST /v1/track {customer_id,feature_id,value,idempotency_key} -> {balance}
+// POST /v1/check {customer_id,feature_id} -> {allowed,balance}
+// POST /v1/checkout {customer_id,product_id,options,success_url} -> {url,total}
+//
+// Auth: Authorization: Bearer am_sk_… JSON bodies are snake_case. Notably the
+// idempotency field is `idempotency_key` (snake_case) — the camelCase form in
+// Autumn's docs is silently ignored and will NOT dedupe.
+package autumn
+
+import (
+ "context"
+ "fmt"
+)
+
+// CreditsFeatureID is the monetary credit-balance feature.
+const CreditsFeatureID = "credits"
+
+// Client is the Autumn API surface the platform depends on. A fake
+// implementation (see fake.go) backs tests and lets the rest of the billing
+// system be built before pointing at the live API.
+type Client interface {
+ // CreateCustomer registers an org as an Autumn customer. Autumn auto-attaches
+ // the default plan (base) and its one-time credit grant.
+ CreateCustomer(ctx context.Context, p CreateCustomerParams) (*Customer, error)
+ // GetCustomer returns the customer's active subscriptions + feature balances.
+ // This is the authoritative read used to sync the is_halted / max_concurrent
+ // projections and to re-check on resume.
+ GetCustomer(ctx context.Context, customerID string) (*Customer, error)
+ // Track reports usage of a feature, deducting from the credit balance. The
+ // returned balance is the post-deduction state, so callers can halt inline
+ // when Remaining <= 0. IdempotencyKey makes retries safe.
+ Track(ctx context.Context, p TrackParams) (*TrackResult, error)
+ // Check reports whether the customer has access/balance for a feature.
+ Check(ctx context.Context, p CheckParams) (*CheckResult, error)
+ // Checkout starts a Stripe checkout for a product — a one-off top-up or a
+ // recurring plan subscription — and returns the URL to redirect the user to.
+ Checkout(ctx context.Context, p CheckoutParams) (*CheckoutResult, error)
+ // SetCreditBalance overwrites the customer's `credits` balance to the given
+ // dollar amount. Used by the migration backfill to carry an org's legacy
+ // balance over to Autumn (Autumn floors at 0 when overage isn't allowed).
+ SetCreditBalance(ctx context.Context, customerID string, balance float64) error
+}
+
+// CreateCustomerParams identifies a new customer (we use the org UUID as the id).
+type CreateCustomerParams struct {
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ Email string `json:"email,omitempty"`
+ // StripeID links an existing Stripe customer (confirmed accepted live) so a
+ // migrated card-on-file org keeps its saved payment method — no re-entry.
+ StripeID string `json:"stripe_id,omitempty"`
+}
+
+// TrackParams reports `Value` units of `FeatureID` for a customer.
+//
+// IdempotencyKey is GLOBAL across all customers (Autumn dedupes on the bare key,
+// not customer+key), so it must be globally unique — use e.g.
+// "<org_id>:<bucket_start>:<feature_id>". A repeat returns 409, surfaced as
+// TrackResult.Duplicate.
+type TrackParams struct {
+ CustomerID string `json:"customer_id"`
+ FeatureID string `json:"feature_id"`
+ Value float64 `json:"value"`
+ IdempotencyKey string `json:"idempotency_key,omitempty"`
+}
+
+// TrackResult carries the post-deduction balance. Duplicate is true when the
+// idempotency_key had already been seen (Autumn returns 409
+// duplicate_idempotency_key) — the usage was applied by the earlier call, and
+// Balance reflects the current re-fetched state so callers can still act on it.
+type TrackResult struct {
+ Balance Balance
+ Duplicate bool
+}
+
+// CheckParams asks whether a customer can use a feature.
+type CheckParams struct {
+ CustomerID string `json:"customer_id"`
+ FeatureID string `json:"feature_id"`
+}
+
+// CheckResult is the access decision + current balance.
+type CheckResult struct {
+ Allowed bool
+ Balance Balance
+}
+
+// CheckoutParams starts a checkout for a product. Options sets per-feature
+// quantities (e.g. credits=10 for a $10 top-up). SuccessURL is where Stripe
+// redirects after payment — our handler re-checks the balance there to resume.
+type CheckoutParams struct {
+ CustomerID string `json:"customer_id"`
+ ProductID string `json:"product_id"`
+ Options []CheckoutOption `json:"options,omitempty"`
+ SuccessURL string `json:"success_url,omitempty"`
+}
+
+// CheckoutOption sets a quantity for a priced feature in the product.
+type CheckoutOption struct {
+ FeatureID string `json:"feature_id"`
+ Quantity int `json:"quantity"`
+}
+
+// CheckoutResult is the Stripe checkout to redirect the user to.
+type CheckoutResult struct {
+ URL string `json:"url"`
+ Total float64 `json:"total"`
+ Currency string `json:"currency"`
+}
+
+// Customer is the Autumn customer record: who they are, their active plans, and
+// their feature balances.
+type Customer struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Email string `json:"email"`
+ Subscriptions []Subscription `json:"subscriptions"`
+ Balances map[string]Balance `json:"balances"`
+}
+
+// Subscription is one active plan the customer holds (base, a concurrency tier,
+// etc.). AddOn distinguishes a stacking add-on (concurrency) from the default.
+type Subscription struct {
+ PlanID string `json:"plan_id"`
+ AddOn bool `json:"add_on"`
+ Status string `json:"status"`
+}
+
+// Balance is a feature balance (for `credits`: the prepaid $ balance).
+type Balance struct {
+ FeatureID string `json:"feature_id"`
+ Granted float64 `json:"granted"`
+ Remaining float64 `json:"remaining"`
+ Usage float64 `json:"usage"`
+ Unlimited bool `json:"unlimited"`
+}
+
+// CreditsRemaining returns the customer's prepaid credit balance ($). Drives the
+// is_halted projection: <= 0 means halt.
+func (c *Customer) CreditsRemaining() float64 {
+ return c.Balances[CreditsFeatureID].Remaining
+}
+
+// ConcurrencyByPlan maps a plan id to the concurrent-sandbox limit it grants.
+// Concurrency is enforced from our DB; Autumn only tells us which plan the org
+// is on. Keep in sync with the Autumn concurrency products.
+var ConcurrencyByPlan = map[string]int{
+ "base": 5,
+ "concurrency_pro": 100,
+ "concurrency_pro_plus": 600,
+ "concurrency_pro_plus_plus": 1000,
+}
+
+// DefaultConcurrency applies when no known concurrency plan is active.
+const DefaultConcurrency = 5
+
+// MaxConcurrency resolves the customer's concurrency limit from their active
+// plans — the highest limit among them (so an add-on tier wins over base).
+func (c *Customer) MaxConcurrency() int {
+ limit := DefaultConcurrency
+ for _, s := range c.Subscriptions {
+ if s.Status != "" && s.Status != "active" {
+ continue
+ }
+ if v, ok := ConcurrencyByPlan[s.PlanID]; ok && v > limit {
+ limit = v
+ }
+ }
+ return limit
+}
+
+// APIError is a non-2xx response from Autumn.
+type APIError struct {
+ StatusCode int
+ Body string
+}
+
+func (e *APIError) Error() string {
+ return fmt.Sprintf("autumn: http %d: %s", e.StatusCode, e.Body)
+}
+
+// IsNotFound reports whether err is a 404 from Autumn (e.g. unknown customer).
+func IsNotFound(err error) bool {
+ var ae *APIError
+ return asAPIError(err, &ae) && ae.StatusCode == 404
+}
diff --git a/internal/billing/autumn/autumn_test.go b/internal/billing/autumn/autumn_test.go
new file mode 100644
index 00000000..b28a6cee
--- /dev/null
+++ b/internal/billing/autumn/autumn_test.go
@@ -0,0 +1,134 @@
+package autumn
+
+import (
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+// The REST client must send the snake_case wire format we validated against the
+// sandbox — especially idempotency_key (the camelCase form is silently ignored).
+func TestRESTClient_Track_WireFormat(t *testing.T) {
+ var got map[string]any
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/track" || r.Method != http.MethodPost {
+ t.Errorf("unexpected %s %s", r.Method, r.URL.Path)
+ }
+ if r.Header.Get("Authorization") != "Bearer am_sk_test_x" {
+ t.Errorf("bad auth header: %q", r.Header.Get("Authorization"))
+ }
+ b, _ := io.ReadAll(r.Body)
+ _ = json.Unmarshal(b, &got)
+ _, _ = w.Write([]byte(`{"balance":{"feature_id":"credits","remaining":4.46,"usage":0.54,"granted":5}}`))
+ }))
+ defer srv.Close()
+
+ c := New("am_sk_test_x", WithBaseURL(srv.URL))
+ res, err := c.Track(context.Background(), TrackParams{
+ CustomerID: "org-1", FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: "k1",
+ })
+ if err != nil {
+ t.Fatalf("track: %v", err)
+ }
+ if got["customer_id"] != "org-1" || got["feature_id"] != "compute_64gb" {
+ t.Fatalf("wrong body: %v", got)
+ }
+ if got["value"].(float64) != 1000 {
+ t.Fatalf("wrong value: %v", got["value"])
+ }
+ if got["idempotency_key"] != "k1" {
+ t.Fatalf("idempotency_key must be snake_case and present, got: %v", got["idempotency_key"])
+ }
+ if res.Balance.Remaining != 4.46 {
+ t.Fatalf("decoded remaining = %v, want 4.46", res.Balance.Remaining)
+ }
+}
+
+func TestRESTClient_GetCustomer_DecodesPlansAndBalance(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, _ = w.Write([]byte(`{
+ "id":"org-1",
+ "subscriptions":[
+ {"plan_id":"base","add_on":false,"status":"active"},
+ {"plan_id":"concurrency_pro","add_on":true,"status":"active"}
+ ],
+ "balances":{"credits":{"feature_id":"credits","remaining":3.38,"granted":5,"usage":1.62}}
+ }`))
+ }))
+ defer srv.Close()
+
+ c := New("am_sk_test_x", WithBaseURL(srv.URL))
+ cust, err := c.GetCustomer(context.Background(), "org-1")
+ if err != nil {
+ t.Fatalf("get: %v", err)
+ }
+ if cust.CreditsRemaining() != 3.38 {
+ t.Fatalf("credits = %v, want 3.38", cust.CreditsRemaining())
+ }
+ if cust.MaxConcurrency() != 100 {
+ t.Fatalf("concurrency = %d, want 100 (base+pro → max)", cust.MaxConcurrency())
+ }
+}
+
+func TestRESTClient_APIError(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusNotFound)
+ _, _ = w.Write([]byte(`{"error":"not found"}`))
+ }))
+ defer srv.Close()
+ c := New("am_sk_test_x", WithBaseURL(srv.URL))
+ _, err := c.GetCustomer(context.Background(), "missing")
+ if !IsNotFound(err) {
+ t.Fatalf("expected IsNotFound, got %v", err)
+ }
+}
+
+func TestMaxConcurrency_Mapping(t *testing.T) {
+ cases := []struct {
+ plans []string
+ want int
+ }{
+ {[]string{"base"}, 5},
+ {[]string{"base", "concurrency_pro"}, 100},
+ {[]string{"base", "concurrency_pro_plus"}, 600},
+ {[]string{"base", "concurrency_pro_plus_plus"}, 1000},
+ {[]string{"base", "concurrency_pro", "concurrency_pro_plus_plus"}, 1000}, // max wins
+ {nil, 5}, // no plans → default
+ }
+ for _, tc := range cases {
+ c := &Customer{}
+ for _, p := range tc.plans {
+ c.Subscriptions = append(c.Subscriptions, Subscription{PlanID: p, Status: "active"})
+ }
+ if got := c.MaxConcurrency(); got != tc.want {
+ t.Errorf("plans %v → %d, want %d", tc.plans, got, tc.want)
+ }
+ }
+}
+
+func TestFake_TrackDeductsAndDedupes(t *testing.T) {
+ f := NewFake()
+ ctx := context.Background()
+ if _, err := f.CreateCustomer(ctx, CreateCustomerParams{ID: "org-1"}); err != nil {
+ t.Fatal(err)
+ }
+ // compute_64gb × 1000 = 0.54 credits.
+ r, _ := f.Track(ctx, TrackParams{CustomerID: "org-1", FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: "k1"})
+ if d := 5 - r.Balance.Remaining; d < 0.539 || d > 0.541 {
+ t.Fatalf("deducted %v, want ~0.54", d)
+ }
+ // same key again → no further deduction.
+ r2, _ := f.Track(ctx, TrackParams{CustomerID: "org-1", FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: "k1"})
+ if r2.Balance.Remaining != r.Balance.Remaining {
+ t.Fatalf("idempotency failed: %v → %v", r.Balance.Remaining, r2.Balance.Remaining)
+ }
+ // top-up restores balance.
+ f.SimulateTopUp("org-1", 10)
+ cust, _ := f.GetCustomer(ctx, "org-1")
+ if cust.CreditsRemaining() < 14 {
+ t.Fatalf("after top-up remaining = %v, want > 14", cust.CreditsRemaining())
+ }
+}
diff --git a/internal/billing/autumn/client.go b/internal/billing/autumn/client.go
new file mode 100644
index 00000000..dea134fe
--- /dev/null
+++ b/internal/billing/autumn/client.go
@@ -0,0 +1,159 @@
+package autumn
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+ "time"
+)
+
+// DefaultBaseURL is the Autumn API root. The sandbox and live environments are
+// selected by the API key (am_sk_test_… vs am_sk_…), not the URL.
+const DefaultBaseURL = "https://api.useautumn.com/v1"
+
+// RESTClient is the live Autumn API client.
+type RESTClient struct {
+ baseURL string
+ apiKey string
+ http *http.Client
+}
+
+// Option configures a RESTClient.
+type Option func(*RESTClient)
+
+// WithBaseURL overrides the API root (tests point this at an httptest server).
+func WithBaseURL(u string) Option { return func(c *RESTClient) { c.baseURL = u } }
+
+// WithHTTPClient overrides the underlying HTTP client.
+func WithHTTPClient(h *http.Client) Option { return func(c *RESTClient) { c.http = h } }
+
+// New builds a live client. apiKey is the Autumn secret key (am_sk_…).
+func New(apiKey string, opts ...Option) *RESTClient {
+ c := &RESTClient{
+ baseURL: DefaultBaseURL,
+ apiKey: apiKey,
+ http: &http.Client{Timeout: 15 * time.Second},
+ }
+ for _, o := range opts {
+ o(c)
+ }
+ return c
+}
+
+var _ Client = (*RESTClient)(nil)
+
+// do executes a JSON request and decodes the response into out (if non-nil).
+func (c *RESTClient) do(ctx context.Context, method, path string, body, out any) error {
+ var rdr io.Reader
+ if body != nil {
+ b, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("autumn: marshal %s: %w", path, err)
+ }
+ rdr = bytes.NewReader(b)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, rdr)
+ if err != nil {
+ return fmt.Errorf("autumn: build request %s: %w", path, err)
+ }
+ req.Header.Set("Authorization", "Bearer "+c.apiKey)
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.http.Do(req)
+ if err != nil {
+ return fmt.Errorf("autumn: %s %s: %w", method, path, err)
+ }
+ defer resp.Body.Close()
+
+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ return &APIError{StatusCode: resp.StatusCode, Body: string(data)}
+ }
+ if out != nil {
+ if err := json.Unmarshal(data, out); err != nil {
+ return fmt.Errorf("autumn: decode %s: %w", path, err)
+ }
+ }
+ return nil
+}
+
+func (c *RESTClient) CreateCustomer(ctx context.Context, p CreateCustomerParams) (*Customer, error) {
+ var cust Customer
+ if err := c.do(ctx, http.MethodPost, "/customers", p, &cust); err != nil {
+ return nil, err
+ }
+ return &cust, nil
+}
+
+func (c *RESTClient) GetCustomer(ctx context.Context, customerID string) (*Customer, error) {
+ var cust Customer
+ if err := c.do(ctx, http.MethodGet, "/customers/"+customerID, nil, &cust); err != nil {
+ return nil, err
+ }
+ return &cust, nil
+}
+
+func (c *RESTClient) Track(ctx context.Context, p TrackParams) (*TrackResult, error) {
+ var resp struct {
+ Balance Balance `json:"balance"`
+ }
+ err := c.do(ctx, http.MethodPost, "/track", p, &resp)
+ if err == nil {
+ return &TrackResult{Balance: resp.Balance}, nil
+ }
+ // A duplicate idempotency_key means this usage was already applied (a retry
+ // after the first call succeeded server-side). Not an error — re-fetch the
+ // current balance so the caller can still act (e.g. halt on remaining <= 0).
+ if isDuplicateIdempotency(err) {
+ cust, gerr := c.GetCustomer(ctx, p.CustomerID)
+ if gerr != nil {
+ return &TrackResult{Duplicate: true}, nil
+ }
+ return &TrackResult{Balance: cust.Balances[CreditsFeatureID], Duplicate: true}, nil
+ }
+ return nil, err
+}
+
+// isDuplicateIdempotency reports whether err is Autumn's 409
+// duplicate_idempotency_key response.
+func isDuplicateIdempotency(err error) bool {
+ var ae *APIError
+ return errors.As(err, &ae) && ae.StatusCode == http.StatusConflict &&
+ strings.Contains(ae.Body, "duplicate_idempotency_key")
+}
+
+func (c *RESTClient) Check(ctx context.Context, p CheckParams) (*CheckResult, error) {
+ var resp struct {
+ Allowed bool `json:"allowed"`
+ Balance Balance `json:"balance"`
+ }
+ if err := c.do(ctx, http.MethodPost, "/check", p, &resp); err != nil {
+ return nil, err
+ }
+ return &CheckResult{Allowed: resp.Allowed, Balance: resp.Balance}, nil
+}
+
+func (c *RESTClient) Checkout(ctx context.Context, p CheckoutParams) (*CheckoutResult, error) {
+ var res CheckoutResult
+ if err := c.do(ctx, http.MethodPost, "/checkout", p, &res); err != nil {
+ return nil, err
+ }
+ return &res, nil
+}
+
+// SetCreditBalance overwrites the `credits` balance via POST /customers/{id}/balances.
+func (c *RESTClient) SetCreditBalance(ctx context.Context, customerID string, balance float64) error {
+ body := map[string]any{
+ "balances": []map[string]any{{"feature_id": CreditsFeatureID, "balance": balance}},
+ }
+ return c.do(ctx, http.MethodPost, "/customers/"+customerID+"/balances", body, nil)
+}
+
+func asAPIError(err error, target **APIError) bool {
+ return errors.As(err, target)
+}
diff --git a/internal/billing/autumn/fake.go b/internal/billing/autumn/fake.go
new file mode 100644
index 00000000..4e1e3f62
--- /dev/null
+++ b/internal/billing/autumn/fake.go
@@ -0,0 +1,157 @@
+package autumn
+
+import (
+ "context"
+ "sync"
+)
+
+// Fake is an in-memory Client for tests. It mirrors Autumn's behavior: customers
+// get the base plan + a signup grant, track() deducts per the credit schema and
+// dedupes on idempotency_key, and checkout() returns a stub URL (call
+// SimulateTopUp/SimulatePlanChange to model payment completing).
+type Fake struct {
+ mu sync.Mutex
+ customers map[string]*Customer
+ seenKeys map[string]bool
+
+ // CreditCosts maps a metered feature to its per-unit credit cost (mirrors the
+ // Autumn credit schema). SignupGrant is the one-time base grant.
+ CreditCosts map[string]float64
+ SignupGrant float64
+}
+
+// NewFake builds a Fake seeded with the production credit schema + $5 grant.
+func NewFake() *Fake {
+ return &Fake{
+ customers: map[string]*Customer{},
+ seenKeys: map[string]bool{},
+ CreditCosts: map[string]float64{
+ "compute_1gb": 0.00000108,
+ "compute_4gb": 0.00000579,
+ "compute_8gb": 0.0000135,
+ "compute_16gb": 0.0000270,
+ "compute_32gb": 0.000193,
+ "compute_64gb": 0.000540,
+ "disk_overage": 0.0000001,
+ },
+ SignupGrant: 5,
+ }
+}
+
+var _ Client = (*Fake)(nil)
+
+func (f *Fake) CreateCustomer(_ context.Context, p CreateCustomerParams) (*Customer, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if c, ok := f.customers[p.ID]; ok {
+ return clone(c), nil
+ }
+ c := &Customer{
+ ID: p.ID,
+ Name: p.Name,
+ Email: p.Email,
+ Subscriptions: []Subscription{
+ {PlanID: "base", AddOn: false, Status: "active"},
+ },
+ Balances: map[string]Balance{
+ CreditsFeatureID: {FeatureID: CreditsFeatureID, Granted: f.SignupGrant, Remaining: f.SignupGrant},
+ },
+ }
+ f.customers[p.ID] = c
+ return clone(c), nil
+}
+
+func (f *Fake) GetCustomer(_ context.Context, customerID string) (*Customer, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ c, ok := f.customers[customerID]
+ if !ok {
+ return nil, &APIError{StatusCode: 404, Body: "customer not found"}
+ }
+ return clone(c), nil
+}
+
+func (f *Fake) Track(_ context.Context, p TrackParams) (*TrackResult, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ c, ok := f.customers[p.CustomerID]
+ if !ok {
+ return nil, &APIError{StatusCode: 404, Body: "customer not found"}
+ }
+ if p.IdempotencyKey != "" {
+ dk := p.IdempotencyKey // global dedupe, mirroring Autumn
+ if f.seenKeys[dk] {
+ return &TrackResult{Balance: c.Balances[CreditsFeatureID], Duplicate: true}, nil // deduped
+ }
+ f.seenKeys[dk] = true
+ }
+ cost := p.Value * f.CreditCosts[p.FeatureID]
+ b := c.Balances[CreditsFeatureID]
+ b.Remaining -= cost
+ b.Usage += cost
+ c.Balances[CreditsFeatureID] = b
+ return &TrackResult{Balance: b}, nil
+}
+
+func (f *Fake) Check(_ context.Context, p CheckParams) (*CheckResult, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ c, ok := f.customers[p.CustomerID]
+ if !ok {
+ return nil, &APIError{StatusCode: 404, Body: "customer not found"}
+ }
+ b := c.Balances[p.FeatureID]
+ return &CheckResult{Allowed: b.Unlimited || b.Remaining > 0, Balance: b}, nil
+}
+
+func (f *Fake) Checkout(_ context.Context, p CheckoutParams) (*CheckoutResult, error) {
+ return &CheckoutResult{
+ URL: "https://checkout.stripe.test/" + p.ProductID,
+ Currency: "usd",
+ }, nil
+}
+
+// SetCreditBalance overwrites the credits balance (migration carry-over).
+func (f *Fake) SetCreditBalance(_ context.Context, customerID string, balance float64) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ c, ok := f.customers[customerID]
+ if !ok {
+ return &APIError{StatusCode: 404, Body: "customer not found"}
+ }
+ b := c.Balances[CreditsFeatureID]
+ b.Remaining = balance
+ c.Balances[CreditsFeatureID] = b
+ return nil
+}
+
+// SimulateTopUp models a completed credit purchase (manual or auto-recharge).
+func (f *Fake) SimulateTopUp(customerID string, credits float64) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if c, ok := f.customers[customerID]; ok {
+ b := c.Balances[CreditsFeatureID]
+ b.Remaining += credits
+ b.Granted += credits
+ c.Balances[CreditsFeatureID] = b
+ }
+}
+
+// SimulatePlanChange models subscribing to / changing a concurrency plan.
+func (f *Fake) SimulatePlanChange(customerID, planID string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if c, ok := f.customers[customerID]; ok {
+ c.Subscriptions = append(c.Subscriptions, Subscription{PlanID: planID, AddOn: true, Status: "active"})
+ }
+}
+
+func clone(c *Customer) *Customer {
+ cp := *c
+ cp.Subscriptions = append([]Subscription(nil), c.Subscriptions...)
+ cp.Balances = make(map[string]Balance, len(c.Balances))
+ for k, v := range c.Balances {
+ cp.Balances[k] = v
+ }
+ return &cp
+}
diff --git a/internal/billing/autumn/integration_test.go b/internal/billing/autumn/integration_test.go
new file mode 100644
index 00000000..6a699d72
--- /dev/null
+++ b/internal/billing/autumn/integration_test.go
@@ -0,0 +1,70 @@
+package autumn
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+)
+
+// Live smoke test against the Autumn sandbox. Skipped unless AUTUMN_SANDBOX_KEY
+// is set, so normal `go test` stays offline. Run with:
+//
+// AUTUMN_SANDBOX_KEY=am_sk_test_… go test ./internal/billing/autumn/ -run TestLive -v
+func TestLive_CustomerTrackFlow(t *testing.T) {
+ key := os.Getenv("AUTUMN_SANDBOX_KEY")
+ if key == "" {
+ t.Skip("set AUTUMN_SANDBOX_KEY to run the live sandbox smoke test")
+ }
+ c := New(key)
+ ctx := context.Background()
+ id := "oc-itest-" + time.Now().Format("20060102150405")
+
+ cust, err := c.CreateCustomer(ctx, CreateCustomerParams{ID: id, Name: "oc integration test"})
+ if err != nil {
+ t.Fatalf("create: %v", err)
+ }
+ if cust.CreditsRemaining() != 5 {
+ t.Fatalf("signup grant = %v, want 5", cust.CreditsRemaining())
+ }
+ if cust.MaxConcurrency() != 5 {
+ t.Fatalf("base concurrency = %d, want 5", cust.MaxConcurrency())
+ }
+
+ // Track 1000s of compute_64gb (× 0.00054 = 0.54 credits). The idempotency key
+ // is GLOBAL, so make it unique per run.
+ idemKey := id + ":compute_64gb:1"
+ r, err := c.Track(ctx, TrackParams{CustomerID: id, FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: idemKey})
+ if err != nil {
+ t.Fatalf("track: %v", err)
+ }
+ if d := 5 - r.Balance.Remaining; d < 0.539 || d > 0.541 {
+ t.Fatalf("deducted %v, want ~0.54", d)
+ }
+
+ // Same key → no further deduction (live idempotency).
+ r2, err := c.Track(ctx, TrackParams{CustomerID: id, FeatureID: "compute_64gb", Value: 1000, IdempotencyKey: idemKey})
+ if err != nil {
+ t.Fatalf("track 2: %v", err)
+ }
+ if !r2.Duplicate {
+ t.Fatalf("expected Duplicate=true on repeated idempotency_key")
+ }
+ if r2.Balance.Remaining != r.Balance.Remaining {
+ t.Fatalf("live idempotency failed: %v → %v", r.Balance.Remaining, r2.Balance.Remaining)
+ }
+
+ // Checkout a top-up → must return a Stripe URL.
+ co, err := c.Checkout(ctx, CheckoutParams{
+ CustomerID: id, ProductID: "top_up",
+ Options: []CheckoutOption{{FeatureID: "credits", Quantity: 10}},
+ SuccessURL: "https://app.opencomputer.dev/billing",
+ })
+ if err != nil {
+ t.Fatalf("checkout: %v", err)
+ }
+ if co.URL == "" {
+ t.Fatalf("checkout returned no url")
+ }
+ t.Logf("live OK: remaining=%.4f checkout=%s", r2.Balance.Remaining, co.URL[:40])
+}
diff --git a/internal/billing/autumn/usage.go b/internal/billing/autumn/usage.go
new file mode 100644
index 00000000..5072b292
--- /dev/null
+++ b/internal/billing/autumn/usage.go
@@ -0,0 +1,34 @@
+package autumn
+
+import "fmt"
+
+// DiskOverageFeatureID is the metered feature for disk used above the included
+// allowance (value tracked in GB-seconds).
+const DiskOverageFeatureID = "disk_overage"
+
+// tierFeatureByMemoryMB maps a sandbox memory tier (MB) to its Autumn compute
+// feature. Keep in sync with the per-tier rates in internal/billing/pricing.go
+// and the credit schema configured in Autumn.
+var tierFeatureByMemoryMB = map[int]string{
+ 1024: "compute_1gb",
+ 4096: "compute_4gb",
+ 8192: "compute_8gb",
+ 16384: "compute_16gb",
+ 32768: "compute_32gb",
+ 65536: "compute_64gb",
+}
+
+// FeatureForMemoryMB returns the Autumn compute feature id for a memory tier,
+// or ("", false) if the tier is unknown (caller should skip + log).
+func FeatureForMemoryMB(mb int) (string, bool) {
+ f, ok := tierFeatureByMemoryMB[mb]
+ return f, ok
+}
+
+// UsageIdempotencyKey builds a globally-unique, retry-stable idempotency key for
+// a usage bucket. Autumn dedupes on the bare key across all customers, so it
+// must include the org; it must also be stable across retries, so it's keyed on
+// the bucket start (not wall-clock now).
+func UsageIdempotencyKey(orgID string, bucketStartUnix int64, featureID string) string {
+ return fmt.Sprintf("usage:%s:%d:%s", orgID, bucketStartUnix, featureID)
+}
diff --git a/internal/billing/autumn/usage_test.go b/internal/billing/autumn/usage_test.go
new file mode 100644
index 00000000..6db6dd16
--- /dev/null
+++ b/internal/billing/autumn/usage_test.go
@@ -0,0 +1,44 @@
+package autumn
+
+import "testing"
+
+func TestFeatureForMemoryMB(t *testing.T) {
+ cases := map[int]string{
+ 1024: "compute_1gb",
+ 4096: "compute_4gb",
+ 8192: "compute_8gb",
+ 16384: "compute_16gb",
+ 32768: "compute_32gb",
+ 65536: "compute_64gb",
+ }
+ for mb, want := range cases {
+ if got, ok := FeatureForMemoryMB(mb); !ok || got != want {
+ t.Errorf("FeatureForMemoryMB(%d) = (%q,%v), want (%q,true)", mb, got, ok, want)
+ }
+ }
+ if got, ok := FeatureForMemoryMB(2048); ok {
+ t.Errorf("FeatureForMemoryMB(2048) = (%q,true), want unknown", got)
+ }
+}
+
+func TestUsageIdempotencyKey(t *testing.T) {
+ // Stable across calls (retry-safe) and namespaced by org+bucket+feature so
+ // it's globally unique under Autumn's bare-key dedupe.
+ a := UsageIdempotencyKey("org-1", 1000, "compute_8gb")
+ if a != "usage:org-1:1000:compute_8gb" {
+ t.Fatalf("unexpected key %q", a)
+ }
+ if UsageIdempotencyKey("org-1", 1000, "compute_8gb") != a {
+ t.Fatal("key not deterministic")
+ }
+ // Any axis change must produce a distinct key.
+ for _, other := range []string{
+ UsageIdempotencyKey("org-2", 1000, "compute_8gb"),
+ UsageIdempotencyKey("org-1", 1001, "compute_8gb"),
+ UsageIdempotencyKey("org-1", 1000, "compute_4gb"),
+ } {
+ if other == a {
+ t.Fatalf("key collision: %q", other)
+ }
+ }
+}
diff --git a/internal/billing/autumn_reporter.go b/internal/billing/autumn_reporter.go
new file mode 100644
index 00000000..acc9fbcd
--- /dev/null
+++ b/internal/billing/autumn_reporter.go
@@ -0,0 +1,238 @@
+package billing
+
+import (
+ "context"
+ "log"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/billing/autumn"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// autumnBucketSize is the fixed window each track() call covers. Buckets are
+// aligned to each org's seed watermark (not wall-clock) and are the unit of
+// idempotency: a retried bucket reuses the same idempotency_key, so Autumn
+// dedupes it. It also bounds the overspend window once enforcement is on
+// (Phase 3) — usage can run at most one bucket past a zero balance before the
+// inline halt fires. 5m matches the legacy reporter's debit cadence.
+const autumnBucketSize = 5 * time.Minute
+
+// autumnUsageStore is the narrow slice of *db.Store the reporter needs. Keeping
+// it an interface lets the bucket/idempotency logic be unit-tested against an
+// in-memory fake without standing up Postgres.
+type autumnUsageStore interface {
+ ListAutumnOrgIDsWithUsage(ctx context.Context) ([]uuid.UUID, error)
+ GetOrg(ctx context.Context, id uuid.UUID) (*db.Org, error)
+ GetOrgUsage(ctx context.Context, orgID string, from, to time.Time) ([]db.OrgUsageSummary, error)
+ SetLastUsageSyncedAt(ctx context.Context, orgID uuid.UUID, t time.Time) error
+}
+
+// HaltFunc halts an org whose Autumn balance is exhausted: hibernate its running
+// sandboxes locally (via EnforceCreditExhaustion) and project is_halted to the
+// edge (D1) so create/wake gates reject it everywhere. Injected via SetHaltFunc;
+// nil keeps the reporter in shadow (log-only) even when enforce is on.
+type HaltFunc func(ctx context.Context, orgID uuid.UUID) error
+
+// AutumnReporter ships per-org compute/disk usage to Autumn via track(). It is
+// the Autumn-side counterpart of UsageReporter and runs only for orgs flagged
+// billing_provider='autumn'.
+//
+// Phase 2 (now): SHADOW. It tracks usage to Autumn (building the real ledger)
+// but never halts — it only logs a parity line comparing our locally-computed
+// cost against Autumn's returned balance, so we can confirm Autumn's credit
+// schema matches pricing.go before any org's sandboxes are gated on it.
+//
+// Phase 3 will flip enforce=true: when a bucket's track() comes back with
+// Remaining <= 0, the reporter halts the org inline (same tightness as today's
+// debit loop) instead of just logging.
+type AutumnReporter struct {
+ store autumnUsageStore
+ client autumn.Client
+ interval time.Duration
+ enforce bool
+ halt HaltFunc // invoked on exhaustion when enforce is on
+ now func() time.Time // injectable clock (tests)
+
+ stop chan struct{}
+ stopped chan struct{}
+}
+
+func NewAutumnReporter(store autumnUsageStore, client autumn.Client) *AutumnReporter {
+ return &AutumnReporter{
+ store: store,
+ client: client,
+ interval: 5 * time.Minute,
+ enforce: false, // shadow until Phase 3
+ now: time.Now,
+ stop: make(chan struct{}),
+ stopped: make(chan struct{}),
+ }
+}
+
+// SetEnforce flips the reporter out of shadow mode: track() responses with a
+// non-positive balance halt the org inline (requires a HaltFunc). Wired in Phase 3.
+func (r *AutumnReporter) SetEnforce(enabled bool) { r.enforce = enabled }
+
+// SetHaltFunc installs the action taken when an org's balance is exhausted.
+func (r *AutumnReporter) SetHaltFunc(fn HaltFunc) { r.halt = fn }
+
+func (r *AutumnReporter) Start() { go r.loop() }
+func (r *AutumnReporter) Stop() { close(r.stop); <-r.stopped }
+
+func (r *AutumnReporter) loop() {
+ defer close(r.stopped)
+ ticker := time.NewTicker(r.interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ticker.C:
+ r.safeReportAll()
+ case <-r.stop:
+ return
+ }
+ }
+}
+
+func (r *AutumnReporter) safeReportAll() {
+ defer func() {
+ if p := recover(); p != nil {
+ log.Printf("autumn-reporter: panic in tick: %v", p)
+ }
+ }()
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ r.reportAll(ctx)
+}
+
+func (r *AutumnReporter) reportAll(ctx context.Context) {
+ orgIDs, err := r.store.ListAutumnOrgIDsWithUsage(ctx)
+ if err != nil {
+ log.Printf("autumn-reporter: failed to list autumn orgs: %v", err)
+ return
+ }
+ if len(orgIDs) == 0 {
+ return
+ }
+ log.Printf("autumn-reporter: tracking usage for %d org(s)", len(orgIDs))
+ for _, orgID := range orgIDs {
+ if err := r.reportOrg(ctx, orgID); err != nil {
+ log.Printf("autumn-reporter: org %s: %v", orgID, err)
+ }
+ }
+}
+
+// reportOrg ships every fully-elapsed bucket since the org's watermark to
+// Autumn, advancing the watermark one bucket at a time so a mid-run failure
+// only replays the unfinished bucket (whose idempotency keys dedupe).
+func (r *AutumnReporter) reportOrg(ctx context.Context, orgID uuid.UUID) error {
+ org, err := r.store.GetOrg(ctx, orgID)
+ if err != nil {
+ return err
+ }
+ if org.BillingProvider != "autumn" {
+ return nil // flag flipped back between listing and now
+ }
+
+ now := r.now()
+
+ // First sight: seed the watermark to now and bill forward only — never
+ // retroactively charge usage that accrued before the org moved to Autumn.
+ if org.LastUsageSyncedAt == nil {
+ if err := r.store.SetLastUsageSyncedAt(ctx, orgID, now); err != nil {
+ return err
+ }
+ log.Printf("autumn-reporter: org %s seeded watermark at %s", orgID, now.Format(time.RFC3339))
+ return nil
+ }
+
+ cursor := *org.LastUsageSyncedAt
+ for bucketEnd := cursor.Add(autumnBucketSize); !bucketEnd.After(now); bucketEnd = cursor.Add(autumnBucketSize) {
+ if err := r.trackBucket(ctx, org, cursor, bucketEnd); err != nil {
+ // Leave the watermark where it is; the next tick replays this
+ // bucket with the same idempotency keys (Autumn dedupes the parts
+ // that already landed).
+ return err
+ }
+ if err := r.store.SetLastUsageSyncedAt(ctx, orgID, bucketEnd); err != nil {
+ return err
+ }
+ cursor = bucketEnd
+ }
+ return nil
+}
+
+// trackBucket reports one [from, to) window: one track() per compute tier plus
+// one for disk overage, then (shadow) logs the parity line.
+func (r *AutumnReporter) trackBucket(ctx context.Context, org *db.Org, from, to time.Time) error {
+ usage, err := r.store.GetOrgUsage(ctx, org.ID.String(), from, to)
+ if err != nil {
+ return err
+ }
+ if len(usage) == 0 {
+ return nil
+ }
+
+ bucketStart := from.Unix()
+ var lastBalance float64
+ var diskGBSeconds float64
+ tracked := false
+
+ for _, u := range usage {
+ diskGBSeconds += DiskOverageGBSeconds(u)
+ if u.TotalSeconds <= 0 {
+ continue
+ }
+ feature, ok := autumn.FeatureForMemoryMB(u.MemoryMB)
+ if !ok {
+ log.Printf("autumn-reporter: org %s unknown memory tier %dMB — skipping", org.ID, u.MemoryMB)
+ continue
+ }
+ res, err := r.client.Track(ctx, autumn.TrackParams{
+ CustomerID: org.ID.String(),
+ FeatureID: feature,
+ Value: u.TotalSeconds,
+ IdempotencyKey: autumn.UsageIdempotencyKey(org.ID.String(), bucketStart, feature),
+ })
+ if err != nil {
+ return err
+ }
+ lastBalance = res.Balance.Remaining
+ tracked = true
+ }
+
+ if diskGBSeconds > 0 {
+ res, err := r.client.Track(ctx, autumn.TrackParams{
+ CustomerID: org.ID.String(),
+ FeatureID: autumn.DiskOverageFeatureID,
+ Value: diskGBSeconds,
+ IdempotencyKey: autumn.UsageIdempotencyKey(org.ID.String(), bucketStart, autumn.DiskOverageFeatureID),
+ })
+ if err != nil {
+ return err
+ }
+ lastBalance = res.Balance.Remaining
+ tracked = true
+ }
+
+ if !tracked {
+ return nil
+ }
+
+ ourCents := CalculateUsageCostCents(usage)
+ log.Printf("autumn-reporter: org %s bucket [%s,%s) our_cost=$%.4f autumn_remaining=$%.4f",
+ org.ID, from.Format("15:04"), to.Format("15:04"), ourCents/100.0, lastBalance)
+
+ if lastBalance <= 0 {
+ if r.enforce && r.halt != nil {
+ if err := r.halt(ctx, org.ID); err != nil {
+ log.Printf("autumn-reporter: org %s halt failed: %v", org.ID, err)
+ } else {
+ log.Printf("autumn-reporter: org %s balance exhausted — halted", org.ID)
+ }
+ } else {
+ log.Printf("autumn-reporter: org %s balance exhausted — WOULD halt (shadow)", org.ID)
+ }
+ }
+ return nil
+}
diff --git a/internal/billing/autumn_reporter_test.go b/internal/billing/autumn_reporter_test.go
new file mode 100644
index 00000000..85d96aeb
--- /dev/null
+++ b/internal/billing/autumn_reporter_test.go
@@ -0,0 +1,232 @@
+package billing
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/opensandbox/opensandbox/internal/billing/autumn"
+ "github.com/opensandbox/opensandbox/internal/db"
+)
+
+// fakeAutumnStore is an in-memory autumnUsageStore. Usage is keyed by the bucket
+// start (Unix seconds), so GetOrgUsage returns exactly what the reporter's
+// bucketing asks for — this tests the reporter's windowing/idempotency without
+// reimplementing GetOrgUsage's SQL clipping.
+type fakeAutumnStore struct {
+ orgs map[uuid.UUID]*db.Org
+ usageByFrom map[int64][]db.OrgUsageSummary
+}
+
+func newFakeAutumnStore() *fakeAutumnStore {
+ return &fakeAutumnStore{
+ orgs: map[uuid.UUID]*db.Org{},
+ usageByFrom: map[int64][]db.OrgUsageSummary{},
+ }
+}
+
+func (f *fakeAutumnStore) ListAutumnOrgIDsWithUsage(_ context.Context) ([]uuid.UUID, error) {
+ var ids []uuid.UUID
+ for id, o := range f.orgs {
+ if o.BillingProvider == "autumn" {
+ ids = append(ids, id)
+ }
+ }
+ return ids, nil
+}
+
+func (f *fakeAutumnStore) GetOrg(_ context.Context, id uuid.UUID) (*db.Org, error) {
+ return f.orgs[id], nil
+}
+
+func (f *fakeAutumnStore) GetOrgUsage(_ context.Context, _ string, from, _ time.Time) ([]db.OrgUsageSummary, error) {
+ return f.usageByFrom[from.Unix()], nil
+}
+
+func (f *fakeAutumnStore) SetLastUsageSyncedAt(_ context.Context, orgID uuid.UUID, t time.Time) error {
+ tc := t
+ f.orgs[orgID].LastUsageSyncedAt = &tc
+ return nil
+}
+
+func creditsRemaining(t *testing.T, fake *autumn.Fake, orgID string) float64 {
+ t.Helper()
+ c, err := fake.GetCustomer(context.Background(), orgID)
+ if err != nil {
+ t.Fatalf("GetCustomer: %v", err)
+ }
+ return c.CreditsRemaining()
+}
+
+// fixed base time so bucket math is exact and reproducible.
+var baseT = time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
+
+func newTestReporter(store autumnUsageStore, client autumn.Client, now time.Time) *AutumnReporter {
+ r := NewAutumnReporter(store, client)
+ r.now = func() time.Time { return now }
+ return r
+}
+
+func TestAutumnReporter_seedsWatermarkWithoutBilling(t *testing.T) {
+ store := newFakeAutumnStore()
+ id := uuid.New()
+ store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT} // LastUsageSyncedAt nil
+
+ fake := autumn.NewFake()
+ fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})
+
+ r := newTestReporter(store, fake, baseT.Add(time.Hour))
+ r.reportAll(context.Background())
+
+ if store.orgs[id].LastUsageSyncedAt == nil {
+ t.Fatal("expected watermark seeded on first sight")
+ }
+ if got := *store.orgs[id].LastUsageSyncedAt; !got.Equal(baseT.Add(time.Hour)) {
+ t.Fatalf("watermark = %v, want seed = now", got)
+ }
+ if bal := creditsRemaining(t, fake, id.String()); bal != 5 {
+ t.Fatalf("balance = %v, want 5 (no retroactive billing on seed)", bal)
+ }
+}
+
+func TestAutumnReporter_tracksCompleteBucketsOnly(t *testing.T) {
+ store := newFakeAutumnStore()
+ id := uuid.New()
+ wm := baseT
+ store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}
+
+ // bucket 0: [baseT, +5m) — a 64GB box for the full 300s.
+ store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 65536, TotalSeconds: 300}}
+ // bucket 1: [+5m, +10m) — a 1GB box + 1GB disk overage for 300s.
+ store.usageByFrom[baseT.Add(5*time.Minute).Unix()] = []db.OrgUsageSummary{
+ {MemoryMB: 1024, TotalSeconds: 300, DiskMB: DiskFreeAllowanceMB + 1024},
+ }
+
+ fake := autumn.NewFake()
+ fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})
+
+ // now = +12m → buckets 0 and 1 are complete; [+10m,+15m) is not.
+ r := newTestReporter(store, fake, baseT.Add(12*time.Minute))
+ r.reportAll(context.Background())
+
+ wantWM := baseT.Add(10 * time.Minute)
+ if got := *store.orgs[id].LastUsageSyncedAt; !got.Equal(wantWM) {
+ t.Fatalf("watermark = %v, want %v (partial bucket deferred)", got, wantWM)
+ }
+
+ // Expected deduction via the Fake's credit schema.
+ cc := fake.CreditCosts
+ want := 5.0 -
+ 300*cc["compute_64gb"] -
+ 300*cc["compute_1gb"] -
+ 300*cc["disk_overage"] // 1GB overage × 300s = 300 GB-seconds
+ if bal := creditsRemaining(t, fake, id.String()); !almostEqual(bal, want) {
+ t.Fatalf("balance = %v, want %v", bal, want)
+ }
+}
+
+func TestAutumnReporter_idempotentReplay(t *testing.T) {
+ store := newFakeAutumnStore()
+ id := uuid.New()
+ wm := baseT
+ store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}
+ store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 65536, TotalSeconds: 300}}
+
+ fake := autumn.NewFake()
+ fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})
+
+ r := newTestReporter(store, fake, baseT.Add(7*time.Minute)) // 1 complete bucket
+ r.reportAll(context.Background())
+ afterFirst := creditsRemaining(t, fake, id.String())
+
+ // Rewind the watermark to force a replay of the same bucket — the stable
+ // idempotency keys must make Autumn dedupe, leaving the balance untouched.
+ store.orgs[id].LastUsageSyncedAt = &wm
+ r.reportAll(context.Background())
+ afterReplay := creditsRemaining(t, fake, id.String())
+
+ if !almostEqual(afterFirst, afterReplay) {
+ t.Fatalf("replay double-charged: first=%v replay=%v", afterFirst, afterReplay)
+ }
+}
+
+func TestAutumnReporter_skipsUnknownTierButAdvances(t *testing.T) {
+ store := newFakeAutumnStore()
+ id := uuid.New()
+ wm := baseT
+ store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}
+ store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 2048, TotalSeconds: 300}} // unmapped tier
+
+ fake := autumn.NewFake()
+ fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})
+
+ r := newTestReporter(store, fake, baseT.Add(7*time.Minute))
+ r.reportAll(context.Background())
+
+ if bal := creditsRemaining(t, fake, id.String()); bal != 5 {
+ t.Fatalf("balance = %v, want 5 (unknown tier not charged)", bal)
+ }
+ if got := *store.orgs[id].LastUsageSyncedAt; !got.Equal(baseT.Add(5 * time.Minute)) {
+ t.Fatalf("watermark = %v, want bucket advanced past unknown tier", got)
+ }
+}
+
+func TestAutumnReporter_haltsOnExhaustionWhenEnforced(t *testing.T) {
+ store := newFakeAutumnStore()
+ id := uuid.New()
+ wm := baseT
+ store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}
+ // A 64GB box for 10000s costs > $5 → drives the $5 grant negative.
+ store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 65536, TotalSeconds: 10000}}
+
+ fake := autumn.NewFake()
+ fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})
+
+ var halted []uuid.UUID
+ r := newTestReporter(store, fake, baseT.Add(7*time.Minute))
+ r.SetEnforce(true)
+ r.SetHaltFunc(func(_ context.Context, orgID uuid.UUID) error {
+ halted = append(halted, orgID)
+ return nil
+ })
+ r.reportAll(context.Background())
+
+ if len(halted) != 1 || halted[0] != id {
+ t.Fatalf("expected halt(%s), got %v", id, halted)
+ }
+ if bal := creditsRemaining(t, fake, id.String()); bal >= 0 {
+ t.Fatalf("balance = %v, want negative (exhausted)", bal)
+ }
+}
+
+func TestAutumnReporter_shadowNeverHalts(t *testing.T) {
+ store := newFakeAutumnStore()
+ id := uuid.New()
+ wm := baseT
+ store.orgs[id] = &db.Org{ID: id, BillingProvider: "autumn", CreatedAt: baseT, LastUsageSyncedAt: &wm}
+ store.usageByFrom[baseT.Unix()] = []db.OrgUsageSummary{{MemoryMB: 65536, TotalSeconds: 10000}}
+
+ fake := autumn.NewFake()
+ fake.CreateCustomer(context.Background(), autumn.CreateCustomerParams{ID: id.String()})
+
+ var halted []uuid.UUID
+ r := newTestReporter(store, fake, baseT.Add(7*time.Minute)) // enforce=false (default)
+ r.SetHaltFunc(func(_ context.Context, orgID uuid.UUID) error {
+ halted = append(halted, orgID)
+ return nil
+ })
+ r.reportAll(context.Background())
+
+ if len(halted) != 0 {
+ t.Fatalf("shadow mode must not halt; got %v", halted)
+ }
+}
+
+func almostEqual(a, b float64) bool {
+ d := a - b
+ if d < 0 {
+ d = -d
+ }
+ return d < 1e-9
+}
diff --git a/internal/config/config.go b/internal/config/config.go
index 6c0275de..ac2fd696 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -150,6 +150,17 @@ type Config struct {
StripeSuccessURL string
StripeCancelURL string
+ // Autumn billing (useautumn.com) — the prepaid credit ledger + concurrency
+ // plans. AutumnSecretKey empty disables the Autumn path (orgs stay legacy).
+ // AutumnBaseURL is an optional override; empty uses autumn.DefaultBaseURL.
+ AutumnSecretKey string
+ AutumnWebhookSecret string
+ AutumnBaseURL string
+ // AutumnEnforce flips the Autumn usage reporter out of shadow: on balance
+ // exhaustion it hibernates the org locally and projects is_halted to the
+ // edge (D1). Default false — ship shadow first, then flip to go live.
+ AutumnEnforce bool
+
// Per-agent paywalled-feature prices (set in Stripe dashboard, referenced
// by ID here). Empty = feature ungated on this deployment (dev mode).
StripeTelegramAgentPriceID string
@@ -369,6 +380,10 @@ func Load() (*Config, error) {
StripeSecretKey: os.Getenv("STRIPE_SECRET_KEY"),
StripeWebhookSecret: os.Getenv("STRIPE_WEBHOOK_SECRET"),
+ AutumnSecretKey: os.Getenv("AUTUMN_SECRET_KEY"),
+ AutumnWebhookSecret: os.Getenv("AUTUMN_WEBHOOK_SECRET"),
+ AutumnBaseURL: os.Getenv("AUTUMN_BASE_URL"),
+ AutumnEnforce: os.Getenv("AUTUMN_ENFORCE") == "true",
StripeTelegramAgentPriceID: os.Getenv("STRIPE_TELEGRAM_AGENT_PRICE_ID"),
StripeSuccessURL: envOrDefault("STRIPE_SUCCESS_URL", "http://localhost:3000/billing?success=true"),
StripeCancelURL: envOrDefault("STRIPE_CANCEL_URL", "http://localhost:3000/billing?cancelled=true"),
diff --git a/internal/config/keyvault.go b/internal/config/keyvault.go
index 2d4b7aab..96af7997 100644
--- a/internal/config/keyvault.go
+++ b/internal/config/keyvault.go
@@ -47,6 +47,8 @@ var kvMapping = map[string]string{
"server-cf-zone-id": "OPENSANDBOX_CF_ZONE_ID",
"server-stripe-secret-key": "STRIPE_SECRET_KEY",
"server-stripe-webhook-secret": "STRIPE_WEBHOOK_SECRET",
+ "server-autumn-secret-key": "AUTUMN_SECRET_KEY",
+ "server-autumn-webhook-secret": "AUTUMN_WEBHOOK_SECRET",
"server-sentry-dsn": "OPENSANDBOX_SENTRY_DSN",
// Machine-size fallback lists (PR #209). Comma-separated ranked
// instance types the autoscaler tries in order on quota / capacity
diff --git a/internal/db/billable_events.go b/internal/db/billable_events.go
index a0bc014a..f97ddf6e 100644
--- a/internal/db/billable_events.go
+++ b/internal/db/billable_events.go
@@ -156,6 +156,7 @@ func (s *Store) ListPendingBillableEventsForSender(ctx context.Context, limit in
JOIN orgs o ON o.id = be.org_id
WHERE be.delivery_state = 'pending'
AND o.billing_mode = 'unified'
+ AND o.billing_provider != 'autumn'
AND o.stripe_customer_id IS NOT NULL
ORDER BY be.created_at, be.id
LIMIT $1
diff --git a/internal/db/migrations/047_orgs_billing_provider.down.sql b/internal/db/migrations/047_orgs_billing_provider.down.sql
new file mode 100644
index 00000000..0c5d2e1e
--- /dev/null
+++ b/internal/db/migrations/047_orgs_billing_provider.down.sql
@@ -0,0 +1 @@
+ALTER TABLE orgs DROP COLUMN billing_provider;
diff --git a/internal/db/migrations/047_orgs_billing_provider.up.sql b/internal/db/migrations/047_orgs_billing_provider.up.sql
new file mode 100644
index 00000000..68872a9c
--- /dev/null
+++ b/internal/db/migrations/047_orgs_billing_provider.up.sql
@@ -0,0 +1,13 @@
+-- Per-org selector for which billing system is authoritative.
+--
+-- 'legacy' — the in-house pipeline: CreditAccount DO (edge) / UsageReporter
+-- (cell) own the credit balance, metering, and halt/resume.
+-- 'autumn' — Autumn (useautumn.com) owns the credit ledger, usage metering,
+-- top-ups, auto-recharge, and the concurrency plans. The cell only
+-- measures usage → track(), and projects is_halted / max_concurrent.
+--
+-- Defaults to 'legacy' so every existing and new org is unaffected until it is
+-- explicitly flipped. The move to Autumn is per-org and reversible (flip back to
+-- 'legacy'); the final cutover flips the default and migrates the stragglers.
+ALTER TABLE orgs ADD COLUMN billing_provider TEXT NOT NULL DEFAULT 'legacy'
+ CHECK (billing_provider IN ('legacy', 'autumn'));
diff --git a/internal/db/migrations/048_orgs_usage_sync_watermark.down.sql b/internal/db/migrations/048_orgs_usage_sync_watermark.down.sql
new file mode 100644
index 00000000..83111e81
--- /dev/null
+++ b/internal/db/migrations/048_orgs_usage_sync_watermark.down.sql
@@ -0,0 +1 @@
+ALTER TABLE orgs DROP COLUMN last_usage_synced_at;
diff --git a/internal/db/migrations/048_orgs_usage_sync_watermark.up.sql b/internal/db/migrations/048_orgs_usage_sync_watermark.up.sql
new file mode 100644
index 00000000..59d1416e
--- /dev/null
+++ b/internal/db/migrations/048_orgs_usage_sync_watermark.up.sql
@@ -0,0 +1,11 @@
+-- Dedicated usage-reporting watermark for the external metered-billing loop
+-- (currently Autumn). Neutral column name so it doesn't lie if the provider
+-- ever changes; the code-side adapter stays vendor-named (cf. stripe_*).
+--
+-- This loop runs in *shadow* alongside the legacy UsageReporter, so it cannot
+-- share last_usage_reported_at — whichever loop advanced it first would starve
+-- the other. This column is the new loop's own high-water mark: usage in
+-- [last_usage_synced_at, now) has been (or is being) shipped via track(). NULL
+-- means "never reported" — the reporter seeds it to now on first sight and bills
+-- forward from there (no retroactive charge on flag-flip).
+ALTER TABLE orgs ADD COLUMN last_usage_synced_at TIMESTAMPTZ;
diff --git a/internal/db/store.go b/internal/db/store.go
index 7feb8423..5c908bc4 100644
--- a/internal/db/store.go
+++ b/internal/db/store.go
@@ -194,6 +194,8 @@ func (s *Store) Migrate(ctx context.Context) error {
{44, "migrations/044_drop_secret_store_fk.up.sql"},
{45, "migrations/045_sandbox_mounts.up.sql"},
{46, "migrations/046_preview_auth.up.sql"},
+ {47, "migrations/047_orgs_billing_provider.up.sql"},
+ {48, "migrations/048_orgs_usage_sync_watermark.up.sql"},
}
for _, m := range migrations {
@@ -278,6 +280,17 @@ type Org struct {
// FreeCreditsRemainingCents is preserved but no longer authoritative.
IsHalted bool `json:"isHalted"`
HaltedAt *time.Time `json:"haltedAt,omitempty"`
+
+ // Per-org billing system selector: 'legacy' (in-house CreditAccount DO /
+ // UsageReporter) or 'autumn' (Autumn owns the credit ledger, usage metering,
+ // top-ups, and concurrency plans). Defaults to 'legacy'; flipped per-org
+ // during the move to Autumn.
+ BillingProvider string `json:"billingProvider"`
+
+ // Watermark for the external metered-billing loop (currently Autumn),
+ // separate from LastUsageReportedAt so the shadow reporter and the legacy
+ // reporter don't starve each other. NULL until first seen by that loop.
+ LastUsageSyncedAt *time.Time `json:"lastUsageSyncedAt,omitempty"`
}
// orgColumns is the list of columns returned by all Org queries.
@@ -286,7 +299,7 @@ const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_
verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value,
workos_org_id, is_personal, owner_user_id, credit_balance_cents,
stripe_customer_id, stripe_subscription_id, last_usage_reported_at, price_locked,
- free_credits_remaining_cents, billing_mode, is_halted, halted_at`
+ free_credits_remaining_cents, billing_mode, is_halted, halted_at, billing_provider, last_usage_synced_at`
// scanOrg scans a row into an Org struct.
func scanOrg(row pgx.Row) (*Org, error) {
@@ -300,7 +313,7 @@ func scanOrg(row pgx.Row) (*Org, error) {
&org.StripeCustomerID, &org.StripeSubscriptionID, &org.LastUsageReportedAt,
&org.PriceLocked,
&org.FreeCreditsRemainingCents, &org.BillingMode,
- &org.IsHalted, &org.HaltedAt,
+ &org.IsHalted, &org.HaltedAt, &org.BillingProvider, &org.LastUsageSyncedAt,
)
return org, err
}
@@ -356,16 +369,25 @@ func (s *Store) GetOrgPlan(ctx context.Context, orgID string) (string, error) {
// Plan from the cap-token wins on insert; on conflict we update plan so a
// pro-upgrade reflected at the edge propagates to the cell on the next
// sandbox-create round-trip without a separate sync job.
-func (s *Store) UpsertOrgFromCapToken(ctx context.Context, orgID uuid.UUID, plan string) error {
+func (s *Store) UpsertOrgFromCapToken(ctx context.Context, orgID uuid.UUID, plan, billingProvider string) error {
if plan != "pro" {
plan = "free"
}
+ // billingProvider mirrors D1's authoritative value (it rides the cap-token
+ // like plan). Empty means the token didn't carry it (older token / a path
+ // that doesn't set it) → keep the existing cell-PG value, and default a
+ // brand-new row to 'legacy'. So a wake/preview token can never clobber an
+ // org that the create path or backfill already flipped to 'autumn'.
_, err := s.pool.Exec(ctx,
- `INSERT INTO orgs (id, name, slug, plan)
- VALUES ($1, $2, $3, $4)
- ON CONFLICT (id) DO UPDATE SET plan = EXCLUDED.plan, updated_at = NOW()
- WHERE orgs.plan IS DISTINCT FROM EXCLUDED.plan`,
- orgID, "org-"+orgID.String()[:8], orgID.String(), plan,
+ `INSERT INTO orgs (id, name, slug, plan, billing_provider)
+ VALUES ($1, $2, $3, $4, COALESCE(NULLIF($5, ''), 'legacy'))
+ ON CONFLICT (id) DO UPDATE SET
+ plan = EXCLUDED.plan,
+ billing_provider = CASE WHEN NULLIF($5, '') IS NULL THEN orgs.billing_provider ELSE $5 END,
+ updated_at = NOW()
+ WHERE orgs.plan IS DISTINCT FROM EXCLUDED.plan
+ OR (NULLIF($5, '') IS NOT NULL AND orgs.billing_provider IS DISTINCT FROM $5)`,
+ orgID, "org-"+orgID.String()[:8], orgID.String(), plan, billingProvider,
)
if err != nil {
return fmt.Errorf("upsert org from cap-token: %w", err)
diff --git a/internal/db/usage.go b/internal/db/usage.go
index 7897eb5b..b91afe4e 100644
--- a/internal/db/usage.go
+++ b/internal/db/usage.go
@@ -290,6 +290,56 @@ func (s *Store) UpdateLastUsageReportedAt(ctx context.Context, orgID uuid.UUID,
return err
}
+// SetBillingProvider flips an org's billing system selector in cell-PG. The
+// migrate tool pairs this with edgeclient.SetAutumnProvider (D1) for an
+// atomic-as-possible per-org cutover; ordering across the two stores is chosen
+// so the legacy and Autumn chargers are never both live for the same org.
+func (s *Store) SetBillingProvider(ctx context.Context, orgID uuid.UUID, provider string) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET billing_provider = $2, updated_at = NOW() WHERE id = $1`,
+ orgID, provider)
+ return err
+}
+
+// SetLastUsageSyncedAt advances the external metered-billing (Autumn) loop's
+// watermark. Separate from last_usage_reported_at so the shadow Autumn reporter
+// and the legacy reporter can run concurrently without starving each other.
+func (s *Store) SetLastUsageSyncedAt(ctx context.Context, orgID uuid.UUID, t time.Time) error {
+ _, err := s.pool.Exec(ctx,
+ `UPDATE orgs SET last_usage_synced_at = $2 WHERE id = $1`,
+ orgID, t)
+ return err
+}
+
+// ListAutumnOrgIDsWithUsage returns org IDs whose billing_provider is 'autumn'
+// and that have scale-event usage not yet shipped to Autumn — either a
+// currently-running sandbox or a scale event that ended after the org's
+// last_usage_synced_at watermark. Orgs first seen (NULL watermark) are included
+// so the reporter can seed them; it bills forward from now, never retroactively.
+func (s *Store) ListAutumnOrgIDsWithUsage(ctx context.Context) ([]uuid.UUID, error) {
+ rows, err := s.pool.Query(ctx,
+ `SELECT DISTINCT se.org_id
+ FROM sandbox_scale_events se
+ JOIN orgs o ON o.id = se.org_id
+ WHERE o.billing_provider = 'autumn'
+ AND (se.ended_at IS NULL
+ OR se.ended_at > COALESCE(o.last_usage_synced_at, o.created_at))`)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ var ids []uuid.UUID
+ for rows.Next() {
+ var id uuid.UUID
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
+ }
+ ids = append(ids, id)
+ }
+ return ids, rows.Err()
+}
+
// ListBillableOrgIDs returns org IDs with plan="pro" AND
// billing_mode='legacy' that have unreported usage: either a
// currently-running sandbox or a scale event that ended after the last
@@ -303,6 +353,7 @@ func (s *Store) ListBillableOrgIDs(ctx context.Context) ([]uuid.UUID, error) {
JOIN orgs o ON o.id = se.org_id
WHERE o.plan = 'pro'
AND o.billing_mode = 'legacy'
+ AND o.billing_provider != 'autumn'
AND (se.ended_at IS NULL OR se.ended_at > o.last_usage_reported_at)`)
if err != nil {
return nil, err
@@ -330,6 +381,7 @@ func (s *Store) ListFreeOrgIDsWithOpenUsage(ctx context.Context) ([]uuid.UUID, e
FROM sandbox_scale_events se
JOIN orgs o ON o.id = se.org_id
WHERE o.plan = 'free'
+ AND o.billing_provider != 'autumn'
AND (se.ended_at IS NULL OR se.ended_at > o.last_usage_reported_at)`)
if err != nil {
return nil, err
diff --git a/internal/edgeclient/client.go b/internal/edgeclient/client.go
index 9f0abb96..32062dc1 100644
--- a/internal/edgeclient/client.go
+++ b/internal/edgeclient/client.go
@@ -287,6 +287,40 @@ func (c *Client) UpdateTemplateStatus(ctx context.Context, id uuid.UUID, status
return nil
}
+// ── Autumn billing projection ──────────────────────────────────────────
+
+// ProjectAutumnOrg triggers the edge to re-read the org's authoritative Autumn
+// state and re-project it into D1 (is_halted / max_concurrent) + dispatch halt
+// to cells. Used by the cell's inline halt (off track()) so the cell never owns
+// Autumn reads or D1 writes — those stay at the edge, same as /webhooks/autumn.
+func (c *Client) ProjectAutumnOrg(ctx context.Context, orgID uuid.UUID) error {
+ body, _ := json.Marshal(map[string]string{"org_id": orgID.String()})
+ respBody, status, err := c.do(ctx, "POST", "/internal/autumn-project", body)
+ if err != nil {
+ return err
+ }
+ if status != 200 {
+ return fmt.Errorf("edge status %d: %s", status, string(respBody))
+ }
+ return nil
+}
+
+// SetAutumnProvider flips D1 orgs.billing_provider for one org (the migrate
+// tool's D1 half; the cell-PG half is a direct store write). On →autumn the
+// edge also projects is_halted/max_concurrent so the edge gates are correct the
+// instant the flag flips.
+func (c *Client) SetAutumnProvider(ctx context.Context, orgID uuid.UUID, provider string) error {
+ body, _ := json.Marshal(map[string]string{"org_id": orgID.String(), "provider": provider})
+ respBody, status, err := c.do(ctx, "POST", "/internal/autumn-set-provider", body)
+ if err != nil {
+ return err
+ }
+ if status != 200 {
+ return fmt.Errorf("edge status %d: %s", status, string(respBody))
+ }
+ return nil
+}
+
// ── Secret stores ──────────────────────────────────────────────────────
// edgeStore intentionally omits createdAt / updatedAt. The edge worker
diff --git a/web/package-lock.json b/web/package-lock.json
index c24917d9..6a80d332 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -58,7 +58,6 @@
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@babel/code-frame": "^7.29.0",
"@babel/generator": "^7.29.0",
@@ -807,7 +806,6 @@
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
"integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==",
"license": "Apache-2.0",
- "peer": true,
"engines": {
"node": ">=8.0.0"
}
@@ -1721,7 +1719,6 @@
"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",
"devOptional": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.2.2"
@@ -1822,7 +1819,6 @@
}
],
"license": "MIT",
- "peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759",
@@ -2295,7 +2291,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=12"
},
@@ -2337,7 +2332,6 @@
"resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.372.8.tgz",
"integrity": "sha512-NAFWVScFGnU5jgGNLkrY/UnGH82uULs9RsJ/f26LkLn1l0MOZfq+/z+2RaOOQQX4NHruIVuxqz3J/50bgRG68A==",
"license": "SEE LICENSE IN LICENSE",
- "peer": true,
"dependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/api-logs": "^0.208.0",
@@ -2399,7 +2393,6 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
- "peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -2412,7 +2405,6 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
- "peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -2433,7 +2425,6 @@
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
"license": "MIT",
- "peer": true,
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
@@ -2528,8 +2519,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/redux-thunk": {
"version": "3.1.0",
@@ -2731,7 +2721,6 @@
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index 441abf14..7764788f 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -342,6 +342,21 @@ export interface BillingState {
maxConcurrentSandboxes: number
hasPaymentMethod: boolean
freeCreditsRemainingCents: number
+ billingProvider?: string // 'legacy' | 'autumn'
+}
+
+// Autumn prepaid billing
+export interface AutumnAutoTopup {
+ enabled: boolean
+ threshold: number
+ quantity: number
+}
+export interface AutumnBilling {
+ creditsRemainingCents: number
+ maxConcurrentSandboxes: number
+ concurrencyPlan: string // 'base' | 'concurrency_pro' | 'concurrency_pro_plus' | 'concurrency_pro_plus_plus'
+ isHalted: boolean
+ autoTopup: AutumnAutoTopup | null
}
export interface StripeInvoice {
@@ -374,6 +389,43 @@ export const redeemPromoCode = (code: string) =>
body: JSON.stringify({ code }),
})
+// Autumn prepaid billing API
+export const getAutumnBilling = () => apiFetch<AutumnBilling>('/billing/autumn')
+
+export const autumnTopup = (credits: number) =>
+ apiFetch<{ url: string }>('/billing/autumn/topup', {
+ method: 'POST',
+ body: JSON.stringify({ credits }),
+ })
+
+export const autumnSubscribeConcurrency = (plan: string) =>
+ apiFetch<{ url: string }>('/billing/autumn/concurrency', {
+ method: 'POST',
+ body: JSON.stringify({ plan }),
+ })
+
+export const setAutumnAutoTopup = (cfg: { enabled: boolean; threshold: number; quantity: number }) =>
+ apiFetch<{ ok: boolean }>('/billing/autumn/auto-topup', {
+ method: 'POST',
+ body: JSON.stringify(cfg),
+ })
+
+// Per-sandbox usage breakdown (compute cost over a recent window)
+export interface SandboxUsageRow {
+ sandboxId: string
+ status: string
+ createdAt?: number
+ seconds: number
+ costCents: number
+}
+export interface SandboxUsage {
+ windowDays: number
+ totalCents: number
+ sandboxes: SandboxUsageRow[]
+}
+export const getSandboxUsage = (days = 30) =>
+ apiFetch<SandboxUsage>(`/usage/sandboxes?days=${days}`)
+
// ── Agents (proxied to sessions-api at /api/dashboard/agents/*) ──
export interface Agent {
diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsx
index 40c78eaa..dab9870e 100644
--- a/web/src/pages/Billing.tsx
+++ b/web/src/pages/Billing.tsx
@@ -4,7 +4,8 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import {
getBilling, billingSetup, billingPortal, getBillingInvoices, redeemPromoCode,
listOrgAgentSubscriptions, listAgents, cancelAgentFeature,
- type StripeInvoice, type OrgAgentSubscription, type Agent,
+ getAutumnBilling, autumnTopup, autumnSubscribeConcurrency, getSandboxUsage, setAutumnAutoTopup,
+ type StripeInvoice, type OrgAgentSubscription, type Agent, type AutumnBilling,
} from '../api/client'
type Tab = 'sandboxes' | 'agents' | 'invoices'
@@ -89,6 +90,12 @@ function PlanTab() {
)
}
+ // Autumn (prepaid) orgs get the credits/top-up/concurrency view instead of
+ // the legacy free-trial / Pro-upgrade card.
+ if (billing?.billingProvider === 'autumn') {
+ return <PrepaidPlan />
+ }
+
return (
<>
{/* Plan Card */}
@@ -256,6 +263,339 @@ function PlanTab() {
)
}
+// ───────────── Prepaid (Autumn) plan view ─────────────
+
+const TOPUP_AMOUNTS = [5, 25, 100] // dollars == credits ($1/credit)
+
+const CONCURRENCY_TIERS = [
+ { id: 'concurrency_pro', label: 'Pro', limit: 100, price: 150 },
+ { id: 'concurrency_pro_plus', label: 'Pro+', limit: 600, price: 500 },
+ { id: 'concurrency_pro_plus_plus', label: 'Pro++', limit: 1000, price: 1000 },
+]
+
+function PrepaidPlan() {
+ const { data: autumn, isLoading } = useQuery({
+ queryKey: ['autumn-billing'], queryFn: getAutumnBilling, refetchInterval: 30_000,
+ })
+ const [amount, setAmount] = useState<number>(25)
+
+ const topupMutation = useMutation({
+ mutationFn: () => autumnTopup(amount),
+ onSuccess: (data) => { window.location.href = data.url },
+ })
+ const planMutation = useMutation({
+ mutationFn: (plan: string) => autumnSubscribeConcurrency(plan),
+ onSuccess: (data) => { window.location.href = data.url },
+ })
+
+ if (isLoading) {
+ return (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 80 }}>
+ <div className="loading-spinner" />
+ </div>
+ )
+ }
+
+ const credits = (autumn?.creditsRemainingCents ?? 0) / 100
+ const halted = autumn?.isHalted ?? false
+ const currentPlan = autumn?.concurrencyPlan ?? 'base'
+
+ return (
+ <>
+ {/* Credits balance */}
+ <div className="glass-card animate-in stagger-1" style={{ padding: 28, marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 16, display: 'block' }}>
+ Prepaid Credits
+ </span>
+ <div style={{ display: 'flex', alignItems: 'baseline', gap: 12, marginBottom: 8 }}>
+ <span className="metric-value" style={{
+ fontSize: 36, fontWeight: 700, fontFamily: 'var(--font-mono)',
+ color: halted ? 'var(--accent-rose)' : 'var(--accent-emerald)',
+ }}>
+ ${credits.toFixed(2)}
+ </span>
+ <span style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>remaining</span>
+ </div>
+ {halted && (
+ <div style={{
+ fontSize: 13, color: 'var(--accent-rose)', marginBottom: 12,
+ display: 'flex', alignItems: 'center', gap: 6,
+ }}>
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
+ <circle cx="12" cy="12" r="10" /><line x1="12" y1="8" x2="12" y2="12" /><line x1="12" y1="16" x2="12.01" y2="16" />
+ </svg>
+ Credits exhausted — top up to resume your sandboxes
+ </div>
+ )}
+
+ {/* Top-up */}
+ <div style={{ marginTop: 18 }}>
+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 10 }}>
+ Add credits (billed at the same per-second rates)
+ </div>
+ <div style={{ display: 'flex', gap: 8, marginBottom: 14, flexWrap: 'wrap' }}>
+ {TOPUP_AMOUNTS.map((a) => (
+ <button
+ key={a}
+ onClick={() => setAmount(a)}
+ style={{
+ padding: '8px 16px', borderRadius: 8, cursor: 'pointer',
+ fontFamily: 'var(--font-mono)', fontSize: 14, fontWeight: 600,
+ border: amount === a ? '1px solid var(--accent-indigo)' : '1px solid var(--border-subtle)',
+ background: amount === a ? 'var(--accent-indigo-soft, rgba(99,102,241,0.12))' : 'transparent',
+ color: amount === a ? 'var(--accent-indigo)' : 'var(--text-secondary)',
+ }}
+ >
+ ${a}
+ </button>
+ ))}
+ <input
+ type="number"
+ min={1}
+ value={amount}
+ onChange={(e) => setAmount(Math.max(1, Math.floor(Number(e.target.value) || 0)))}
+ style={{
+ width: 90, padding: '8px 12px', borderRadius: 8,
+ border: '1px solid var(--border-subtle)', background: 'transparent',
+ color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontSize: 14,
+ }}
+ />
+ </div>
+ <button
+ className="btn-primary"
+ disabled={topupMutation.isPending || amount < 1}
+ onClick={() => topupMutation.mutate()}
+ style={{ padding: '10px 20px' }}
+ >
+ {topupMutation.isPending ? 'Redirecting…' : `Top up $${amount}`}
+ </button>
+ {topupMutation.isError && (
+ <div style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>
+ {(topupMutation.error as Error).message}
+ </div>
+ )}
+ </div>
+ </div>
+
+ <AutoTopupCard current={autumn?.autoTopup ?? null} />
+
+ {/* Concurrency plans */}
+ <div className="glass-card animate-in stagger-3" style={{ padding: 28 }}>
+ <span className="section-title" style={{ marginBottom: 8, display: 'block' }}>
+ Concurrency
+ </span>
+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16 }}>
+ You can run <strong style={{ color: 'var(--text-primary)' }}>{autumn?.maxConcurrentSandboxes ?? 5}</strong> sandboxes
+ at once on the <strong style={{ color: 'var(--text-primary)' }}>{currentPlan === 'base' ? 'Base' : currentPlan}</strong> tier.
+ Subscribe to a higher tier for more — billed monthly, separate from usage credits.
+ </div>
+ <div style={{ display: 'grid', gap: 10 }}>
+ {CONCURRENCY_TIERS.map((tier) => {
+ const active = currentPlan === tier.id
+ return (
+ <div
+ key={tier.id}
+ style={{
+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
+ padding: '14px 16px', borderRadius: 10,
+ border: active ? '1px solid var(--accent-indigo)' : '1px solid var(--border-subtle)',
+ }}
+ >
+ <div>
+ <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--text-primary)' }}>
+ {tier.label} — {tier.limit} concurrent
+ </div>
+ <div style={{ fontSize: 12, color: 'var(--text-tertiary)', fontFamily: 'var(--font-mono)' }}>
+ ${tier.price}/mo
+ </div>
+ </div>
+ <button
+ className="btn-secondary"
+ disabled={active || planMutation.isPending}
+ onClick={() => planMutation.mutate(tier.id)}
+ style={{ padding: '8px 16px' }}
+ >
+ {active ? 'Current' : 'Subscribe'}
+ </button>
+ </div>
+ )
+ })}
+ <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginTop: 4 }}>
+ Need more than 1000? <a href="mailto:[email protected]" style={{ color: 'var(--accent-indigo)' }}>Contact us</a>.
+ </div>
+ </div>
+ {planMutation.isError && (
+ <div style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 10 }}>
+ {(planMutation.error as Error).message}
+ </div>
+ )}
+ </div>
+
+ <UsageBreakdown />
+ </>
+ )
+}
+
+function UsageBreakdown() {
+ const { data, isLoading } = useQuery({
+ queryKey: ['sandbox-usage'], queryFn: () => getSandboxUsage(30),
+ })
+
+ const rows = data?.sandboxes ?? []
+
+ return (
+ <div className="glass-card animate-in stagger-4" style={{ padding: 28, marginTop: 14 }}>
+ <span className="section-title" style={{ marginBottom: 4, display: 'block' }}>
+ Usage by sandbox
+ </span>
+ <div style={{ fontSize: 12, color: 'var(--text-tertiary)', marginBottom: 16 }}>
+ Compute cost over the last {data?.windowDays ?? 30} days (disk overage not included).
+ </div>
+
+ {isLoading ? (
+ <div style={{ display: 'flex', justifyContent: 'center', padding: 24 }}>
+ <div className="loading-spinner" />
+ </div>
+ ) : rows.length === 0 ? (
+ <div style={{ fontSize: 13, color: 'var(--text-secondary)' }}>
+ No recent sandbox usage to show yet.
+ </div>
+ ) : (
+ <div style={{ display: 'grid', gap: 1 }}>
+ <div style={{
+ display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 12,
+ fontSize: 11, color: 'var(--text-tertiary)', textTransform: 'uppercase',
+ letterSpacing: '0.04em', padding: '0 4px 8px',
+ }}>
+ <span>Sandbox</span><span style={{ textAlign: 'right' }}>Runtime</span><span style={{ textAlign: 'right' }}>Cost</span>
+ </div>
+ {rows.map((r) => (
+ <div
+ key={r.sandboxId}
+ style={{
+ display: 'grid', gridTemplateColumns: '1fr auto auto', gap: 12,
+ alignItems: 'center', padding: '10px 4px',
+ borderTop: '1px solid var(--border-subtle)', fontSize: 13,
+ }}
+ >
+ <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text-primary)', overflow: 'hidden', textOverflow: 'ellipsis' }}>
+ {r.sandboxId}
+ <span style={{ marginLeft: 8, fontSize: 11, color: 'var(--text-tertiary)', fontFamily: 'var(--font-body)' }}>
+ {r.status}
+ </span>
+ </span>
+ <span style={{ textAlign: 'right', color: 'var(--text-secondary)', fontFamily: 'var(--font-mono)' }}>
+ {formatDuration(r.seconds)}
+ </span>
+ <span style={{ textAlign: 'right', color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontWeight: 600 }}>
+ ${(r.costCents / 100).toFixed(2)}
+ </span>
+ </div>
+ ))}
+ <div style={{
+ display: 'grid', gridTemplateColumns: '1fr auto', gap: 12,
+ padding: '12px 4px 0', borderTop: '1px solid var(--border-subtle)',
+ marginTop: 4, fontSize: 13, fontWeight: 600,
+ }}>
+ <span style={{ color: 'var(--text-secondary)' }}>Total</span>
+ <span style={{ textAlign: 'right', color: 'var(--text-primary)', fontFamily: 'var(--font-mono)' }}>
+ ${((data?.totalCents ?? 0) / 100).toFixed(2)}
+ </span>
+ </div>
+ </div>
+ )}
+ </div>
+ )
+}
+
+function formatDuration(seconds: number): string {
+ if (seconds < 60) return `${seconds}s`
+ if (seconds < 3600) return `${Math.round(seconds / 60)}m`
+ return `${(seconds / 3600).toFixed(1)}h`
+}
+
+const autoTopupInputStyle = {
+ width: 80, padding: '6px 10px', borderRadius: 8, border: '1px solid var(--border-subtle)',
+ background: 'transparent', color: 'var(--text-primary)', fontFamily: 'var(--font-mono)', fontSize: 13,
+}
+
+function AutoTopupCard({ current }: { current: AutumnBilling['autoTopup'] }) {
+ const queryClient = useQueryClient()
+ const [enabled, setEnabled] = useState(current?.enabled ?? false)
+ const [threshold, setThreshold] = useState(current?.threshold ?? 5)
+ const [quantity, setQuantity] = useState(current?.quantity ?? 25)
+ const [saved, setSaved] = useState(false)
+
+ const mutation = useMutation({
+ mutationFn: () => setAutumnAutoTopup({ enabled, threshold, quantity }),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })
+ setSaved(true)
+ setTimeout(() => setSaved(false), 3000)
+ },
+ })
+
+ return (
+ <div className="glass-card animate-in stagger-2" style={{ padding: 28, marginBottom: 14 }}>
+ <span className="section-title" style={{ marginBottom: 8, display: 'block' }}>
+ Automatic Top-up
+ </span>
+ <div style={{ fontSize: 13, color: 'var(--text-secondary)', marginBottom: 16 }}>
+ Keep your balance from running out — when it drops below the threshold we
+ automatically add credits to your saved card.
+ </div>
+ <label style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16, cursor: 'pointer', fontSize: 13 }}>
+ <input type="checkbox" checked={enabled} onChange={(e) => setEnabled(e.target.checked)} />
+ <span style={{ color: 'var(--text-primary)' }}>Enable automatic top-up</span>
+ </label>
+ {enabled && (
+ <div style={{ display: 'flex', gap: 20, marginBottom: 16, flexWrap: 'wrap' }}>
+ <label style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
+ When balance falls below
+ <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4 }}>
+ <span style={{ color: 'var(--text-secondary)' }}>$</span>
+ <input
+ type="number" min={0} value={threshold}
+ onChange={(e) => setThreshold(Math.max(0, Math.floor(Number(e.target.value) || 0)))}
+ style={autoTopupInputStyle}
+ />
+ </div>
+ </label>
+ <label style={{ fontSize: 12, color: 'var(--text-tertiary)' }}>
+ Add credits
+ <div style={{ display: 'flex', alignItems: 'center', gap: 4, marginTop: 4 }}>
+ <span style={{ color: 'var(--text-secondary)' }}>$</span>
+ <input
+ type="number" min={1} value={quantity}
+ onChange={(e) => setQuantity(Math.max(1, Math.floor(Number(e.target.value) || 0)))}
+ style={autoTopupInputStyle}
+ />
+ </div>
+ </label>
+ </div>
+ )}
+ <button
+ className="btn-secondary"
+ disabled={mutation.isPending}
+ onClick={() => mutation.mutate()}
+ style={{ padding: '8px 16px' }}
+ >
+ {mutation.isPending ? 'Saving…' : saved ? 'Saved ✓' : 'Save'}
+ </button>
+ {enabled && (
+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)', marginTop: 10 }}>
+ Requires a payment method on file — added automatically on your first top-up.
+ </div>
+ )}
+ {mutation.isError && (
+ <div style={{ fontSize: 12, color: 'var(--accent-rose)', marginTop: 8 }}>
+ {(mutation.error as Error).message}
+ </div>
+ )}
+ </div>
+ )
+}
+
// ───────────── Agents tab ─────────────
function AgentsTab() {