An open-source, faster Devin alternative
TypeScript
billing: stop in-flight model calls on a work-minute halt; admission reports halt_reason
Mohamed Habib via Computer19dde13baa6f
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 2f94deb3..98560f86 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@@ -101,6 +101,7 @@ describe("managed-agent credit admission", () => {paid: false,modelAccess: null,usagePlan: "base",+ haltReason: "credits_exhausted",});await expect(getManagedAgentBillingAdmission(env(null), "org_test"),@@ -112,6 +113,7 @@ describe("managed-agent credit admission", () => {paid: false,modelAccess: "full",usagePlan: null,+ haltReason: null,});await expect(getManagedAgentBillingAdmission(env(0, null, "pro"), "org_test"),@@ -123,6 +125,7 @@ describe("managed-agent credit admission", () => {paid: true,modelAccess: "full",usagePlan: "pro",+ haltReason: null,});});@@ -139,6 +142,7 @@ describe("managed-agent credit admission", () => {paid: true,modelAccess: "fallback",usagePlan: plan,+ haltReason: "credits_exhausted",});const request = new Request("https://mo-oc-dev.com/api/managed-agents/sessions/session_1/turns",@@ -179,6 +183,7 @@ describe("managed-agent credit admission", () => {paid: true,modelAccess: "fallback",usagePlan: "pro",+ haltReason: "credits_exhausted",});});diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.tsindex e3128fc2..60dcc643 100644--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts@@ -36,6 +36,12 @@ export interface ManagedAgentBillingAdmission {* 'base' default reads as "pro".*/usagePlan: ManagedAgentUsagePlan | null;+ /**+ * Additive: why the org is halted (orgs.halt_reason, e.g. "trial_days",+ * "credits_empty", "payment"), so a paywall can say which limit was hit.+ * null when not halted.+ */+ haltReason: string | null;}function normalizedUsagePlan(@@ -106,6 +112,7 @@ export async function getManagedAgentBillingAdmission(paid,modelAccess: !isHalted ? "full" : fallback ? "fallback" : null,usagePlan: normalizedUsagePlan(row),+ haltReason: isHalted ? row?.halt_reason ?? "credits_exhausted" : null,};}diff --git a/cloudflare-workers/api-edge/src/model_meter.test.ts b/cloudflare-workers/api-edge/src/model_meter.test.tsindex 2e135962..c777c3fe 100644--- a/cloudflare-workers/api-edge/src/model_meter.test.ts+++ b/cloudflare-workers/api-edge/src/model_meter.test.ts@@ -6,6 +6,7 @@ vi.mock("./autumn_webhook", () => ({getAutumnCustomer: vi.fn(),trackAutumnUsage: vi.fn(async () => 1),projectOrg: vi.fn(async () => {}),+ haltKeepsFallback: (reason: string | null | undefined) => reason == null || reason === "credits_exhausted",}));import { getOrKey, patchOrKey } from "./openrouter";@@ -21,7 +22,7 @@ const gProject = projectOrg as unknown as ReturnType<typeof vi.fn>;// ── in-memory D1 for orgs + managed_model_keys ──────────────────────────────class FakeDb {- orgs = new Map<string, { id: string; model_markup_bps: number; billing_provider: string }>();+ orgs = new Map<string, { id: string; model_markup_bps: number; billing_provider: string; is_halted?: number; halt_reason?: string | null }>();keys: ManagedModelKeyRow[] = [];prepare(sql: string) {return new Stmt(this, sql);@@ -188,6 +189,28 @@ describe("model_meter cap + halt (§5.4/§7)", () => {await runModelMeter(env(db), 0);expect(gProject).toHaveBeenCalledWith(expect.anything(), "org1");});++ it("caps the active key at its usage on a work-minute halt, credits or not", async () => {+ const db = new FakeDb();+ db.orgs.set("org1", { id: "org1", model_markup_bps: 0, billing_provider: "autumn", is_halted: 1, halt_reason: "trial_minutes" });+ db.keys.push(key({ committed_micro: 500000 }));+ gOrKey.mockResolvedValue(orKey(0.5, 10));+ gCust.mockResolvedValue({ id: "org1", balances: { credits: { remaining: 9.5 } } }); // trial tokens left++ await runModelMeter(env(db), 0);+ expect(gPatch).toHaveBeenCalledWith(expect.anything(), "hash1", { limitUsd: expect.closeTo(0.5, 5) });+ });++ it("keeps a credit-rule halt on its credits", async () => {+ const db = new FakeDb();+ db.orgs.set("org1", { id: "org1", model_markup_bps: 0, billing_provider: "autumn", is_halted: 1, halt_reason: "credits_exhausted" });+ db.keys.push(key({ committed_micro: 500000 }));+ gOrKey.mockResolvedValue(orKey(0.5, 1));+ gCust.mockResolvedValue({ id: "org1", balances: { credits: { remaining: 10 } } });++ await runModelMeter(env(db), 0);+ expect(gPatch).toHaveBeenCalledWith(expect.anything(), "hash1", { limitUsd: expect.closeTo(10.5, 5) });+ });});describe("syncModelCaps (Autumn webhook)", () => {@@ -204,6 +227,17 @@ describe("syncModelCaps (Autumn webhook)", () => {expect(db.keys[0].committed_micro).toBe(8000000);});+ it("lifts a work-minute halt's zero cap once the org is no longer halted", async () => {+ const db = new FakeDb();+ db.orgs.set("org1", { id: "org1", model_markup_bps: 0, billing_provider: "autumn", is_halted: 0, halt_reason: null });+ db.keys.push(key({ committed_micro: 500000 }));+ gOrKey.mockResolvedValue(orKey(0.5, 0.5)); // zeroed by the halt+ gCust.mockResolvedValue({ id: "org1", balances: { credits: { remaining: 9.5 } } }); // subscribed++ await syncModelCaps(env(db), "org1");+ expect(gPatch).toHaveBeenCalledWith(expect.anything(), "hash1", { limitUsd: expect.closeTo(10, 5) });+ });+it("leaves non-autumn orgs alone", async () => {const db = new FakeDb();db.orgs.set("org1", { id: "org1", model_markup_bps: 0, billing_provider: "stripe" });diff --git a/cloudflare-workers/api-edge/src/model_meter.ts b/cloudflare-workers/api-edge/src/model_meter.tsindex 9129ead7..491c1122 100644--- a/cloudflare-workers/api-edge/src/model_meter.ts+++ b/cloudflare-workers/api-edge/src/model_meter.ts@@ -12,7 +12,7 @@// 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, projectOrg, trackAutumnUsage } from "./autumn_webhook";+import { type AutumnEnv, getAutumnCustomer, haltKeepsFallback, projectOrg, trackAutumnUsage } from "./autumn_webhook";import { getOrKey, patchOrKey, type OpenRouterEnv } from "./openrouter";import type { ManagedModelKeyRow } from "./model_billing";@@ -111,10 +111,22 @@ async function meterOrg(env: ModelMeterEnv, orgId: string, keys: ManagedModelKey// 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));}- await pushCaps(env, keys, usage, remaining, bps);+ await pushCaps(env, keys, usage, await spendableUsd(env, orgId, remaining), bps);return debited;}+// spendableUsd is what the org's keys may still spend: its credits, or nothing+// while a work-minute halt stands (trial over, allowance and credits used,+// payment, lapsed). The @computer calls OpenRouter with the org's key directly,+// so a zero cap is what stops its in-flight turns; a credit-rule halt is already+// at zero credits.+async function spendableUsd(env: ModelMeterEnv, orgId: string, creditsUsd: number): Promise<number> {+ const row = await env.OPENCOMPUTER_DB.prepare("SELECT is_halted, halt_reason FROM orgs WHERE id = ?1")+ .bind(orgId)+ .first<{ is_halted: number; halt_reason: string | null }>();+ return row?.is_halted === 1 && !haltKeepsFallback(row.halt_reason) ? 0 : creditsUsd;+}+// 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@@ -139,7 +151,8 @@ export async function syncModelCaps(env: ModelMeterEnv, orgId: string): Promise<usage.set(k.id, { usageUsd: ok.usage, limitUsd: ok.limit });}const remaining = (await getAutumnCustomer(env, orgId))?.balances?.credits?.remaining;- await pushCaps(env, keys, usage, typeof remaining === "number" ? remaining : 0, markupBps(env, org));+ const credits = typeof remaining === "number" ? remaining : 0;+ await pushCaps(env, keys, usage, await spendableUsd(env, orgId, credits), markupBps(env, org));}// debitKey moves a key's NEW OpenRouter spend into Autumn, exactly-once (§7):