An open-source, faster Devin alternative
TypeScript
billing: warnings before the stop (orgs.billing_warning, admission warning)
Mohamed Habib via Computer94309401a882
diff --git a/cloudflare-workers/api-edge/migrations/0015_orgs_billing_warning.sql b/cloudflare-workers/api-edge/migrations/0015_orgs_billing_warning.sqlnew file mode 100644index 00000000..a45a6137--- /dev/null+++ b/cloudflare-workers/api-edge/migrations/0015_orgs_billing_warning.sql@@ -0,0 +1,9 @@+-- orgs.billing_warning (serverless-agents-ws 086, step 4): the limit an org is+-- about to hit, so each surface warns before the stop. trial_minutes |+-- trial_days | trial_tokens | allowance_80 | credits_low | payment_failed; NULL+-- when none is near or the org is halted (halt_reason says why).+-- orgs.billing_warning_at: when the current run of warnings began; it holds+-- while any warning stands and clears with it, so a surface can tell each+-- reason once per run.+ALTER TABLE orgs ADD COLUMN billing_warning TEXT;+ALTER TABLE orgs ADD COLUMN billing_warning_at INTEGER;diff --git a/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts b/cloudflare-workers/api-edge/src/agent_runtime_usage.test.tsindex 16edd3dc..bf00a97a 100644--- a/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts+++ b/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts@@ -57,6 +57,39 @@ async function post(fields: Record<string, unknown>, envOverrides: Partial<Autumdescribe("managed-agent runtime usage billing", () => {afterEach(() => vi.restoreAllMocks());+ it("re-projects a trial whose minutes cross the warning line", async () => {+ const trial = (minutes: number) =>+ Response.json({+ id: "org_1",+ subscriptions: [{ plan_id: "trial", add_on: false, status: "active" }],+ balances: { work_minutes: { remaining: minutes }, credits: { remaining: 10 } },+ });+ const writes: string[] = [];+ const db = {+ prepare: (sql: string) => ({+ bind: () => ({+ first: async () => (sql.startsWith("SELECT is_halted") ? { is_halted: 0, usage_plan: "base" } : null),+ run: async () => {+ writes.push(sql);+ return { meta: { changes: 1 } };+ },+ }),+ }),+ } as unknown as D1Database;+ const fetchMock = vi+ .spyOn(globalThis, "fetch")+ .mockResolvedValueOnce(trial(121))+ .mockResolvedValueOnce(Response.json({ balance: { remaining: 119 } }))+ .mockResolvedValueOnce(trial(119))+ .mockResolvedValue(new Response(null, { status: 200 }));++ const response = await post({ close_reason: "turn_settled", idempotency_key: "crt_1:4" }, { OPENCOMPUTER_DB: db });++ expect(response.status).toBe(200);+ expect(fetchMock.mock.calls.filter(([url]) => String(url).includes("/customers/org_1"))).toHaveLength(2);+ expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(true);+ });+it("bills an org on a work-minute plan in work minutes", async () => {const fetchMock = vi.spyOn(globalThis, "fetch")diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts b/cloudflare-workers/api-edge/src/autumn_webhook.test.tsindex d5ed9496..7abd04dc 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts@@ -4,6 +4,7 @@ import {autumnWebhook,autumnSetAutoTopup,autumnUsagePlanPurchase,+ billingWarning,billingWebhookEvents,haltReason,planChangeKind,@@ -335,6 +336,7 @@ describe("billing funnel events from Autumn", () => {if (args[0] === "base") org.payment_past_due_at = null;} else if (sql.includes("SET is_halted")) {org.usage_plan = args[3];+ org.billing_warning = args[7];}return { meta: { changes: 1 } };},@@ -376,6 +378,14 @@ describe("billing funnel events from Autumn", () => {});});+ it("writes the warning next to the halt reason", async () => {+ mockAutumn([{ plan_id: "pro" }]);+ const db = fakeDb("pro", Math.floor(Date.now() / 1000) - 3600);+ const r = await syncAutumnToD1({ ...env, OPENCOMPUTER_DB: db }, "org_1");+ expect(r?.warning).toBe("payment_failed");+ expect(db.org.billing_warning).toBe("payment_failed");+ });+it("calls a plan that ends while past due lapsed, whoever projects it", async () => {const posted = mockAutumn([]);const db = fakeDb("pro", 1_700_000_000);@@ -494,3 +504,61 @@ describe("halt rules", () => {).toBe("trial_days");});});++describe("warnings before the stop", () => {+ const now = 1_800_000_000;+ const day = 86_400;+ const customer = (+ plans: string[],+ balances: { minutes?: number; credits?: number },+ autoTopup = false,+ ): Parameters<typeof billingWarning>[0] => ({+ id: "org_1",+ subscriptions: plans.map((plan_id) => ({ plan_id, add_on: false, status: "active" })),+ balances: {+ ...(balances.minutes === undefined ? {} : { work_minutes: { remaining: balances.minutes } }),+ credits: { remaining: balances.credits ?? 0 },+ },+ ...(autoTopup+ ? { billing_controls: { auto_topups: [{ feature_id: "credits", enabled: true, threshold: 5, quantity: 10 }] } }+ : {}),+ });+ const fresh = { trialStartedAt: now - day, paymentPastDueAt: null };++ it("warns a trial at 480 minutes, 2 days left or $8 spent", () => {+ expect(billingWarning(customer(["trial"], { minutes: 121, credits: 2.5 }), fresh, now)).toBeNull();+ expect(billingWarning(customer(["trial"], { minutes: 120, credits: 5 }), fresh, now)).toBe("trial_minutes");+ expect(billingWarning(customer(["trial"], { minutes: 300, credits: 2 }), fresh, now)).toBe("trial_tokens");+ expect(+ billingWarning(customer(["trial"], { minutes: 300, credits: 5 }), { ...fresh, trialStartedAt: now - 5 * day }, now),+ ).toBe("trial_days");+ });++ it("names the trial limit closest to stopping", () => {+ const day6 = { ...fresh, trialStartedAt: now - 6 * day };+ // 1 day of 7 left (14%) against 100 of 600 minutes (17%).+ expect(billingWarning(customer(["trial"], { minutes: 100, credits: 5 }), day6, now)).toBe("trial_days");+ expect(billingWarning(customer(["trial"], { minutes: 30, credits: 5 }), day6, now)).toBe("trial_minutes");+ expect(billingWarning(customer(["trial"], { minutes: 100, credits: 0.5 }), day6, now)).toBe("trial_tokens");+ });++ it("warns a paid org at 80% of its minutes, then about low credits", () => {+ expect(billingWarning(customer(["pro"], { minutes: 401, credits: 1 }), fresh, now)).toBeNull();+ expect(billingWarning(customer(["pro"], { minutes: 400, credits: 20 }), fresh, now)).toBe("allowance_80");+ expect(billingWarning(customer(["max"], { minutes: 4_000, credits: 4 }), fresh, now)).toBe("credits_low");+ expect(billingWarning(customer(["pro"], { minutes: 0, credits: 4.99 }), fresh, now)).toBe("credits_low");+ expect(billingWarning(customer(["pro"], { minutes: 0, credits: 4 }, true), fresh, now)).toBe("allowance_80");+ });++ it("puts a failing payment first, inside its grace", () => {+ const pastDue = { ...fresh, paymentPastDueAt: now - day };+ expect(billingWarning(customer(["pro"], { minutes: 0, credits: 1 }), pastDue, now)).toBe("payment_failed");+ expect(billingWarning(customer(["pro"], { minutes: 0, credits: 1 }), { ...fresh, paymentPastDueAt: now - 3 * day }, now)).toBeNull();+ });++ it("says nothing once halted, or to a credit-only org", () => {+ expect(billingWarning(customer(["trial"], { minutes: 0, credits: 5 }), fresh, now)).toBeNull();+ expect(billingWarning(customer([], { minutes: 0 }), fresh, now)).toBeNull();+ expect(billingWarning(customer(["base"], { credits: 1 }), { trialStartedAt: null, paymentPastDueAt: null }, now)).toBeNull();+ });+});diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 93aa703d..1b167c80 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -571,6 +571,9 @@ export async function agentRuntimeUsageInternal(idempotencyKey: p.idempotency_key,});if (remaining !== null && remaining <= 0) await projectOrg(env, p.org_id);+ else if (workMinutes && remaining !== null && customer && minutesWarningCrossed(customer, remaining)) {+ await projectOrg(env, p.org_id);+ }if (workMinutes) {await recordWorkMinutes(env, p.org_id, customer, {minutes: Number(p.quantity_seconds) / 60,@@ -688,6 +691,85 @@ export function haltReason(return "lapsed";}+// ── warnings before the stop (serverless-agents-ws 086, step 4) ─────────────++export type BillingWarning =+ | "trial_minutes"+ | "trial_days"+ | "trial_tokens"+ | "allowance_80"+ | "credits_low"+ | "payment_failed";++const TRIAL_MINUTES = 600;+const TRIAL_CREDITS = 10;+// Trial: warn at 480 of 600 minutes, 2 days left, or $8 of the $10 spent.+const TRIAL_WARN_MINUTES_LEFT = 120;+const TRIAL_WARN_DAYS_LEFT = 2;+const TRIAL_WARN_CREDITS_LEFT = 2;+// Paid: warn at 80% of the month's minutes, and when the credits that pay past+// them run under $5 with no auto top-up to refill them.+const PLAN_WORK_MINUTES: Record<string, number> = { pro: 2_000, max: 25_000 };+const ALLOWANCE_WARN_FRACTION = 0.2;+const CREDITS_LOW = 5;++function hasAutoTopup(customer: AutumnCustomer): boolean {+ return (customer.billing_controls?.auto_topups ?? []).some((a) => a.feature_id === CREDITS_FEATURE_ID && a.enabled);+}++// billingWarning says which limit an org is about to hit, or null when none is+// near or it is already halted. A failing payment comes first, since it stops+// the org whatever its usage; otherwise the trial warns about the limit with+// the smallest share left, and a paid org about low credits before 80% of its+// minutes, since credits are the last thing between it and the stop.+export function billingWarning(+ customer: AutumnCustomer,+ org: { trialStartedAt: number | null; paymentPastDueAt: number | null },+ nowSec: number,+): BillingWarning | null {+ if (haltReason(customer, org, nowSec) !== null) return null;+ const plan = activeUsagePlan(customer);+ // Any paid org, credit plans included, is told its payment failed.+ if (plan !== "base" && org.paymentPastDueAt != null) return "payment_failed";+ const credits = customer.balances?.[CREDITS_FEATURE_ID]?.remaining ?? 0;+ const minutesBalance = customer.balances?.[WORK_MINUTES_FEATURE_ID];+ if (minutesBalance === undefined && org.trialStartedAt == null) return null;+ const minutes = minutesBalance?.remaining ?? 0;++ if (plan !== "base") {+ const allowance = PLAN_WORK_MINUTES[plan];+ if (minutesBalance === undefined || allowance === undefined) return null;+ const allowanceNear = minutes <= allowance * ALLOWANCE_WARN_FRACTION;+ if (allowanceNear && credits < CREDITS_LOW && !hasAutoTopup(customer)) return "credits_low";+ return allowanceNear ? "allowance_80" : null;+ }++ // haltReason returned null, so this is a running trial.+ const near: Array<[BillingWarning, number]> = [];+ if (minutes <= TRIAL_WARN_MINUTES_LEFT) near.push(["trial_minutes", minutes / TRIAL_MINUTES]);+ if (org.trialStartedAt != null) {+ const daysLeft = TRIAL_DAYS - (nowSec - org.trialStartedAt) / DAY_SEC;+ if (daysLeft <= TRIAL_WARN_DAYS_LEFT) near.push(["trial_days", daysLeft / TRIAL_DAYS]);+ }+ if (credits <= TRIAL_WARN_CREDITS_LEFT) near.push(["trial_tokens", credits / TRIAL_CREDITS]);+ near.sort((a, b) => a[1] - b[1]);+ return near[0]?.[0] ?? null;+}++// minutesWarningCrossed: did this track move the minutes past a warning line+// (480 trial minutes, 80% of the month)? Only usage differs between the two+// reads, so the clock-driven reasons are left out of the comparison.+function minutesWarningCrossed(before: AutumnCustomer, minutesRemaining: number): boolean {+ const minutes = { ...before.balances?.[WORK_MINUTES_FEATURE_ID], remaining: minutesRemaining };+ const after: AutumnCustomer = { ...before, balances: { ...before.balances, [WORK_MINUTES_FEATURE_ID]: minutes } };+ const noClock = { trialStartedAt: null, paymentPastDueAt: null };+ const nowSec = Math.floor(Date.now() / 1000);+ return billingWarning(before, noClock, nowSec) !== billingWarning(after, noClock, nowSec);+}++// The trial age at which trial_days starts, for the billing clock.+export const TRIAL_WARN_AFTER_SEC = (TRIAL_DAYS - TRIAL_WARN_DAYS_LEFT) * DAY_SEC;+// syncAutumnToD1 reads Autumn's authoritative balance/plans and writes the D1// projection (is_halted / usage_plan / max_concurrent) WITHOUT any cell dispatch. Returns the// halt transition so callers can decide whether to actively hibernate. Reusable@@ -698,6 +780,7 @@ export interface AutumnSyncResult {maxConcurrent: number;halted: boolean;haltReason: HaltReason | null;+ warning: BillingWarning | null;wasHalted: boolean;usagePlan: UsagePlan;}@@ -726,12 +809,10 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promisetrial_started_at: number | null;}>();const wasHalted = prevRow?.is_halted === 1;- const reason = haltReason(- cust,- { trialStartedAt: prevRow?.trial_started_at ?? null, paymentPastDueAt: prevRow?.payment_past_due_at ?? null },- nowSec,- );+ const clock = { trialStartedAt: prevRow?.trial_started_at ?? null, paymentPastDueAt: prevRow?.payment_past_due_at ?? null };+ const reason = haltReason(cust, clock, nowSec);const halted = reason !== null;+ const warning = billingWarning(cust, clock, nowSec);const maxConcurrent = prevRow?.autumn_concurrency_override ?? projectedMaxConcurrent;// Compare-and-set the plan first: the webhook, checkout-return and the cron can@@ -752,18 +833,22 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise}}+ // billing_warning_at marks when the org started being warned and holds while+ // any warning stands, so a surface can tell each reason once per episode.await env.OPENCOMPUTER_DB.prepare(`UPDATE orgs SET is_halted = ?1, halted_at = ?2, max_concurrent_sandboxes = ?3, usage_plan = ?4, updated_at = ?5,- halt_reason = ?7 WHERE id = ?6`,+ halt_reason = ?7, billing_warning = ?8,+ billing_warning_at = CASE WHEN ?8 IS NULL THEN NULL ELSE COALESCE(billing_warning_at, ?5) END+ WHERE id = ?6`,)- .bind(halted ? 1 : 0, halted ? nowSec : null, maxConcurrent, usagePlan, nowSec, orgID, reason)+ .bind(halted ? 1 : 0, halted ? nowSec : null, maxConcurrent, usagePlan, nowSec, orgID, reason, warning).run();// After the writes, so the event's send time never widens the window in which// a concurrent projection can interleave.if (planChange) await emitBillingEvent(env, "billing.plan_changed", { orgId: orgID, data: planChange });- return { customer: cust, creditsRemaining, maxConcurrent, halted, haltReason: reason, wasHalted, usagePlan };+ return { customer: cust, creditsRemaining, maxConcurrent, halted, haltReason: reason, warning, wasHalted, usagePlan };}// autumnSetProviderInternal flips D1 orgs.billing_provider for one org (thediff --git a/cloudflare-workers/api-edge/src/billing_clock.test.ts b/cloudflare-workers/api-edge/src/billing_clock.test.tsindex c0dd80b4..2438308c 100644--- a/cloudflare-workers/api-edge/src/billing_clock.test.ts+++ b/cloudflare-workers/api-edge/src/billing_clock.test.ts@@ -5,7 +5,7 @@ import { runBillingClock } from "./billing_clock";describe("billing clock", () => {afterEach(() => vi.restoreAllMocks());- it("re-projects orgs whose trial or payment grace has run out", async () => {+ it("re-projects orgs whose trial, payment grace or trial warning is due", async () => {const project = vi.spyOn(autumn, "projectOrg").mockResolvedValue();let bound: unknown[] = [];let sql = "";@@ -24,7 +24,7 @@ describe("billing clock", () => {expect(await runBillingClock(env, 1_800_000_000_000)).toBe(2);// Least recently updated first, so orgs that stay unhalted can't fill every batch.expect(sql).toMatch(/ORDER BY updated_at\s+LIMIT/);- expect(bound).toEqual([1_800_000_000 - 7 * 86_400, 1_800_000_000 - 3 * 86_400, 50]);+ expect(bound).toEqual([1_800_000_000 - 7 * 86_400, 1_800_000_000 - 3 * 86_400, 50, 1_800_000_000 - 5 * 86_400]);expect(project.mock.calls.map((c) => c[1])).toEqual(["org_a", "org_b"]);});});diff --git a/cloudflare-workers/api-edge/src/billing_clock.ts b/cloudflare-workers/api-edge/src/billing_clock.tsindex 9b6747af..0a085dc2 100644--- a/cloudflare-workers/api-edge/src/billing_clock.ts+++ b/cloudflare-workers/api-edge/src/billing_clock.ts@@ -2,12 +2,14 @@// time passing rather than usage. A trial ends on day 7 and a failing payment// halts after its grace even when the org does nothing, so the */5 cron// re-projects the orgs whose clock has run out; projectOrg decides and halts.-// A halted or paid-up org no longer matches. One that matches but stays+// It also re-projects a trial reaching 2 days left that is not yet warned, so+// the trial_days warning goes out on time rather than on the next activity.+// A halted, warned or paid-up org no longer matches. One that matches but stays// unhalted (a credit-only signup before the Autumn trial plan exists) is// re-projected every tick, so the batch takes the least recently updated rows// first: projectOrg stamps updated_at, and such rows cannot starve the rest.-import { type AutumnEnv, PAYMENT_GRACE_DAYS, TRIAL_DAYS, projectOrg } from "./autumn_webhook";+import { type AutumnEnv, PAYMENT_GRACE_DAYS, TRIAL_DAYS, TRIAL_WARN_AFTER_SEC, projectOrg } from "./autumn_webhook";const DAY_SEC = 86_400;// Bounds one tick; the next tick continues.@@ -18,11 +20,17 @@ export async function runBillingClock(env: AutumnEnv, nowMs: number): Promise<nuconst due = await env.OPENCOMPUTER_DB.prepare(`SELECT id FROM orgsWHERE billing_provider = 'autumn' AND is_halted = 0- AND ((usage_plan = 'base' AND trial_started_at <= ?1) OR payment_past_due_at <= ?2)+ AND ((usage_plan = 'base' AND trial_started_at <= ?1) OR payment_past_due_at <= ?2+ OR (usage_plan = 'base' AND trial_started_at <= ?4 AND billing_warning IS NULL))ORDER BY updated_atLIMIT ?3`,)- .bind(nowSec - TRIAL_DAYS * DAY_SEC, nowSec - PAYMENT_GRACE_DAYS * DAY_SEC, MAX_ORGS_PER_RUN)+ .bind(+ nowSec - TRIAL_DAYS * DAY_SEC,+ nowSec - PAYMENT_GRACE_DAYS * DAY_SEC,+ MAX_ORGS_PER_RUN,+ nowSec - TRIAL_WARN_AFTER_SEC,+ ).all<{ id: string }>();let projected = 0;for (const { id } of due.results ?? []) {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 98560f86..a6ca19c8 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@@ -17,6 +17,7 @@ class FakeStatement {private readonly plan: string,private readonly billingProvider: string,private readonly haltReason: string | null,+ private readonly warning: [string, number] | null = null,) {}bind(orgID: string): this {@@ -35,6 +36,8 @@ class FakeStatement {plan: this.plan,billing_provider: this.billingProvider,halt_reason: this.haltReason,+ billing_warning: this.warning?.[0] ?? null,+ billing_warning_at: this.warning?.[1] ?? null,}) as T | null;}}@@ -46,14 +49,13 @@ function env(plan = "free",billingProvider = "autumn",haltReason: string | null = null,+ warning: [string, number] | null = null,) {return {OPENCOMPUTER_DB: {prepare(sql: string) {- expect(sql).toBe(- "SELECT is_halted, halted_at, usage_plan, plan, billing_provider, halt_reason FROM orgs WHERE id = ?1",- );- return new FakeStatement(halted, haltedAt, usagePlan, plan, billingProvider, haltReason);+ expect(sql).toContain("halt_reason, billing_warning, billing_warning_at");+ return new FakeStatement(halted, haltedAt, usagePlan, plan, billingProvider, haltReason, warning);},} as unknown as D1Database,};@@ -102,6 +104,8 @@ describe("managed-agent credit admission", () => {modelAccess: null,usagePlan: "base",haltReason: "credits_exhausted",+ warning: null,+ warningSince: null,});await expect(getManagedAgentBillingAdmission(env(null), "org_test"),@@ -114,6 +118,8 @@ describe("managed-agent credit admission", () => {modelAccess: "full",usagePlan: null,haltReason: null,+ warning: null,+ warningSince: null,});await expect(getManagedAgentBillingAdmission(env(0, null, "pro"), "org_test"),@@ -126,6 +132,8 @@ describe("managed-agent credit admission", () => {modelAccess: "full",usagePlan: "pro",haltReason: null,+ warning: null,+ warningSince: null,});});@@ -143,6 +151,8 @@ describe("managed-agent credit admission", () => {modelAccess: "fallback",usagePlan: plan,haltReason: "credits_exhausted",+ warning: null,+ warningSince: null,});const request = new Request("https://mo-oc-dev.com/api/managed-agents/sessions/session_1/turns",@@ -163,6 +173,21 @@ describe("managed-agent credit admission", () => {},);+ it("reports the warning before the stop, and none once halted", async () => {+ await expect(+ getManagedAgentBillingAdmission(+ env(0, null, "base", "free", "autumn", null, ["trial_minutes", 1_789_700_000]),+ "org_test",+ ),+ ).resolves.toMatchObject({ allowed: true, warning: "trial_minutes", warningSince: 1_789_700_000 });+ await expect(+ getManagedAgentBillingAdmission(+ env(1, 1_789_707_077, "base", "free", "autumn", "trial_minutes", ["trial_minutes", 1_789_700_000]),+ "org_test",+ ),+ ).resolves.toMatchObject({ haltReason: "trial_minutes", warning: null, warningSince: null });+ });+it("keeps the fallback for a paid org halted on the credit rule", async () => {await expect(getManagedAgentBillingAdmission(env(1, 1_789_707_077, "max", "free", "autumn", "credits_exhausted"), "org_test"),@@ -184,6 +209,8 @@ describe("managed-agent credit admission", () => {modelAccess: "fallback",usagePlan: "pro",haltReason: "credits_exhausted",+ warning: null,+ warningSince: null,});});diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.tsindex 60dcc643..6aa47ec7 100644--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts@@ -12,6 +12,8 @@ interface ManagedAgentCreditRow {usage_plan: string | null;plan: string | null;halt_reason: string | null;+ billing_warning?: string | null;+ billing_warning_at?: number | null;}// "full": the org's selected models. "fallback": credits are exhausted on a@@ -42,6 +44,19 @@ export interface ManagedAgentBillingAdmission {* null when not halted.*/haltReason: string | null;+ /**+ * Additive (086): the limit the org is about to hit (orgs.billing_warning:+ * "trial_minutes", "trial_days", "trial_tokens", "allowance_80",+ * "credits_low", "payment_failed"), so a surface can warn before the stop.+ * null when nothing is near or the org is halted.+ */+ warning: string | null;+ /**+ * When the current run of warnings began (orgs.billing_warning_at, unix+ * seconds). It holds while any warning stands, so (warning, warningSince)+ * names one warning to tell once.+ */+ warningSince: number | null;}function normalizedUsagePlan(@@ -84,7 +99,8 @@ export async function getManagedAgentBillingAdmission(selfHeal?: ManagedAgentSelfHeal,): Promise<ManagedAgentBillingAdmission> {const row = await env.OPENCOMPUTER_DB.prepare(- "SELECT is_halted, halted_at, usage_plan, plan, billing_provider, halt_reason FROM orgs WHERE id = ?1",+ `SELECT is_halted, halted_at, usage_plan, plan, billing_provider, halt_reason, billing_warning, billing_warning_at+ FROM orgs WHERE id = ?1`,).bind(orgID).first<ManagedAgentCreditRow>();@@ -113,6 +129,8 @@ export async function getManagedAgentBillingAdmission(modelAccess: !isHalted ? "full" : fallback ? "fallback" : null,usagePlan: normalizedUsagePlan(row),haltReason: isHalted ? row?.halt_reason ?? "credits_exhausted" : null,+ warning: isHalted ? null : row?.billing_warning ?? null,+ warningSince: isHalted || !row?.billing_warning ? null : row.billing_warning_at ?? null,};}diff --git a/cloudflare-workers/api-edge/src/model_meter.test.ts b/cloudflare-workers/api-edge/src/model_meter.test.tsindex c777c3fe..3b199f2a 100644--- a/cloudflare-workers/api-edge/src/model_meter.test.ts+++ b/cloudflare-workers/api-edge/src/model_meter.test.ts@@ -6,11 +6,12 @@ vi.mock("./autumn_webhook", () => ({getAutumnCustomer: vi.fn(),trackAutumnUsage: vi.fn(async () => 1),projectOrg: vi.fn(async () => {}),+ billingWarning: vi.fn(() => null),haltKeepsFallback: (reason: string | null | undefined) => reason == null || reason === "credits_exhausted",}));import { getOrKey, patchOrKey } from "./openrouter";-import { getAutumnCustomer, trackAutumnUsage, projectOrg } from "./autumn_webhook";+import { billingWarning, getAutumnCustomer, trackAutumnUsage, projectOrg } from "./autumn_webhook";import { runModelMeter, syncModelCaps, type ModelMeterEnv } from "./model_meter";import type { ManagedModelKeyRow } from "./model_billing";@@ -19,6 +20,7 @@ const gPatch = patchOrKey as unknown as ReturnType<typeof vi.fn>;const gCust = getAutumnCustomer as unknown as ReturnType<typeof vi.fn>;const gTrack = trackAutumnUsage as unknown as ReturnType<typeof vi.fn>;const gProject = projectOrg as unknown as ReturnType<typeof vi.fn>;+const gWarning = billingWarning as unknown as ReturnType<typeof vi.fn>;// ── in-memory D1 for orgs + managed_model_keys ──────────────────────────────class FakeDb {@@ -83,6 +85,7 @@ beforeEach(() => {gCust.mockReset();gTrack.mockReset().mockResolvedValue(1);gProject.mockReset().mockResolvedValue(undefined);+ gWarning.mockReset().mockReturnValue(null);});afterEach(() => vi.clearAllMocks());@@ -102,6 +105,19 @@ describe("model_meter debit (persist-before-track, §7)", () => {expect(db.keys[0].pending_idem).toBeNull(); // cleared after success});+ it("re-projects when spend moves the org's warning", async () => {+ const db = new FakeDb();+ db.orgs.set("org1", { id: "org1", model_markup_bps: 0, billing_provider: "autumn" });+ db.keys.push(key({ committed_micro: 0 }));+ gOrKey.mockResolvedValue(orKey(8.5));+ gCust.mockResolvedValue({ id: "org1", balances: { credits: { remaining: 1.5 } } });+ gWarning.mockReturnValue("trial_tokens");++ await runModelMeter(env(db), 0);++ expect(gProject).toHaveBeenCalledWith(expect.anything(), "org1");+ });+it("skips non-autumn orgs entirely — no debit, no halt (decoupled; the fixed OR-key budget is the ceiling)", async () => {const db = new FakeDb();db.orgs.set("org1", { id: "org1", model_markup_bps: 0, billing_provider: "legacy" });diff --git a/cloudflare-workers/api-edge/src/model_meter.ts b/cloudflare-workers/api-edge/src/model_meter.tsindex 491c1122..acc0dd8e 100644--- a/cloudflare-workers/api-edge/src/model_meter.ts+++ b/cloudflare-workers/api-edge/src/model_meter.ts@@ -12,7 +12,14 @@// into the Autumn ledger + keeps the cap aligned with the shared balance. Mirrors// the autumn_meter idempotency model (Autumn dedupes the track key).-import { type AutumnEnv, getAutumnCustomer, haltKeepsFallback, projectOrg, trackAutumnUsage } from "./autumn_webhook";+import {+ type AutumnEnv,+ billingWarning,+ getAutumnCustomer,+ haltKeepsFallback,+ projectOrg,+ trackAutumnUsage,+} from "./autumn_webhook";import { getOrKey, patchOrKey, type OpenRouterEnv } from "./openrouter";import type { ManagedModelKeyRow } from "./model_billing";@@ -31,6 +38,9 @@ interface OrgMeterRow {id: string;model_markup_bps: number;billing_provider: string;+ trial_started_at?: number | null;+ payment_past_due_at?: number | null;+ billing_warning?: string | null;}function markupBps(env: ModelMeterEnv, org: OrgMeterRow): number {@@ -73,7 +83,8 @@ export async function runModelMeter(env: ModelMeterEnv, _nowMs: number): Promiseasync function meterOrg(env: ModelMeterEnv, orgId: string, keys: ManagedModelKeyRow[]): Promise<boolean> {const org = await env.OPENCOMPUTER_DB.prepare(- "SELECT id, model_markup_bps, billing_provider FROM orgs WHERE id = ?1",+ `SELECT id, model_markup_bps, billing_provider, trial_started_at, payment_past_due_at, billing_warning+ FROM orgs WHERE id = ?1`,).bind(orgId).first<OrgMeterRow>();@@ -110,6 +121,10 @@ async function meterOrg(env: ModelMeterEnv, orgId: string, keys: ManagedModelKeyif (remaining <= 0) {// Halt immediately (mirror autumn_meter) — don't wait on the Autumn webhook.await projectOrg(env, orgId).catch((e) => console.error(`model-meter: projectOrg ${orgId} failed`, e));+ } else if (debited && cust && warningMoved(cust, org)) {+ // Spend crossed a warning line (trial $8 spent, paid credits low): project+ // now so the warning goes out on this tick, not on the next webhook.+ await projectOrg(env, orgId).catch((e) => console.error(`model-meter: projectOrg ${orgId} failed`, e));}await pushCaps(env, keys, usage, await spendableUsd(env, orgId, remaining), bps);return debited;@@ -127,6 +142,11 @@ async function spendableUsd(env: ModelMeterEnv, orgId: string, creditsUsd: numbereturn row?.is_halted === 1 && !haltKeepsFallback(row.halt_reason) ? 0 : creditsUsd;}+function warningMoved(cust: Parameters<typeof billingWarning>[0], org: OrgMeterRow): boolean {+ const clock = { trialStartedAt: org.trial_started_at ?? null, paymentPastDueAt: org.payment_past_due_at ?? null };+ return billingWarning(cust, clock, Math.floor(Date.now() / 1000)) !== (org.billing_warning ?? null);+}+// syncModelCaps pushes one org's caps off its current Autumn balance now, for the// Autumn webhook: an upgrade or grant lifts a key still capped at the old balance// at once instead of on the next tick (a free org that upgraded kept hitting