Skip to content

An open-source, faster Devin alternative

TypeScript

token-billing steps 4-5: edge managedAvailable + Managed picker in the UI/SDK

Igor Zalutski1e9003e111d8
diff --git a/cloudflare-workers/api-edge/scripts/enable-model-billing.mjs b/cloudflare-workers/api-edge/scripts/enable-model-billing.mjs
new file mode 100644
index 00000000..6e833276
--- /dev/null
+++ b/cloudflare-workers/api-edge/scripts/enable-model-billing.mjs
@@ -0,0 +1,44 @@
+// Operator helper: enable Managed model billing for one org by calling the edge's
+// POST /internal/model-billing/enable (token-billing §5.1). Signs the CF_ADMIN_SECRET
+// HMAC for you. Use it to provision a dev/test org so "Managed" resolves in the UI.
+//
+// CF_ADMIN_SECRET=… node enable-model-billing.mjs \
+// --edge https://opencomputer-edge-prod.<acct>.workers.dev \
+// --org <org_id> [--disable]
+//
+// Prereqs on the edge: OPENROUTER_PROVISIONING_KEY + OC_MANAGED_CRED_HMAC_SECRET set;
+// the matching OC_MANAGED_CRED_HMAC_SECRET set on sessions-api. The edge mints the
+// org's OpenRouter key and binds it to sessions-api as a managed credential, then
+// flips orgs.model_billing_status='active' (→ /billing.managedAvailable=true).
+
+import { createHmac } from "node:crypto";
+
+const args = Object.fromEntries(
+ process.argv.slice(2).reduce((acc, a, i, arr) => {
+ if (a.startsWith("--")) acc.push([a.slice(2), arr[i + 1]?.startsWith("--") || arr[i + 1] === undefined ? "true" : arr[i + 1]]);
+ return acc;
+ }, []),
+);
+
+const edge = (args.edge || process.env.EDGE_URL || "").replace(/\/+$/, "");
+const org = args.org || process.env.ORG_ID;
+const secret = process.env.CF_ADMIN_SECRET;
+const op = args.disable === "true" ? "disable" : "enable";
+
+if (!edge || !org || !secret) {
+ console.error("usage: CF_ADMIN_SECRET=… node enable-model-billing.mjs --edge <url> --org <org_id> [--disable]");
+ process.exit(1);
+}
+
+const body = JSON.stringify({ org_id: org });
+const ts = Math.floor(Date.now() / 1000).toString();
+const sig = createHmac("sha256", secret).update(`${ts}.${body}`).digest("hex");
+
+const res = await fetch(`${edge}/internal/model-billing/${op}`, {
+ method: "POST",
+ headers: { "content-type": "application/json", "X-Timestamp": ts, "X-Signature": sig },
+ body,
+});
+const text = await res.text();
+console.log(`${op} → HTTP ${res.status}: ${text}`);
+process.exit(res.ok ? 0 : 1);
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 62a3239e..e0c12891 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -981,12 +981,12 @@ export async function handleDashboard(
// dashboard renders instead of 404-erroring on a missing route.
if (sub === "/billing" && method === "GET") {
const org = await env.OPENCOMPUTER_DB.prepare(
- `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted, max_concurrent_sandboxes, billing_provider
+ `SELECT plan, stripe_customer_id, stripe_subscription_id, free_credits_remaining_cents, credit_balance_cents, is_halted, max_concurrent_sandboxes, billing_provider, model_billing_status
FROM orgs WHERE id = ?1`,
).bind(caller.orgID).first<{
plan: string; stripe_customer_id: string | null; stripe_subscription_id: string | null;
free_credits_remaining_cents: number; credit_balance_cents: number; is_halted: number;
- max_concurrent_sandboxes: number; billing_provider: string;
+ max_concurrent_sandboxes: number; billing_provider: string; model_billing_status: string | null;
}>();
if (!org) return json({ error: "org not found" }, 404);
// Cross-check against the live DO state — the D1 mirror gets written by
@@ -1020,6 +1020,10 @@ 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').
+ managedAvailable: org.model_billing_status === "active",
// 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/model_billing.test.ts b/cloudflare-workers/api-edge/src/model_billing.test.ts
index 27a119a5..4e961c26 100644
--- a/cloudflare-workers/api-edge/src/model_billing.test.ts
+++ b/cloudflare-workers/api-edge/src/model_billing.test.ts
@@ -92,7 +92,7 @@ class FakeStmt {
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]));
+ if (row) cols.forEach((c, i) => ((row as unknown as Record<string, unknown>)[c] = this.args[i]));
return;
}
throw new Error(`FakeStmt: unhandled run() sql: ${s}`);
diff --git a/sdks/typescript/package-lock.json b/sdks/typescript/package-lock.json
index 9aa3e19e..a4377dac 100644
--- a/sdks/typescript/package-lock.json
+++ b/sdks/typescript/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@opencomputer/sdk",
- "version": "0.9.3",
+ "version": "0.9.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@opencomputer/sdk",
- "version": "0.9.3",
+ "version": "0.9.4",
"license": "MIT",
"devDependencies": {
"@types/node": "^25.3.0",
diff --git a/sdks/typescript/package.json b/sdks/typescript/package.json
index 6a9f3ed2..6d1d6fdf 100644
--- a/sdks/typescript/package.json
+++ b/sdks/typescript/package.json
@@ -1,6 +1,6 @@
{
"name": "@opencomputer/sdk",
- "version": "0.9.3",
+ "version": "0.9.4",
"description": "TypeScript SDK for OpenComputer - cloud sandbox platform",
"type": "module",
"main": "dist/index.js",
diff --git a/sdks/typescript/src/agents/agents.ts b/sdks/typescript/src/agents/agents.ts
index 24279662..bf08fb22 100644
--- a/sdks/typescript/src/agents/agents.ts
+++ b/sdks/typescript/src/agents/agents.ts
@@ -1,5 +1,5 @@
import type { Http, Query } from "./http.js";
-import type { Agent, Limits, Runtime } from "./types.js";
+import type { Agent, CredentialRef, Limits, Runtime } from "./types.js";
export interface CreateAgentParams {
name: string;
@@ -8,9 +8,10 @@ export interface CreateAgentParams {
model: string;
/** Defaults to `claude`. Fixes the model's provider (see `model`); immutable after create. */
runtime?: Runtime;
- /** Model provider key for the runtime (Anthropic for `claude`, OpenAI for `codex`), stored as a sealed credential. Or pass `credential`, or rely on the org default. */
+ /** Model provider key for the runtime (Anthropic for `claude`, OpenAI for `codex`), stored as a sealed credential. Mutually exclusive with `credential`. */
key?: string;
- credential?: string;
+ /** Model source: `"managed"` (run via OpenComputer, billed to credits) or a `cred_…` id. Omit for the org default. Mutually exclusive with `key`. */
+ credential?: CredentialRef;
limits?: Limits;
}
@@ -19,7 +20,8 @@ export interface UpdateAgentParams {
/** Stay within the agent's runtime provider (`anthropic/…` for `claude`, `openai/…` for `codex`); the runtime itself is immutable. */
model?: string;
key?: string;
- credential?: string;
+ /** Re-point the model source: `"managed"`, a `cred_…` id, or `null` to clear (org default). Mutually exclusive with `key`. */
+ credential?: CredentialRef | null;
limits?: Limits;
}
diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.ts
index ea89802b..c7c898a4 100644
--- a/sdks/typescript/src/agents/types.ts
+++ b/sdks/typescript/src/agents/types.ts
@@ -14,6 +14,14 @@ export interface Limits { tokens?: number; turnSeconds?: number; turns?: number;
// keeps known values discoverable while still accepting future ones.
export type Runtime = "claude" | "codex" | (string & {});
+// A credential id (`newId("cred")` → `cred_…`). The template keeps the shape
+// checkable while still accepting any concrete id.
+export type CredentialId = `cred_${string}`;
+// How an agent picks its model source: the reserved "managed" sentinel (run via
+// OpenComputer, billed to credits) or a specific BYO credential id. Omit/null to
+// inherit the org default.
+export type CredentialRef = "managed" | CredentialId;
+
export interface Actor {
id?: string;
type?: "human" | "agent" | "system" | (string & {});
@@ -27,7 +35,7 @@ export interface Agent {
model: string;
runtime: Runtime;
revision?: number;
- credentialId?: string | null;
+ credentialId?: CredentialRef | null;
limits?: Limits;
createdAt?: string;
updatedAt?: string;
@@ -71,7 +79,7 @@ export interface SessionData {
}
export interface Credential {
- id: string;
+ id: CredentialId;
provider: string;
name?: string;
last4?: string;
diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.ts
index fd730c1e..48762742 100644
--- a/web/src/api/schemas.ts
+++ b/web/src/api/schemas.ts
@@ -192,6 +192,10 @@ 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.tsx
index 49ceb405..506af851 100644
--- a/web/src/pages/AgentDetail.tsx
+++ b/web/src/pages/AgentDetail.tsx
@@ -10,6 +10,7 @@ import {
createSession,
getCredentials,
createCredential,
+ getBilling,
type Agent,
} from '@/api/client'
import type { Session } from '@/api/schemas'
@@ -33,6 +34,7 @@ import { getRuntime } from '@/lib/runtimes'
// credential provider come from the agent's runtime (see @/lib/runtimes).
const ORG_DEFAULT = '__default__' // no pinned credential → org default resolves
const NEW_CRED = '__new__' // create one inline
+const MANAGED = 'managed' // run via OpenComputer, billed to credits (token-billing §6.6)
export default function AgentDetail() {
const { agentId = '' } = useParams()
@@ -61,6 +63,9 @@ 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)
@@ -176,11 +181,18 @@ 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
const credOptions = [
{ value: ORG_DEFAULT, label: 'Org default (no pinned credential)' },
+ ...(showManaged
+ ? [{ value: MANAGED, label: 'Managed · billed to credits' }]
+ : []),
...providerCreds.map((c) => ({ value: c.id, label: credLabel(c.id) })),
{ value: NEW_CRED, label: '+ New credential…' },
]
+ // ORG_DEFAULT → clear the pin (null); MANAGED → the "managed" sentinel; else a cred id.
const onCredChange = (v: string) => {
if (v === NEW_CRED) {
setCredNew(true)
diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx
index a09d8358..9b51a5e0 100644
--- a/web/src/pages/Agents.tsx
+++ b/web/src/pages/Agents.tsx
@@ -8,6 +8,7 @@ import {
createAgent,
getCredentials,
createCredential,
+ getBilling,
type Agent,
} from '@/api/client'
import { PageHeader } from '@/components/page-header'
@@ -31,9 +32,12 @@ import {
runtimeOptions,
} from '@/lib/runtimes'
-// Sentinel for the "create one inline" choice in the credential picker. The model
+// Sentinels for the non-credential choices in the credential picker. The model
// list + credential provider both follow the chosen runtime (see @/lib/runtimes).
const NEW_CRED = '__new__'
+// "Managed" model access: run via OpenComputer, billed to credits (no BYO key).
+// Sent to the API as the reserved credential value "managed" (token-billing §6.6).
+const MANAGED = 'managed'
export default function Agents() {
const queryClient = useQueryClient()
@@ -47,6 +51,10 @@ 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 ?? false
const [showCreate, setShowCreate] = useState(false)
const [name, setName] = useState('')
const [prompt, setPrompt] = useState('')
@@ -67,9 +75,11 @@ export default function Agents() {
)
const hasDefault = providerCreds.some((c) => c.is_default)
- // Lowest-friction default for a provider's creds: org default → first → "new".
+ // Lowest-friction default, mirroring backend resolution (token-billing §6.6):
+ // a BYO org default wins; else Managed (when available); else first BYO; else "new".
const defaultCredFor = (creds: typeof providerCreds) =>
- creds.find((c) => c.is_default)?.id ?? creds[0]?.id ?? NEW_CRED
+ creds.find((c) => c.is_default)?.id ??
+ (managedAvailable ? MANAGED : creds[0]?.id ?? NEW_CRED)
const resetForm = () => {
setName('')
@@ -101,8 +111,12 @@ export default function Agents() {
setNewCredKey('')
}
- // Build options: this runtime's provider creds + "New credential…".
+ // 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' }]
+ : []),
...providerCreds.map((c) => ({
value: c.id,
label: `${c.name || 'Unnamed'}${c.last4 ? ` ·· ${c.last4}` : ''}${
@@ -118,7 +132,9 @@ export default function Agents() {
// - NEW_CRED → create the credential first, pin the new id.
// - else → pin the chosen existing credential.
let credentialId: string | undefined
- if (credChoice === NEW_CRED) {
+ if (credChoice === MANAGED) {
+ credentialId = MANAGED // run via OpenComputer, billed to credits — no key
+ } else if (credChoice === NEW_CRED) {
const cred = await createCredential({
key: newCredKey.trim(),
provider: rt.provider,
@@ -317,7 +333,11 @@ export default function Agents() {
<Field
label="Credential"
htmlFor="agent-cred"
- description={`The ${rt.provider} key this agent runs on (matches the runtime). Reuse one from Credentials, or add a new one here.`}
+ description={
+ credChoice === MANAGED
+ ? 'Run via OpenComputer, billed to your credits — no key needed.'
+ : `The ${rt.provider} key this agent runs on (matches the runtime). Reuse one from Credentials, or add a new one here.`
+ }
>
<Select
key={runtime}