Skip to content

An open-source, faster Devin alternative

TypeScript

token-billing step 1 (edge): managed OpenRouter key lifecycle + state

Igor Zalutskidfd605687ccc
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 09e4f661..268915f7 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -26,6 +26,7 @@ import {
createAutumnCustomer,
} from "./autumn_webhook";
import { runAutumnMeter } from "./autumn_meter";
+import { disableManagedBilling, enableManagedBilling } from "./model_billing";
import * as secretStores from "./secret_stores";
import * as snapshots from "./snapshots";
import * as templates from "./templates";
@@ -56,6 +57,14 @@ export interface Env extends DashboardEnv {
// as the API key so /v3 sandboxes are owned by + billed to the customer org.
// Unset → the feature is inert (JWT keys rejected). See dashboard.ts.
OC_PROVISION_SECRET?: string;
+ // Token / model-usage billing (token-billing.md). The edge holds ONE OpenRouter
+ // secret — a management/provisioning key — and mints per-org inference keys.
+ OPENROUTER_PROVISIONING_KEY: string;
+ OPENROUTER_BASE_URL?: string; // default https://openrouter.ai/api/v1
+ OPENROUTER_MARKUP_BPS?: string; // env-default markup (bps) when the org's is 0
+ // DEDICATED HMAC secret for handing a freshly-minted OR key to sessions-api
+ // (NOT the generic internal-auth — this route carries a live model key). §6.7.5.
+ OC_MANAGED_CRED_HMAC_SECRET: string;
}
// ── small helpers ────────────────────────────────────────────────────────
@@ -1767,6 +1776,37 @@ export default {
return new Response(await r.text(), { status: r.status, headers: { "content-type": "application/json" } });
}
+ // /internal/model-billing/enable|disable — operator-triggered managed-billing
+ // provisioning for one autumn org (token-billing §5.1). HMAC-auth'd with the
+ // shared CF_ADMIN_SECRET (same scheme as do-mark-free). Body: { org_id }. Not
+ // UI-exposed; the driver for controlled rollout + tests until an automatic
+ // enable trigger lands. `enable` drives off→provisioning→active idempotently
+ // (safe to re-call to resume a partial provision); `disable` marks the org's
+ // key for drain + offboard.
+ if (
+ (path === "/internal/model-billing/enable" || path === "/internal/model-billing/disable") &&
+ req.method === "POST"
+ ) {
+ 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);
+ 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);
+ try {
+ if (path === "/internal/model-billing/disable") {
+ await disableManagedBilling(env, parsed.org_id);
+ return json({ ok: true });
+ }
+ const res = await enableManagedBilling(env, parsed.org_id);
+ return json(res, res.status === "active" ? 200 : 500);
+ } catch (e) {
+ return json({ error: e instanceof Error ? e.message : String(e) }, 500);
+ }
+ }
+
// /internal/secret-stores/:id — HMAC-auth'd, called by CP at sandbox-create
// time to materialize the encrypted entry list. CP decrypts with the
// shared SECRET_ENCRYPTION_KEY before injecting into worker env.
diff --git a/cloudflare-workers/api-edge/src/model_billing.test.ts b/cloudflare-workers/api-edge/src/model_billing.test.ts
new file mode 100644
index 00000000..27a119a5
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/model_billing.test.ts
@@ -0,0 +1,315 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ createOrKey,
+ deleteOrKey,
+ getOrKey,
+ OpenRouterError,
+ patchOrKey,
+} from "./openrouter";
+import {
+ enableManagedBilling,
+ type ManagedModelKeyRow,
+ type ModelBillingEnv,
+ ownerIdForOrg,
+} from "./model_billing";
+
+// ── in-memory D1 fake tailored to model_billing's queries ───────────────────
+
+interface OrgRow {
+ id: string;
+ billing_provider: string;
+ model_billing_status: string;
+ model_markup_bps: number;
+}
+
+class FakeDb {
+ orgs = new Map<string, OrgRow>();
+ keys: ManagedModelKeyRow[] = [];
+
+ prepare(sql: string) {
+ return new FakeStmt(this, sql);
+ }
+}
+
+class FakeStmt {
+ private args: unknown[] = [];
+ constructor(
+ private db: FakeDb,
+ private sql: string,
+ ) {}
+ bind(...args: unknown[]) {
+ this.args = args;
+ return this;
+ }
+
+ async first<T>(): Promise<T | null> {
+ const s = this.sql;
+ if (s.includes("FROM orgs")) {
+ return (this.db.orgs.get(this.args[0] as string) ?? null) as T | null;
+ }
+ if (s.includes("FROM managed_model_keys")) {
+ const orgId = this.args[0] as string;
+ let rows = this.db.keys.filter((k) => k.org_id === orgId && k.status === "active");
+ if (s.includes("or_key_hash IS NOT NULL")) {
+ rows = rows.filter((k) => k.or_key_hash !== null && k.managed_credential_id !== null);
+ }
+ rows.sort((a, b) => b.created_at - a.created_at);
+ return (rows[0] ?? null) as T | null;
+ }
+ return null;
+ }
+
+ async run(): Promise<void> {
+ const s = this.sql;
+ if (s.startsWith("UPDATE orgs SET model_billing_status")) {
+ const org = this.db.orgs.get(this.args[1] as string);
+ if (org) org.model_billing_status = this.args[0] as string;
+ return;
+ }
+ if (s.startsWith("INSERT INTO managed_model_keys")) {
+ const [id, org_id, operation_id, created_at] = this.args as [string, string, string, number];
+ this.db.keys.push({
+ id,
+ org_id,
+ or_key_hash: null,
+ managed_credential_id: null,
+ operation_id,
+ status: "active",
+ committed_micro: 0,
+ pending_from_micro: null,
+ pending_to_micro: null,
+ pending_idem: null,
+ attempts: 0,
+ last_error: null,
+ created_at,
+ superseded_at: null,
+ });
+ return;
+ }
+ if (s.startsWith("UPDATE managed_model_keys SET")) {
+ // parse "SET a = ?1, b = ?2 WHERE id = ?N"
+ const setClause = s.slice(s.indexOf("SET ") + 4, s.indexOf(" WHERE"));
+ const cols = setClause.split(",").map((c) => c.trim().split(" ")[0]);
+ const id = this.args[this.args.length - 1] as string;
+ const row = this.db.keys.find((k) => k.id === id);
+ if (row) cols.forEach((c, i) => ((row as Record<string, unknown>)[c] = this.args[i]));
+ return;
+ }
+ throw new Error(`FakeStmt: unhandled run() sql: ${s}`);
+ }
+}
+
+// ── fetch router: OpenRouter + Autumn + sessions-api ────────────────────────
+
+interface RouterOpts {
+ remainingCredits?: number; // Autumn balance
+ lookupCredId?: string | null; // GET /internal/managed-credential result
+ createdHash?: string;
+}
+
+function makeFetch(opts: RouterOpts = {}) {
+ const calls: { url: string; method: string; body: unknown }[] = [];
+ const spy = vi.fn(async (url: string, init?: RequestInit) => {
+ const method = init?.method ?? "GET";
+ const body = init?.body ? JSON.parse(init.body as string) : undefined;
+ calls.push({ url, method, body });
+
+ // Autumn getAutumnCustomer
+ if (url.includes("/customers/")) {
+ return new Response(
+ JSON.stringify({ id: "x", balances: { credits: { remaining: opts.remainingCredits ?? 5 } } }),
+ { status: 200 },
+ );
+ }
+ // OpenRouter create / get / patch / delete keys
+ if (url.includes("/keys")) {
+ if (method === "POST") {
+ return new Response(
+ JSON.stringify({ key: "sk-or-test-PLAINTEXT", data: { hash: opts.createdHash ?? "hash-abc", limit: body?.limit, usage: 0, disabled: false } }),
+ { status: 200 },
+ );
+ }
+ if (method === "DELETE") return new Response("", { status: 200 });
+ if (method === "PATCH") return new Response(JSON.stringify({ data: { hash: "hash-abc", limit: body?.limit } }), { status: 200 });
+ return new Response(JSON.stringify({ data: { hash: "hash-abc", usage: 0.5, limit: 5, disabled: false } }), { status: 200 });
+ }
+ // sessions-api hand-off
+ if (url.includes("/internal/managed-credential")) {
+ if (method === "POST") return new Response(JSON.stringify({ managed_credential_id: "cred_bound" }), { status: 200 });
+ // GET lookup
+ return new Response(JSON.stringify({ managed_credential_id: opts.lookupCredId ?? null }), { status: 200 });
+ }
+ throw new Error(`unexpected fetch: ${method} ${url}`);
+ });
+ return { spy, calls };
+}
+
+function makeEnv(db: FakeDb): ModelBillingEnv {
+ return {
+ OPENCOMPUTER_DB: db as unknown as D1Database,
+ OPENROUTER_PROVISIONING_KEY: "or-mgmt-key",
+ OPENROUTER_BASE_URL: "https://or.test/api/v1",
+ AUTUMN_SECRET_KEY: "autumn-key",
+ AUTUMN_BASE_URL: "https://autumn.test/v1",
+ SESSIONS_API_URL: "https://sa.test",
+ OC_MANAGED_CRED_HMAC_SECRET: "hmac-secret",
+ };
+}
+
+function seedOrg(db: FakeDb, over: Partial<OrgRow> = {}): string {
+ const id = over.id ?? "org1";
+ db.orgs.set(id, {
+ id,
+ billing_provider: "autumn",
+ model_billing_status: "off",
+ model_markup_bps: 0,
+ ...over,
+ });
+ return id;
+}
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe("openrouter client", () => {
+ it("createOrKey sends name+limit+null reset, returns plaintext once", async () => {
+ const { spy, calls } = makeFetch();
+ vi.stubGlobal("fetch", spy);
+ const out = await createOrKey(makeEnv(new FakeDb()), { name: "oc-org-x", limitUsd: 4.2 });
+ expect(out.key).toBe("sk-or-test-PLAINTEXT");
+ expect(out.data.hash).toBe("hash-abc");
+ expect(calls[0].body).toMatchObject({ name: "oc-org-x", limit: 4.2, limit_reset: null });
+ });
+
+ it("getOrKey unwraps data envelope", async () => {
+ vi.stubGlobal("fetch", makeFetch().spy);
+ const k = await getOrKey(makeEnv(new FakeDb()), "hash-abc");
+ expect(k.usage).toBe(0.5);
+ });
+
+ it("patchOrKey maps limitUsd→limit", async () => {
+ const { spy, calls } = makeFetch();
+ vi.stubGlobal("fetch", spy);
+ await patchOrKey(makeEnv(new FakeDb()), "hash-abc", { limitUsd: 9 });
+ expect(calls[0].method).toBe("PATCH");
+ expect(calls[0].body).toMatchObject({ limit: 9 });
+ });
+
+ it("deleteOrKey swallows 404", async () => {
+ const spy = vi.fn(async () => new Response("gone", { status: 404 }));
+ vi.stubGlobal("fetch", spy);
+ await expect(deleteOrKey(makeEnv(new FakeDb()), "h")).resolves.toBeUndefined();
+ });
+
+ it("throws OpenRouterError with op+status on failure", async () => {
+ const spy = vi.fn(async () => new Response("nope", { status: 401 }));
+ vi.stubGlobal("fetch", spy);
+ await expect(getOrKey(makeEnv(new FakeDb()), "h")).rejects.toMatchObject({
+ name: "OpenRouterError",
+ op: "get_key",
+ status: 401,
+ });
+ });
+});
+
+describe("enableManagedBilling state machine", () => {
+ it("off → active: mints key, binds credential, flips org", async () => {
+ const db = new FakeDb();
+ const orgId = seedOrg(db);
+ const { spy, calls } = makeFetch({ remainingCredits: 5 });
+ vi.stubGlobal("fetch", spy);
+
+ const res = await enableManagedBilling(makeEnv(db), orgId);
+
+ expect(res).toEqual({ status: "active", credentialId: "cred_bound" });
+ expect(db.orgs.get(orgId)!.model_billing_status).toBe("active");
+ const row = db.keys.find((k) => k.org_id === orgId)!;
+ expect(row.or_key_hash).toBe("hash-abc");
+ expect(row.managed_credential_id).toBe("cred_bound");
+
+ // OR key created with limit = remaining/(1+markup) = 5/1 = 5
+ const create = calls.find((c) => c.url.endsWith("/keys") && c.method === "POST")!;
+ expect(create.body).toMatchObject({ name: `oc-org-${orgId}`, limit: 5 });
+ // hand-off carries owner=oc-org:..., provider openrouter, the plaintext + ids
+ const bind = calls.find((c) => c.url.includes("/internal/managed-credential") && c.method === "POST")!;
+ expect(bind.body).toMatchObject({
+ owner_id: ownerIdForOrg(orgId),
+ provider: "openrouter",
+ key: "sk-or-test-PLAINTEXT",
+ or_key_hash: "hash-abc",
+ });
+ expect((bind.body as { operation_id: string }).operation_id).toMatch(/^op_/);
+ });
+
+ it("applies markup to the initial cap (remaining / (1+bps))", async () => {
+ const db = new FakeDb();
+ const orgId = seedOrg(db, { model_markup_bps: 2000 }); // +20%
+ const { spy, calls } = makeFetch({ remainingCredits: 6 });
+ vi.stubGlobal("fetch", spy);
+
+ await enableManagedBilling(makeEnv(db), orgId);
+ const create = calls.find((c) => c.url.endsWith("/keys") && c.method === "POST")!;
+ expect((create.body as { limit: number }).limit).toBeCloseTo(6 / 1.2, 5); // 5.0
+ });
+
+ it("refuses non-autumn orgs", async () => {
+ const db = new FakeDb();
+ const orgId = seedOrg(db, { billing_provider: "legacy" });
+ vi.stubGlobal("fetch", makeFetch().spy);
+ await expect(enableManagedBilling(makeEnv(db), orgId)).rejects.toThrow(/not autumn/);
+ expect(db.orgs.get(orgId)!.model_billing_status).not.toBe("active");
+ });
+
+ it("is idempotent: a complete active row re-call mints nothing new", async () => {
+ const db = new FakeDb();
+ const orgId = seedOrg(db, { model_billing_status: "active" });
+ db.keys.push({
+ id: "mmk_1", org_id: orgId, or_key_hash: "hash-old", managed_credential_id: "cred_old",
+ operation_id: "op_1", status: "active", committed_micro: 0, pending_from_micro: null,
+ pending_to_micro: null, pending_idem: null, attempts: 0, last_error: null, created_at: 1, superseded_at: null,
+ });
+ const { spy, calls } = makeFetch();
+ vi.stubGlobal("fetch", spy);
+
+ const res = await enableManagedBilling(makeEnv(db), orgId);
+ expect(res).toEqual({ status: "active", credentialId: "cred_old" });
+ expect(calls.find((c) => c.method === "POST" && c.url.endsWith("/keys"))).toBeUndefined(); // no new key
+ expect(db.keys.length).toBe(1);
+ });
+
+ it("lost-bind recovery: adopts an already-bound credential without recreating", async () => {
+ const db = new FakeDb();
+ const orgId = seedOrg(db, { model_billing_status: "provisioning" });
+ db.keys.push({
+ id: "mmk_1", org_id: orgId, or_key_hash: "hash-x", managed_credential_id: null,
+ operation_id: "op_1", status: "active", committed_micro: 0, pending_from_micro: null,
+ pending_to_micro: null, pending_idem: null, attempts: 0, last_error: null, created_at: 1, superseded_at: null,
+ });
+ const { spy, calls } = makeFetch({ lookupCredId: "cred_recovered" });
+ vi.stubGlobal("fetch", spy);
+
+ const res = await enableManagedBilling(makeEnv(db), orgId);
+ expect(res.status).toBe("active");
+ expect(db.keys[0].managed_credential_id).toBe("cred_recovered");
+ expect(calls.find((c) => c.method === "POST" && c.url.endsWith("/keys"))).toBeUndefined(); // no recreate
+ expect(calls.find((c) => c.url.includes("/internal/managed-credential") && c.method === "GET")).toBeTruthy();
+ });
+
+ it("lost-bind recovery: deletes the orphan key + recreates when no credential is bound", async () => {
+ const db = new FakeDb();
+ const orgId = seedOrg(db, { model_billing_status: "provisioning" });
+ db.keys.push({
+ id: "mmk_1", org_id: orgId, or_key_hash: "hash-orphan", managed_credential_id: null,
+ operation_id: "op_1", status: "active", committed_micro: 0, pending_from_micro: null,
+ pending_to_micro: null, pending_idem: null, attempts: 0, last_error: null, created_at: 1, superseded_at: null,
+ });
+ const { spy, calls } = makeFetch({ lookupCredId: null, createdHash: "hash-new" });
+ vi.stubGlobal("fetch", spy);
+
+ const res = await enableManagedBilling(makeEnv(db), orgId);
+ expect(res.status).toBe("active");
+ expect(calls.find((c) => c.method === "DELETE")).toBeTruthy(); // orphan deleted
+ expect(calls.find((c) => c.method === "POST" && c.url.endsWith("/keys"))).toBeTruthy(); // recreated
+ expect(db.keys[0].or_key_hash).toBe("hash-new");
+ expect(db.keys[0].managed_credential_id).toBe("cred_bound");
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/model_billing.ts b/cloudflare-workers/api-edge/src/model_billing.ts
new file mode 100644
index 00000000..f1de348c
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/model_billing.ts
@@ -0,0 +1,372 @@
+// Token / model-usage billing — provisioning state machine + the edge→sessions-api
+// key hand-off (design: .agents/work/token-billing.md §5.1, §6.7.5). The edge owns
+// the whole OpenRouter lifecycle (Autumn/OR are edge-native); this module drives one
+// managed org from `model_billing_status` off → provisioning → active, minting a
+// per-org OR key and binding it to a sessions-api credential.
+//
+// The metering cron (model_meter, §5.4) is a separate file (step 3); this is step 1:
+// the key lifecycle + per-org state only.
+
+import { type AutumnApiEnv, getAutumnCustomer } from "./autumn_webhook";
+import {
+ createOrKey,
+ deleteOrKey,
+ type OpenRouterEnv,
+} from "./openrouter";
+
+export interface ModelBillingEnv extends OpenRouterEnv, AutumnApiEnv {
+ OPENCOMPUTER_DB: D1Database;
+ // sessions-api base URL (shared with the dashboard /v3 proxy). Default = prod.
+ SESSIONS_API_URL?: string;
+ // DEDICATED HMAC secret for the plaintext-key hand-off (§6.7.5 / P2-f). NOT the
+ // generic internal-auth secret — this route carries a live model key. Shared
+ // only with sessions-api.
+ OC_MANAGED_CRED_HMAC_SECRET: string;
+ // Optional env-default markup (basis points) when the org row's is 0. Org wins.
+ OPENROUTER_MARKUP_BPS?: string;
+}
+
+// Bounded retries before parking the org in 'error' (§5.1).
+const MAX_PROVISION_ATTEMPTS = 5;
+// Accepted clock skew on the hand-off HMAC (replay window, §6.7.5).
+const HANDOFF_SKEW_SEC = 60;
+const DEFAULT_SESSIONS_API = "https://api.opencomputer.dev";
+const HANDOFF_PATH = "/internal/managed-credential";
+
+export type ManagedKeyStatus = "active" | "superseded" | "deleting";
+
+export interface ManagedModelKeyRow {
+ id: string;
+ org_id: string;
+ or_key_hash: string | null;
+ managed_credential_id: string | null;
+ operation_id: string | null;
+ status: ManagedKeyStatus;
+ committed_micro: number;
+ pending_from_micro: number | null;
+ pending_to_micro: number | null;
+ pending_idem: string | null;
+ attempts: number;
+ last_error: string | null;
+ created_at: number;
+ superseded_at: number | null;
+}
+
+interface OrgBillingRow {
+ id: string;
+ billing_provider: string;
+ model_billing_status: string;
+ model_markup_bps: number;
+}
+
+// sessions-api owner id for an OC org. MUST match sessions-api's ownerIdForOrg
+// (src/v3/auth/org-token.ts) — the managed credential is stored + resolved under it.
+export function ownerIdForOrg(orgId: string): string {
+ return "oc-org:" + orgId;
+}
+
+// Stable, human-greppable OR key name (also our reconcile anchor). One per org.
+function orKeyName(orgId: string): string {
+ return `oc-org-${orgId}`;
+}
+
+function newRowId(): string {
+ return "mmk_" + crypto.randomUUID().replace(/-/g, "");
+}
+function newOperationId(): string {
+ return "op_" + crypto.randomUUID().replace(/-/g, "");
+}
+
+function markupBps(env: ModelBillingEnv, org: OrgBillingRow): number {
+ if (org.model_markup_bps && org.model_markup_bps > 0) return org.model_markup_bps;
+ const envDefault = parseInt(env.OPENROUTER_MARKUP_BPS ?? "", 10);
+ return Number.isFinite(envDefault) && envDefault > 0 ? envDefault : 0;
+}
+
+// ── D1 access ──────────────────────────────────────────────────────────────
+
+async function getOrg(env: ModelBillingEnv, orgId: string): Promise<OrgBillingRow | null> {
+ return env.OPENCOMPUTER_DB.prepare(
+ "SELECT id, billing_provider, model_billing_status, model_markup_bps FROM orgs WHERE id = ?1",
+ )
+ .bind(orgId)
+ .first<OrgBillingRow>();
+}
+
+async function setOrgStatus(env: ModelBillingEnv, orgId: string, status: string): Promise<void> {
+ await env.OPENCOMPUTER_DB.prepare("UPDATE orgs SET model_billing_status = ?1 WHERE id = ?2")
+ .bind(status, orgId)
+ .run();
+}
+
+// The org's resumable provisioning row: its single non-deleting key. (Normally one
+// 'active'; a 'superseded' is a rotation we don't resume here.)
+async function getResumableRow(env: ModelBillingEnv, orgId: string): Promise<ManagedModelKeyRow | null> {
+ return env.OPENCOMPUTER_DB.prepare(
+ "SELECT * FROM managed_model_keys WHERE org_id = ?1 AND status = 'active' ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(orgId)
+ .first<ManagedModelKeyRow>();
+}
+
+export async function getActiveKeyRow(env: ModelBillingEnv, orgId: string): Promise<ManagedModelKeyRow | null> {
+ return env.OPENCOMPUTER_DB.prepare(
+ "SELECT * FROM managed_model_keys WHERE org_id = ?1 AND status = 'active' AND or_key_hash IS NOT NULL AND managed_credential_id IS NOT NULL ORDER BY created_at DESC LIMIT 1",
+ )
+ .bind(orgId)
+ .first<ManagedModelKeyRow>();
+}
+
+async function insertRow(env: ModelBillingEnv, row: { id: string; orgId: string; operationId: string; createdAt: number }): Promise<ManagedModelKeyRow> {
+ await env.OPENCOMPUTER_DB.prepare(
+ "INSERT INTO managed_model_keys (id, org_id, operation_id, status, committed_micro, attempts, created_at) VALUES (?1, ?2, ?3, 'active', 0, 0, ?4)",
+ )
+ .bind(row.id, row.orgId, row.operationId, row.createdAt)
+ .run();
+ return {
+ id: row.id,
+ org_id: row.orgId,
+ or_key_hash: null,
+ managed_credential_id: null,
+ operation_id: row.operationId,
+ status: "active",
+ committed_micro: 0,
+ pending_from_micro: null,
+ pending_to_micro: null,
+ pending_idem: null,
+ attempts: 0,
+ last_error: null,
+ created_at: row.createdAt,
+ superseded_at: null,
+ };
+}
+
+// Targeted column updates. `or_key_hash`/`managed_credential_id` accept null so the
+// recover-by-delete path (lost plaintext) can clear the hash before recreating.
+async function updateRow(
+ env: ModelBillingEnv,
+ id: string,
+ fields: Partial<Pick<ManagedModelKeyRow, "or_key_hash" | "managed_credential_id" | "status" | "attempts" | "last_error" | "superseded_at">>,
+): Promise<void> {
+ const sets: string[] = [];
+ const vals: unknown[] = [];
+ for (const [k, v] of Object.entries(fields)) {
+ sets.push(`${k} = ?${sets.length + 1}`);
+ vals.push(v);
+ }
+ if (sets.length === 0) return;
+ vals.push(id);
+ await env.OPENCOMPUTER_DB.prepare(`UPDATE managed_model_keys SET ${sets.join(", ")} WHERE id = ?${vals.length}`)
+ .bind(...vals)
+ .run();
+}
+
+// ── Autumn balance → initial OR cap ─────────────────────────────────────────
+
+async function remainingCreditsUsd(env: ModelBillingEnv, orgId: string): Promise<number> {
+ const cust = await getAutumnCustomer(env, orgId);
+ const remaining = cust?.balances?.credits?.remaining;
+ return typeof remaining === "number" ? remaining : 0;
+}
+
+// Initial provider-spend cap = remaining / (1+markup) so the Autumn balance is the
+// hard customer budget even with markup (§7). usage=0 at provision time.
+function initialCapUsd(remainingUsd: number, bps: number): number {
+ return Math.max(0, remainingUsd / (1 + bps / 10000));
+}
+
+// ── edge → sessions-api hand-off (HMAC, §6.7.5) ─────────────────────────────
+
+async function hmacHex(secret: string, data: string): Promise<string> {
+ const key = await crypto.subtle.importKey(
+ "raw",
+ new TextEncoder().encode(secret),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign"],
+ );
+ const mac = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));
+ return [...new Uint8Array(mac)].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+// Signs `${ts}.${method}.${path}.${body}` (path includes query) and calls
+// sessions-api. Returns the parsed JSON. `path` must start with HANDOFF_PATH.
+async function signedHandoff(
+ env: ModelBillingEnv,
+ method: "POST" | "GET",
+ path: string,
+ body: string,
+): Promise<unknown> {
+ if (!env.OC_MANAGED_CRED_HMAC_SECRET) {
+ throw new Error("model-billing: OC_MANAGED_CRED_HMAC_SECRET unset — refusing hand-off");
+ }
+ const base = (env.SESSIONS_API_URL ?? DEFAULT_SESSIONS_API).replace(/\/+$/, "");
+ const ts = Math.floor(Date.now() / 1000).toString();
+ const sig = await hmacHex(env.OC_MANAGED_CRED_HMAC_SECRET, `${ts}.${method}.${path}.${body}`);
+ const resp = await fetch(`${base}${path}`, {
+ method,
+ headers: {
+ "content-type": "application/json",
+ "x-oc-managed-ts": ts,
+ "x-oc-managed-sig": sig,
+ },
+ body: method === "GET" ? undefined : body,
+ });
+ const text = await resp.text();
+ if (!resp.ok) throw new Error(`managed-credential ${method} ${resp.status}: ${text.slice(0, 200)}`);
+ return text ? JSON.parse(text) : null;
+}
+
+// Hand the freshly-minted plaintext OR key to sessions-api to seal. Idempotent per
+// (owner_id, operation_id): a re-call rotates rather than duplicates. Returns the
+// managed_credential_id. The plaintext is NEVER persisted on the edge.
+async function bindManagedCredential(
+ env: ModelBillingEnv,
+ p: { ownerId: string; orKeyHash: string; operationId: string; key: string },
+): Promise<string> {
+ const body = JSON.stringify({
+ owner_id: p.ownerId,
+ provider: "openrouter",
+ key: p.key,
+ or_key_hash: p.orKeyHash,
+ operation_id: p.operationId,
+ });
+ const out = (await signedHandoff(env, "POST", HANDOFF_PATH, body)) as { managed_credential_id?: string };
+ if (!out?.managed_credential_id) throw new Error("managed-credential POST: no managed_credential_id in response");
+ return out.managed_credential_id;
+}
+
+// Lost-response recovery (§5.1): is a managed credential already bound for this
+// (owner, or_key_hash)? Returns its id, or null if not bound (plaintext is gone →
+// caller must delete + recreate the OR key).
+async function lookupManagedCredential(
+ env: ModelBillingEnv,
+ p: { ownerId: string; orKeyHash: string },
+): Promise<string | null> {
+ const qs = `?owner_id=${encodeURIComponent(p.ownerId)}&or_key_hash=${encodeURIComponent(p.orKeyHash)}`;
+ const out = (await signedHandoff(env, "GET", HANDOFF_PATH + qs, "")) as { managed_credential_id?: string | null };
+ return out?.managed_credential_id ?? null;
+}
+
+// ── the state machine ───────────────────────────────────────────────────────
+
+export interface EnableResult {
+ status: "active" | "error";
+ credentialId?: string;
+}
+
+// enableManagedBilling drives one autumn org off→provisioning→active, idempotently.
+// Safe to re-invoke: it resumes from persisted state (insert → create OR key → bind
+// → flip), repairing partial failures (§5.1 partial-failure repair).
+export async function enableManagedBilling(env: ModelBillingEnv, orgId: string): Promise<EnableResult> {
+ const org = await getOrg(env, orgId);
+ if (!org) throw new Error(`model-billing: org ${orgId} not found`);
+ // Managed billing is autumn-only (§3 invariant 6).
+ if (org.billing_provider !== "autumn") {
+ throw new Error(`model-billing: org ${orgId} is '${org.billing_provider}', not autumn — refusing`);
+ }
+
+ await setOrgStatus(env, orgId, "provisioning");
+
+ let row = await getResumableRow(env, orgId);
+ if (!row) {
+ row = await insertRow(env, {
+ id: newRowId(),
+ orgId,
+ operationId: newOperationId(),
+ createdAt: Math.floor(Date.now() / 1000),
+ });
+ }
+ return driveProvisioning(env, org, row);
+}
+
+async function driveProvisioning(env: ModelBillingEnv, org: OrgBillingRow, row: ManagedModelKeyRow): Promise<EnableResult> {
+ try {
+ // Step 2: mint the OR key (once). Persist the hash before binding so a lost
+ // bind response is recoverable.
+ if (!row.or_key_hash) {
+ const remaining = await remainingCreditsUsd(env, org.id);
+ const limitUsd = initialCapUsd(remaining, markupBps(env, org));
+ const created = await createOrKey(env, { name: orKeyName(org.id), limitUsd });
+ await updateRow(env, row.id, { or_key_hash: created.data.hash, attempts: 0, last_error: null });
+ row.or_key_hash = created.data.hash;
+
+ // Step 3: hand the plaintext to sessions-api immediately (still in memory,
+ // never persisted). On success persist the credential id.
+ const credId = await bindManagedCredential(env, {
+ ownerId: ownerIdForOrg(org.id),
+ orKeyHash: created.data.hash,
+ operationId: row.operation_id!,
+ key: created.key,
+ });
+ await updateRow(env, row.id, { managed_credential_id: credId });
+ row.managed_credential_id = credId;
+ } else if (!row.managed_credential_id) {
+ // Step 3 recovery: the OR key exists but the bind never completed (its
+ // response was lost, or it crashed before persisting). The plaintext is
+ // one-time and gone, so we CANNOT re-send. Look it up; adopt if bound, else
+ // delete the orphan key and recreate from step 2.
+ const existing = await lookupManagedCredential(env, {
+ ownerId: ownerIdForOrg(org.id),
+ orKeyHash: row.or_key_hash,
+ });
+ if (existing) {
+ await updateRow(env, row.id, { managed_credential_id: existing });
+ row.managed_credential_id = existing;
+ } else {
+ await deleteOrKey(env, row.or_key_hash);
+ await updateRow(env, row.id, { or_key_hash: null });
+ row.or_key_hash = null;
+ return driveProvisioning(env, org, row);
+ }
+ }
+
+ // Step 4: flip the org active — Managed is now offered + resolvable.
+ await setOrgStatus(env, org.id, "active");
+ console.log(`model-billing: org ${org.id} active (key ${row.or_key_hash}, cred ${row.managed_credential_id})`);
+ return { status: "active", credentialId: row.managed_credential_id ?? undefined };
+ } catch (e) {
+ const attempts = row.attempts + 1;
+ const msg = e instanceof Error ? e.message : String(e);
+ await updateRow(env, row.id, { attempts, last_error: msg });
+ if (attempts >= MAX_PROVISION_ATTEMPTS) {
+ await setOrgStatus(env, org.id, "error");
+ console.error(`model-billing: org ${org.id} parked in 'error' after ${attempts} attempts: ${msg}`);
+ return { status: "error" };
+ }
+ console.error(`model-billing: org ${org.id} provisioning attempt ${attempts} failed: ${msg}`);
+ throw e;
+ }
+}
+
+// reconcileManagedBilling repairs an org whose status disagrees with its rows
+// (§5.1 / §5.7). Drives 'active' orgs back to a consistent active state and resumes
+// stuck 'provisioning' ones. Returns the resolved state.
+export async function reconcileManagedBilling(env: ModelBillingEnv, orgId: string): Promise<EnableResult> {
+ const org = await getOrg(env, orgId);
+ if (!org) throw new Error(`model-billing: org ${orgId} not found`);
+ if (org.model_billing_status === "off") return { status: "error" };
+
+ const complete = await getActiveKeyRow(env, orgId);
+ if (complete) {
+ if (org.model_billing_status !== "active") await setOrgStatus(env, orgId, "active");
+ return { status: "active", credentialId: complete.managed_credential_id ?? undefined };
+ }
+ // No complete key but status isn't off → finish provisioning.
+ return enableManagedBilling(env, orgId);
+}
+
+// disableManagedBilling marks the org's active key 'deleting' (§5.8). The metering
+// cron (step 3) keeps polling it until spend quiesces, does a final debit, then
+// DELETEs the OR key + revokes the credential, and flips the org 'off' once no
+// usable key remains. We only move state here; we do NOT delete mid-spend.
+export async function disableManagedBilling(env: ModelBillingEnv, orgId: string): Promise<void> {
+ const row = await getActiveKeyRow(env, orgId);
+ if (row) {
+ await updateRow(env, row.id, { status: "deleting" });
+ console.log(`model-billing: org ${orgId} key ${row.or_key_hash} → deleting (drain + offboard handled by cron)`);
+ } else {
+ // Nothing usable to drain → off immediately.
+ await setOrgStatus(env, orgId, "off");
+ }
+}
diff --git a/cloudflare-workers/api-edge/src/openrouter.ts b/cloudflare-workers/api-edge/src/openrouter.ts
new file mode 100644
index 00000000..110d7200
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/openrouter.ts
@@ -0,0 +1,186 @@
+// OpenRouter management-key client. The edge holds exactly ONE OpenRouter secret —
+// OPENROUTER_PROVISIONING_KEY, a *management/provisioning* key — and makes every OR
+// API call with it: mint per-org inference keys, read their cumulative spend, push
+// caps, delete on offboard, and read account analytics. The minted inference keys
+// are the per-org billing keys; their plaintext is returned by `POST /keys` exactly
+// ONCE and is never re-fetchable — the edge hands it straight to sessions-api to seal
+// (it is never persisted on the edge). This keeps the "Autumn/OR are edge-native"
+// invariant: one OR secret, in one place.
+//
+// Surfaces + behaviours verified live 2026-06-29 (§9.7 spike, token-billing.md):
+// per-key `usage` is cumulative USD and monotonic; both the Anthropic Messages and
+// the OpenAI Responses inference paths echo cost. `analytics/query` + key
+// create/list/get/patch/delete require a management key (an inference key gets 401).
+
+export interface OpenRouterEnv {
+ // A management/provisioning key (NOT an inference key). Mints + manages per-org
+ // keys and reads analytics. Stored write-only as a Cloudflare secret.
+ OPENROUTER_PROVISIONING_KEY: string;
+ // Override for tests; defaults to OpenRouter prod.
+ OPENROUTER_BASE_URL?: string;
+}
+
+const OR_DEFAULT_BASE = "https://openrouter.ai/api/v1";
+
+// A managed OR key as returned by GET/POST/PATCH /keys (the `data` envelope). The
+// plaintext key string is NOT here — it only appears once, on create, as the
+// sibling `key` field (see OpenRouterCreatedKey).
+export interface OpenRouterKey {
+ hash: string; // non-secret key id — what we persist + poll
+ name: string;
+ label?: string;
+ disabled: boolean;
+ limit: number | null; // USD spend cap; null = uncapped (we always set one)
+ limit_remaining: number | null;
+ limit_reset: string | null; // we always use null (cap managed dynamically)
+ usage: number; // cumulative USD spent on this key — monotonic, our cost of record
+ created_at?: string;
+ updated_at?: string;
+}
+
+// POST /keys response: the plaintext key (returned ONCE) + the key metadata.
+export interface OpenRouterCreatedKey {
+ key: string; // plaintext inference key — hand to sessions-api, never persist on edge
+ data: OpenRouterKey;
+}
+
+// One row of POST /analytics/query, dims [api_key_id, model] (token-billing §5.4 step 4).
+export interface OpenRouterAnalyticsRow {
+ api_key_id?: string;
+ model?: string;
+ total_usage?: number; // USD
+ tokens_prompt?: number;
+ tokens_completion?: number;
+ [k: string]: unknown;
+}
+
+// Our OR *account* float (GET /credits), monitored by reconcile (§5.7 / §8).
+export interface OpenRouterCredits {
+ total_credits: number;
+ total_usage: number;
+}
+
+// Carries the failing op + HTTP code so callers can emit
+// model_or_api_errors_total{op,http_code} without re-parsing messages (§8).
+export class OpenRouterError extends Error {
+ constructor(
+ readonly op: string,
+ readonly status: number,
+ readonly body: string,
+ ) {
+ super(`openrouter ${op} ${status}: ${body.slice(0, 300)}`);
+ this.name = "OpenRouterError";
+ }
+}
+
+async function orFetch(
+ env: OpenRouterEnv,
+ op: string,
+ method: string,
+ path: string,
+ body?: unknown,
+): Promise<unknown> {
+ const base = env.OPENROUTER_BASE_URL || OR_DEFAULT_BASE;
+ const resp = await fetch(`${base}${path}`, {
+ method,
+ headers: {
+ Authorization: `Bearer ${env.OPENROUTER_PROVISIONING_KEY}`,
+ "content-type": "application/json",
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ const text = await resp.text();
+ if (!resp.ok) throw new OpenRouterError(op, resp.status, text);
+ // OR wraps single resources in `{ data: ... }`; lists/analytics vary by endpoint.
+ return text ? JSON.parse(text) : null;
+}
+
+// createOrKey mints a per-org inference key. `limit` is the USD spend cap (the hard
+// budget — OR refuses calls past it in real time); `limit_reset:null` because we
+// manage the cap dynamically off the shared credit pool (§5.4 step 3). Returns the
+// plaintext key (once) + metadata.
+export async function createOrKey(
+ env: OpenRouterEnv,
+ p: { name: string; limitUsd: number },
+): Promise<OpenRouterCreatedKey> {
+ const out = (await orFetch(env, "create_key", "POST", "/keys", {
+ name: p.name,
+ limit: p.limitUsd,
+ limit_reset: null,
+ })) as OpenRouterCreatedKey;
+ if (!out?.key || !out?.data?.hash) {
+ throw new OpenRouterError("create_key", 200, "missing key/hash in response");
+ }
+ return out;
+}
+
+// getOrKey reads one key's cumulative usage + current cap — the billing poll (§5.4).
+export async function getOrKey(env: OpenRouterEnv, hash: string): Promise<OpenRouterKey> {
+ const out = (await orFetch(env, "get_key", "GET", `/keys/${encodeURIComponent(hash)}`)) as {
+ data: OpenRouterKey;
+ };
+ return out.data;
+}
+
+// patchOrKey pushes a new cap and/or disables the key (cap push + emergency disable, §5.4/§5.8).
+export async function patchOrKey(
+ env: OpenRouterEnv,
+ hash: string,
+ patch: { limitUsd?: number; disabled?: boolean; name?: string },
+): Promise<OpenRouterKey> {
+ const body: Record<string, unknown> = {};
+ if (patch.limitUsd !== undefined) body.limit = patch.limitUsd;
+ if (patch.disabled !== undefined) body.disabled = patch.disabled;
+ if (patch.name !== undefined) body.name = patch.name;
+ const out = (await orFetch(env, "patch_key", "PATCH", `/keys/${encodeURIComponent(hash)}`, body)) as {
+ data: OpenRouterKey;
+ };
+ return out.data;
+}
+
+// deleteOrKey offboards a key (§5.8). Idempotent-ish: a 404 means already gone.
+export async function deleteOrKey(env: OpenRouterEnv, hash: string): Promise<void> {
+ try {
+ await orFetch(env, "delete_key", "DELETE", `/keys/${encodeURIComponent(hash)}`);
+ } catch (e) {
+ if (e instanceof OpenRouterError && e.status === 404) return;
+ throw e;
+ }
+}
+
+// listOrKeys lists all keys on the account (audit / reconcile, §5.7).
+export async function listOrKeys(env: OpenRouterEnv): Promise<OpenRouterKey[]> {
+ const out = (await orFetch(env, "list_keys", "GET", "/keys")) as { data?: OpenRouterKey[] };
+ return out.data ?? [];
+}
+
+// getOrCredits reads our OR account float (§5.7 / §8 — alert when low).
+export async function getOrCredits(env: OpenRouterEnv): Promise<OpenRouterCredits> {
+ const out = (await orFetch(env, "get_credits", "GET", "/credits")) as {
+ data?: OpenRouterCredits;
+ } & Partial<OpenRouterCredits>;
+ // Some OR responses nest under `data`, some don't — accept either.
+ return (out.data ?? (out as OpenRouterCredits));
+}
+
+// queryOrAnalytics pulls per-key/per-model spend for the dashboard rollup (§5.4 step 4).
+// Management-key only. `dateFrom`/`dateTo` are ISO dates (YYYY-MM-DD).
+export async function queryOrAnalytics(
+ env: OpenRouterEnv,
+ p: {
+ dimensions: string[];
+ granularity?: string;
+ metrics?: string[];
+ dateFrom?: string;
+ dateTo?: string;
+ },
+): Promise<OpenRouterAnalyticsRow[]> {
+ const out = (await orFetch(env, "analytics_query", "POST", "/analytics/query", {
+ dimensions: p.dimensions,
+ granularity: p.granularity ?? "day",
+ metrics: p.metrics ?? ["total_usage", "tokens_prompt", "tokens_completion"],
+ ...(p.dateFrom ? { date_from: p.dateFrom } : {}),
+ ...(p.dateTo ? { date_to: p.dateTo } : {}),
+ })) as { data?: OpenRouterAnalyticsRow[] };
+ return out.data ?? [];
+}
diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.toml
index e1126e51..955ae1e1 100644
--- a/cloudflare-workers/api-edge/wrangler.prod.toml
+++ b/cloudflare-workers/api-edge/wrangler.prod.toml
@@ -56,6 +56,14 @@ new_sqlite_classes = ["CreditAccount"]
# SECRET_ENCRYPTION_KEY — envelope-encryption key for D1 secret_store_entries
# (must match Infisical /shared/ key the CPs use, so
# plaintext stays in sync across edge ↔ cells)
+# OPENROUTER_PROVISIONING_KEY — OpenRouter MANAGEMENT/provisioning key (mints
+# per-org inference keys + reads analytics). Token
+# billing dormant until this is set. (token-billing.md)
+# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for handing a minted OR key to
+# sessions-api (shared only with sessions-api; NOT the
+# generic internal-auth — this route carries a live key)
+# Optional vars: OPENROUTER_BASE_URL (default https://openrouter.ai/api/v1),
+# OPENROUTER_MARKUP_BPS (env-default markup; per-org orgs.model_markup_bps wins).
# Edge-native autumn billing: every 5 min, meter autumn orgs' usage_samples to
# Autumn + halt on exhaustion (src/autumn_meter.ts). One place, not per-cell.
diff --git a/cloudflare-workers/api-edge/wrangler.toml b/cloudflare-workers/api-edge/wrangler.toml
index d024d890..8ac8d6e6 100644
--- a/cloudflare-workers/api-edge/wrangler.toml
+++ b/cloudflare-workers/api-edge/wrangler.toml
@@ -86,6 +86,13 @@ new_sqlite_classes = ["CreditAccount"]
# WORKOS_API_KEY — server-side WorkOS API for /auth/login
# WORKOS_CLIENT_ID — WorkOS client identifier
# EVENT_SECRET — HMAC for /internal/halt-list endpoint (shared with CP halt_reconciler)
+# OPENROUTER_PROVISIONING_KEY — OpenRouter MANAGEMENT/provisioning key (token
+# billing; mints per-org keys + reads analytics). Dormant
+# until set. See .agents/work/token-billing.md.
+# OC_MANAGED_CRED_HMAC_SECRET — dedicated HMAC for the minted-OR-key hand-off to
+# sessions-api (shared only with sessions-api).
+# Optional vars: OPENROUTER_BASE_URL (default https://openrouter.ai/api/v1),
+# OPENROUTER_MARKUP_BPS (env-default markup; per-org orgs.model_markup_bps wins).
# Edge-native autumn billing: every 5 min, meter autumn orgs' usage_samples to
# Autumn + halt on exhaustion (src/autumn_meter.ts). One place, not per-cell.
diff --git a/cloudflare-workers/schema_phase9_model_billing.sql b/cloudflare-workers/schema_phase9_model_billing.sql
new file mode 100644
index 00000000..05fb2449
--- /dev/null
+++ b/cloudflare-workers/schema_phase9_model_billing.sql
@@ -0,0 +1,67 @@
+-- Phase 9: Token / model-usage billing — managed OpenRouter keys + per-org state.
+--
+-- Adds the edge-native state for billing an org's LLM token usage out of the same
+-- Autumn `credits` pool as compute (design: .agents/work/token-billing.md). The
+-- edge provisions one OpenRouter key per managed org, meters its spend, and pushes
+-- the cap to mirror the shared balance; this schema holds the per-key ledger + the
+-- per-org provisioning state.
+--
+-- EDGE-ONLY (D1), unlike billing_provider (phase 7 / migration 047, which mirrors
+-- to each cell's Postgres via the cap-token). The Go cell holds no OpenRouter or
+-- Autumn client and never gates on model-billing state, so there is deliberately
+-- NO cell-PG mirror migration for these.
+--
+-- Apply with:
+-- wrangler d1 execute opencomputer-dev --remote --file cloudflare-workers/schema_phase9_model_billing.sql
+-- wrangler d1 execute opencomputer-prod --remote --file cloudflare-workers/schema_phase9_model_billing.sql
+--
+-- SQLite/D1 has no `ADD COLUMN IF NOT EXISTS`, so the ALTERs are one-shot like the
+-- earlier phases. Run BEFORE deploying api-edge code that reads these columns.
+
+-- Per-org provisioning state machine (token-billing §5.1). Drives off→provisioning
+-- →active (or error). `active` ⇒ Managed is offered + resolvable for the org.
+-- 'off' — not enabled (default; all existing orgs unaffected).
+-- 'provisioning' — OR key being minted + bound to a sessions-api credential.
+-- 'active' — a managed credential is bound; Managed available.
+-- 'error' — provisioning failed after bounded retries (alert; stays off).
+ALTER TABLE orgs ADD COLUMN model_billing_status TEXT NOT NULL DEFAULT 'off';
+
+-- Markup applied to OpenRouter cost before debiting Autumn, in basis points
+-- (0 = at-cost; 2000 = +20%). Per-org override of an env default. BOTH the debit
+-- and the cap-push math depend on it (token-billing §7). See §9.2 for why
+-- at-cost (0) loses ~5% to OR's credit-purchase fee.
+ALTER TABLE orgs ADD COLUMN model_markup_bps INTEGER NOT NULL DEFAULT 0;
+
+-- Partial index: the "which orgs run Managed" sweep stays tight while almost
+-- everyone is still 'off'.
+CREATE INDEX IF NOT EXISTS idx_orgs_model_billing_active
+ ON orgs(model_billing_status) WHERE model_billing_status = 'active';
+
+-- One row per provisioned OpenRouter key (token-billing §4). Normally one 'active'
+-- per org; ≥1 transiently during a rotation. Per-key watermark so each key's spend
+-- is debited independently until it quiesces, and so the in-flight debit interval
+-- is durable across cron crashes (persist-before-track, §5.4/§7).
+--
+-- The plaintext OR key is NEVER stored here — only the non-secret hash + the
+-- sessions-api credential id that points at the sealed secret (Infisical).
+CREATE TABLE IF NOT EXISTS managed_model_keys (
+ id TEXT PRIMARY KEY,
+ org_id TEXT NOT NULL,
+ or_key_hash TEXT, -- OpenRouter key hash (non-secret); null between insert + create
+ managed_credential_id TEXT, -- sessions-api credential row id (the sealed key); null until bound
+ operation_id TEXT, -- idempotency id for the edge→sessions-api bind hand-off (§5.1/§6.7.5)
+ status TEXT NOT NULL CHECK (status IN ('active', 'superseded', 'deleting')),
+ committed_micro INTEGER NOT NULL DEFAULT 0, -- OR usage already debited to Autumn (micro-USD watermark)
+ pending_from_micro INTEGER, -- the single in-flight debit interval [from,to), immutable until committed
+ pending_to_micro INTEGER,
+ pending_idem TEXT, -- "model_spend:<org>:<from>:<to>" — stable across retries
+ attempts INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ created_at INTEGER NOT NULL, -- unix seconds
+ superseded_at INTEGER
+);
+
+-- The hot lookups: an org's active key (resolve/cap) and its still-draining
+-- superseded/deleting keys (poll until quiesced).
+CREATE INDEX IF NOT EXISTS idx_managed_model_keys_org_status
+ ON managed_model_keys(org_id, status);