Skip to content

An open-source, faster Devin alternative

TypeScript

Gate: work-minute halt rules, halt_reason, billing clock

Mohamed Habib via Computer0cdebf1a17f4
diff --git a/cloudflare-workers/api-edge/migrations/0014_orgs_halt_reason.sql b/cloudflare-workers/api-edge/migrations/0014_orgs_halt_reason.sql
new file mode 100644
index 00000000..bbccabc0
--- /dev/null
+++ b/cloudflare-workers/api-edge/migrations/0014_orgs_halt_reason.sql
@@ -0,0 +1,6 @@
+-- orgs.halt_reason (serverless-agents-ws 086, step 4): why is_halted is set, so
+-- each surface shows the right paywall. trial_minutes | trial_days |
+-- trial_tokens | credits_empty | payment | lapsed for orgs on work minutes;
+-- credits_exhausted for credit-only orgs (the pre-086 rule, which keeps paid
+-- orgs on the fallback model). NULL when not halted, or halted before 0014.
+ALTER TABLE orgs ADD COLUMN halt_reason TEXT;
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
index 186e0715..a806d832 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
@@ -5,6 +5,7 @@ import {
autumnSetAutoTopup,
autumnUsagePlanPurchase,
billingWebhookEvents,
+ haltReason,
planChangeKind,
syncAutumnToD1,
summarizeAutumnCreditBalance,
@@ -436,3 +437,55 @@ describe("billing funnel events from Autumn", () => {
expect(posted.map((p) => p.event)).toEqual(["billing.payment_failed"]);
});
});
+
+describe("halt rules", () => {
+ const now = 1_800_000_000;
+ const day = 86_400;
+ const customer = (
+ plans: string[],
+ balances: { minutes?: number; credits?: number },
+ ): Parameters<typeof haltReason>[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 },
+ },
+ });
+ const fresh = { trialStartedAt: now - day, paymentPastDueAt: null };
+
+ it("keeps credit-only orgs on the credit rule", () => {
+ const org = { trialStartedAt: null, paymentPastDueAt: null };
+ expect(haltReason(customer(["base"], { credits: 3 }), org, now)).toBeNull();
+ expect(haltReason(customer(["base"], { credits: 0 }), org, now)).toBe("credits_exhausted");
+ expect(haltReason(customer(["max"], { credits: 0 }), org, now)).toBe("credits_exhausted");
+ });
+
+ it("ends the trial at day 7, 600 minutes or the token credit", () => {
+ expect(haltReason(customer(["trial"], { minutes: 100, credits: 5 }), fresh, now)).toBeNull();
+ expect(
+ haltReason(customer(["trial"], { minutes: 100, credits: 5 }), { ...fresh, trialStartedAt: now - 7 * day }, now),
+ ).toBe("trial_days");
+ expect(haltReason(customer(["trial"], { minutes: 0, credits: 5 }), fresh, now)).toBe("trial_minutes");
+ expect(haltReason(customer(["trial"], { minutes: 100, credits: 0 }), fresh, now)).toBe("trial_tokens");
+ });
+
+ it("halts a paid org only when minutes and credits are both used", () => {
+ expect(haltReason(customer(["pro"], { minutes: 0, credits: 4 }), fresh, now)).toBeNull();
+ expect(haltReason(customer(["pro"], { minutes: 12, credits: 0 }), fresh, now)).toBeNull();
+ expect(haltReason(customer(["max"], { minutes: 0, credits: 0 }), fresh, now)).toBe("credits_empty");
+ });
+
+ it("halts a paid org once its payment is 3 days past due", () => {
+ const pastDue = (days: number) => ({ ...fresh, paymentPastDueAt: now - days * day });
+ expect(haltReason(customer(["pro"], { minutes: 500 }), pastDue(2), now)).toBeNull();
+ expect(haltReason(customer(["pro"], { minutes: 500 }), pastDue(3), now)).toBe("payment");
+ });
+
+ it("calls a work-minute org with no plan lapsed, and gives no second trial", () => {
+ expect(haltReason(customer([], { minutes: 0, credits: 0 }), fresh, now)).toBe("lapsed");
+ expect(
+ haltReason(customer(["trial"], { minutes: 600, credits: 10 }), { ...fresh, trialStartedAt: now - 40 * day }, now),
+ ).toBe("trial_days");
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.ts
index c13ce164..7c865cd2 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts
@@ -628,6 +628,65 @@ export async function selfHealHalt(env: AutumnEnv, orgID: string): Promise<boole
return row?.is_halted === 1;
}
+// ── halt rules (serverless-agents-ws 086, step 4) ───────────────────────────
+
+export const TRIAL_DAYS = 7;
+// A paid org whose payment is failing keeps working this long before it halts.
+export const PAYMENT_GRACE_DAYS = 3;
+const DAY_SEC = 86_400;
+
+export type HaltReason =
+ | "trial_minutes"
+ | "trial_days"
+ | "trial_tokens"
+ | "credits_empty"
+ | "payment"
+ | "lapsed"
+ | "credits_exhausted";
+
+// Credit-only halts keep a paid org's managed agents on the open-weight
+// fallback model; every work-minute halt stops the org. NULL: halted before
+// halt_reason existed, read as the old rule until the next projection.
+export function haltKeepsFallback(reason: string | null | undefined): boolean {
+ return reason == null || reason === "credits_exhausted";
+}
+
+function hasActiveSubscription(customer: AutumnCustomer, planID: string): boolean {
+ return (customer.subscriptions ?? []).some((s) => s.plan_id === planID && (!s.status || s.status === "active"));
+}
+
+// haltReason decides whether an org is halted, and why. An org is on work
+// minutes once Autumn shows a work_minutes balance or the edge recorded its
+// trial; every other org keeps the credit rule until it is migrated (step 8).
+export function haltReason(
+ customer: AutumnCustomer,
+ org: { trialStartedAt: number | null; paymentPastDueAt: number | null },
+ nowSec: number,
+): HaltReason | null {
+ const credits = customer.balances?.[CREDITS_FEATURE_ID]?.remaining ?? 0;
+ const minutesBalance = customer.balances?.[WORK_MINUTES_FEATURE_ID];
+ if (minutesBalance === undefined && org.trialStartedAt == null) {
+ return credits <= 0 ? "credits_exhausted" : null;
+ }
+ const minutes = minutesBalance?.remaining ?? 0;
+
+ if (activeUsagePlan(customer) !== "base") {
+ if (org.paymentPastDueAt != null && nowSec - org.paymentPastDueAt >= PAYMENT_GRACE_DAYS * DAY_SEC) {
+ return "payment";
+ }
+ return minutes <= 0 && credits <= 0 ? "credits_empty" : null;
+ }
+ if (hasActiveSubscription(customer, "trial")) {
+ // Autumn re-enables trial when a paid plan ends; the original start still
+ // counts, so a cancelled org gets no second trial.
+ if (org.trialStartedAt != null && nowSec - org.trialStartedAt >= TRIAL_DAYS * DAY_SEC) return "trial_days";
+ if (minutes <= 0) return "trial_minutes";
+ if (credits <= 0) return "trial_tokens";
+ return null;
+ }
+ return "lapsed";
+}
+
// 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
@@ -637,6 +696,7 @@ export interface AutumnSyncResult {
creditsRemaining: number; // dollars
maxConcurrent: number;
halted: boolean;
+ haltReason: HaltReason | null;
wasHalted: boolean;
usagePlan: UsagePlan;
}
@@ -649,13 +709,12 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
}
const 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);
const prevRow = await env.OPENCOMPUTER_DB.prepare(
- "SELECT is_halted, autumn_concurrency_override, usage_plan, payment_past_due_at FROM orgs WHERE id = ?1",
+ "SELECT is_halted, autumn_concurrency_override, usage_plan, payment_past_due_at, trial_started_at FROM orgs WHERE id = ?1",
)
.bind(orgID)
.first<{
@@ -663,8 +722,15 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
autumn_concurrency_override: number | null;
usage_plan: UsagePlan;
payment_past_due_at: number | null;
+ trial_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 halted = reason !== null;
const maxConcurrent = prevRow?.autumn_concurrency_override ?? projectedMaxConcurrent;
// Compare-and-set the plan first: the webhook, checkout-return and the cron can
@@ -686,16 +752,17 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
}
await env.OPENCOMPUTER_DB.prepare(
- `UPDATE orgs SET is_halted = ?1, halted_at = ?2, max_concurrent_sandboxes = ?3, usage_plan = ?4, updated_at = ?5 WHERE id = ?6`,
+ `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`,
)
- .bind(halted ? 1 : 0, halted ? nowSec : null, maxConcurrent, usagePlan, nowSec, orgID)
+ .bind(halted ? 1 : 0, halted ? nowSec : null, maxConcurrent, usagePlan, nowSec, orgID, reason)
.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, wasHalted, usagePlan };
+ return { customer: cust, creditsRemaining, maxConcurrent, halted, haltReason: reason, wasHalted, usagePlan };
}
// autumnSetProviderInternal flips D1 orgs.billing_provider for one org (the
@@ -751,6 +818,8 @@ export async function projectOrg(env: AutumnEnv, orgID: string): Promise<void> {
// webhook both call projectOrg, so this is the straggler safety net (a halted
// org with a leftover running box gets re-dispatched on the next sight).
if (!r.wasHalted || (await hasRunningSandboxes(env, orgID))) {
+ // The cells stamp and resume by "credits_exhausted" whatever the cause; the
+ // reason a surface shows lives in orgs.halt_reason.
await dispatchToCells(env, orgID, "/admin/halt-org", { org_id: orgID, reason: "credits_exhausted" });
}
}
diff --git a/cloudflare-workers/api-edge/src/billing_clock.test.ts b/cloudflare-workers/api-edge/src/billing_clock.test.ts
new file mode 100644
index 00000000..4ee304eb
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/billing_clock.test.ts
@@ -0,0 +1,26 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import * as autumn from "./autumn_webhook";
+import { runBillingClock } from "./billing_clock";
+
+describe("billing clock", () => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it("re-projects orgs whose trial or payment grace has run out", async () => {
+ const project = vi.spyOn(autumn, "projectOrg").mockResolvedValue();
+ let bound: unknown[] = [];
+ const env = {
+ OPENCOMPUTER_DB: {
+ prepare: () => ({
+ bind: (...args: unknown[]) => {
+ bound = args;
+ return { all: async () => ({ results: [{ id: "org_a" }, { id: "org_b" }] }) };
+ },
+ }),
+ },
+ } as unknown as autumn.AutumnEnv;
+
+ expect(await runBillingClock(env, 1_800_000_000_000)).toBe(2);
+ expect(bound).toEqual([1_800_000_000 - 7 * 86_400, 1_800_000_000 - 3 * 86_400, 50]);
+ 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.ts
new file mode 100644
index 00000000..9df17588
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/billing_clock.ts
@@ -0,0 +1,34 @@
+// Billing clock (serverless-agents-ws 086, step 4): the halts that come from
+// 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, so each org is projected about
+// once per transition.
+
+import { type AutumnEnv, PAYMENT_GRACE_DAYS, TRIAL_DAYS, projectOrg } from "./autumn_webhook";
+
+const DAY_SEC = 86_400;
+// Bounds one tick; the next tick continues.
+const MAX_ORGS_PER_RUN = 50;
+
+export async function runBillingClock(env: AutumnEnv, nowMs: number): Promise<number> {
+ const nowSec = Math.floor(nowMs / 1000);
+ const due = await env.OPENCOMPUTER_DB.prepare(
+ `SELECT id FROM orgs
+ WHERE billing_provider = 'autumn' AND is_halted = 0
+ AND ((usage_plan = 'base' AND trial_started_at <= ?1) OR payment_past_due_at <= ?2)
+ LIMIT ?3`,
+ )
+ .bind(nowSec - TRIAL_DAYS * DAY_SEC, nowSec - PAYMENT_GRACE_DAYS * DAY_SEC, MAX_ORGS_PER_RUN)
+ .all<{ id: string }>();
+ let projected = 0;
+ for (const { id } of due.results ?? []) {
+ try {
+ await projectOrg(env, id);
+ projected++;
+ } catch (err) {
+ console.error(`billing-clock: project ${id} failed`, err);
+ }
+ }
+ return projected;
+}
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index b7c1b765..dba6b6f8 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -71,6 +71,7 @@ import {
createAutumnCustomer,
} from "./autumn_webhook";
import { runAutumnMeter } from "./autumn_meter";
+import { runBillingClock } from "./billing_clock";
import { disableManagedBilling, enableManagedBilling } from "./model_billing";
import { runModelMeter, syncModelCaps } from "./model_meter";
import {
@@ -6325,6 +6326,9 @@ export default {
ctx.waitUntil(
runAutumnMeter(env, Date.now()).catch((err) => console.error("autumn-meter: run failed", err)),
);
+ ctx.waitUntil(
+ runBillingClock(env, Date.now()).catch((err) => console.error("billing-clock: run failed", err)),
+ );
if (env.OPENROUTER_PROVISIONING_KEY) {
ctx.waitUntil(
runModelMeter(env, Date.now()).catch((err) => console.error("model-meter: run failed", err)),
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.ts
index 8875fdc4..2f94deb3 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
@@ -16,6 +16,7 @@ class FakeStatement {
private readonly usagePlan: string,
private readonly plan: string,
private readonly billingProvider: string,
+ private readonly haltReason: string | null,
) {}
bind(orgID: string): this {
@@ -33,6 +34,7 @@ class FakeStatement {
usage_plan: this.usagePlan,
plan: this.plan,
billing_provider: this.billingProvider,
+ halt_reason: this.haltReason,
}) as T | null;
}
}
@@ -43,14 +45,15 @@ function env(
usagePlan = "base",
plan = "free",
billingProvider = "autumn",
+ haltReason: string | null = null,
) {
return {
OPENCOMPUTER_DB: {
prepare(sql: string) {
expect(sql).toBe(
- "SELECT is_halted, halted_at, usage_plan, plan, billing_provider FROM orgs WHERE id = ?1",
+ "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);
+ return new FakeStatement(halted, haltedAt, usagePlan, plan, billingProvider, haltReason);
},
} as unknown as D1Database,
};
@@ -147,6 +150,21 @@ describe("managed-agent credit admission", () => {
},
);
+ it.each(["credits_empty", "payment", "trial_days"])(
+ "stops a paid org halted on the work-minute rule (%s)",
+ async (reason) => {
+ await expect(
+ getManagedAgentBillingAdmission(env(1, 1_789_707_077, "pro", "free", "autumn", reason), "org_test"),
+ ).resolves.toMatchObject({ allowed: false, isHalted: true, paid: true, modelAccess: 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"),
+ ).resolves.toMatchObject({ allowed: true, modelAccess: "fallback" });
+ });
+
it("keeps an existing Pro org eligible before its usage-plan projection", async () => {
await expect(
getManagedAgentBillingAdmission(
diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts
index 4b011c2f..e3128fc2 100644
--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts
+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts
@@ -1,4 +1,4 @@
-import { isPaidUsagePlan } from "./autumn_webhook";
+import { haltKeepsFallback, isPaidUsagePlan } from "./autumn_webhook";
import { insufficientCreditsResponse } from "./billing_onramp";
export interface ManagedAgentCreditGateEnv {
@@ -11,6 +11,7 @@ interface ManagedAgentCreditRow {
halted_at: number | null;
usage_plan: string | null;
plan: string | null;
+ halt_reason: string | null;
}
// "full": the org's selected models. "fallback": credits are exhausted on a
@@ -77,7 +78,7 @@ 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 FROM orgs WHERE id = ?1",
+ "SELECT is_halted, halted_at, usage_plan, plan, billing_provider, halt_reason FROM orgs WHERE id = ?1",
)
.bind(orgID)
.first<ManagedAgentCreditRow>();
@@ -92,14 +93,18 @@ export async function getManagedAgentBillingAdmission(
// 'base' default. Keep their established Pro entitlement effective until an
// Autumn projection refines usage_plan to the authoritative pro/max value.
const paid = isPaidUsagePlan(row?.usage_plan) || row?.plan === "pro";
- const allowed = !isHalted || paid;
+ // Only a credit-rule halt keeps a paid org on the fallback model; a
+ // work-minute halt (trial over, allowance and credits used, payment, lapsed)
+ // stops it like any other org.
+ const fallback = paid && haltKeepsFallback(row?.halt_reason);
+ const allowed = !isHalted || fallback;
return {
allowed,
isHalted,
haltedAt: isHalted ? row?.halted_at ?? null : null,
reason: allowed ? null : "insufficient_credits",
paid,
- modelAccess: !isHalted ? "full" : paid ? "fallback" : null,
+ modelAccess: !isHalted ? "full" : fallback ? "fallback" : null,
usagePlan: normalizedUsagePlan(row),
};
}
diff --git a/cloudflare-workers/api-edge/src/model_billing.ts b/cloudflare-workers/api-edge/src/model_billing.ts
index e62b284b..d83fd5ea 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, isPaidUsagePlan } from "./autumn_webhook";
+import { type AutumnApiEnv, getAutumnCustomer, haltKeepsFallback, isPaidUsagePlan } from "./autumn_webhook";
import {
createOrKey,
deleteOrKey,
@@ -68,6 +68,7 @@ interface OrgBillingRow {
model_markup_bps: number;
is_halted?: number;
usage_plan?: string | null;
+ halt_reason?: string | null;
}
// sessions-api owner id for an OC org. MUST match sessions-api's ownerIdForOrg
@@ -98,7 +99,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, usage_plan FROM orgs WHERE id = ?1",
+ "SELECT id, billing_provider, model_billing_status, model_markup_bps, is_halted, usage_plan, halt_reason FROM orgs WHERE id = ?1",
)
.bind(orgId)
.first<OrgBillingRow>();
@@ -326,9 +327,9 @@ export async function enableManagedBilling(
// 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.
- // 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)) {
+ // Paid orgs halted on the credit rule stay admitted: the managed-agent gateway
+ // moves their model calls to the open-weight fallback. A work-minute halt stops.
+ if (org.is_halted === 1 && !(isPaidUsagePlan(org.usage_plan) && haltKeepsFallback(org.halt_reason))) {
const stillHalted =
org.billing_provider === "autumn" && selfHeal ? await selfHeal(orgId) : true;
if (stillHalted) return { status: "halted" };