An open-source, faster Devin alternative
TypeScript
managed (slice 2, redo): provision at agent-create, drop the async machinery
Igor Zalutski189fd24d9597
diff --git a/.agents/work/managed-keys-for-everyone.md b/.agents/work/managed-keys-for-everyone.mdindex 7d272812..c88f9b63 100644--- a/.agents/work/managed-keys-for-everyone.md+++ b/.agents/work/managed-keys-for-everyone.md@@ -1,13 +1,18 @@# Managed keys for everyone — decouple Managed from billing-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.+Status: **Implemented (2026-06-29); pending review + deploy.** Slice 1 (decouple) + Slice 2+(provision at agent-create, kill `managedAvailable`). edge/web on+`feat/managed-keys-for-everyone` (PR #452); sessions-api on a companion PR. 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`.++**Design note (the path we landed on after review):** the first cut of Slice 2 used a+background reconcile **sweep** + signup hook to provision every org ahead of time. That was+async machinery whose only purpose was to avoid one cross-service call — it provisions+*eventually* (2h drain), parks errors, and offers Managed before it's provisioned. Dropped+it for **just-in-time provisioning at agent-create** (sessions-api → edge enable,+synchronous, idempotent). Agent-create is the single chokepoint both create paths flow+through, so it covers everything with no sweep, no flag, no window, no wasted keys.## 1. Objective@@ -110,12 +115,15 @@ customers (pro + active Stripe sub): **33 on legacy** (all `model_billing_status`autumn_meter.ts:61`).- **Global config first** for the budget; add a per-org `managed_budget` column only whentop-ups need to differ.-- **Enablement = make Managed an INVARIANT, not a conditional.** Every org has a managed- credential the same way every org has an Autumn customer — provisioned at org birth +- backfilled, never gated. No runtime "provision-if-needed" branch, no `managedAvailable`- flag. (Rejected: the per-org enable step, AND a lazy provision-on-first-use trigger —- both keep a fork in the hot path and a new cross-service call. Reuses the existing- `enableManagedBilling`; **no new endpoint**.)+- **Enablement = provision at AGENT CREATE (just-in-time), no flag.** When an agent is+ created with `credential: managed`, sessions-api ensures the org's OpenRouter key is+ provisioned (idempotent) before the create returns — bound before any session resolves+ it. Managed is offered to all (no `managedAvailable` flag); an org that never picks+ Managed is simply never provisioned. (Rejected: the per-org enable step; AND the+ background invariant sweep + signup hook — async machinery that only provisioned+ *eventually*, parked errors, and existed solely to dodge one cross-service call.+ Agent-create is synchronous → no window, no wasted keys, no cron. Reuses the existing+ enable route — **no new endpoint**.)## 7b. Slices@@ -125,30 +133,27 @@ 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`) — 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 signup- handler, beside the existing `createAutumnCustomer` call (`index.ts:~1251`,- best-effort — don't fail signup on a provisioning hiccup; the sweep heals it).- - **Backfill + self-heal via a reconcile sweep:** a small edge cron (mirrors the- model_meter / autumn_meter cron pattern) that ensures every org is provisioned.- Path-agnostic (also covers the Go/WorkOS `ProvisionOrgAndUser` create path → cell PG →- D1), subsumes the one-time backfill, and repairs any failed provision — with zero- hot-path code. *Step 0: verify whether the edge signup handler is the ONLY org-create- path; if it is, the org-birth hook + a one-shot backfill may suffice and the cron is- optional.*- - **Remove `managedAvailable`:** delete it from edge `/billing` (`dashboard.ts:996–1040`)- and the web (`AgentDetail.tsx`, `Agents.tsx`, `schemas.ts`) — Managed is always- offered. Must land WITH the provisioning, never before (else offer-then-fail).- - **sessions-api:** no trigger change — resolve "just works" because the credential is- always bound. (Verify `credentials.ts:328` resolve has no provider assumption.)- - **Tradeoff:** one OR key per org (free until used; $10 cap). Consistent with the- invariant choice; if key-count ever bites, fall back to lazy-at-first-use.+- **Slice 2 (provision at agent-create + kill `managedAvailable`) — DONE:**+ - **edge (PR #452):** removed the async (`runManagedProvisioner` sweep + signup hook);+ the enable route (`/internal/model-billing/enable`) now *also* accepts the scoped+ `OC_MANAGED_CRED_HMAC_SECRET` so sessions-api can call it (no new endpoint; no broad+ `CF_ADMIN_SECRET` on sessions-api; `disable` stays admin-only). `managedAvailable`+ deleted from `/billing` (`dashboard.ts`) + web (`Agents.tsx`, `AgentDetail.tsx`,+ `schemas.ts`) → Managed always offered. Copy made provider-neutral (`Managed · no key+ needed`). 26 edge tests + edge/web tsc green.+ - **sessions-api (companion PR):** `ensureManagedProvisioned(owner)`+ (`core/credentials.ts`) — if the org has no managed credential, sign the enable call+ with `OC_MANAGED_CRED_HMAC_SECRET` (scheme `${ts}.${body}`, `X-Timestamp`/`X-Signature`)+ and POST `OPENCOMPUTER_API_URL/internal/model-billing/enable`; the edge mints + binds+ back; confirm bound. Called synchronously from agent-create (`core/agents.ts`, the+ `credential: managed` branch); throws on failure so we never create a Managed agent+ that can't run. Idempotent. tsc green.+ - **Must deploy together** — flag removal (edge/web) + agent-create provisioning+ (sessions-api) are one rollout, else Managed is offered but unprovisioned.+ - **No backfill needed** — existing orgs provision when they next create a Managed+ agent; no existing Managed agents sit on unprovisioned orgs (only `2f9094d9` had it).+ - **Open:** P2 legacy→autumn upgrade should baseline `committed_micro` at the provider+ flip (`autumn_webhook`) so prior fixed-budget usage isn't retro-debited. Not yet done.## 8. Non-goalsdiff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 69580c0f..a6300da1 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, runManagedProvisioner } from "./model_billing";+import { disableManagedBilling, enableManagedBilling } from "./model_billing";import { runModelMeter } from "./model_meter";import * as secretStores from "./secret_stores";import * as snapshots from "./snapshots";@@ -1265,12 +1265,6 @@ 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@@ -1810,8 +1804,15 @@ export default {const ts = req.headers.get("X-Timestamp") ?? "";const sig = req.headers.get("X-Signature") ?? "";const body = await req.text();- const expected = await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${body}`);- if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);+ // CF_ADMIN_SECRET authorizes both ops. `enable` is additionally accepted with the+ // scoped OC_MANAGED_CRED_HMAC_SECRET, so sessions-api can ensure-provision at+ // agent-create without holding the broad admin secret. `disable` stays admin-only.+ const adminOk = constantTimeEqual(await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${body}`), sig);+ const managedOk =+ path === "/internal/model-billing/enable" && env.OC_MANAGED_CRED_HMAC_SECRET+ ? constantTimeEqual(await hmacHex(env.OC_MANAGED_CRED_HMAC_SECRET, `${ts}.${body}`), sig)+ : false;+ if (!adminOk && !managedOk) return json({ error: "signature mismatch" }, 401);if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300) return json({ error: "timestamp out of window" }, 401);const parsed = JSON.parse(body) as { org_id?: string };if (!parsed.org_id) return json({ error: "org_id required" }, 400);@@ -2142,23 +2143,13 @@ export default {// key's spend → debit Autumn `model_spend` → push the markup-correct cap + halt.// Dormant unless OPENROUTER_PROVISIONING_KEY is set + managed keys exist.async scheduled(_event: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {- // Autumn meter + the credit-debiting model meter are Autumn-specific.- if (env.AUTUMN_SECRET_KEY) {- ctx.waitUntil(- runAutumnMeter(env, Date.now()).catch((err) => console.error("autumn-meter: run failed", err)),- );- if (env.OPENROUTER_PROVISIONING_KEY) {- ctx.waitUntil(- runModelMeter(env, Date.now()).catch((err) => console.error("model-meter: run failed", err)),- );- }- }- // Managed provisioning is OpenRouter-only (decoupled from billing) — it must run- // even where Autumn is absent or disabled. Keeps Managed an invariant: drains any org- // without a managed credential (backfill + new orgs from any path + failed provisions).+ if (!env.AUTUMN_SECRET_KEY) return;+ ctx.waitUntil(+ runAutumnMeter(env, Date.now()).catch((err) => console.error("autumn-meter: run failed", err)),+ );if (env.OPENROUTER_PROVISIONING_KEY) {ctx.waitUntil(- runManagedProvisioner(env).catch((err) => console.error("managed-provisioner: run failed", err)),+ runModelMeter(env, Date.now()).catch((err) => console.error("model-meter: run failed", err)),);}},diff --git a/cloudflare-workers/api-edge/src/model_billing.test.ts b/cloudflare-workers/api-edge/src/model_billing.test.tsindex 342405f2..4df7901c 100644--- a/cloudflare-workers/api-edge/src/model_billing.test.ts+++ b/cloudflare-workers/api-edge/src/model_billing.test.ts@@ -9,7 +9,6 @@ import {import {disableManagedBilling,enableManagedBilling,- runManagedProvisioner,type ManagedModelKeyRow,type ModelBillingEnv,ownerIdForOrg,@@ -67,14 +66,6 @@ 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: [] };}@@ -376,22 +367,3 @@ describe("disableManagedBilling (rollback / hard offboard)", () => {});});-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 bed9df00..8109f12d 100644--- a/cloudflare-workers/api-edge/src/model_billing.ts+++ b/cloudflare-workers/api-edge/src/model_billing.ts@@ -409,35 +409,6 @@ 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 OR