An open-source, faster Devin alternative
TypeScript
CLI and API paywall by halt reason; CLI footer warnings
Mohamed Habib via Computer61eafb8ded81
diff --git a/cli/README.md b/cli/README.mdindex 6ab9be11..dae74f9c 100644--- a/cli/README.md+++ b/cli/README.md@@ -185,3 +185,11 @@ When credits are exhausted every command fails with HTTP `402` and a structured`insufficient_credits` error whose `hint` and `details.upgradeUrl` point atcheckout for Pro ($200/mo). Agents driving the CLI should stop, relay that link tothe user, and resume once billing is sorted rather than retrying.++On work-minute pricing (the trial and the $20 / $200 plans) the `402` also+carries `details.haltReason` (`trial_days`, `trial_minutes`, `trial_tokens`,+`credits_empty`, `payment`, `lapsed`); its `hint` says why in words to relay to+the user, and the link is the Billing page. Before a stop, `run` prints a+warning line instead of the balance, and the `--json` `credits` block carries+`billingWarning` (`trial_minutes`, `trial_days`, `trial_tokens`,+`allowance_80`, `credits_low`, `payment_failed`).diff --git a/cli/src/api.test.ts b/cli/src/api.test.tsindex fe5773d6..94558588 100644--- a/cli/src/api.test.ts+++ b/cli/src/api.test.ts@@ -353,6 +353,33 @@ test("memory precondition failures surface the API's code", async (context) => {);});+test("a 402 carries the halt reason and prefers the action link", async (context) => {+ context.mock.method(globalThis, "fetch", async () =>+ Response.json(+ {+ error: {+ code: "insufficient_credits",+ message: "Your 7-day trial has ended.",+ haltReason: "trial_days",+ actionUrl: "https://app.opencomputer.dev/billing",+ upgradeUrl: "https://app.opencomputer.dev/billing?plan=max",+ },+ },+ { status: 402 },+ ),+ );+ const client = new OpenComputerClient({+ apiUrl: "https://app.opencomputer.dev",+ apiKey: "test",+ });+ await assert.rejects(client.credits(), (error: unknown) =>+ error instanceof APIError &&+ error.status === 402 &&+ error.haltReason === "trial_days" &&+ error.actionUrl === "https://app.opencomputer.dev/billing",+ );+});+test("managed GitHub App requests use project-scoped status and connect routes", async (context) => {const requests: Request[] = [];context.mock.method(diff --git a/cli/src/api.ts b/cli/src/api.tsindex a4b0a384..b58aa33f 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -440,6 +440,8 @@ export class APIError extends Error {readonly code?: string,/** Where the human can resolve the error (e.g. billing checkout). */readonly actionUrl?: string,+ /** Why billing halted the org (the edge's orgs.halt_reason), on a 402. */+ readonly haltReason?: string,) {super(message);}@@ -469,6 +471,12 @@ export interface CreditsStatus {lowCreditThresholdCents: number;isLow: boolean;isHalted: boolean;+ /** Why billing halted the org (orgs.halt_reason); absent from older APIs. */+ haltReason?: string | null;+ /** The warning to show before a halt (orgs.billing_warning). */+ billingWarning?: string | null;+ /** On work-minute pricing (the trial and the $20 / $200 plans). */+ workMinutes?: boolean;billingUrl: string;upgradeUrl: string;plans: Array<{ id: "pro" | "max"; name?: string; priceUsd: number; creditsUsd: number }>;@@ -575,7 +583,8 @@ export class OpenComputerClient {errorMessage(body, response.status),response.status,errorCode(body),- errorField(body, "upgradeUrl") ?? errorField(body, "actionUrl"),+ errorField(body, "actionUrl") ?? errorField(body, "upgradeUrl"),+ errorField(body, "haltReason"),);}return response;diff --git a/cli/src/billing.test.ts b/cli/src/billing.test.tsindex 24daf1d2..02406dd4 100644--- a/cli/src/billing.test.ts+++ b/cli/src/billing.test.ts@@ -56,6 +56,7 @@ test("json credits block carries a machine-readable warning", () => {plan: "base",remainingCents: 340,upgradeUrl: base.upgradeUrl,+ billingUrl: base.billingUrl,});assert.equal(creditsSummary({ ...base, isLow: true })?.warning, "low_credits");assert.equal(@@ -65,6 +66,56 @@ test("json credits block carries a machine-readable warning", () => {assert.equal(creditsSummary(null), undefined);});+const trial: CreditsStatus = { ...base, workMinutes: true, haltReason: null, billingWarning: null };++test("run footer names the work-minute halt and links Billing with no plan forced", () => {+ const cases: Record<string, RegExp> = {+ trial_days: /Your 7-day trial has ended\. Pick a plan to keep going/,+ trial_minutes: /trial's 600 work minutes/,+ trial_tokens: /trial's model credit/,+ credits_empty: /Buy credits or upgrade/,+ payment: /Update your payment method/,+ lapsed: /Your plan has ended/,+ };+ for (const [haltReason, copy] of Object.entries(cases)) {+ for (const usagePlan of ["base", "pro", "max"] as const) {+ const footer = creditsFooter({ ...trial, usagePlan, isHalted: true, haltReason });+ assert.match(footer, copy);+ assert.match(footer, /: https:\/\/app\.opencomputer\.dev\/billing\n$/);+ assert.doesNotMatch(footer, /plan=|top.?up/i);+ }+ }+ // The credit rule keeps its copy.+ assert.match(+ creditsFooter({ ...base, isHalted: true, haltReason: "credits_exhausted" }),+ /You've used your free credits/,+ );+});++test("run footer shows the pre-halt warning, and is otherwise quiet on work minutes", () => {+ assert.equal(creditsFooter(trial), "");+ assert.equal(creditsFooter({ ...trial, isLow: true }), "");+ assert.match(+ creditsFooter({ ...trial, billingWarning: "trial_minutes" }),+ /almost out of work minutes\. Pick a plan to keep going: https:\/\/app\.opencomputer\.dev\/billing/,+ );+ assert.match(creditsFooter({ ...trial, usagePlan: "pro", billingWarning: "allowance_80" }), /80% of this month's work minutes/);+ assert.match(creditsFooter({ ...trial, usagePlan: "max", billingWarning: "credits_low" }), /credits are running low/);+ assert.match(creditsFooter({ ...trial, usagePlan: "pro", billingWarning: "payment_failed" }), /payment didn't go through/);+ // An unknown warning from a newer API is ignored.+ assert.equal(creditsFooter({ ...trial, billingWarning: "something_new" }), "");++ const summary = creditsSummary({ ...trial, isLow: true, billingWarning: "trial_days" });+ assert.equal(summary?.warning, undefined);+ assert.equal(summary?.billingWarning, "trial_days");+ assert.equal(+ creditsSummary({ ...trial, isHalted: true, haltReason: "trial_minutes" })?.haltReason,+ "trial_minutes",+ );+ assert.match(formatBilling({ ...trial, billingWarning: "trial_days" }), /trial ends soon/);+ assert.match(formatBilling({ ...trial, isHalted: true, haltReason: "lapsed" }), /^Your plan has ended\./);+});+test("billing table lists only Pro ($200) unless the org is on legacy Pro", () => {const free = formatBilling(base);assert.match(free, /Plan\s+Free/);diff --git a/cli/src/billing.ts b/cli/src/billing.tsindex 996621bc..5b6e739f 100644--- a/cli/src/billing.ts+++ b/cli/src/billing.ts@@ -24,9 +24,48 @@ const PLAN_NAME: Record<"pro" | "max", string> = {max: "Pro",};+// Work-minute pricing (serverless-agents-ws 086): why an org is halted, by the+// edge's halt_reason, and what to do, always on the Billing page. The credit+// rule ("credits_exhausted", or an older API with no reason) keeps the copy+// below.+const PAYWALL: Record<string, { why: string; action: string }> = {+ trial_days: { why: "Your 7-day trial has ended.", action: "Pick a plan to keep going" },+ trial_minutes: { why: "You've used your trial's 600 work minutes.", action: "Pick a plan to keep going" },+ trial_tokens: { why: "You've used your trial's model credit.", action: "Pick a plan to keep going" },+ credits_empty: {+ why: "You've used this month's work minutes and your credits.",+ action: "Buy credits or upgrade to keep going",+ },+ payment: { why: "Your last payment didn't go through.", action: "Update your payment method to keep going" },+ lapsed: { why: "Your plan has ended.", action: "Pick a plan to keep going" },+};++/** The paywall for a work-minute halt reason; undefined for the credit rule. */+export function paywallFor(reason: string | null | undefined): { why: string; action: string } | undefined {+ return reason && Object.hasOwn(PAYWALL, reason) ? PAYWALL[reason] : undefined;+}++// Before the stop: orgs.billing_warning, by reason.+const WARNINGS: Record<string, string> = {+ trial_minutes: "Your trial is almost out of work minutes. Pick a plan to keep going",+ trial_days: "Your 7-day trial ends soon. Pick a plan to keep going",+ trial_tokens: "Your trial's model credit is almost used. Pick a plan to keep going",+ allowance_80: "You've used 80% of this month's work minutes. Buy credits or upgrade so work doesn't stop",+ credits_low: "Your credits are running low. Buy credits so work doesn't stop",+ payment_failed: "Your last payment didn't go through. Update your payment method so work doesn't stop",+};++export function billingWarningText(reason: string | null | undefined): string | undefined {+ return reason && Object.hasOwn(WARNINGS, reason) ? WARNINGS[reason] : undefined;+}+/** Human-readable summary for `opencomputer billing`. */export function formatBilling(status: CreditsStatus): string {+ const paywall = status.isHalted ? paywallFor(status.haltReason) : undefined;+ const warning = status.isHalted ? undefined : billingWarningText(status.billingWarning);const lines = [+ ...(paywall ? [`${paywall.why} ${paywall.action}: ${status.billingUrl}`, ""] : []),+ ...(warning ? [`${warning}: ${status.billingUrl}`, ""] : []),`Plan ${PLAN_LABEL[status.usagePlan]}`,`Credits left ${formatCreditCount(status.creditsRemainingCents)}${status.isHalted ? " (exhausted — sessions paused)" : status.isLow ? " (running low)" : ""@@ -52,6 +91,15 @@ export function formatBilling(status: CreditsStatus): string {*/export function creditsFooter(status: CreditsStatus | null): string {if (!status) return "";+ if (status.isHalted) {+ const paywall = paywallFor(status.haltReason);+ if (paywall) return `\n${paywall.why} ${paywall.action}: ${status.billingUrl}\n`;+ } else {+ const warning = billingWarningText(status.billingWarning);+ if (warning) return `\n${warning}: ${status.billingUrl}\n`;+ }+ // Work-minute orgs hear from billing only through the warnings above.+ if (status.workMinutes) return "";const left = formatCreditCount(status.creditsRemainingCents);const onPro = status.usagePlan === UPGRADE_PLAN;if (status.isHalted) {@@ -78,7 +126,12 @@ export interface CreditsSummary {plan: CreditsStatus["usagePlan"];remainingCents: number;warning?: "insufficient_credits" | "low_credits";+ /** Why the org is halted, on work-minute pricing (orgs.halt_reason). */+ haltReason?: string;+ /** The pre-halt warning (trial_minutes, allowance_80, credits_low, ...). */+ billingWarning?: string;upgradeUrl: string;+ billingUrl: string;}export function creditsSummary(@@ -87,14 +140,17 @@ export function creditsSummary(if (!status) return undefined;const warning = status.isHalted? "insufficient_credits"- : status.isLow+ : status.isLow && !status.workMinutes? "low_credits": undefined;return {plan: status.usagePlan,remainingCents: status.creditsRemainingCents,...(warning ? { warning } : {}),+ ...(status.isHalted && status.haltReason ? { haltReason: status.haltReason } : {}),+ ...(!status.isHalted && status.billingWarning ? { billingWarning: status.billingWarning } : {}),upgradeUrl: status.upgradeUrl,+ billingUrl: status.billingUrl,};}diff --git a/cli/src/errors.test.ts b/cli/src/errors.test.tsindex 5a609b7d..ec77550b 100644--- a/cli/src/errors.test.ts+++ b/cli/src/errors.test.ts@@ -65,3 +65,35 @@ test("out-of-credits responses tell the agent to stop and surface the upgrade liassert.match(pro.hint, /renew/);assert.doesNotMatch(pro.hint, /upgrade/i);});++test("a work-minute 402 says why and links Billing", () => {+ const trial = structuredError(+ new APIError(+ "Your 7-day trial has ended.",+ 402,+ "insufficient_credits",+ "https://app.opencomputer.dev/billing",+ "trial_days",+ ),+ );+ assert.equal(trial.code, "insufficient_credits");+ assert.match(trial.hint, /^Your 7-day trial has ended\. Pick a plan to keep going at https:\/\/app\.opencomputer\.dev\/billing,/);+ assert.match(trial.hint, /Do not retry/);+ assert.deepEqual(trial.details, {+ status: 402,+ apiCode: "insufficient_credits",+ haltReason: "trial_days",+ upgradeUrl: "https://app.opencomputer.dev/billing",+ });++ const payment = structuredError(+ new APIError("Payment failed.", 402, "insufficient_credits", undefined, "payment"),+ );+ assert.match(payment.hint, /Update your payment method to keep going on the Billing page/);++ // The credit rule keeps its copy.+ const exhausted = structuredError(+ new APIError("Out.", 402, "insufficient_credits", "https://app.opencomputer.dev/billing?plan=max", "credits_exhausted"),+ );+ assert.match(exhausted.hint, /upgrade to Pro/);+});diff --git a/cli/src/errors.ts b/cli/src/errors.tsindex c084500c..f1910c29 100644--- a/cli/src/errors.ts+++ b/cli/src/errors.ts@@ -1,4 +1,5 @@import { APIError } from "./api.js";+import { paywallFor } from "./billing.js";export interface StructuredCLIError {code: string;@@ -31,6 +32,24 @@ export function structuredError(error: unknown): StructuredCLIError {if (error instanceof APIError) {if (error.code === "insufficient_credits" || error.status === 402) {const url = error.actionUrl;+ const paywall = paywallFor(error.haltReason);+ if (paywall) {+ return {+ code: "insufficient_credits",+ message,+ // Worded for the user, so an agent can relay it as is.+ hint:+ `${paywall.why} ${paywall.action}` ++ (url ? ` at ${url}` : " on the Billing page") ++ ", then run the command again. Do not retry until then.",+ details: {+ status: error.status,+ apiCode: error.code ?? "insufficient_credits",+ haltReason: error.haltReason,+ ...(url ? { upgradeUrl: url } : {}),+ },+ };+ }// A $200 Pro org that has used its monthly credits gets the plain billing// page (no `?plan=`): there is nothing to upgrade to, so don't say so.const renewOnly = url !== undefined && !url.includes("?plan=");diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.tsindex 36d933d5..f9183079 100644--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts@@ -46,7 +46,7 @@ const DEFAULT_BASE_URL = "https://api.useautumn.com/v1";const CREDITS_FEATURE_ID = "credits";// Work-minute plans (trial, pro and max v2; serverless-agents-ws 086) carry a// work_minutes balance; credit-based plans do not.-const WORK_MINUTES_FEATURE_ID = "work_minutes";+export const WORK_MINUTES_FEATURE_ID = "work_minutes";const AGENT_RUNTIME_FEATURE_ID = "agent_runtime_2gb_1vcpu";// blue sends two overlapping measures of a managed session: one segment per// settled turn (any runtime), and the microVM's lease, which also counts idlediff --git a/cloudflare-workers/api-edge/src/billing_events.ts b/cloudflare-workers/api-edge/src/billing_events.tsindex db4c04c6..82311357 100644--- a/cloudflare-workers/api-edge/src/billing_events.ts+++ b/cloudflare-workers/api-edge/src/billing_events.ts@@ -21,6 +21,8 @@ export type BillingEventName =| "billing.trial_started"| "billing.work_minutes_recorded"| "billing.first_work_minute"+ | "billing.warning_shown"+ | "billing.paywall_shown"| "billing.checkout_opened"| "billing.plan_changed"| "billing.payment_failed"diff --git a/cloudflare-workers/api-edge/src/billing_onramp.test.ts b/cloudflare-workers/api-edge/src/billing_onramp.test.tsindex c15a86ec..88174e27 100644--- a/cloudflare-workers/api-edge/src/billing_onramp.test.ts+++ b/cloudflare-workers/api-edge/src/billing_onramp.test.ts@@ -1,7 +1,9 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import {activeUsagePlan,billingLinks,+ billingWarningOf,+ emitPaywallShown,FREE_CREDITS_PAYWALL,insufficientCreditsLegacyResponse,insufficientCreditsResponse,@@ -14,6 +16,8 @@ import type { AutumnCustomer } from "./autumn_webhook";const req = new Request("https://app.opencomputer.dev/api/v3/sessions");describe("billing_onramp", () => {+ afterEach(() => vi.restoreAllMocks());+it("low-credit threshold is 30% of the plan grant", () => {expect(lowCreditThresholdCents("base")).toBe(300);expect(lowCreditThresholdCents("pro")).toBe(6_000);@@ -54,7 +58,7 @@ describe("billing_onramp", () => {it("never offers top-ups or the retired $20 plan in any 402", async () => {for (const plan of [undefined, "base", "pro", "max"] as const) {- const body = (await insufficientCreditsResponse(req, plan).json()) as {+ const body = (await insufficientCreditsResponse(req, { plan }).json()) as {error: Record<string, string>;};expect(body.error.message).not.toMatch(/top.?up|\$20\b|plan=pro/i);@@ -63,11 +67,11 @@ describe("billing_onramp", () => {});it("points a legacy $20 Pro org at the $200 Pro, and does not upsell a $200 Pro org", async () => {- const legacy = (await insufficientCreditsResponse(req, "pro").json()) as {+ const legacy = (await insufficientCreditsResponse(req, { plan: "pro" }).json()) as {error: Record<string, string>;};expect(legacy.error.message).toContain("upgrade to Pro ($200/mo) at https://app.opencomputer.dev/billing?plan=max");- const max = (await insufficientCreditsResponse(req, "max").json()) as {+ const max = (await insufficientCreditsResponse(req, { plan: "max" }).json()) as {error: Record<string, string>;};expect(max.error.message).not.toMatch(/upgrade/i);@@ -98,4 +102,77 @@ describe("billing_onramp", () => {expect(body.upgradeUrl).toBe("https://app.opencomputer.dev/billing?plan=max");expect(body.creditsRemainingCents).toBe(0);});++ it("402 names the work-minute halt reason, links Billing with no plan forced", async () => {+ const cases = {+ trial_days: "Your 7-day trial has ended. Ask the user to pick a plan",+ trial_minutes: "You've used your trial's 600 work minutes.",+ trial_tokens: "You've used your trial's model credit.",+ credits_empty: "buy credits or upgrade",+ payment: "update their payment method",+ lapsed: "Your plan has ended.",+ };+ for (const [haltReason, copy] of Object.entries(cases)) {+ for (const plan of ["base", "pro", "max"] as const) {+ const body = (await insufficientCreditsResponse(req, { plan, haltReason }).json()) as {+ error: Record<string, string>;+ };+ expect(body.error.code).toBe("insufficient_credits");+ expect(body.error.haltReason).toBe(haltReason);+ expect(body.error.message).toContain(copy);+ expect(body.error.message).toMatch(/at https:\/\/app\.opencomputer\.dev\/billing[ ;]/);+ expect(body.error.message).toMatch(/do not retry/);+ expect(body.error.message).not.toMatch(/top.?up|plan=/i);+ expect(body.error.actionUrl).toBe("https://app.opencomputer.dev/billing");+ // Old clients still find the upgrade link where they looked for it.+ expect(body.error.upgradeUrl).toBe("https://app.opencomputer.dev/billing?plan=max");+ }+ }+ });++ it("keeps the credit-rule copy for credits_exhausted and an unknown reason", async () => {+ const exhausted = (await insufficientCreditsResponse(req, { haltReason: "credits_exhausted" }).json()) as {+ error: Record<string, unknown>;+ };+ expect(exhausted.error.haltReason).toBe("credits_exhausted");+ expect(exhausted.error.message).toContain("You've used your free credits.");+ const unknown = (await insufficientCreditsResponse(req, { haltReason: "gold" }).json()) as {+ error: Record<string, unknown>;+ };+ expect(unknown.error.haltReason).toBeNull();+ expect(unknown.error.actionUrl).toBe("https://app.opencomputer.dev/billing?plan=max");+ });++ it("legacy sandbox 402 carries the halt reason flat", async () => {+ const body = (await insufficientCreditsLegacyResponse(req, {}, { haltReason: "payment" }).json()) as Record<+ string,+ unknown+ >;+ expect(body.haltReason).toBe("payment");+ expect(body.error).toContain("update their payment method at https://app.opencomputer.dev/billing");+ expect(body.actionUrl).toBe("https://app.opencomputer.dev/billing");+ });++ it("counts billing.paywall_shown once per org and reason within the hour", async () => {+ const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("{}"));+ const env = { POSTHOG_PROJECT_TOKEN: "phc_test" };+ await emitPaywallShown(env, "org_dedupe", "trial_minutes");+ await emitPaywallShown(env, "org_dedupe", "trial_minutes");+ expect(fetchMock).toHaveBeenCalledTimes(1);+ expect(JSON.parse(String(fetchMock.mock.calls[0]![1]?.body))).toMatchObject({+ event: "billing.paywall_shown",+ properties: { reason: "trial_minutes", surface: "api", org_id: "org_dedupe" },+ });+ await emitPaywallShown(env, "org_dedupe", "trial_days");+ await emitPaywallShown(env, "org_dedupe_2", null);+ expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(JSON.parse(String(fetchMock.mock.calls[2]![1]?.body)).properties.reason).toBe("credits_exhausted");+ });++ it("reads only known billing warnings", () => {+ expect(billingWarningOf("allowance_80")).toBe("allowance_80");+ expect(billingWarningOf("payment_failed")).toBe("payment_failed");+ expect(billingWarningOf("soon")).toBeNull();+ expect(billingWarningOf(null)).toBeNull();+ });});diff --git a/cloudflare-workers/api-edge/src/billing_onramp.ts b/cloudflare-workers/api-edge/src/billing_onramp.tsindex a0363fa4..19cd6eef 100644--- a/cloudflare-workers/api-edge/src/billing_onramp.ts+++ b/cloudflare-workers/api-edge/src/billing_onramp.ts@@ -7,9 +7,13 @@import {activeUsagePlan,type AutumnSyncEnv,+ type HaltReason,syncAutumnToD1,type UsagePlan,+ WORK_MINUTES_FEATURE_ID,} from "./autumn_webhook";+import { emitBillingEvent, type BillingEventsEnv } from "./billing_events";+import { coloGet, coloPut } from "./colo_cache";export { activeUsagePlan, type UsagePlan };@@ -57,11 +61,41 @@ export function billingLinks(request: Request): BillingLinks {};}-// Agent-facing out-of-credits message. Free (and unknown/legacy) orgs get the+// Agent-facing paywall by orgs.halt_reason (serverless-agents-ws 086). Every+// work-minute halt points at the Billing page with no plan forced: the trial+// and lapsed orgs pick a plan there, a paid org buys credits or upgrades, and a+// failed payment updates its card. Wording follows blue's Slack paywall+// (src/computer/admission.ts outOfCreditsNotice).+const WORK_MINUTE_PAYWALL: Record<Exclude<HaltReason, "credits_exhausted">, (billingUrl: string) => string> = {+ trial_days: (u) => `Your 7-day trial has ended. Ask the user to pick a plan at ${u} to keep going`,+ trial_minutes: (u) => `You've used your trial's 600 work minutes. Ask the user to pick a plan at ${u} to keep going`,+ trial_tokens: (u) => `You've used your trial's model credit. Ask the user to pick a plan at ${u} to keep going`,+ credits_empty: (u) =>+ `You've used this month's work minutes and your credits. Ask the user to buy credits or upgrade at ${u} to keep going`,+ payment: (u) => `The last payment didn't go through. Ask the user to update their payment method at ${u}`,+ lapsed: (u) => `Your plan has ended. Ask the user to pick a plan at ${u} to keep going`,+};++/** A known work-minute halt reason, or null (the credit rule, or unknown). */+export function workMinuteHaltReason(reason: string | null | undefined): Exclude<HaltReason, "credits_exhausted"> | null {+ return reason && Object.hasOwn(WORK_MINUTE_PAYWALL, reason)+ ? (reason as Exclude<HaltReason, "credits_exhausted">)+ : null;+}++// Out-of-credits message for an org halted on the credit rule (no halt_reason+// yet, or "credits_exhausted"). Free (and unknown/legacy) orgs get the// paywall; a legacy $20 Pro org is pointed at the same Pro upgrade; a $200 Pro-// org keeps its current halt (a later step moves it to GLM) but is never-// offered a top-up.-export function insufficientCreditsMessage(links: BillingLinks, plan?: UsagePlan | null): string {+// org keeps its current halt but is never offered a top-up.+export function insufficientCreditsMessage(+ links: BillingLinks,+ plan?: UsagePlan | null,+ reason?: string | null,+): string {+ const minuteReason = workMinuteHaltReason(reason);+ if (minuteReason) {+ return `${WORK_MINUTE_PAYWALL[minuteReason](links.billingUrl)}; do not retry until they have.`;+ }if (plan === "max") {return ("You've used this month's Pro credits. They renew at the start of the next billing period; " +@@ -80,21 +114,34 @@ export function insufficientCreditsMessage(links: BillingLinks, plan?: UsagePlan);}+/** What a 402 needs to know about the org: its plan and why it is halted. */+export interface PaywallContext {+ plan?: UsagePlan | null;+ // orgs.halt_reason. null/undefined: halted before halt_reason existed, or a+ // legacy (non-Autumn) org; the 402 keeps the credit-rule copy.+ haltReason?: string | null;+}+// The 402 body every credit gate returns. `error` is an object (code/message)// for the managed-agents API; sandbox routes historically used a string-// `error`, so callers there spread `legacyStringError()` instead.-export function insufficientCreditsError(request: Request, plan?: UsagePlan | null) {+// `error`, so callers there spread `legacyStringError()` instead. `haltReason`+// is additive: clients that know it render the paywall by reason; older ones+// keep reading `code`, `message` and `actionUrl`.+export function insufficientCreditsError(request: Request, paywall: PaywallContext = {}) {const links = billingLinks(request);+ const { plan, haltReason } = paywall;+ const minuteReason = workMinuteHaltReason(haltReason);return {code: "insufficient_credits" as const,- message: insufficientCreditsMessage(links, plan),- actionUrl: plan === "max" ? links.billingUrl : links.upgradeUrl,+ message: insufficientCreditsMessage(links, plan, haltReason),+ haltReason: minuteReason ?? (haltReason === "credits_exhausted" ? haltReason : null),+ actionUrl: minuteReason || plan === "max" ? links.billingUrl : links.upgradeUrl,...links,};}-export function insufficientCreditsResponse(request: Request, plan?: UsagePlan | null): Response {- return Response.json({ error: insufficientCreditsError(request, plan) }, { status: 402 });+export function insufficientCreditsResponse(request: Request, paywall: PaywallContext = {}): Response {+ return Response.json({ error: insufficientCreditsError(request, paywall) }, { status: 402 });}// Sandbox-route flavour: keeps `error` a string (the `oc` Go CLI prints it@@ -102,13 +149,14 @@ export function insufficientCreditsResponse(request: Request, plan?: UsagePlan |export function insufficientCreditsLegacyResponse(request: Request,extra: Record<string, unknown> = {},- plan?: UsagePlan | null,+ paywall: PaywallContext = {},): Response {- const e = insufficientCreditsError(request, plan);+ const e = insufficientCreditsError(request, paywall);return Response.json({error: e.message,code: e.code,+ haltReason: e.haltReason,actionUrl: e.actionUrl,billingUrl: e.billingUrl,upgradeUrl: e.upgradeUrl,@@ -118,12 +166,68 @@ export function insufficientCreditsLegacyResponse();}+// Reads the org's plan and halt reason for a 402. After a self-heal the D1+// projection is fresh, so this reflects the reason Autumn just confirmed.+export async function paywallContext(db: D1Database, orgID: string): Promise<PaywallContext> {+ try {+ const row = await db+ .prepare("SELECT usage_plan, halt_reason FROM orgs WHERE id = ?1")+ .bind(orgID)+ .first<{ usage_plan: string | null; halt_reason: string | null }>();+ return { plan: usagePlanOf(row?.usage_plan), haltReason: row?.halt_reason ?? null };+ } catch {+ return { plan: "base", haltReason: null };+ }+}++export function usagePlanOf(value: string | null | undefined): UsagePlan {+ return value === "pro" || value === "max" ? value : "base";+}++// Funnel events for a paywall or warning a client may hit in a loop (a retry+// loop, or the CLI after every run) are counted at most once per org and+// reason per EVENT_DEDUPE_SEC: per isolate in memory, and across a colo's+// isolates through the Cache API. Best-effort: an isolate in another colo may+// count the same one again.+const EVENT_DEDUPE_SEC = 3_600;+const eventSeen = new Map<string, number>();++export async function onceAnHour(key: string, emit: () => Promise<void>, nowMs = Date.now()): Promise<void> {+ const until = eventSeen.get(key);+ if (until !== undefined && until > nowMs) return;+ eventSeen.set(key, nowMs + EVENT_DEDUPE_SEC * 1000);+ if (eventSeen.size > 10_000) {+ for (const [k, v] of eventSeen) if (v <= nowMs) eventSeen.delete(k);+ }+ if (await coloGet<boolean>("billing-event", key)) return;+ await coloPut("billing-event", key, true, EVENT_DEDUPE_SEC);+ await emit();+}++// billing.paywall_shown {reason, surface: "api"}, for every 402 a halt produces.+export function emitPaywallShown(+ env: BillingEventsEnv,+ orgID: string,+ haltReason: string | null | undefined,+): Promise<void> {+ const reason = haltReason || "credits_exhausted";+ return onceAnHour(`paywall:${orgID}:${reason}`, () =>+ emitBillingEvent(env, "billing.paywall_shown", { orgId: orgID, data: { reason, surface: "api" } }),+ );+}+export interface CreditsStatus {usagePlan: UsagePlan;creditsRemainingCents: number;lowCreditThresholdCents: number;isLow: boolean;isHalted: boolean;+ // Additive (086). Why the org is halted (orgs.halt_reason), null when not.+ haltReason: string | null;+ // The pre-halt warning to show (orgs.billing_warning), null when none.+ billingWarning: BillingWarning | null;+ // On work-minute pricing (trial, or the v2 plans); false: the credit rule.+ workMinutes: boolean;billingUrl: string;upgradeUrl: string;// Plans shown to this org. `name` is the display name (`max` is "Pro").@@ -131,6 +235,21 @@ export interface CreditsStatus {plans: Array<{ id: "pro" | "max"; name: string; priceUsd: number; creditsUsd: number }>;}+// orgs.billing_warning: set by the billing clock before an org halts.+export const BILLING_WARNINGS = [+ "trial_minutes",+ "trial_days",+ "trial_tokens",+ "allowance_80",+ "credits_low",+ "payment_failed",+] as const;+export type BillingWarning = (typeof BILLING_WARNINGS)[number];++export function billingWarningOf(value: unknown): BillingWarning | null {+ return (BILLING_WARNINGS as readonly unknown[]).includes(value) ? (value as BillingWarning) : null;+}+const PRO_OFFER = { id: "max", name: PLAN_DISPLAY_NAMES.max, priceUsd: UPGRADE_PLAN_PRICE_USD, creditsUsd: 2_000 } as const;const LEGACY_PRO_OFFER = { id: "pro", name: PLAN_DISPLAY_NAMES.pro, priceUsd: 20, creditsUsd: 200 } as const;@@ -144,11 +263,14 @@ export function usagePlanOffers(current: UsagePlan): CreditsStatus["plans"] {// GET /api/billing/credits — API-key authenticated credit status for the CLI.// Re-syncs Autumn → D1 like the dashboard endpoint so a fresh upgrade clears a// halt on the next CLI call too. Legacy (Stripe) orgs have no Autumn customer-// and get a 404 — clients treat that as "no credit meter".+// and get a 404 — clients treat that as "no credit meter". The CLI is the only+// caller and shows a warning it returns, so billing.warning_shown is counted+// here (deduped like the paywall event).export async function handleCreditsStatus(req: Request,env: AutumnSyncEnv & { AUTUMN_SECRET_KEY?: string },caller: { orgID: string },+ waitUntil: (p: Promise<unknown>) => void = () => {},): Promise<Response> {if (!env.AUTUMN_SECRET_KEY) {return Response.json({ error: "autumn billing not configured" }, { status: 503 });@@ -165,14 +287,51 @@ export async function handleCreditsStatus(const creditsRemainingCents = Math.max(0, Math.round(r.creditsRemaining * 100));const threshold = lowCreditThresholdCents(usagePlan);const links = billingLinks(req);+ const org = await billingOrgState(env.OPENCOMPUTER_DB, caller.orgID);+ const billingWarning = r.halted ? null : org.billingWarning;const status: CreditsStatus = {usagePlan,creditsRemainingCents,lowCreditThresholdCents: threshold,isLow: !r.halted && creditsRemainingCents <= threshold,isHalted: r.halted,+ haltReason: r.haltReason,+ billingWarning,+ workMinutes: r.customer.balances?.[WORK_MINUTES_FEATURE_ID] !== undefined || org.trialStartedAt != null,...links,plans: usagePlanOffers(usagePlan),};+ if (billingWarning) {+ waitUntil(+ onceAnHour(`warning:${caller.orgID}:${billingWarning}`, () =>+ emitBillingEvent(env, "billing.warning_shown", {+ orgId: caller.orgID,+ data: { reason: billingWarning, surface: "cli" },+ }),+ ),+ );+ }return Response.json(status);}++// billing_warning arrives in migration 0015; until it is applied the column+// read fails and the status carries no warning.+async function billingOrgState(+ db: D1Database,+ orgID: string,+): Promise<{ billingWarning: BillingWarning | null; trialStartedAt: number | null }> {+ try {+ const row = await db+ .prepare("SELECT billing_warning, trial_started_at FROM orgs WHERE id = ?1")+ .bind(orgID)+ .first<{ billing_warning: string | null; trial_started_at: number | null }>();+ return { billingWarning: billingWarningOf(row?.billing_warning), trialStartedAt: row?.trial_started_at ?? null };+ } catch {+ const row = await db+ .prepare("SELECT trial_started_at FROM orgs WHERE id = ?1")+ .bind(orgID)+ .first<{ trial_started_at: number | null }>()+ .catch(() => null);+ return { billingWarning: null, trialStartedAt: row?.trial_started_at ?? null };+ }+}diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 5b8040a3..e042a375 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -42,6 +42,7 @@ import {} from "./managed_agents";import { computerEnabledFor } from "./computer";import { enableManagedBilling } from "./model_billing";+import { paywallContext } from "./billing_onramp";import { insufficientManagedAgentCredits } from "./managed_agent_credit_gate";export interface DashboardEnv extends BillingEventsEnv {@@ -1085,7 +1086,8 @@ export async function handleDashboard(async (id) => (await syncAutumnToD1(env, id).catch(() => null))?.halted ?? true,);if (billing.status === "halted") {- return insufficientManagedAgentCredits(req);+ // No paywall_shown here: the web app counts its own (surface "web").+ return insufficientManagedAgentCredits(req, await paywallContext(env.OPENCOMPUTER_DB, caller.orgID));}if (billing.status !== "active") {return json({ error: "managed model billing is unavailable" }, 503);diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex dba6b6f8..77c70f94 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -76,9 +76,15 @@ import { disableManagedBilling, enableManagedBilling } from "./model_billing";import { runModelMeter, syncModelCaps } from "./model_meter";import {enforceManagedAgentCreditGate,- insufficientManagedAgentCredits,} from "./managed_agent_credit_gate";-import { handleCreditsStatus, insufficientCreditsLegacyResponse, type UsagePlan } from "./billing_onramp";+import {+ emitPaywallShown,+ handleCreditsStatus,+ insufficientCreditsLegacyResponse,+ insufficientCreditsResponse,+ paywallContext,+ usagePlanOf,+} from "./billing_onramp";export { ManagedAgentBillingService } from "./managed_agent_billing_service";import { runRetentionSweep } from "./retention";import * as secretStores from "./secret_stores";@@ -1476,22 +1482,23 @@ async function refreshOrgPolicy(env: Env, orgID: string): Promise<OrgPolicy | nureturn policy;}-// The usage plan behind an out-of-credits 402, so its message fits the org:-// free gets the paywall, legacy $20 Pro the upgrade to Pro, $200 Pro no upsell.-// Only read on the (rare) halted path; any failure falls back to the paywall.-function usagePlanOf(value: string | null | undefined): UsagePlan {- return value === "pro" || value === "max" ? value : "base";-}--async function haltedUsagePlan(env: Env, orgID: string): Promise<UsagePlan> {- try {- const row = await env.OPENCOMPUTER_DB.prepare("SELECT usage_plan FROM orgs WHERE id = ?1")- .bind(orgID)- .first<{ usage_plan: string | null }>();- return usagePlanOf(row?.usage_plan);- } catch {- return "base";- }+// The 402 for a halted Autumn org, so its message fits the org: a work-minute+// halt names its reason and links Billing; on the credit rule, free gets the+// paywall, legacy $20 Pro the upgrade to Pro, $200 Pro no upsell. Counted as+// billing.paywall_shown. Only read on the (rare) halted path, after the+// self-heal re-projected the row; any failure falls back to the paywall.+async function haltedOrgResponse(+ req: Request,+ env: Env,+ ctx: ExecutionContext,+ orgID: string,+ structured = false,+): Promise<Response> {+ const paywall = await paywallContext(env.OPENCOMPUTER_DB, orgID);+ ctx.waitUntil(emitPaywallShown(env, orgID, paywall.haltReason));+ return structured+ ? insufficientCreditsResponse(req, paywall)+ : insufficientCreditsLegacyResponse(req, {}, paywall);}// enforceCreatePolicy applies every org-level gate for creating or forking a@@ -1510,6 +1517,7 @@ async function haltedUsagePlan(env: Env, orgID: string): Promise<UsagePlan> {async function enforceCreatePolicy(req: Request,env: Env,+ ctx: ExecutionContext,orgID: string,org: OrgPolicy,sizes: { cpuCount: number; memoryMB: number; diskMB: number },@@ -1524,7 +1532,7 @@ async function enforceCreatePolicy(// pay per GB-second); only the per-org max_disk_mb cap applies.if (org.billing_provider === "autumn") {if (org.is_halted === 1 && (await selfHealHalt(env, orgID))) {- return insufficientCreditsLegacyResponse(req, {}, await haltedUsagePlan(env, orgID));+ return haltedOrgResponse(req, env, ctx, orgID);}} else if (plan === "free") {// Legacy free-tier gate. is_halted is the D1 fast path; otherwise ask the@@ -2271,7 +2279,7 @@ async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop// them concurrently — under a burst these were two serial D1 round-trips// (~90ms) sitting on the create hot path.const [gate, cell] = await Promise.all([- enforceCreatePolicy(req, env, caller.orgID, org, {+ enforceCreatePolicy(req, env, ctx, caller.orgID, org, {cpuCount: bodyCpuCount,memoryMB: bodyMemoryMB,diskMB: bodyDiskMB,@@ -3491,7 +3499,9 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, calconst stillHalted =haltRow.billing_provider === "autumn" ? await selfHealHalt(env, caller.orgID) : true;if (stillHalted) {- return insufficientCreditsLegacyResponse(req, {}, usagePlanOf(haltRow.usage_plan));+ return haltRow.billing_provider === "autumn"+ ? haltedOrgResponse(req, env, ctx, caller.orgID)+ : insufficientCreditsLegacyResponse(req, {}, { plan: usagePlanOf(haltRow.usage_plan) });}}}@@ -6004,7 +6014,7 @@ export default {selfHealHalt(env, id),);if (billing.status === "halted") {- return insufficientManagedAgentCredits(req);+ return haltedOrgResponse(req, env, ctx, caller.orgID, true);}if (billing.status !== "active") {return json({ error: "managed model billing is unavailable" }, 503);@@ -6022,6 +6032,7 @@ export default {env,caller.orgID,(id) => selfHealHalt(env, id),+ (p) => ctx.waitUntil(p),);if (creditError) return creditError;}@@ -6083,7 +6094,7 @@ export default {// previously ungated at the edge and leaned on a cell-side concurrent// check that read stale cell PG and could only ever count one cell's// sandboxes — wrong once an org spans cells. Enforce from D1 here.- const fcGate = await enforceCreatePolicy(req, env, caller.orgID, org, { cpuCount: fcCpu, memoryMB: fcMem, diskMB: fcDisk }, fcActive);+ const fcGate = await enforceCreatePolicy(req, env, ctx, caller.orgID, org, { cpuCount: fcCpu, memoryMB: fcMem, diskMB: fcDisk }, fcActive);if (fcGate) return fcGate;const plan = org.plan === "pro" ? "pro" : "free";// org.runtime, deliberately NOT the SDK-version routing createSandbox@@ -6240,7 +6251,7 @@ export default {if (path === "/api/billing/credits" && req.method === "GET") {const caller = await authenticate(req, env, ctx);if (!caller) return json({ error: "missing or invalid API key" }, 401);- return handleCreditsStatus(req, env, caller);+ return handleCreditsStatus(req, env, caller, (p) => ctx.waitUntil(p));}if (path === "/api/whoami" && req.method === "GET") {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 a6ca19c8..e79bad9f 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@@ -285,6 +285,30 @@ describe("managed-agent credit admission", () => {expect(response?.status).toBe(402);});+ it("names the work-minute halt in the 402 and counts the paywall once", async () => {+ const request = new Request(+ "https://mo-oc-dev.com/api/managed-agents/sessions/session_1/turns",+ { method: "POST" },+ );+ const waits: Promise<unknown>[] = [];+ const response = await enforceManagedAgentCreditGate(+ request,+ env(1, 1_789_707_077, "base", "free", "autumn", "trial_days"),+ "org_test",+ undefined,+ (p) => waits.push(p),+ );+ expect(response?.status).toBe(402);+ const body = (await response!.json()) as { error: Record<string, unknown> };+ expect(body.error).toMatchObject({+ code: "insufficient_credits",+ haltReason: "trial_days",+ actionUrl: "https://mo-oc-dev.com/billing",+ });+ expect(body.error.message).toContain("7-day trial has ended");+ expect(waits).toHaveLength(1);+ });+it("returns a typed, actionable 402", async () => {const response = insufficientManagedAgentCredits(new Request("https://mo-oc-dev.com/api/managed-agents/sessions"),diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.tsindex 6aa47ec7..41de0ea2 100644--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts@@ -1,7 +1,8 @@import { haltKeepsFallback, isPaidUsagePlan } from "./autumn_webhook";-import { insufficientCreditsResponse } from "./billing_onramp";+import type { BillingEventsEnv } from "./billing_events";+import { emitPaywallShown, insufficientCreditsResponse, type PaywallContext } from "./billing_onramp";-export interface ManagedAgentCreditGateEnv {+export interface ManagedAgentCreditGateEnv extends BillingEventsEnv {OPENCOMPUTER_DB: D1Database;}@@ -134,8 +135,8 @@ export async function getManagedAgentBillingAdmission(};}-export function insufficientManagedAgentCredits(request: Request): Response {- return insufficientCreditsResponse(request);+export function insufficientManagedAgentCredits(request: Request, paywall: PaywallContext = {}): Response {+ return insufficientCreditsResponse(request, paywall);}export async function enforceManagedAgentCreditGate(@@ -143,14 +144,19 @@ export async function enforceManagedAgentCreditGate(env: ManagedAgentCreditGateEnv,orgID: string,selfHeal?: ManagedAgentSelfHeal,+ waitUntil: (p: Promise<unknown>) => void = () => {},): Promise<Response | null> {if (!isManagedAgentBillableRequest(request.method, new URL(request.url).pathname)) {return null;}try {- return (await getManagedAgentBillingAdmission(env, orgID, selfHeal)).allowed- ? null- : insufficientManagedAgentCredits(request);+ const admission = await getManagedAgentBillingAdmission(env, orgID, selfHeal);+ if (admission.allowed) return null;+ waitUntil(emitPaywallShown(env, orgID, admission.haltReason));+ return insufficientManagedAgentCredits(request, {+ plan: admission.usagePlan,+ haltReason: admission.haltReason,+ });} 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/docs/agents/api.mdx b/docs/agents/api.mdxindex 533e27f9..66861a5e 100644--- a/docs/agents/api.mdx+++ b/docs/agents/api.mdx@@ -36,7 +36,7 @@ what to branch on; the `message` is short and safe to show.| --- | --- || `400` | Invalid body, query or header || `401` | Missing or invalid API key |-| `402` | `insufficient_credits`: prepaid credits are exhausted |+| `402` | `insufficient_credits`: the organization is out of minutes or credits; `error.haltReason` says why and `error.actionUrl` links Billing || `403` | The key may not perform this operation || `404` | The route or the target does not exist || `409` | The request conflicts with current state, for example a reused `Idempotency-Key` |diff --git a/skills/opencomputer/SKILL.md b/skills/opencomputer/SKILL.mdindex dbba9323..52b571a6 100644--- a/skills/opencomputer/SKILL.md+++ b/skills/opencomputer/SKILL.md@@ -63,8 +63,13 @@ the same way**. Do **not** retry or work around it. Instead:credits renew next billing period.3. Resume once they confirm they've upgraded.-A response that carries `warning: "low_credits"` (or a "credits left (running-low)" line) still succeeded — finish the task, then mention the balance and+When the error carries a `haltReason` (the trial ended, the month's minutes+and credits are used, a payment failed, or the plan ended), relay the `hint`+as is: it says why and links the Billing page, where the user picks a plan,+buys credits or updates their card.++A response that carries `warning: "low_credits"` or a `billingWarning` (or a+warning line after `run`) still succeeded — finish the task, then mention the balance andthe upgrade link to the user so they can act before sessions pause.## CLI Reference