An open-source, faster Devin alternative
TypeScript
billing: keep paid orgs on a fallback model when credits run out
Devin AI4c5413f3a572
diff --git a/cloudflare-workers/api-edge/migrations/0009_orgs_usage_plan.sql b/cloudflare-workers/api-edge/migrations/0009_orgs_usage_plan.sqlnew file mode 100644index 00000000..b1b96813--- /dev/null+++ b/cloudflare-workers/api-edge/migrations/0009_orgs_usage_plan.sql@@ -0,0 +1,9 @@+-- orgs.usage_plan — the org's active Autumn usage plan: 'base' | 'pro' | 'max'.+--+-- Projected from Autumn by syncAutumnToD1 alongside is_halted, so the+-- managed-agent credit gate can tell paid orgs from free ones without an+-- Autumn round trip. A halted paid org (pro/max) keeps running managed agents+-- on the open-weight fallback model; a halted base org hard-stops and must+-- upgrade. Rows default to 'base' until their next projection, which keeps an+-- unprojected org on the stricter free-tier behavior.+ALTER TABLE orgs ADD COLUMN usage_plan TEXT NOT NULL DEFAULT 'base';diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 90662eea..24f21164 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -51,6 +51,30 @@ const CONCURRENCY_BY_PLAN: Record<string, number> = {};const DEFAULT_CONCURRENCY = 50;+export type UsagePlan = "base" | "pro" | "max";++const USAGE_PLAN_RANK: Record<string, number> = { base: 0, pro: 1, max: 2 };++export function activeUsagePlan(customer: AutumnCustomer): UsagePlan {+ let plan: UsagePlan = "base";+ let rank = 0;+ for (const s of customer.subscriptions ?? []) {+ if (s.status && s.status !== "active") continue;+ const r = USAGE_PLAN_RANK[s.plan_id];+ if (r !== undefined && r >= rank) {+ rank = r;+ plan = s.plan_id as UsagePlan;+ }+ }+ return plan;+}++// Paid usage plans keep running managed agents on the open-weight fallback+// model once credits are exhausted; base orgs hard-stop and must upgrade.+export function isPaidUsagePlan(plan: string | null | undefined): boolean {+ return plan === "pro" || plan === "max";+}+const HANDLED_EVENTS = new Set(["billing.updated","billing.auto_topup_succeeded",@@ -424,7 +448,7 @@ export async function selfHealHalt(env: AutumnEnv, orgID: string): Promise<boole}// syncAutumnToD1 reads Autumn's authoritative balance/plans and writes the D1-// projection (is_halted / max_concurrent) WITHOUT any cell dispatch. Returns the+// projection (is_halted / usage_plan / 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 {@@ -433,6 +457,7 @@ export interface AutumnSyncResult {maxConcurrent: number;halted: boolean;wasHalted: boolean;+ usagePlan: UsagePlan;}export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise<AutumnSyncResult | null> {@@ -444,6 +469,7 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promiseconst creditsRemaining = cust.balances?.[CREDITS_FEATURE_ID]?.remaining ?? 0;const halted = creditsRemaining <= 0;+ const usagePlan = activeUsagePlan(cust);const projectedMaxConcurrent = maxConcurrency(cust.subscriptions ?? []);const nowSec = Math.floor(Date.now() / 1000);@@ -454,12 +480,12 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promiseconst maxConcurrent = prevRow?.autumn_concurrency_override ?? projectedMaxConcurrent;await env.OPENCOMPUTER_DB.prepare(- `UPDATE orgs SET is_halted = ?1, halted_at = ?2, max_concurrent_sandboxes = ?3, updated_at = ?4 WHERE id = ?5`,+ `UPDATE orgs SET is_halted = ?1, halted_at = ?2, max_concurrent_sandboxes = ?3, usage_plan = ?4, updated_at = ?5 WHERE id = ?6`,)- .bind(halted ? 1 : 0, halted ? nowSec : null, maxConcurrent, nowSec, orgID)+ .bind(halted ? 1 : 0, halted ? nowSec : null, maxConcurrent, usagePlan, nowSec, orgID).run();- return { customer: cust, creditsRemaining, maxConcurrent, halted, wasHalted };+ return { customer: cust, creditsRemaining, maxConcurrent, halted, wasHalted, usagePlan };}// autumnSetProviderInternal flips D1 orgs.billing_provider for one org (thediff --git a/cloudflare-workers/api-edge/src/billing_onramp.ts b/cloudflare-workers/api-edge/src/billing_onramp.tsindex b3d1ec0a..ec85f48d 100644--- a/cloudflare-workers/api-edge/src/billing_onramp.ts+++ b/cloudflare-workers/api-edge/src/billing_onramp.ts@@ -5,12 +5,13 @@// that fires before the hard stop.import {- type AutumnCustomer,+ activeUsagePlan,type AutumnSyncEnv,syncAutumnToD1,+ type UsagePlan,} from "./autumn_webhook";-export type UsagePlan = "base" | "pro" | "max";+export { activeUsagePlan, type UsagePlan };// Mirror of PLAN_CREDIT_GRANTS in autumn_webhook.ts (dollars). The base grant is// the signup credit; low-balance fires at LOW_CREDIT_FRACTION of the plan grant.@@ -21,26 +22,10 @@ const PLAN_GRANT_CENTS: Record<UsagePlan, number> = {};const LOW_CREDIT_FRACTION = 0.3;-const USAGE_PLAN_RANK: Record<string, number> = { base: 0, pro: 1, max: 2 };-export function lowCreditThresholdCents(plan: UsagePlan): number {return Math.round(PLAN_GRANT_CENTS[plan] * LOW_CREDIT_FRACTION);}-export function activeUsagePlan(customer: AutumnCustomer): UsagePlan {- let plan: UsagePlan = "base";- let rank = 0;- for (const s of customer.subscriptions ?? []) {- if (s.status && s.status !== "active") continue;- const r = USAGE_PLAN_RANK[s.plan_id];- if (r !== undefined && r >= rank) {- rank = r;- plan = s.plan_id as UsagePlan;- }- }- return plan;-}-export interface BillingLinks {billingUrl: string;upgradeUrl: string;diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex a52d2e59..587864e3 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -39,6 +39,7 @@ import {proxyPublicTemplateInspection,} from "./managed_agents";import { enableManagedBilling } from "./model_billing";+import { insufficientManagedAgentCredits } from "./managed_agent_credit_gate";export interface DashboardEnv {OPENCOMPUTER_DB: D1Database;@@ -1009,6 +1010,9 @@ export async function handleDashboard(if (sub === "/managed-agents/sessions" && method === "POST") {try {const billing = await enableManagedBilling(env, caller.orgID);+ if (billing.status === "halted") {+ return insufficientManagedAgentCredits(req);+ }if (billing.status !== "active") {return json({ error: "managed model billing is unavailable" }, 503);}diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.test.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.test.tsindex a16fb7b7..36d2bad9 100644--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.test.ts@@ -13,6 +13,7 @@ class FakeStatement {constructor(private readonly halted: number | null,private readonly haltedAt: number | null,+ private readonly usagePlan: string,) {}bind(orgID: string): this {@@ -24,16 +25,26 @@ class FakeStatement {expect(this.orgID).toBe("org_test");return (this.halted === null? null- : { is_halted: this.halted, halted_at: this.haltedAt }) as T | null;+ : {+ is_halted: this.halted,+ halted_at: this.haltedAt,+ usage_plan: this.usagePlan,+ }) as T | null;}}-function env(halted: number | null, haltedAt: number | null = null) {+function env(+ halted: number | null,+ haltedAt: number | null = null,+ usagePlan = "base",+) {return {OPENCOMPUTER_DB: {prepare(sql: string) {- expect(sql).toBe("SELECT is_halted, halted_at FROM orgs WHERE id = ?1");- return new FakeStatement(halted, haltedAt);+ expect(sql).toBe(+ "SELECT is_halted, halted_at, usage_plan FROM orgs WHERE id = ?1",+ );+ return new FakeStatement(halted, haltedAt, usagePlan);},} as unknown as D1Database,};@@ -78,6 +89,8 @@ describe("managed-agent credit admission", () => {isHalted: true,haltedAt: 1_789_707_077,reason: "insufficient_credits",+ paid: false,+ modelAccess: null,});await expect(getManagedAgentBillingAdmission(env(null), "org_test"),@@ -86,7 +99,55 @@ describe("managed-agent credit admission", () => {isHalted: false,haltedAt: null,reason: null,+ paid: false,+ modelAccess: "full",});+ await expect(+ getManagedAgentBillingAdmission(env(0, null, "pro"), "org_test"),+ ).resolves.toEqual({+ allowed: true,+ isHalted: false,+ haltedAt: null,+ reason: null,+ paid: true,+ modelAccess: "full",+ });+ });++ it.each(["pro", "max"])(+ "admits an exhausted %s org onto the fallback model",+ async (plan) => {+ await expect(+ getManagedAgentBillingAdmission(env(1, 1_789_707_077, plan), "org_test"),+ ).resolves.toEqual({+ allowed: true,+ isHalted: true,+ haltedAt: 1_789_707_077,+ reason: null,+ paid: true,+ modelAccess: "fallback",+ });+ const request = new Request(+ "https://mo-oc-dev.com/api/managed-agents/sessions/session_1/turns",+ { method: "POST" },+ );+ await expect(+ enforceManagedAgentCreditGate(request, env(1, 1_789_707_077, plan), "org_test"),+ ).resolves.toBeNull();+ },+ );++ it("hard-stops an exhausted base org with the upgrade 402", async () => {+ const request = new Request(+ "https://mo-oc-dev.com/api/managed-agents/sessions/session_1/turns",+ { method: "POST" },+ );+ const response = await enforceManagedAgentCreditGate(+ request,+ env(1, 1_789_707_077, "base"),+ "org_test",+ );+ expect(response?.status).toBe(402);});it("returns a typed, actionable 402", async () => {diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.tsindex c282eba2..7d8b452e 100644--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts@@ -1,3 +1,4 @@+import { isPaidUsagePlan } from "./autumn_webhook";import { insufficientCreditsResponse } from "./billing_onramp";export interface ManagedAgentCreditGateEnv {@@ -7,13 +8,21 @@ export interface ManagedAgentCreditGateEnv {interface ManagedAgentCreditRow {is_halted: number;halted_at: number | null;+ usage_plan: string | null;}+// "full": the org's selected models. "fallback": credits are exhausted on a+// paid plan, so model calls run on the open-weight fallback model. null: the+// org is denied (base plan out of credits).+export type ManagedAgentModelAccess = "full" | "fallback";+export interface ManagedAgentBillingAdmission {allowed: boolean;isHalted: boolean;haltedAt: number | null;reason: "insufficient_credits" | null;+ paid: boolean;+ modelAccess: ManagedAgentModelAccess | null;}export function isManagedAgentBillableRequest(@@ -40,16 +49,20 @@ export async function getManagedAgentBillingAdmission(orgID: string,): Promise<ManagedAgentBillingAdmission> {const row = await env.OPENCOMPUTER_DB.prepare(- "SELECT is_halted, halted_at FROM orgs WHERE id = ?1",+ "SELECT is_halted, halted_at, usage_plan FROM orgs WHERE id = ?1",).bind(orgID).first<ManagedAgentCreditRow>();const isHalted = row?.is_halted === 1;+ const paid = isPaidUsagePlan(row?.usage_plan);+ const allowed = !isHalted || paid;return {- allowed: !isHalted,+ allowed,isHalted,haltedAt: row?.halted_at ?? null,- reason: isHalted ? "insufficient_credits" : null,+ reason: allowed ? null : "insufficient_credits",+ paid,+ modelAccess: !isHalted ? "full" : paid ? "fallback" : null,};}@@ -66,9 +79,9 @@ export async function enforceManagedAgentCreditGate(return null;}try {- return (await isManagedAgentCreditHalted(env, orgID))- ? insufficientManagedAgentCredits(request)- : null;+ return (await getManagedAgentBillingAdmission(env, orgID)).allowed+ ? null+ : insufficientManagedAgentCredits(request);} catch (error) {// D1 is the low-latency projection, not the financial authority. Preserve// availability and rely on the provider key limit as the hard backstop.diff --git a/cloudflare-workers/api-edge/src/model_billing.test.ts b/cloudflare-workers/api-edge/src/model_billing.test.tsindex eb0f1a36..7562d570 100644--- a/cloudflare-workers/api-edge/src/model_billing.test.ts+++ b/cloudflare-workers/api-edge/src/model_billing.test.ts@@ -22,6 +22,7 @@ interface OrgRow {model_billing_status: string;model_markup_bps: number;is_halted?: number;+ usage_plan?: string;}class FakeDb {@@ -243,6 +244,34 @@ describe("enableManagedBilling state machine", () => {expect(db.orgs.get(orgId)!.model_billing_status).toBe("off");});+ it.each(["pro", "max"])(+ "keeps an exhausted %s org admitted for the fallback model",+ async (plan) => {+ const db = new FakeDb();+ const orgId = seedOrg(db, {+ is_halted: 1,+ usage_plan: plan,+ model_billing_status: "active",+ });+ db.keys.push({+ id: "mmk_1",+ org_id: orgId,+ status: "active",+ or_key_hash: "hash",+ managed_credential_id: "cred_1",+ created_at: 1,+ } as ManagedModelKeyRow);+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);++ await expect(enableManagedBilling(makeEnv(db), orgId)).resolves.toEqual({+ status: "active",+ credentialId: "cred_1",+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ },+ );+it("off → active: mints key, binds credential, flips org", async () => {const db = new FakeDb();const orgId = seedOrg(db);diff --git a/cloudflare-workers/api-edge/src/model_billing.ts b/cloudflare-workers/api-edge/src/model_billing.tsindex 874b1b75..ef614a46 100644--- a/cloudflare-workers/api-edge/src/model_billing.ts+++ b/cloudflare-workers/api-edge/src/model_billing.ts@@ -7,7 +7,7 @@// The metering cron (model_meter, §5.4) is a separate file (step 3); this is step 1:// the key lifecycle + per-org state only.-import { type AutumnApiEnv, getAutumnCustomer } from "./autumn_webhook";+import { type AutumnApiEnv, getAutumnCustomer, isPaidUsagePlan } from "./autumn_webhook";import {createOrKey,deleteOrKey,@@ -67,6 +67,7 @@ interface OrgBillingRow {model_billing_status: string;model_markup_bps: number;is_halted?: number;+ usage_plan?: string | null;}// sessions-api owner id for an OC org. MUST match sessions-api's ownerIdForOrg@@ -97,7 +98,7 @@ function markupBps(env: ModelBillingEnv, org: OrgBillingRow): number {async function getOrg(env: ModelBillingEnv, orgId: string): Promise<OrgBillingRow | null> {return env.OPENCOMPUTER_DB.prepare(- "SELECT id, billing_provider, model_billing_status, model_markup_bps, is_halted FROM orgs WHERE id = ?1",+ "SELECT id, billing_provider, model_billing_status, model_markup_bps, is_halted, usage_plan FROM orgs WHERE id = ?1",).bind(orgId).first<OrgBillingRow>();@@ -319,7 +320,11 @@ export async function enableManagedBilling(env: ModelBillingEnv, orgId: string):// Reuse the row this path already reads so session creation pays no extra D1// round trip for credit admission. OpenRouter's per-org key limit remains the// hard backstop if this asynchronously maintained projection briefly lags.- if (org.is_halted === 1) return { status: "halted" };+ // Paid orgs stay admitted: the managed-agent gateway moves their model calls+ // to the open-weight fallback instead of stopping them.+ if (org.is_halted === 1 && !isPaidUsagePlan(org.usage_plan)) {+ return { status: "halted" };+ }if (org.model_billing_status === "active") {const active = await getActiveKeyRow(env, orgId);if (active) {diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsxindex 54b98a02..670be7e3 100644--- a/web/src/components/app-shell.tsx+++ b/web/src/components/app-shell.tsx@@ -517,8 +517,14 @@ function SidebarCreditMeter({ onNavigate }: { onNavigate?: () => void }) {// data → no banner.function HaltBanner() {const location = useLocation()- const { isHalted, isLow, usagePlan, creditsRemainingCents, upgradePlan } =- useCreditState()+ const {+ isHalted,+ isLow,+ modelFallback,+ usagePlan,+ creditsRemainingCents,+ upgradePlan,+ } = useCreditState()const onBilling = location.pathname.startsWith('/billing')const state = isHalted ? 'halted' : isLow ? 'low' : nulluseEffect(() => {@@ -560,6 +566,25 @@ function HaltBanner() {</div>)}+ if (modelFallback) {+ return (+ <div className="flex items-center justify-center gap-2 border-b border-amber-500/40 bg-amber-500/10 px-4 py-2.5 text-center text-sm font-medium text-amber-700 sm:px-8 dark:text-amber-400">+ <CircleAlert className="size-4 shrink-0" />+ <span>+ You've used this month's credits — agents keep running on an+ open-weight model (GLM) and sandboxes are paused.{' '}+ <Link+ to="/billing"+ onClick={click}+ className="font-semibold underline underline-offset-2"+ >+ Top up+ </Link>{' '}+ to switch back to your selected models.+ </span>+ </div>+ )+ }return (<div className="border-destructive/40 bg-status-error-bg text-destructive flex items-center justify-center gap-2 border-b px-4 py-2.5 text-center text-sm font-medium sm:px-8"><CircleAlert className="size-4 shrink-0" />diff --git a/web/src/hooks/useCreditState.ts b/web/src/hooks/useCreditState.tsindex e1aa8424..7fc7f752 100644--- a/web/src/hooks/useCreditState.ts+++ b/web/src/hooks/useCreditState.ts@@ -14,6 +14,10 @@ export interface CreditState {usagePlan: UsagePlanId | undefinedcreditsRemainingCents: number | undefinedisHalted: boolean+ // Out of credits on base: agent sessions are blocked until the org upgrades.+ sessionsBlocked: boolean+ // Out of credits on Pro/Max: agents keep running on the fallback model.+ modelFallback: boolean// Below the low-credit threshold but not yet halted; only for prepaid orgs// with the on-ramp experiment enabled.isLow: boolean@@ -30,6 +34,7 @@ export function useCreditState(): CreditState {})const usagePlan = data?.usagePlanconst isHalted = data?.isHalted ?? false+ const paid = usagePlan === 'pro' || usagePlan === 'max'const isLow =billingOnrampV2Enabled &&!isHalted &&@@ -40,6 +45,8 @@ export function useCreditState(): CreditState {usagePlan,creditsRemainingCents: data?.creditsRemainingCents,isHalted,+ sessionsBlocked: isHalted && !paid,+ modelFallback: isHalted && paid,isLow,upgradePlan: upgradePlanFor(usagePlan ?? 'base'),}diff --git a/web/src/hooks/useHalted.ts b/web/src/hooks/useHalted.tsindex bedb024c..0a80fcbf 100644--- a/web/src/hooks/useHalted.ts+++ b/web/src/hooks/useHalted.ts@@ -1,8 +1,9 @@import { useQuery } from '@tanstack/react-query'import { getAutumnBilling } from '@/api/client'-// Out-of-credits (halt) state, shared across the halt banner and the credit-gated-// controls (composer, new-session) so they stay in sync and share one 30s poll.+// Out-of-credits state for the credit-gated agent controls (composer,+// new-session), sharing the halt banner's 30s poll. Only base orgs are blocked:+// Pro/Max orgs keep running agents on the fallback model once credits run out.// Autumn orgs only; legacy orgs 404 on /billing/autumn → error → treated as not halted.export function useHalted(): boolean {const { data } = useQuery({@@ -11,5 +12,6 @@ export function useHalted(): boolean {retry: false,refetchInterval: (q) => (q.state.error ? false : 30_000),})- return data?.isHalted ?? false+ if (!data?.isHalted) return false+ return data.usagePlan !== 'pro' && data.usagePlan !== 'max'}diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex a6a67d64..7383379c 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -322,7 +322,7 @@ function PlaygroundChat({session?.status === 'running' ||session?.status === 'waiting_runtime'const credits = useCreditState()- const halted = credits.isHalted+ const halted = credits.sessionsBlockedconst turnFinished =!agentWorking && status === 'ready' && messages.length > 0const inspectorEvents = useLiveSessionEvents(