An open-source, faster Devin alternative
TypeScript
managed (slice 2): Managed is an invariant — kill managedAvailable, provision every org
Igor Zalutskiab47c3180111
diff --git a/.agents/work/managed-keys-for-everyone.md b/.agents/work/managed-keys-for-everyone.mdindex afad5dcb..7d272812 100644--- a/.agents/work/managed-keys-for-everyone.md+++ b/.agents/work/managed-keys-for-everyone.md@@ -1,9 +1,14 @@# Managed keys for everyone — decouple Managed from billing-Status: **Slice 1 implemented (2026-06-29); Slice 2 pending.** Builds on the shipped-Managed work (`token-billing.md`, PRs #445 + sessions-api #34). Governing principle:+Status: **Slices 1 + 2 implemented (2026-06-29) on `feat/managed-keys-for-everyone`+(PR #452); pending review + deploy.** Builds on the shipped Managed work+(`token-billing.md`, PRs #445 + sessions-api #34). Governing principle:`oc-bg-agents/.agents/conventions/shift-left-over-feature-flags.md`.+**Step 0 resolved:** there ARE two org-create paths — the edge signup handler AND the+Go/WorkOS cell path (`oauth_handlers.go` → `store.go:1620 INSERT INTO orgs` → D1). So the+reconcile sweep is required (path-agnostic); the signup hook is immediacy-only.+## 1. Objective**Enable Managed model keys for every org and delete the conditional enablement.**@@ -120,10 +125,13 @@ customers (pro + active Stripe sub): **33 on legacy** (all `model_billing_status(`model_meter.ts` early-return). Tests updated + non-autumn cases added (21/21 green,tsc clean). After this, *any* org can be enabled with bounded exposure and zerowrongful halts. *Still requires the per-org enable step — that's Slice 2.*-- **Slice 2 (make Managed an invariant + kill `managedAvailable`):** No new endpoint, no- sessions-api→edge trigger, no hot-path fork. `enableManagedBilling` /- `reconcileManagedBilling` already mint+bind idempotently; we just make *every* org carry- a managed credential (like every org carries an Autumn customer).+- **Slice 2 (make Managed an invariant + kill `managedAvailable`) — DONE (PR #452):**+ `runManagedProvisioner` sweep (edge `scheduled()`, batched, idempotent) drains every+ unprovisioned org via `enableManagedBilling`; signup hook provisions at org birth for+ immediacy; `managedAvailable` deleted from edge `/billing` + web (`Agents.tsx`,+ `AgentDetail.tsx`, `schemas.ts`) → Managed always offered; no sessions-api change. Edge+ + web tsc clean, 22/22 edge tests (incl. the sweep test). No new endpoint, no+ cross-service trigger, no hot-path fork. Below is the design as built:- **Provision at org birth:** add `enableManagedBilling(orgID)` in the edge signuphandler, beside the existing `createAutumnCustomer` call (`index.ts:~1251`,best-effort — don't fail signup on a provisioning hiccup; the sweep heals it).diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 2ef71ee1..762e300d 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -989,19 +989,9 @@ export async function handleDashboard(max_concurrent_sandboxes: number; billing_provider: string;}>();if (!org) return json({ error: "org not found" }, 404);- // Managed model access (token-billing §6.6) — read SEPARATELY + defensively so the- // critical billing read above never depends on the phase-9 column. If schema_phase9- // hasn't been applied yet (Worker deployed first), the column is missing → this- // throws → managedAvailable=false, and existing billing is unaffected (P0 ordering).- let managedAvailable = false;- try {- const m = await env.OPENCOMPUTER_DB.prepare(- `SELECT model_billing_status FROM orgs WHERE id = ?1`,- ).bind(caller.orgID).first<{ model_billing_status: string | null }>();- managedAvailable = m?.model_billing_status === "active";- } catch {- /* phase-9 not migrated yet → Managed simply unavailable */- }+ // Managed is a universal capability (every org is provisioned a managed credential by+ // runManagedProvisioner), so there is no per-org "available" flag to read or return —+ // the UI always offers Managed.// Cross-check against the live DO state — the D1 mirror gets written by// the DO after every debit but lags a touch, and on initial signup the// column reads its column-default (500) before the DO has ever been@@ -1033,11 +1023,6 @@ export async function handleDashboard(isHalted: !!org.is_halted,maxConcurrentSandboxes: org.max_concurrent_sandboxes,billingProvider: org.billing_provider,- // Managed model access (token-billing §6.6): the single gating authority the UI- // reads to offer the "Managed" credential option. True only once the edge has- // provisioned the org's OpenRouter key + bound it (model_billing_status='active').- // Read defensively above so a missing phase-9 column never breaks billing.- managedAvailable,// Upcoming-invoice + meters would come from Stripe API on demand;// surface stubs for now so the UI has stable keys to render against.upcomingInvoice: null,diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 426970b5..70bfce36 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -26,7 +26,7 @@ import {createAutumnCustomer,} from "./autumn_webhook";import { runAutumnMeter } from "./autumn_meter";-import { disableManagedBilling, enableManagedBilling } from "./model_billing";+import { disableManagedBilling, enableManagedBilling, runManagedProvisioner } from "./model_billing";import { runModelMeter } from "./model_meter";import * as secretStores from "./secret_stores";import * as snapshots from "./snapshots";@@ -1265,6 +1265,12 @@ async function authCallback(req: Request, env: Env): Promise<Response> {).bind(orgID, userID, nowSec).run();+ // Managed is an invariant: provision the org's OpenRouter key at birth so it "just+ // works" immediately. Best-effort — a hiccup must not break signup; the reconcile+ // sweep (scheduled) backfills + heals, and also covers the Go/WorkOS create path.+ await enableManagedBilling(env, orgID).catch((e) =>+ console.error(`signup: managed provisioning failed for ${orgID} (sweep will retry)`, e),+ );}// Mint session JWT — same signing secret as cap-token but a different@@ -2144,6 +2150,11 @@ export default {ctx.waitUntil(runModelMeter(env, Date.now()).catch((err) => console.error("model-meter: run failed", err)),);+ // Keep Managed an invariant: drain any org without a managed credential (backfill ++ // new orgs from any create path + failed provisions). Idempotent, bounded per tick.+ ctx.waitUntil(+ runManagedProvisioner(env).catch((err) => console.error("managed-provisioner: run failed", err)),+ );}},} satisfies ExportedHandler<Env>;diff --git a/cloudflare-workers/api-edge/src/model_billing.test.ts b/cloudflare-workers/api-edge/src/model_billing.test.tsindex bc73407a..342405f2 100644--- a/cloudflare-workers/api-edge/src/model_billing.test.ts+++ b/cloudflare-workers/api-edge/src/model_billing.test.ts@@ -9,6 +9,7 @@ import {import {disableManagedBilling,enableManagedBilling,+ runManagedProvisioner,type ManagedModelKeyRow,type ModelBillingEnv,ownerIdForOrg,@@ -66,6 +67,14 @@ class FakeStmt {const orgId = this.args[0] as string;return { results: this.db.keys.filter((k) => k.org_id === orgId) as T[] };}+ // runManagedProvisioner: unprovisioned orgs (not active/error), bounded by LIMIT.+ if (this.sql.includes("FROM orgs")) {+ const rows = [...this.db.orgs.values()].filter(+ (o) => !["active", "error"].includes(o.model_billing_status ?? "off"),+ );+ const limit = typeof this.args[0] === "number" ? this.args[0] : rows.length;+ return { results: rows.slice(0, limit) as T[] };+ }return { results: [] };}@@ -366,3 +375,23 @@ describe("disableManagedBilling (rollback / hard offboard)", () => {expect(db.orgs.get(orgId)!.model_billing_status).toBe("off");});});++describe("runManagedProvisioner (Managed-as-invariant sweep)", () => {+ it("provisions every unprovisioned org (any provider), leaving active/error alone", async () => {+ const db = new FakeDb();+ seedOrg(db, { id: "a", model_billing_status: "off" }); // autumn, fresh+ seedOrg(db, { id: "b", model_billing_status: "active" }); // already provisioned+ seedOrg(db, { id: "c", model_billing_status: "error" }); // parked — leave alone+ seedOrg(db, { id: "d", billing_provider: "legacy" }); // non-autumn, off by default+ const { spy } = makeFetch();+ vi.stubGlobal("fetch", spy);++ await runManagedProvisioner(makeEnv(db));++ expect(db.orgs.get("a")!.model_billing_status).toBe("active");+ expect(db.orgs.get("d")!.model_billing_status).toBe("active"); // legacy provisions too+ expect(db.orgs.get("c")!.model_billing_status).toBe("error"); // untouched+ expect(db.keys.some((k) => k.org_id === "a")).toBe(true);+ expect(db.keys.some((k) => k.org_id === "c")).toBe(false); // never touched+ });+});diff --git a/cloudflare-workers/api-edge/src/model_billing.ts b/cloudflare-workers/api-edge/src/model_billing.tsindex 8109f12d..bed9df00 100644--- a/cloudflare-workers/api-edge/src/model_billing.ts+++ b/cloudflare-workers/api-edge/src/model_billing.ts@@ -409,6 +409,35 @@ export async function reconcileManagedBilling(env: ModelBillingEnv, orgId: strinreturn enableManagedBilling(env, orgId);}+// runManagedProvisioner makes "every org has a managed credential" an INVARIANT rather+// than a per-org opt-in. It drains orgs that aren't provisioned yet — a bounded batch per+// tick — via the idempotent enableManagedBilling. One mechanism covers the one-time+// backfill, every new org (regardless of create path: edge signup OR the Go/WorkOS cell+// path), and any half/failed provision — with zero hot-path code and no managedAvailable+// flag. Orgs parked in 'error' (exhausted retries) are left alone.+const PROVISION_BATCH = 20;+export async function runManagedProvisioner(env: ModelBillingEnv): Promise<void> {+ const res = await env.OPENCOMPUTER_DB.prepare(+ `SELECT id FROM orgs WHERE COALESCE(model_billing_status,'off') NOT IN ('active','error')+ ORDER BY created_at LIMIT ?1`,+ )+ .bind(PROVISION_BATCH)+ .all<{ id: string }>();+ const orgs = res.results ?? [];+ if (orgs.length === 0) return;+ let done = 0;+ for (const { id } of orgs) {+ try {+ await enableManagedBilling(env, id);+ done++;+ } catch (e) {+ // Best-effort: one org's failure never blocks the rest; the next tick retries.+ console.error(`managed-provisioner: org ${id} failed`, e);+ }+ }+ console.log(`managed-provisioner: ${done}/${orgs.length} provisioned this run`);+}+// disableManagedBilling is the rollback path: a synchronous HARD offboard. The// graceful-drain cron (§5.8 — keep polling until spend quiesces, final debit, then// delete) isn't built yet, so disable does the teardown directly: delete the ORdiff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex 48762742..fd730c1e 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -192,10 +192,6 @@ export const BillingStateSchema = z.object({hasPaymentMethod: z.boolean(),freeCreditsRemainingCents: z.number(),billingProvider: z.string().optional(),- // Managed model access (token-billing §6.6): the single gating authority for- // offering the "Managed · billed to credits" credential option. Optional so an- // older edge without the field validates (treated as unavailable).- managedAvailable: z.boolean().optional(),})export const AutumnAutoTopupSchema = z.object({diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsxindex 506af851..e5a7982b 100644--- a/web/src/pages/AgentDetail.tsx+++ b/web/src/pages/AgentDetail.tsx@@ -10,7 +10,6 @@ import {createSession,getCredentials,createCredential,- getBilling,type Agent,} from '@/api/client'import type { Session } from '@/api/schemas'@@ -63,9 +62,6 @@ export default function AgentDetail() {queryKey: ['credentials'],queryFn: getCredentials,})- // Managed availability gates the "Managed" entry (token-billing §6.6/§6.8.C).- const { data: billing } = useQuery({ queryKey: ['billing'], queryFn: getBilling })- const managedAvailable = billing?.managedAvailable ?? false// Model list + credential provider follow the agent's runtime (immutable after// create): claude→anthropic, codex→openai. Falls back to claude while loading.const rt = getRuntime(agent?.runtime)@@ -181,14 +177,10 @@ export default function AgentDetail() {const credSelectValue = credNew? NEW_CRED: (agent?.credential_id ?? ORG_DEFAULT)- // Show Managed when it's available, or when this agent already runs Managed (so the- // current value renders even if availability later changes). It carries no provider.- const showManaged = managedAvailable || agent?.credential_id === MANAGED+ // Managed is always offered (every org carries a managed credential); it has no provider.const credOptions = [{ value: ORG_DEFAULT, label: 'Org default (no pinned credential)' },- ...(showManaged- ? [{ value: MANAGED, label: 'Managed · billed to credits' }]- : []),+ { value: MANAGED, label: 'Managed · billed to credits' },...providerCreds.map((c) => ({ value: c.id, label: credLabel(c.id) })),{ value: NEW_CRED, label: '+ New credential…' },]diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsxindex 9b51a5e0..737a6943 100644--- a/web/src/pages/Agents.tsx+++ b/web/src/pages/Agents.tsx@@ -8,7 +8,6 @@ import {createAgent,getCredentials,createCredential,- getBilling,type Agent,} from '@/api/client'import { PageHeader } from '@/components/page-header'@@ -51,10 +50,6 @@ export default function Agents() {queryKey: ['credentials'],queryFn: getCredentials,})- // Managed availability gates the "Managed" picker entry (the single authority —- // token-billing §6.6/§6.8.C). Absent/false → only BYO credentials are offered.- const { data: billing } = useQuery({ queryKey: ['billing'], queryFn: getBilling })- const managedAvailable = billing?.managedAvailable ?? falseconst [showCreate, setShowCreate] = useState(false)const [name, setName] = useState('')const [prompt, setPrompt] = useState('')@@ -76,10 +71,9 @@ export default function Agents() {const hasDefault = providerCreds.some((c) => c.is_default)// Lowest-friction default, mirroring backend resolution (token-billing §6.6):- // a BYO org default wins; else Managed (when available); else first BYO; else "new".+ // a BYO org default wins; else Managed (always available to every org).const defaultCredFor = (creds: typeof providerCreds) =>- creds.find((c) => c.is_default)?.id ??- (managedAvailable ? MANAGED : creds[0]?.id ?? NEW_CRED)+ creds.find((c) => c.is_default)?.id ?? MANAGEDconst resetForm = () => {setName('')@@ -114,9 +108,7 @@ export default function Agents() {// Build options: Managed (if available, billed to credits — no provider filter, it// has no provider) + this runtime's provider creds + "New credential…".const credOptions = [- ...(managedAvailable- ? [{ value: MANAGED, label: 'Managed · billed to credits' }]- : []),+ { value: MANAGED, label: 'Managed · billed to credits' },...providerCreds.map((c) => ({value: c.id,label: `${c.name || 'Unnamed'}${c.last4 ? ` ·· ${c.last4}` : ''}${