An open-source, faster Devin alternative
TypeScript
feat(billing): payment on-ramps for dashboard + CLI behind billing_onramp_v2 (#811)
devin-ai-integration[bot]5664544398f4
diff --git a/cli/README.md b/cli/README.mdindex 5a84b6a2..dd22b5c5 100644--- a/cli/README.md+++ b/cli/README.md@@ -142,3 +142,20 @@ Use `opencomputer sessions tail <session-id> --json` for durable NDJSON sessionevents. All commands accept `--json`; mutations accept`--idempotency-key <stable-retry-key>`. Run`opencomputer doctor --json` for the sub-second local pre-deploy scan.++## Billing and credits++New organizations start on prepaid credits. `opencomputer run` prints the+remaining balance after each run (a `credits` block under `--json`, with+`warning: "low_credits"` when the balance is running low), and+`opencomputer billing` shows the plan table:++```bash+opencomputer billing+opencomputer upgrade pro # prints the checkout link for Pro ($20/mo, $200 credits)+```++When credits are exhausted every command fails with HTTP `402` and a structured+`insufficient_credits` error whose `hint` and `details.upgradeUrl` point at+checkout. Agents driving the CLI should stop, relay that link to the user, and+resume once billing is sorted rather than retrying.diff --git a/cli/src/api.ts b/cli/src/api.tsindex d186fd26..29a1d7ad 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -396,20 +396,40 @@ export class APIError extends Error {readonly status: number,/** The typed reason from `{ error: { code } }` when the API sent one. */readonly code?: string,+ /** Where the human can resolve the error (e.g. billing checkout). */+ readonly actionUrl?: string,) {super(message);}}+// The API sends typed fields either nested under `error: { code, ... }`+// (managed-agents routes) or flat beside a string `error` (sandbox routes).+function errorField(body: unknown, field: string): string | undefined {+ if (!body || typeof body !== "object") return undefined;+ const record = body as Record<string, unknown>;+ const error = record.error;+ if (error && typeof error === "object") {+ const value = (error as Record<string, unknown>)[field];+ if (typeof value === "string") return value;+ }+ const flat = record[field];+ return typeof flat === "string" ? flat : undefined;+}+function errorCode(body: unknown): string | undefined {- if (body && typeof body === "object") {- const error = (body as Record<string, unknown>).error;- if (error && typeof error === "object") {- const code = (error as Record<string, unknown>).code;- if (typeof code === "string") return code;- }- }- return undefined;+ return errorField(body, "code");+}++export interface CreditsStatus {+ usagePlan: "base" | "pro" | "max";+ creditsRemainingCents: number;+ lowCreditThresholdCents: number;+ isLow: boolean;+ isHalted: boolean;+ billingUrl: string;+ upgradeUrl: string;+ plans: Array<{ id: "pro" | "max"; priceUsd: number; creditsUsd: number }>;}function errorMessage(body: unknown, status: number): string {@@ -493,6 +513,7 @@ export class OpenComputerClient {errorMessage(body, response.status),response.status,errorCode(body),+ errorField(body, "upgradeUrl") ?? errorField(body, "actionUrl"),);}return response;@@ -509,6 +530,18 @@ export class OpenComputerClient {return body as T;}+ /** Prepaid credit status; `null` for orgs without a credit meter (legacy billing). */+ async credits(): Promise<CreditsStatus | null> {+ try {+ return await this.request<CreditsStatus>("/api/billing/credits");+ } catch (error) {+ if (error instanceof APIError && (error.status === 404 || error.status === 503)) {+ return null;+ }+ throw error;+ }+ }+startLogin() {return this.request<{device_code: string;diff --git a/cli/src/billing.test.ts b/cli/src/billing.test.tsnew file mode 100644index 00000000..8642f5ac--- /dev/null+++ b/cli/src/billing.test.ts@@ -0,0 +1,71 @@+import assert from "node:assert/strict";+import test from "node:test";++import type { CreditsStatus } from "./api.js";+import {+ creditsFooter,+ creditsSummary,+ formatBilling,+ upgradeUrlFor,+} from "./billing.js";++const base: CreditsStatus = {+ usagePlan: "base",+ creditsRemainingCents: 340,+ lowCreditThresholdCents: 150,+ isLow: false,+ isHalted: false,+ billingUrl: "https://app.opencomputer.dev/billing",+ upgradeUrl: "https://app.opencomputer.dev/billing?plan=pro",+ plans: [+ { id: "pro", priceUsd: 20, creditsUsd: 200 },+ { id: "max", priceUsd: 200, creditsUsd: 2000 },+ ],+};++test("run footer nudges free orgs, warns when low, and is silent for healthy paid plans", () => {+ assert.match(creditsFooter(base), /\$3\.40 free credits left/);+ assert.match(creditsFooter(base), /plan=pro/);+ assert.match(+ creditsFooter({ ...base, creditsRemainingCents: 90, isLow: true }),+ /running low/,+ );+ assert.match(+ creditsFooter({ ...base, creditsRemainingCents: 0, isHalted: true }),+ /exhausted/,+ );+ assert.equal(+ creditsFooter({ ...base, usagePlan: "pro", creditsRemainingCents: 15_000 }),+ "",+ );+ assert.equal(creditsFooter(null), "");+});++test("json credits block carries a machine-readable warning", () => {+ assert.deepEqual(creditsSummary(base), {+ plan: "base",+ remainingCents: 340,+ upgradeUrl: base.upgradeUrl,+ });+ assert.equal(creditsSummary({ ...base, isLow: true })?.warning, "low_credits");+ assert.equal(+ creditsSummary({ ...base, isHalted: true })?.warning,+ "insufficient_credits",+ );+ assert.equal(creditsSummary(null), undefined);+});++test("billing table lists plans and marks the current one", () => {+ const text = formatBilling({ ...base, usagePlan: "pro" });+ assert.match(text, /Pro \(\$20\/mo\)/);+ assert.match(text, /pro\s+\$20\/mo.*\(current\)/);+ assert.match(text, /max\s+\$200\/mo — \$2,000/);+});++test("upgrade url falls back to the API origin when no credit status is available", () => {+ assert.equal(+ upgradeUrlFor(null, "https://app.opencomputer.dev/", "max"),+ "https://app.opencomputer.dev/billing?plan=max",+ );+ assert.equal(upgradeUrlFor(base, "https://x", "pro"), base.upgradeUrl);+});diff --git a/cli/src/billing.ts b/cli/src/billing.tsnew file mode 100644index 00000000..f47321fa--- /dev/null+++ b/cli/src/billing.ts@@ -0,0 +1,98 @@+import type { CreditsStatus, OpenComputerClient } from "./api.js";++export function formatUsd(cents: number): string {+ return `$${(cents / 100).toFixed(2)}`;+}++const PLAN_LABEL: Record<CreditsStatus["usagePlan"], string> = {+ base: "Usage (prepaid)",+ pro: "Pro ($20/mo)",+ max: "Max ($200/mo)",+};++/** Human-readable summary for `opencomputer billing`. */+export function formatBilling(status: CreditsStatus): string {+ const lines = [+ `Plan ${PLAN_LABEL[status.usagePlan]}`,+ `Credits left ${formatUsd(status.creditsRemainingCents)}${+ status.isHalted ? " (exhausted — sessions paused)" : status.isLow ? " (running low)" : ""+ }`,+ "",+ "Plans:",+ ...status.plans.map(+ (p) =>+ ` ${p.id.padEnd(5)} $${p.priceUsd}/mo — $${p.creditsUsd.toLocaleString("en-US")} in credits every month` ++ (p.id === status.usagePlan ? " (current)" : ""),+ ),+ "",+ `Upgrade: ${status.upgradeUrl}`,+ `Top up: ${status.billingUrl}`,+ ];+ return `${lines.join("\n")}\n`;+}++/**+ * One-line footer after a `run`. Empty when the org is on a paid plan with a+ * healthy balance so paying customers aren't nagged.+ */+export function creditsFooter(status: CreditsStatus | null): string {+ if (!status) return "";+ const left = formatUsd(status.creditsRemainingCents);+ if (status.isHalted) {+ return `\nCredits exhausted — upgrade to keep running: ${status.upgradeUrl}\n`;+ }+ if (status.isLow) {+ return (+ `\n${left} credits left (running low). Pro is $20/mo for $200 in credits: ${status.upgradeUrl}\n`+ );+ }+ if (status.usagePlan === "base") {+ return `\n${left} free credits left · upgrade to Pro ($20/mo, $200 credits): ${status.upgradeUrl}\n`;+ }+ return "";+}++/** Machine-readable `credits` block appended to `--json` results. */+export interface CreditsSummary {+ plan: CreditsStatus["usagePlan"];+ remainingCents: number;+ warning?: "insufficient_credits" | "low_credits";+ upgradeUrl: string;+}++export function creditsSummary(+ status: CreditsStatus | null,+): CreditsSummary | undefined {+ if (!status) return undefined;+ const warning = status.isHalted+ ? "insufficient_credits"+ : status.isLow+ ? "low_credits"+ : undefined;+ return {+ plan: status.usagePlan,+ remainingCents: status.creditsRemainingCents,+ ...(warning ? { warning } : {}),+ upgradeUrl: status.upgradeUrl,+ };+}++/** Best-effort fetch: billing must never fail an otherwise successful command. */+export async function fetchCredits(+ client: OpenComputerClient,+): Promise<CreditsStatus | null> {+ try {+ return await client.credits();+ } catch {+ return null;+ }+}++export function upgradeUrlFor(+ status: CreditsStatus | null,+ apiUrl: string,+ plan: "pro" | "max",+): string {+ const base = status?.billingUrl ?? `${apiUrl.replace(/\/$/, "")}/billing`;+ return `${base}?plan=${plan}`;+}diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 0825c72f..d0faff03 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -11,6 +11,13 @@ import {type MemoryDocumentMeta,} from "./api.js";import { login, logout } from "./auth.js";+import {+ creditsFooter,+ creditsSummary,+ fetchCredits,+ formatBilling,+ upgradeUrlFor,+} from "./billing.js";import { codexLogin } from "./codex-oauth.js";import { resolveConfig } from "./config.js";import {@@ -1183,6 +1190,39 @@ export async function runCommand(return;}+ if (command === "billing" || command === "credits") {+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const status = await client.credits();+ if (globals.json) printJSON(status);+ else if (!status) {+ process.stdout.write(+ `This organization is not on prepaid credits. Manage billing at ${config.apiUrl}/billing\n`,+ );+ } else process.stdout.write(formatBilling(status));+ return;+ }++ if (command === "upgrade") {+ const plan = args.shift() ?? "pro";+ if (plan !== "pro" && plan !== "max") {+ throw new Error("Usage: opencomputer upgrade [pro|max]");+ }+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const status = await fetchCredits(client);+ const url = upgradeUrlFor(status, config.apiUrl, plan);+ if (globals.json) {+ printJSON({ plan, url, credits: creditsSummary(status) });+ } else {+ const offer = status?.plans.find((p) => p.id === plan);+ process.stdout.write(+ `Open this link to upgrade to ${plan === "pro" ? "Pro" : "Max"}` ++ (offer ? ` ($${offer.priceUsd}/mo, $${offer.creditsUsd.toLocaleString("en-US")} in credits every month)` : "") ++ `:\n\n ${url}\n\nCheckout completes in the browser; the CLI resumes working as soon as the plan is active.\n`,+ );+ }+ return;+ }+if (command === "init") {const spa = flag(args, "--spa");const agentOnly = flag(args, "--agent-only");@@ -1362,7 +1402,17 @@ export async function runCommand(globals.verbose === true,globals.idempotencyKey,);- if (globals.json) printJSON(result);+ const credits = await fetchCredits(client);+ if (globals.json) {+ const summary = creditsSummary(credits);+ printJSON(+ summary+ ? { ...(result as Record<string, unknown>), credits: summary }+ : result,+ );+ } else {+ process.stderr.write(creditsFooter(credits));+ }return;}diff --git a/cli/src/errors.test.ts b/cli/src/errors.test.tsindex e92dc9d3..f30675e4 100644--- a/cli/src/errors.test.ts+++ b/cli/src/errors.test.ts@@ -33,3 +33,26 @@ test("memory precondition and size failures map to their own codes", () => {"precondition_required",);});++test("out-of-credits responses tell the agent to stop and surface the upgrade link", () => {+ const halted = structuredError(+ new APIError(+ "Out of prepaid credits.",+ 402,+ "insufficient_credits",+ "https://app.opencomputer.dev/billing?plan=pro",+ ),+ );+ assert.equal(halted.code, "insufficient_credits");+ assert.match(halted.hint, /do not retry/);+ assert.match(halted.hint, /https:\/\/app\.opencomputer\.dev\/billing\?plan=pro/);+ assert.deepEqual(halted.details, {+ status: 402,+ apiCode: "insufficient_credits",+ upgradeUrl: "https://app.opencomputer.dev/billing?plan=pro",+ });++ const bare = structuredError(new APIError("Payment required.", 402));+ assert.equal(bare.code, "insufficient_credits");+ assert.match(bare.hint, /opencomputer upgrade pro/);+});diff --git a/cli/src/errors.ts b/cli/src/errors.tsindex 8afcff89..768ea69c 100644--- a/cli/src/errors.ts+++ b/cli/src/errors.ts@@ -29,6 +29,22 @@ export function structuredError(error: unknown): StructuredCLIError {}const message = error instanceof Error ? error.message : String(error);if (error instanceof APIError) {+ if (error.code === "insufficient_credits" || error.status === 402) {+ const url = error.actionUrl;+ return {+ code: "insufficient_credits",+ message,+ hint:+ "Out of prepaid credits \u2014 do not retry. Tell the user to upgrade to Pro ($20/mo, $200 credits)" ++ (url ? ` at ${url}` : " with `opencomputer upgrade pro`") ++ ", then run the command again.",+ details: {+ status: error.status,+ apiCode: error.code ?? "insufficient_credits",+ ...(url ? { upgradeUrl: url } : {}),+ },+ };+ }const code =error.status === 401 || error.status === 403? "authentication_required"diff --git a/cli/src/index.ts b/cli/src/index.tsindex aedb95c4..89c47a75 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -47,6 +47,8 @@ Usage:opencomputer login [--no-browser] [--force]opencomputer logout [--local]opencomputer whoami+ opencomputer billing+ opencomputer upgrade [pro|max]opencomputer agentsopencomputer init <directory|.>opencomputer template validate [directory] [--repository-url <url>] [--app-url <url>]diff --git a/cloudflare-workers/api-edge/src/billing_onramp.test.ts b/cloudflare-workers/api-edge/src/billing_onramp.test.tsnew file mode 100644index 00000000..f82b137c--- /dev/null+++ b/cloudflare-workers/api-edge/src/billing_onramp.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";+import {+ activeUsagePlan,+ billingLinks,+ insufficientCreditsLegacyResponse,+ insufficientCreditsResponse,+ lowCreditThresholdCents,+} from "./billing_onramp";+import type { AutumnCustomer } from "./autumn_webhook";++const req = new Request("https://app.opencomputer.dev/api/v3/sessions");++describe("billing_onramp", () => {+ it("low-credit threshold is 30% of the plan grant", () => {+ expect(lowCreditThresholdCents("base")).toBe(150);+ expect(lowCreditThresholdCents("pro")).toBe(6_000);+ expect(lowCreditThresholdCents("max")).toBe(60_000);+ });++ it("picks the highest active usage plan", () => {+ const customer = {+ subscriptions: [+ { plan_id: "pro", status: "active" },+ { plan_id: "max", status: "canceled" },+ ],+ } as unknown as AutumnCustomer;+ expect(activeUsagePlan(customer)).toBe("pro");+ expect(activeUsagePlan({} as AutumnCustomer)).toBe("base");+ });++ it("builds deep links off the request origin", () => {+ expect(billingLinks(req, "max")).toEqual({+ billingUrl: "https://app.opencomputer.dev/billing",+ upgradeUrl: "https://app.opencomputer.dev/billing?plan=max",+ });+ });++ it("402 body carries a stable code, do-not-retry hint and upgrade url", async () => {+ const res = insufficientCreditsResponse(req);+ expect(res.status).toBe(402);+ const body = (await res.json()) as { error: Record<string, string> };+ expect(body.error.code).toBe("insufficient_credits");+ expect(body.error.message).toMatch(/do not retry/);+ expect(body.error.upgradeUrl).toBe("https://app.opencomputer.dev/billing?plan=pro");+ expect(body.error.actionUrl).toBe("https://app.opencomputer.dev/billing");+ });++ it("legacy sandbox 402 keeps `error` a string and adds structured fields", async () => {+ const res = insufficientCreditsLegacyResponse(req, { creditsRemainingCents: 0 });+ const body = (await res.json()) as Record<string, unknown>;+ expect(typeof body.error).toBe("string");+ expect(body.code).toBe("insufficient_credits");+ expect(body.upgradeUrl).toBe("https://app.opencomputer.dev/billing?plan=pro");+ expect(body.creditsRemainingCents).toBe(0);+ });+});diff --git a/cloudflare-workers/api-edge/src/billing_onramp.ts b/cloudflare-workers/api-edge/src/billing_onramp.tsnew file mode 100644index 00000000..b3d1ec0a--- /dev/null+++ b/cloudflare-workers/api-edge/src/billing_onramp.ts@@ -0,0 +1,146 @@+// Billing on-ramp surface shared by the CLI / SDK error paths and the+// `GET /api/billing/credits` status endpoint. Everything an agent-driven client+// (Claude / Codex running the CLI) needs to steer the human to payment lives+// here: a stable error code, a checkout deep link, and a low-balance signal+// that fires before the hard stop.++import {+ type AutumnCustomer,+ type AutumnSyncEnv,+ syncAutumnToD1,+} from "./autumn_webhook";++export type UsagePlan = "base" | "pro" | "max";++// Mirror of PLAN_CREDIT_GRANTS in autumn_webhook.ts (dollars). The base grant is+// the signup credit; low-balance fires at LOW_CREDIT_FRACTION of the plan grant.+const PLAN_GRANT_CENTS: Record<UsagePlan, number> = {+ base: 500,+ pro: 20_000,+ max: 200_000,+};+const LOW_CREDIT_FRACTION = 0.3;++const USAGE_PLAN_RANK: Record<string, number> = { base: 0, pro: 1, max: 2 };++export function lowCreditThresholdCents(plan: UsagePlan): number {+ return Math.round(PLAN_GRANT_CENTS[plan] * LOW_CREDIT_FRACTION);+}++export function activeUsagePlan(customer: AutumnCustomer): UsagePlan {+ let plan: UsagePlan = "base";+ let rank = 0;+ for (const s of customer.subscriptions ?? []) {+ if (s.status && s.status !== "active") continue;+ const r = USAGE_PLAN_RANK[s.plan_id];+ if (r !== undefined && r >= rank) {+ rank = r;+ plan = s.plan_id as UsagePlan;+ }+ }+ return plan;+}++export interface BillingLinks {+ billingUrl: string;+ upgradeUrl: string;+}++export function billingLinks(request: Request, plan: "pro" | "max" = "pro"): BillingLinks {+ const origin = new URL(request.url).origin;+ return {+ billingUrl: `${origin}/billing`,+ upgradeUrl: `${origin}/billing?plan=${plan}`,+ };+}++// 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) {+ const links = billingLinks(request);+ return {+ code: "insufficient_credits" as const,+ message:+ `Out of prepaid credits. Ask the user to upgrade to Pro ($20/mo, $200 credits) at ${links.upgradeUrl} ` ++ `or top up at ${links.billingUrl}; do not retry until they have.`,+ actionUrl: links.billingUrl,+ ...links,+ };+}++export function insufficientCreditsResponse(request: Request): Response {+ return Response.json({ error: insufficientCreditsError(request) }, { status: 402 });+}++// Sandbox-route flavour: keeps `error` a string (the `oc` Go CLI prints it+// verbatim) while adding the structured fields alongside for newer clients.+export function insufficientCreditsLegacyResponse(+ request: Request,+ extra: Record<string, unknown> = {},+): Response {+ const e = insufficientCreditsError(request);+ return Response.json(+ {+ error: e.message,+ code: e.code,+ actionUrl: e.actionUrl,+ billingUrl: e.billingUrl,+ upgradeUrl: e.upgradeUrl,+ ...extra,+ },+ { status: 402 },+ );+}++export interface CreditsStatus {+ usagePlan: UsagePlan;+ creditsRemainingCents: number;+ lowCreditThresholdCents: number;+ isLow: boolean;+ isHalted: boolean;+ billingUrl: string;+ upgradeUrl: string;+ plans: Array<{ id: "pro" | "max"; priceUsd: number; creditsUsd: number }>;+}++export const USAGE_PLAN_OFFERS: CreditsStatus["plans"] = [+ { id: "pro", priceUsd: 20, creditsUsd: 200 },+ { id: "max", priceUsd: 200, creditsUsd: 2_000 },+];++// GET /api/billing/credits — API-key authenticated credit status for the CLI.+// Re-syncs Autumn → D1 like the dashboard endpoint so a fresh top-up 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".+export async function handleCreditsStatus(+ req: Request,+ env: AutumnSyncEnv & { AUTUMN_SECRET_KEY?: string },+ caller: { orgID: string },+): Promise<Response> {+ if (!env.AUTUMN_SECRET_KEY) {+ return Response.json({ error: "autumn billing not configured" }, { status: 503 });+ }+ let r;+ try {+ r = await syncAutumnToD1(env as AutumnSyncEnv, caller.orgID);+ } catch (e) {+ console.error("billing/credits sync:", e);+ return Response.json({ error: "autumn unavailable" }, { status: 502 });+ }+ if (!r) return Response.json({ error: "no autumn customer for org" }, { status: 404 });+ const usagePlan = activeUsagePlan(r.customer);+ const creditsRemainingCents = Math.max(0, Math.round(r.creditsRemaining * 100));+ const threshold = lowCreditThresholdCents(usagePlan);+ const links = billingLinks(req, usagePlan === "pro" ? "max" : "pro");+ const status: CreditsStatus = {+ usagePlan,+ creditsRemainingCents,+ lowCreditThresholdCents: threshold,+ isLow: !r.halted && creditsRemainingCents <= threshold,+ isHalted: r.halted,+ ...links,+ plans: USAGE_PLAN_OFFERS,+ };+ return Response.json(status);+}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 62ff42a4..1ae70f0e 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -76,6 +76,7 @@ import {enforceManagedAgentCreditGate,insufficientManagedAgentCredits,} from "./managed_agent_credit_gate";+import { handleCreditsStatus, insufficientCreditsLegacyResponse } from "./billing_onramp";export { ManagedAgentBillingService } from "./managed_agent_billing_service";import { runRetentionSweep } from "./retention";import * as secretStores from "./secret_stores";@@ -1390,6 +1391,7 @@ async function refreshOrgPolicy(env: Env, orgID: string): Promise<OrgPolicy | nu// (inherit the checkpoint's value or the default), so size gates skip it —// the defaults are always within limits.async function enforceCreatePolicy(+ req: Request,env: Env,orgID: string,org: OrgPolicy,@@ -1405,13 +1407,13 @@ 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 json({ error: "credits exhausted — top up to resume" }, 402);+ return insufficientCreditsLegacyResponse(req);}} else if (plan === "free") {// Legacy free-tier gate. is_halted is the D1 fast path; otherwise ask the// CreditAccount DO for an authoritative balance read. Pro orgs skip this.if (org.is_halted === 1) {- return json({ error: "free trial credits exhausted — upgrade to resume" }, 402);+ return insufficientCreditsLegacyResponse(req);}const doStub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(orgID));const checkResp = await doStub.fetch(`https://do/check?org_id=${encodeURIComponent(orgID)}`, { method: "POST" });@@ -1422,7 +1424,7 @@ async function enforceCreatePolicy(}const check = await checkResp.json<{ allowed: boolean; balance_cents: number }>();if (!check.allowed) {- return json({ error: "free trial credits exhausted — upgrade to resume", balance_cents: check.balance_cents }, 402);+ return insufficientCreditsLegacyResponse(req, { balance_cents: check.balance_cents });}}@@ -2152,7 +2154,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(env, caller.orgID, org, {+ enforceCreatePolicy(req, env, caller.orgID, org, {cpuCount: bodyCpuCount,memoryMB: bodyMemoryMB,diskMB: bodyDiskMB,@@ -3372,10 +3374,7 @@ async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, calconst stillHalted =haltRow.billing_provider === "autumn" ? await selfHealHalt(env, caller.orgID) : true;if (stillHalted) {- return json(- { error: "org is halted — upgrade to pro or wait for credit refill" },- 402,- );+ return insufficientCreditsLegacyResponse(req);}}}@@ -5585,7 +5584,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(env, caller.orgID, org, { cpuCount: fcCpu, memoryMB: fcMem, diskMB: fcDisk }, fcActive);+ const fcGate = await enforceCreatePolicy(req, env, 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@@ -5737,6 +5736,14 @@ export default {// /api/whoami — return the authenticated caller's org (+ user). Lets a// trusted service resolve an osb_ key to its OC org without custodying it// (agent-sandbox-ownership Phase 0.5: sessions-api maps osb_ → oc-org:<id>).+ // /api/billing/credits — API-key credit status for the CLI (plan, balance,+ // low-balance flag, checkout deep links). See billing_onramp.ts.+ 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);+ }+if (path === "/api/whoami" && req.method === "GET") {const caller = await authenticate(req, env, ctx);if (!caller) return json({ error: "missing or invalid API key" }, 401);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 b1699085..a16fb7b7 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@@ -94,14 +94,15 @@ describe("managed-agent credit admission", () => {new Request("https://mo-oc-dev.com/api/managed-agents/sessions"),);expect(response.status).toBe(402);- await expect(response.json()).resolves.toEqual({- error: {- code: "insufficient_credits",- message:- "Insufficient prepaid credits. Top up or enable automatic top-up: https://mo-oc-dev.com/billing",- actionUrl: "https://mo-oc-dev.com/billing",- },+ const body = (await response.json()) as { error: Record<string, unknown> };+ expect(body.error).toMatchObject({+ code: "insufficient_credits",+ actionUrl: "https://mo-oc-dev.com/billing",+ billingUrl: "https://mo-oc-dev.com/billing",+ upgradeUrl: "https://mo-oc-dev.com/billing?plan=pro",});+ expect(body.error.message).toContain("https://mo-oc-dev.com/billing?plan=pro");+ expect(body.error.message).toContain("do not retry");});it("allows active organizations and fails open when D1 is unavailable", async () => {diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.tsindex ab715dbf..c282eba2 100644--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts@@ -1,3 +1,5 @@+import { insufficientCreditsResponse } from "./billing_onramp";+export interface ManagedAgentCreditGateEnv {OPENCOMPUTER_DB: D1Database;}@@ -52,18 +54,7 @@ export async function getManagedAgentBillingAdmission(}export function insufficientManagedAgentCredits(request: Request): Response {- const billingURL = new URL("/billing", request.url).toString();- return Response.json(- {- error: {- code: "insufficient_credits",- message:- `Insufficient prepaid credits. Top up or enable automatic top-up: ${billingURL}`,- actionUrl: billingURL,- },- },- { status: 402 },- );+ return insufficientCreditsResponse(request);}export async function enforceManagedAgentCreditGate(diff --git a/skills/opencomputer/SKILL.md b/skills/opencomputer/SKILL.mdindex 3fe2fb79..faad10b7 100644--- a/skills/opencomputer/SKILL.md+++ b/skills/opencomputer/SKILL.md@@ -49,6 +49,23 @@ with an auth error (`401`, "unauthorized", "missing API key"):Do **not** ask for an API key in chat. For CI or service automation, the usermay instead configure `OPENCOMPUTER_API_KEY` themselves.+### 3. Out of credits (`402`, `insufficient_credits`)++If any command fails with HTTP `402`, `code: "insufficient_credits"`, or a+message mentioning "credits exhausted" / "out of prepaid credits", the+organization has no prepaid credits left and **every further command will fail+the same way**. Do **not** retry or work around it. Instead:++1. Stop and tell the user their OpenComputer credits are exhausted.+2. Relay the upgrade link from the error verbatim (it looks like+ `https://app.opencomputer.dev/billing?plan=pro`). Pro is $20/month for $200 in+ credits; one-off top-ups are on the same page.+3. Resume once they confirm they've upgraded or topped up.++A response that carries `warning: "low_credits"` (or a "credits left (running+low)" line) still succeeded — finish the task, then mention the balance and+the upgrade link to the user so they can act before sessions pause.+## CLI Reference### Sandbox Lifecyclediff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsxindex 9d3e869e..54b98a02 100644--- a/web/src/components/app-shell.tsx+++ b/web/src/components/app-shell.tsx@@ -1,4 +1,4 @@-import { Suspense, useState } from 'react'+import { Suspense, useEffect, useState } from 'react'import {Link,NavLink,@@ -31,7 +31,7 @@ import {type LucideIcon,} from 'lucide-react'import { useAuth } from '@/hooks/useAuth'-import { getAutumnBilling, logout } from '@/api/client'+import { logout } from '@/api/client'import { Button } from '@/components/ui/button'import {Sheet,@@ -51,6 +51,16 @@ import { ErrorBoundary } from '@/components/error-boundary'import { AgentSecurityAlertBanner } from '@/components/agent-security-alert'import { cn } from '@/lib/utils'import { managedAgentsExperimentEnabled } from '@/managed-agents/feature'+import { useCreditState } from '@/hooks/useCreditState'+import {+ BASE_GRANT_CENTS,+ PLAN_OFFERS,+ billingOnrampV2Enabled,+ formatUsd,+ trackUpsellClicked,+ trackUpsellShown,+ upgradeHref,+} from '@/lib/billing-onramp'import { getManagedProject } from '@/managed-agents/api'import {projectEnvironmentSearch,@@ -405,6 +415,8 @@ function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {))}</nav>+ <SidebarCreditMeter onNavigate={onNavigate} />+<div className="border-t p-3">{managedAgentsExperimentEnabled ? (<ManagedProfileMenu onNavigate={onNavigate} />@@ -433,33 +445,154 @@ function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {)}-// Org-wide halt notice. Prepaid (autumn) orgs that exhaust credits get halted+// Always-visible balance for prepaid orgs that haven't subscribed yet, so the+// first "you should pay" moment isn't the hard stop. Paid plans and legacy+// orgs (404 on /billing/autumn) render nothing.+function SidebarCreditMeter({ onNavigate }: { onNavigate?: () => void }) {+ const { usagePlan, creditsRemainingCents, isLow, isHalted } = useCreditState()+ const visible =+ billingOnrampV2Enabled &&+ usagePlan === 'base' &&+ creditsRemainingCents !== undefined+ useEffect(() => {+ if (visible)+ trackUpsellShown({+ surface: 'sidebar_meter',+ plan: 'pro',+ usagePlan,+ creditsRemainingCents,+ })+ // Fire once per mount; balance changes shouldn't re-count an impression.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [visible])+ if (!visible) return null+ const grant = Math.max(BASE_GRANT_CENTS, creditsRemainingCents)+ const pct = Math.max(0, Math.min(100, (creditsRemainingCents / grant) * 100))+ return (+ <div className="border-t px-3 py-3">+ <div className="text-muted-foreground flex items-center justify-between font-mono text-[11px]">+ <span>Free credits</span>+ <span+ className={cn(+ isHalted && 'text-destructive',+ isLow && 'text-amber-600',+ )}+ >+ {formatUsd(creditsRemainingCents)} left+ </span>+ </div>+ <div className="bg-secondary mt-1.5 h-1 overflow-hidden rounded-full">+ <div+ className={cn(+ 'h-full rounded-full',+ isHalted ? 'bg-destructive' : isLow ? 'bg-amber-500' : 'bg-primary',+ )}+ style={{ width: `${pct}%` }}+ />+ </div>+ <Link+ to={upgradeHref('pro')}+ onClick={() => {+ trackUpsellClicked({+ surface: 'sidebar_meter',+ plan: 'pro',+ usagePlan,+ creditsRemainingCents,+ })+ onNavigate?.()+ }}+ className="text-foreground mt-2 block text-xs font-medium underline-offset-2 hover:underline"+ >+ Upgrade to Pro — ${PLAN_OFFERS.pro.creditsUsd}/mo of credits for $+ {PLAN_OFFERS.pro.priceUsd}+ </Link>+ </div>+ )+}++// Org-wide credit notice. Prepaid (autumn) orgs that exhaust credits get halted// (sandboxes hibernate); show a banner everywhere except Billing so users know-// why things paused and where to resolve it. Legacy orgs 404 on /billing/autumn-// → no data → no banner.+// why things paused and where to resolve it. Below the low-credit threshold the+// banner is an amber nudge instead. Legacy orgs 404 on /billing/autumn → no+// data → no banner.function HaltBanner() {const location = useLocation()- const { data } = useQuery({- queryKey: ['autumn-billing'],- queryFn: getAutumnBilling,- retry: false,- refetchInterval: (q) => (q.state.error ? false : 30_000),- })- const halted = data?.isHalted ?? false- if (!halted || location.pathname.startsWith('/billing')) return null+ const { isHalted, isLow, usagePlan, creditsRemainingCents, upgradePlan } =+ useCreditState()+ const onBilling = location.pathname.startsWith('/billing')+ const state = isHalted ? 'halted' : isLow ? 'low' : null+ useEffect(() => {+ if (state && !onBilling)+ trackUpsellShown({+ surface: state === 'halted' ? 'halt_banner' : 'low_credit_banner',+ plan: upgradePlan,+ usagePlan,+ creditsRemainingCents,+ })+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [state, onBilling])+ if (!state || onBilling) return null+ const offer = PLAN_OFFERS[upgradePlan]+ const planName = upgradePlan === 'pro' ? 'Pro' : 'Max'+ const click = () =>+ trackUpsellClicked({+ surface: state === 'halted' ? 'halt_banner' : 'low_credit_banner',+ plan: upgradePlan,+ usagePlan,+ creditsRemainingCents,+ })+ if (state === 'low') {+ return (+ <div className="flex items-center justify-center gap-2 border-b border-amber-500/40 bg-amber-500/10 px-4 py-2.5 text-center text-sm font-medium text-amber-700 sm:px-8 dark:text-amber-400">+ <CircleAlert className="size-4 shrink-0" />+ <span>+ {formatUsd(creditsRemainingCents ?? 0)} of credits left — sessions+ pause at $0.{' '}+ <Link+ to={upgradeHref(upgradePlan)}+ onClick={click}+ className="font-semibold underline underline-offset-2"+ >+ Upgrade to {planName}+ </Link>{' '}+ for ${offer.creditsUsd}/mo of credits at ${offer.priceUsd}/mo.+ </span>+ </div>+ )+ }return (<div className="border-destructive/40 bg-status-error-bg text-destructive flex items-center justify-center gap-2 border-b px-4 py-2.5 text-center text-sm font-medium sm:px-8"><CircleAlert className="size-4 shrink-0" /><span>Your agent sessions and sandboxes are paused — you're out ofprepaid credits.{' '}- <Link- to="/billing"- className="font-semibold underline underline-offset-2"- >- Top up & turn on auto-recharge- </Link>{' '}- to resume.+ {billingOnrampV2Enabled ? (+ <>+ <Link+ to={upgradeHref(upgradePlan)}+ onClick={click}+ className="font-semibold underline underline-offset-2"+ >+ Upgrade to {planName} (${offer.priceUsd}/mo, ${offer.creditsUsd}{' '}+ credits)+ </Link>{' '}+ or{' '}+ <Link to="/billing" className="underline underline-offset-2">+ top up+ </Link>{' '}+ to resume.+ </>+ ) : (+ <>+ <Link+ to="/billing"+ className="font-semibold underline underline-offset-2"+ >+ Top up & turn on auto-recharge+ </Link>{' '}+ to resume.+ </>+ )}</span></div>)diff --git a/web/src/components/post-session-upsell.tsx b/web/src/components/post-session-upsell.tsxnew file mode 100644index 00000000..798afbb4--- /dev/null+++ b/web/src/components/post-session-upsell.tsx@@ -0,0 +1,123 @@+import { useEffect } from 'react'+import { Link } from 'react-router-dom'+import { Sparkles } from 'lucide-react'+import { Panel } from '@/components/panel'+import { Button } from '@/components/ui/button'+import { useCreditState } from '@/hooks/useCreditState'+import {+ BASE_GRANT_CENTS,+ PLAN_OFFERS,+ billingOnrampV2Enabled,+ formatUsd,+ trackFirstSessionCompleted,+ trackUpsellClicked,+ trackUpsellShown,+ upgradeHref,+} from '@/lib/billing-onramp'++const SEEN_KEY = 'oc.billing.upsell_sessions'+const MAX_SESSIONS = 3++// Sessions this browser has already shown the card for. The card is only+// worth showing on the first few sessions — after that the value is proven+// and the sidebar meter/banner take over.+function rememberSession(sessionId: string): { index: number; show: boolean } {+ try {+ const parsed: unknown = JSON.parse(localStorage.getItem(SEEN_KEY) ?? '[]')+ const seen = Array.isArray(parsed)+ ? parsed.filter((v): v is string => typeof v === 'string')+ : []+ const existing = seen.indexOf(sessionId)+ if (existing >= 0) return { index: existing, show: existing < MAX_SESSIONS }+ if (seen.length >= MAX_SESSIONS) return { index: seen.length, show: false }+ seen.push(sessionId)+ localStorage.setItem(SEEN_KEY, JSON.stringify(seen))+ return { index: seen.length - 1, show: true }+ } catch {+ return { index: 0, show: true }+ }+}++// Shown under a serverless-agent session once it has finished a turn. Sessions+// don't expose per-session cost, so the card speaks in terms of the org's free+// credit grant instead.+export function PostSessionUpsell({+ sessionId,+ completed,+ className,+}: {+ sessionId: string+ completed: boolean+ className?: string+}) {+ const { usagePlan, isHalted, creditsRemainingCents } = useCreditState()+ const spentCents =+ creditsRemainingCents === undefined+ ? null+ : Math.max(0, BASE_GRANT_CENTS - creditsRemainingCents)+ const eligible =+ billingOnrampV2Enabled &&+ completed &&+ usagePlan === 'base' &&+ !isHalted &&+ spentCents !== null &&+ spentCents > 0+ const seen = eligible ? rememberSession(sessionId) : null+ const show = seen?.show ?? false++ useEffect(() => {+ if (!show) return+ if (seen?.index === 0)+ trackFirstSessionCompleted({+ sessionId,+ costCents: spentCents ?? 0,+ usagePlan,+ })+ trackUpsellShown({+ surface: 'post_session_card',+ plan: 'pro',+ usagePlan,+ creditsRemainingCents,+ })+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [show, sessionId])++ if (!show || spentCents === null) return null+ const pro = PLAN_OFFERS.pro+ return (+ <Panel+ className={`flex flex-wrap items-center justify-between gap-4 p-4 ${className ?? ''}`}+ >+ <div className="flex min-w-0 items-start gap-3">+ <Sparkles className="text-muted-foreground mt-0.5 size-4 shrink-0" />+ <div className="text-sm">+ <p className="font-medium">+ You've used {formatUsd(spentCents)} of your{' '}+ {formatUsd(BASE_GRANT_CENTS)} free credits —{' '}+ {formatUsd(creditsRemainingCents ?? 0)} left.+ </p>+ <p className="text-muted-foreground mt-0.5">+ Pro is ${pro.priceUsd}/mo for ${pro.creditsUsd} in credits —{' '}+ {Math.round(pro.creditsUsd / (BASE_GRANT_CENTS / 100))}× your free+ grant every month, and your agents never pause.+ </p>+ </div>+ </div>+ <Button asChild size="sm">+ <Link+ to={upgradeHref('pro')}+ onClick={() =>+ trackUpsellClicked({+ surface: 'post_session_card',+ plan: 'pro',+ usagePlan,+ creditsRemainingCents,+ })+ }+ >+ Upgrade to Pro — ${pro.priceUsd}/mo+ </Link>+ </Button>+ </Panel>+ )+}diff --git a/web/src/hooks/useCreditState.ts b/web/src/hooks/useCreditState.tsnew file mode 100644index 00000000..e1aa8424--- /dev/null+++ b/web/src/hooks/useCreditState.ts@@ -0,0 +1,46 @@+import { useQuery } from '@tanstack/react-query'+import { getAutumnBilling } from '@/api/client'+import type { AutumnBilling } from '@/api/schemas'+import {+ billingOnrampV2Enabled,+ lowCreditThresholdCents,+ upgradePlanFor,+ type PaidPlanId,+ type UsagePlanId,+} from '@/lib/billing-onramp'++export interface CreditState {+ billing: AutumnBilling | undefined+ usagePlan: UsagePlanId | undefined+ creditsRemainingCents: number | undefined+ isHalted: boolean+ // Below the low-credit threshold but not yet halted; only for prepaid orgs+ // with the on-ramp experiment enabled.+ isLow: boolean+ upgradePlan: PaidPlanId+}++// Shares the same 30s poll as useHalted/HaltBanner via the 'autumn-billing' key.+export function useCreditState(): CreditState {+ const { data } = useQuery({+ queryKey: ['autumn-billing'],+ queryFn: getAutumnBilling,+ retry: false,+ refetchInterval: (q) => (q.state.error ? false : 30_000),+ })+ const usagePlan = data?.usagePlan+ const isHalted = data?.isHalted ?? false+ const isLow =+ billingOnrampV2Enabled &&+ !isHalted &&+ data !== undefined &&+ data.creditsRemainingCents <= lowCreditThresholdCents(data.usagePlan)+ return {+ billing: data,+ usagePlan,+ creditsRemainingCents: data?.creditsRemainingCents,+ isHalted,+ isLow,+ upgradePlan: upgradePlanFor(usagePlan ?? 'base'),+ }+}diff --git a/web/src/lib/billing-onramp.ts b/web/src/lib/billing-onramp.tsnew file mode 100644index 00000000..9940b7b0--- /dev/null+++ b/web/src/lib/billing-onramp.ts@@ -0,0 +1,119 @@+import posthog from 'posthog-js'++// Payment on-ramp experiment (low-credit banner, sidebar meter, post-session+// upsell, Pro-first halt copy). Set the build-time value to "0" to fall back to+// the halt-only behaviour.+export const billingOnrampV2Enabled =+ import.meta.env.VITE_BILLING_ONRAMP_V2 !== '0'++export type UsagePlanId = 'base' | 'pro' | 'max'+export type PaidPlanId = Exclude<UsagePlanId, 'base'>++export const PLAN_OFFERS: Record<+ PaidPlanId,+ { priceUsd: number; creditsUsd: number }+> = {+ pro: { priceUsd: 20, creditsUsd: 200 },+ max: { priceUsd: 200, creditsUsd: 2000 },+}++// Monthly grant per plan; the base grant is the signup allowance.+export const BASE_GRANT_CENTS = 500+const PLAN_GRANT_CENTS: Record<UsagePlanId, number> = {+ base: BASE_GRANT_CENTS,+ pro: 20_000,+ max: 200_000,+}+const LOW_CREDIT_FRACTION = 0.3++export function lowCreditThresholdCents(plan: UsagePlanId): number {+ return Math.round(PLAN_GRANT_CENTS[plan] * LOW_CREDIT_FRACTION)+}++export function upgradePlanFor(plan: UsagePlanId): PaidPlanId {+ return plan === 'pro' ? 'max' : 'pro'+}++export function upgradeHref(plan: PaidPlanId): string {+ return `/billing?plan=${plan}`+}++export function formatUsd(cents: number): string {+ return `$${(cents / 100).toFixed(2)}`+}++export type UpsellSurface =+ | 'sidebar_meter'+ | 'low_credit_banner'+ | 'halt_banner'+ | 'session_composer'+ | 'post_session_card'+ | 'byok_gate'+ | 'billing_page'+ | 'billing_deeplink'++interface UpsellProps {+ surface: UpsellSurface+ plan?: PaidPlanId+ usagePlan?: UsagePlanId+ creditsRemainingCents?: number+}++const SURFACE_KEY = 'oc.billing.upsell_surface'++export function trackUpsellShown(props: UpsellProps): void {+ posthog.capture('upsell_shown', props)+}++export function trackUpsellClicked(props: UpsellProps): void {+ posthog.capture('upsell_clicked', props)+ try {+ sessionStorage.setItem(SURFACE_KEY, props.surface)+ } catch {+ // storage unavailable (private mode); attribution is best-effort+ }+}++// The surface that sent the user to /billing, so checkout/activation can be+// attributed to it after the Stripe round trip.+export function attributedSurface(): UpsellSurface | undefined {+ try {+ return (+ (sessionStorage.getItem(SURFACE_KEY) as UpsellSurface | null) ?? undefined+ )+ } catch {+ return undefined+ }+}++export function trackCheckoutStarted(props: {+ plan?: PaidPlanId+ topupUsd?: number+ usagePlan?: UsagePlanId+}): void {+ posthog.capture('checkout_started', {+ ...props,+ surface: attributedSurface(),+ })+}++export function trackPlanActivated(props: {+ plan?: PaidPlanId+ topupUsd?: number+ usagePlan?: UsagePlanId+}): void {+ posthog.capture('plan_activated', { ...props, surface: attributedSurface() })+ try {+ sessionStorage.removeItem(SURFACE_KEY)+ } catch {+ // ignore+ }+}++export function trackFirstSessionCompleted(props: {+ sessionId: string+ costCents?: number+ usagePlan?: UsagePlanId+}): void {+ posthog.capture('first_session_completed', props)+}diff --git a/web/src/managed-agents/BYOK.tsx b/web/src/managed-agents/BYOK.tsxindex 1255c379..bf1e4acb 100644--- a/web/src/managed-agents/BYOK.tsx+++ b/web/src/managed-agents/BYOK.tsx@@ -1,4 +1,4 @@-import { useState } from 'react'+import { useEffect, useState } from 'react'import { Link } from 'react-router-dom'import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import { BrainCircuit, Link2, LockKeyhole, Loader2, Trash2 } from 'lucide-react'@@ -16,6 +16,12 @@ import { StatusBadge } from '@/components/status-badge'import { Button } from '@/components/ui/button'import { useAuth } from '@/hooks/useAuth'import { notifyError, notifySuccess } from '@/lib/errors'+import {+ PLAN_OFFERS,+ trackUpsellClicked,+ trackUpsellShown,+ upgradeHref,+} from '@/lib/billing-onramp'import {connectManagedModelApiKey,deleteManagedModelRoute,@@ -63,6 +69,10 @@ export function ManagedProjectBYOK({ projectId }: { projectId: string }) {? autumnBilling.data?.usagePlan: billing.data?.planconst planEligible = hasBYOKPlanAccess(usagePlan)+ const showGate = !billing.isLoading && !billing.isError && !planEligible+ useEffect(() => {+ if (showGate) trackUpsellShown({ surface: 'byok_gate', plan: 'pro' })+ }, [showGate])const billingLoading =billing.isLoading ||(billing.data?.billingProvider === 'autumn' && autumnBilling.isLoading)@@ -172,10 +182,17 @@ export function ManagedProjectBYOK({ projectId }: { projectId: string }) {<EmptyStateicon={LockKeyhole}title="BYOK is available on Pro"- description="Upgrade to Pro to connect your model provider and configure a project model route."+ description={`Bring your own provider keys and route this project's models through them. Pro is $${PLAN_OFFERS.pro.priceUsd}/mo and includes $${PLAN_OFFERS.pro.creditsUsd} in credits every month.`}action={<Button asChild>- <Link to="/billing">Upgrade to Pro</Link>+ <Link+ to={upgradeHref('pro')}+ onClick={() =>+ trackUpsellClicked({ surface: 'byok_gate', plan: 'pro' })+ }+ >+ Upgrade to Pro — ${PLAN_OFFERS.pro.priceUsd}/mo+ </Link></Button>}/>diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex 28faa854..73f3388b 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -63,6 +63,14 @@ import {type ManagedProjectOverview,} from './api'import { ManagedAgentChatTransport } from './chat-transport'+import { PostSessionUpsell } from '@/components/post-session-upsell'+import { useCreditState } from '@/hooks/useCreditState'+import {+ PLAN_OFFERS,+ billingOnrampV2Enabled,+ trackUpsellClicked,+ upgradeHref,+} from '@/lib/billing-onramp'import { DebugInspector } from './DebugInspector'import { isNearScrollEnd } from './scroll-follow'import { createStartCommand, starterCommands } from './onboarding'@@ -313,6 +321,10 @@ function PlaygroundChat({running ||session?.status === 'running' ||session?.status === 'waiting_runtime'+ const credits = useCreditState()+ const halted = credits.isHalted+ const turnFinished =+ !agentWorking && status === 'ready' && messages.length > 0useEffect(() => {if (!initialPrompt || session || initialPromptSentRef.current) return@@ -334,7 +346,7 @@ function PlaygroundChat({const send = () => {const input = prompt.trim()- if (!input || admitting) return+ if (!input || admitting || halted) returnif (agentWorking) {const sessionId = liveSessionIdif (!sessionId) {@@ -460,7 +472,43 @@ function PlaygroundChat({</div><div className="bg-panel shrink-0 border-t p-4">- {error ? (+ {liveSessionId ? (+ <PostSessionUpsell+ sessionId={liveSessionId}+ completed={turnFinished}+ className="mb-3"+ />+ ) : null}+ {halted ? (+ <p className="text-destructive mb-2 text-xs">+ Out of credits — this agent can't run until you{' '}+ <Link+ to={upgradeHref(credits.upgradePlan)}+ className="font-medium underline"+ onClick={() =>+ trackUpsellClicked({+ surface: 'session_composer',+ plan: credits.upgradePlan,+ usagePlan: credits.usagePlan,+ creditsRemainingCents: credits.creditsRemainingCents,+ })+ }+ >+ upgrade to {credits.upgradePlan === 'max' ? 'Max' : 'Pro'} — $+ {PLAN_OFFERS[credits.upgradePlan].priceUsd}/mo+ </Link>+ {billingOnrampV2Enabled ? (+ <>+ {' '}+ or{' '}+ <Link to="/billing" className="underline">+ top up+ </Link>+ </>+ ) : null}+ .+ </p>+ ) : error ? (<p className="text-destructive mb-2 text-xs">{error.message}</p>) : null}{admissionNotice ? (@@ -499,7 +547,7 @@ function PlaygroundChat({variant={inputMode === 'interrupt' ? 'destructive' : 'default'}- disabled={!prompt.trim() || admitting}+ disabled={!prompt.trim() || admitting || halted}onClick={send}>{admitting ? (@@ -511,7 +559,11 @@ function PlaygroundChat({</Button></div>) : (- <Button size="sm" disabled={!prompt.trim()} onClick={send}>+ <Button+ size="sm"+ disabled={!prompt.trim() || halted}+ onClick={send}+ ><Send /> Send</Button>)}diff --git a/web/src/managed-agents/Session.tsx b/web/src/managed-agents/Session.tsxindex babc6f85..8c69fcb5 100644--- a/web/src/managed-agents/Session.tsx+++ b/web/src/managed-agents/Session.tsx@@ -11,6 +11,7 @@ import {import { Link, useParams, useSearchParams } from 'react-router-dom'import { EmptyState } from '@/components/empty-state'import { PageHeader } from '@/components/page-header'+import { PostSessionUpsell } from '@/components/post-session-upsell'import {Panel,PanelContent,@@ -121,6 +122,11 @@ export default function ManagedSessionDetail() {}/>+ <PostSessionUpsell+ sessionId={session.data.id}+ completed={session.data.status === 'completed'}+ />+<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-4"><Panel className="p-4"><p className="text-muted-foreground text-xs">Status</p>@@ -255,7 +261,7 @@ export default function ManagedSessionDetail() {{turn.input}</p>{payload !== undefined ? (- <details className="ml-auto mt-2 max-w-2xl">+ <details className="mt-2 ml-auto max-w-2xl"><summary className="text-muted-foreground cursor-pointer text-xs">Payload</summary>diff --git a/web/src/pages/Billing.tsx b/web/src/pages/Billing.tsxindex 24e9db30..959b236c 100644--- a/web/src/pages/Billing.tsx+++ b/web/src/pages/Billing.tsx@@ -34,6 +34,12 @@ import { EmptyState } from '@/components/empty-state'import { ConfirmDialog } from '@/components/confirm-dialog'import { ResourceTable, type Column } from '@/components/resource-table'import { cn } from '@/lib/utils'+import {+ billingOnrampV2Enabled,+ trackCheckoutStarted,+ trackPlanActivated,+ trackUpsellShown,+} from '@/lib/billing-onramp'type Tab = 'usage' | 'invoices'@@ -243,7 +249,8 @@ function PlanTab() {/* ── Prepaid (Autumn) ─────────────────────────────────────────────────────── */-const TOPUP_AMOUNTS = [5, 25, 100]+const TOPUP_AMOUNTS = billingOnrampV2Enabled ? [10, 25, 100] : [5, 25, 100]+const DEFAULT_TOPUP = billingOnrampV2Enabled ? 10 : 25const CONCURRENCY_TIERS = [{ id: 'concurrency_pro', label: 'Pro', limit: 100, price: 150 },@@ -293,18 +300,53 @@ function PrepaidPlan() {const redirectedPlan = searchParams.get('usage-plan')const pendingUsagePlan =redirectedPlan === 'pro' || redirectedPlan === 'max' ? redirectedPlan : null+ // `?plan=pro|max` (upsell deep link) opens the upgrade confirmation directly.+ const requestedPlan = searchParams.get('plan')+ const deepLinkedPlan =+ billingOnrampV2Enabled &&+ (requestedPlan === 'pro' || requestedPlan === 'max')+ ? requestedPlan+ : nullconst activationToastShown = useRef(false)const { data: autumn, isLoading } = useQuery({queryKey: ['autumn-billing'],queryFn: getAutumnBilling,refetchInterval: pendingUsagePlan != null ? 1_500 : 30_000,})- const [amount, setAmount] = useState(25)+ const [amount, setAmount] = useState(DEFAULT_TOPUP)const [confirmTopup, setConfirmTopup] = useState(false)const [confirmPlanId, setConfirmPlanId] = useState<string | null>(null)const [confirmUsagePlanId, setConfirmUsagePlanId] = useState<'pro' | 'max' | null>(null)+ // While `?plan=` is in the URL it drives the dialog; closing it clears the+ // param so the same link can reopen it later.+ const openUsagePlanId =+ confirmUsagePlanId ??+ (deepLinkedPlan && autumn && autumn.usagePlan !== deepLinkedPlan+ ? deepLinkedPlan+ : null)+ const clearDeepLink = () => {+ if (!searchParams.has('plan')) return+ const next = new URLSearchParams(searchParams)+ next.delete('plan')+ setSearchParams(next, { replace: true })+ }+ const closeUsagePlanDialog = () => {+ setConfirmUsagePlanId(null)+ clearDeepLink()+ }++ useEffect(() => {+ if (!deepLinkedPlan || !autumn) return+ trackUpsellShown({+ surface: 'billing_deeplink',+ plan: deepLinkedPlan,+ usagePlan: autumn.usagePlan,+ creditsRemainingCents: autumn.creditsRemainingCents,+ })+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [deepLinkedPlan, autumn?.usagePlan])const [usageProduct, setUsageProduct] = useState<'sandboxes' | 'serverless-agents'>('serverless-agents')@@ -318,6 +360,7 @@ function PrepaidPlan() {toast.success(`${label} plan activated`, {description: 'Your monthly credits are ready to use.',})+ trackPlanActivated({ plan: pendingUsagePlan })activationToastShown.current = true}const next = new URLSearchParams(searchParams)@@ -335,6 +378,9 @@ function PrepaidPlan() {mutationFn: () => autumnTopup(amount),onSuccess: (d) => {setConfirmTopup(false)+ trackCheckoutStarted({ topupUsd: amount, usagePlan: autumn?.usagePlan })+ if (!d.url)+ trackPlanActivated({ topupUsd: amount, usagePlan: autumn?.usagePlan })onPurchase(d)},onError: (e) => notifyError("Couldn't complete the top-up.", e),@@ -350,12 +396,14 @@ function PrepaidPlan() {const usagePlanMutation = useMutation({mutationFn: (plan: 'pro' | 'max') => autumnSubscribeUsagePlan(plan),onSuccess: (d, plan) => {- setConfirmUsagePlanId(null)+ closeUsagePlanDialog()+ trackCheckoutStarted({ plan, usagePlan: autumn?.usagePlan })if (!d.url) {const label = plan === 'pro' ? 'Pro' : 'Max'toast.success(`${label} plan updated`, {description: 'Your billing status and credits are refreshing.',})+ trackPlanActivated({ plan, usagePlan: autumn?.usagePlan })}onPurchase(d)},@@ -384,7 +432,7 @@ function PrepaidPlan() {const currentPlan = autumn?.concurrencyPlan ?? 'base'const tier = CONCURRENCY_TIERS.find((t) => t.id === confirmPlanId)const selectedUsagePlan = USAGE_PLANS.find(- (plan) => plan.id === confirmUsagePlanId,+ (plan) => plan.id === openUsagePlanId,)const hasCard =(billing?.hasPaymentMethod ?? false) ||@@ -482,11 +530,26 @@ function PrepaidPlan() {</div>) : null}{halted ? (- <p className="text-status-error mt-2 flex items-center gap-1.5 text-sm">- <CircleAlert className="size-4 shrink-0" />- Credits exhausted — top up to resume your agent sessions and- sandboxes- </p>+ <div className="text-status-error mt-2 space-y-2 text-sm">+ <p className="flex items-center gap-1.5">+ <CircleAlert className="size-4 shrink-0" />+ Credits exhausted — your agent sessions and sandboxes are paused+ </p>+ {billingOnrampV2Enabled && autumn?.usagePlan !== 'max' ? (+ <Button+ size="sm"+ onClick={() =>+ setConfirmUsagePlanId(+ autumn?.usagePlan === 'pro' ? 'max' : 'pro',+ )+ }+ >+ {autumn?.usagePlan === 'pro'+ ? 'Upgrade to Max — $200/mo'+ : 'Upgrade to Pro — $20/mo for $200 credits'}+ </Button>+ ) : null}+ </div>) : null}<div className="mt-5">@@ -608,7 +671,7 @@ function PrepaidPlan() {/><ConfirmDialogopen={!!selectedUsagePlan}- onOpenChange={(open) => !open && setConfirmUsagePlanId(null)}+ onOpenChange={(open) => !open && closeUsagePlanDialog()}title={`Switch to ${selectedUsagePlan?.label ?? ''}`}description={selectedUsagePlan