Skip to content

An open-source, faster Devin alternative

TypeScript

feat: document and gate BYOK to Pro plans (#683)

Mohamed Habibd0427be471b8
diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.ts
index 4b880e23..ad63acb7 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts
@@ -3,10 +3,23 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import {
handleAgentWebhookInvocation,
handleManagedAgentChannelConnection,
+ hasBYOKPlanAccess,
mintManagedAgentsAssertion,
proxyManagedAgents,
} from "./managed_agents";
+function legacyPlanEnv(plan: string) {
+ return {
+ OPENCOMPUTER_DB: {
+ prepare: () => ({
+ bind: () => ({
+ first: async () => ({ plan, billing_provider: "legacy" }),
+ }),
+ }),
+ } as unknown as D1Database,
+ };
+}
+
function decodePayload(token: string): Record<string, unknown> {
const payload = token.split(".")[1];
return JSON.parse(
@@ -38,6 +51,54 @@ describe("managed agents proxy", () => {
expect(Number(payload.exp) - Number(payload.iat)).toBe(120);
});
+ it("allows BYOK for Pro and Max but not the base plan", async () => {
+ await expect(
+ hasBYOKPlanAccess(legacyPlanEnv("base"), "org_test"),
+ ).resolves.toBe(false);
+ await expect(
+ hasBYOKPlanAccess(legacyPlanEnv("pro"), "org_test"),
+ ).resolves.toBe(true);
+ await expect(
+ hasBYOKPlanAccess(legacyPlanEnv("max"), "org_test"),
+ ).resolves.toBe(true);
+ });
+
+ it("reads BYOK eligibility from an active Autumn subscription", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () =>
+ Response.json({
+ id: "org_test",
+ subscriptions: [
+ { plan_id: "base", add_on: false, status: "active" },
+ { plan_id: "pro", add_on: false, status: "active" },
+ ],
+ }),
+ ),
+ );
+ const autumnDB = {
+ prepare: () => ({
+ bind: () => ({
+ first: async () => ({
+ plan: "free",
+ billing_provider: "autumn",
+ }),
+ }),
+ }),
+ } as unknown as D1Database;
+
+ await expect(
+ hasBYOKPlanAccess(
+ {
+ OPENCOMPUTER_DB: autumnDB,
+ AUTUMN_SECRET_KEY: "autumn-test",
+ AUTUMN_BASE_URL: "https://autumn.test/v1",
+ },
+ "org_test",
+ ),
+ ).resolves.toBe(true);
+ });
+
it("returns the public model-access OAuth receipt without custody fields", async () => {
vi.stubGlobal(
"fetch",
@@ -73,6 +134,7 @@ describe("managed agents proxy", () => {
{
OC_MANAGED_AGENTS_SECRET: "test-secret",
MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ ...legacyPlanEnv("pro"),
},
{ orgID: "org_test", userID: "user_test", role: "admin" },
"/api/managed-agents",
@@ -131,6 +193,82 @@ describe("managed agents proxy", () => {
expect(fetchSpy).not.toHaveBeenCalled();
});
+ it("rejects BYOK connection and enablement on the base plan", async () => {
+ const fetchSpy = vi.fn();
+ vi.stubGlobal("fetch", fetchSpy);
+ const env = {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ ...legacyPlanEnv("base"),
+ };
+
+ const connect = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/model-access/connections",
+ {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ provider: "openai" }),
+ },
+ ),
+ env,
+ { orgID: "org_test", userID: "user_test", role: "admin" },
+ "/api/managed-agents",
+ );
+ expect(connect.status).toBe(403);
+ await expect(connect.json()).resolves.toMatchObject({
+ error: { code: "model_access_plan_required" },
+ });
+
+ const enable = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/projects/prj_test/model-access/bindings/openai/development",
+ {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ enabled: true }),
+ },
+ ),
+ env,
+ { orgID: "org_test", userID: "user_test", role: "admin" },
+ "/api/managed-agents",
+ );
+ expect(enable.status).toBe(403);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
+
+ it("allows a downgraded organization to disable BYOK", async () => {
+ const fetchSpy = vi.fn(async () =>
+ Response.json({
+ organizationId: "org_test",
+ projectId: "prj_test",
+ provider: "openai",
+ environment: "development",
+ enabled: false,
+ }),
+ );
+ vi.stubGlobal("fetch", fetchSpy);
+ const response = await proxyManagedAgents(
+ new Request(
+ "https://mo-oc-dev.com/api/managed-agents/projects/prj_test/model-access/bindings/openai/development",
+ {
+ method: "PUT",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ enabled: false }),
+ },
+ ),
+ {
+ OC_MANAGED_AGENTS_SECRET: "test-secret",
+ MANAGED_AGENTS_API_URL: "https://managedagents.test",
+ ...legacyPlanEnv("base"),
+ },
+ { orgID: "org_test", userID: "user_test", role: "admin" },
+ "/api/managed-agents",
+ );
+ expect(response.status).toBe(200);
+ expect(fetchSpy).toHaveBeenCalledOnce();
+ });
+
it("forwards webhook text and payload without requiring a user API key", async () => {
const fetchSpy = vi.fn(
async (_target: URL | RequestInfo, init?: RequestInit) => {
diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.ts
index df90ef7e..d8ad482c 100644
--- a/cloudflare-workers/api-edge/src/managed_agents.ts
+++ b/cloudflare-workers/api-edge/src/managed_agents.ts
@@ -1,6 +1,11 @@
+import { getAutumnCustomer } from "./autumn_webhook";
+
export interface ManagedAgentsEnv {
MANAGED_AGENTS_API_URL?: string;
OC_MANAGED_AGENTS_SECRET?: string;
+ OPENCOMPUTER_DB?: D1Database;
+ AUTUMN_SECRET_KEY?: string;
+ AUTUMN_BASE_URL?: string;
}
export interface ManagedAgentsCaller {
@@ -12,6 +17,51 @@ export interface ManagedAgentsCaller {
const DEFAULT_MANAGED_AGENTS_API_URL = "https://managedagents.opencomputer.dev";
const MAX_AGENT_SOURCE_BYTES = 10 * 1024 * 1024;
+export async function hasBYOKPlanAccess(
+ env: ManagedAgentsEnv,
+ orgID: string,
+): Promise<boolean> {
+ if (!env.OPENCOMPUTER_DB) return false;
+ const org = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT plan, billing_provider FROM orgs WHERE id = ?1",
+ )
+ .bind(orgID)
+ .first<{ plan: string; billing_provider: string }>();
+ if (!org) return false;
+ if (org.billing_provider !== "autumn") {
+ return org.plan === "pro" || org.plan === "max";
+ }
+ if (!env.AUTUMN_SECRET_KEY) {
+ throw new Error("Autumn billing is not configured");
+ }
+ const customer = await getAutumnCustomer(
+ {
+ AUTUMN_SECRET_KEY: env.AUTUMN_SECRET_KEY,
+ AUTUMN_BASE_URL: env.AUTUMN_BASE_URL,
+ },
+ orgID,
+ );
+ return (
+ customer?.subscriptions?.some(
+ (subscription) =>
+ (!subscription.status || subscription.status === "active") &&
+ (subscription.plan_id === "pro" || subscription.plan_id === "max"),
+ ) === true
+ );
+}
+
+function byokPlanRequired(): Response {
+ return Response.json(
+ {
+ error: {
+ code: "model_access_plan_required",
+ message: "Upgrade to Pro to connect or enable a BYOK account.",
+ },
+ },
+ { status: 403 },
+ );
+}
+
function b64url(value: ArrayBuffer | Uint8Array): string {
const bytes = value instanceof Uint8Array ? value : new Uint8Array(value);
let encoded = "";
@@ -1258,7 +1308,12 @@ export async function proxyManagedAgents(
request.method.toUpperCase() === "POST" &&
suffix === "/model-access/connections"
) {
- const payload = record(await request.clone().json().catch(() => null));
+ const payload = record(
+ await request
+ .clone()
+ .json()
+ .catch(() => null),
+ );
if (payload?.provider !== "openai") {
return Response.json(
{
@@ -1271,6 +1326,45 @@ export async function proxyManagedAgents(
);
}
}
+ const method = request.method.toUpperCase();
+ const modelAccessConnectionWrite =
+ method === "POST" &&
+ (suffix === "/model-access/connections" ||
+ /^\/model-access\/connections\/[^/]+\/(validate|complete)$/.test(suffix));
+ const modelAccessBindingEnable =
+ method === "PUT" &&
+ /^\/projects\/[^/]+\/model-access\/bindings\/[^/]+\/[^/]+$/.test(suffix) &&
+ record(
+ await request
+ .clone()
+ .json()
+ .catch(() => null),
+ )?.enabled === true;
+ if (modelAccessConnectionWrite || modelAccessBindingEnable) {
+ try {
+ if (!(await hasBYOKPlanAccess(env, caller.orgID))) {
+ return byokPlanRequired();
+ }
+ } catch (error) {
+ console.error(
+ JSON.stringify({
+ level: "error",
+ event: "managed_agents.byok_entitlement_failed",
+ orgId: caller.orgID,
+ message: error instanceof Error ? error.message : String(error),
+ }),
+ );
+ return Response.json(
+ {
+ error: {
+ code: "billing_unavailable",
+ message: "BYOK plan eligibility could not be verified.",
+ },
+ },
+ { status: 503 },
+ );
+ }
+ }
const bindingProvider = suffix.match(
/^\/projects\/[^/]+\/model-access\/bindings\/([^/]+)\/[^/]+$/,
)?.[1];
diff --git a/docs/agents/byok.mdx b/docs/agents/byok.mdx
new file mode 100644
index 00000000..d7cab5ee
--- /dev/null
+++ b/docs/agents/byok.mdx
@@ -0,0 +1,86 @@
+---
+title: "Bring your own model account (BYOK)"
+description: "Use a Codex account for model inference in Serverless Agents"
+---
+
+BYOK lets a Serverless Agent use an organization-connected Codex account for
+eligible OpenAI models. OpenComputer keeps the authorization in its control
+plane; it is never added to your deployment, agent source, or runtime
+environment.
+
+BYOK is available on the **Pro and Max plans**. Runtime compute is still charged
+to your OpenComputer account. Model calls routed through your Codex account have
+no OpenComputer model-inference charge and remain subject to the provider's
+allowances and terms.
+
+## Connect a Codex account
+
+Only an organization admin can connect or replace the organization account.
+From a linked project repository, run:
+
+```bash
+npx --yes --package=@opencomputer/cli@latest -- opencomputer model-access connect codex
+```
+
+To choose a project explicitly, including when you are outside its repository,
+add its slug:
+
+```bash
+npx --yes --package=@opencomputer/cli@latest -- opencomputer model-access connect codex --project my-project
+```
+
+The CLI opens the authorized OAuth flow in your browser, stores the account for
+the organization, and enables it for both development and production in the
+selected project. The CLI exits after the callback completes.
+
+An organization has one Codex account. Connecting again replaces that account
+for every project that uses it.
+
+## Enable an existing account for another project
+
+Open the project's **BYOK** page and select **Enable for this project**. You can
+also run the connect command with `--project`; if the organization account is
+already connected, OpenComputer enables the project without requiring another
+OAuth flow.
+
+Project enablement always covers both development and production. Select
+**Disable for this project** to return only that project to Managed inference,
+or disconnect the organization account to stop using it in every project.
+
+## Select a Codex model
+
+Use the native `openai` provider in agent code:
+
+```tsx
+import { useModel } from "@opencomputer/agent";
+
+export default function Agent() {
+ useModel({ provider: "openai", model: "gpt-5.6-sol" });
+ return "You are a helpful assistant.";
+}
+```
+
+The debug inspector labels a successful subscription-funded route **Codex
+account · BYOK**. If no connected and enabled account can serve the request,
+OpenComputer uses Managed inference when available. Managed fallback model
+calls are charged normally and are shown as Managed in session and usage
+details.
+
+To request an OpenAI model through Managed OpenRouter explicitly, use its full
+OpenRouter identifier instead:
+
+```tsx
+useModel({ provider: "openrouter", model: "openai/gpt-5" });
+```
+
+## Troubleshooting
+
+- **The BYOK page asks you to upgrade:** the organization must be on Pro or Max.
+- **The organization account is connected but the project is not enabled:**
+ select **Enable for this project** or rerun the CLI command with `--project`.
+- **The account is revoked or needs authentication:** rerun the connect command
+ to replace it.
+- **A session used Managed inference:** confirm the project is enabled and that
+ agent code uses `provider: "openai"` with a Codex-supported model.
+
+See [Models](/agents/models) for the general `useModel()` contract.
diff --git a/docs/agents/models.mdx b/docs/agents/models.mdx
index 1fca151e..8531ffd1 100644
--- a/docs/agents/models.mdx
+++ b/docs/agents/models.mdx
@@ -1,6 +1,6 @@
---
title: "Models"
-description: "Select a managed model with useModel"
+description: "Select a model with useModel"
---
`useModel()` selects the model that powers the next agent step. OpenComputer
@@ -74,3 +74,13 @@ the credential to agent code.
For credentials used by your own HTTP tools instead of model inference, use
[Secrets and outbound requests](/agents/secrets).
+
+## Use a connected model account
+
+Organizations on Pro or Max can connect a Codex account and route eligible
+OpenAI models through it. Use the native `openai` provider when you want the
+connected account; Managed OpenRouter models continue to use the
+`openrouter/provider/model` form.
+
+See [Bring your own model account (BYOK)](/agents/byok) for setup, project
+enablement, billing behavior, and troubleshooting.
diff --git a/docs/docs.json b/docs/docs.json
index cf2e4ace..59d29c0b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -46,6 +46,7 @@
"agents/channels",
"agents/outboxes",
"agents/secrets",
+ "agents/byok",
"agents/deployments"
]
},
diff --git a/web/src/managed-agents/BYOK.test.ts b/web/src/managed-agents/BYOK.test.ts
index cc5b793e..3e96278c 100644
--- a/web/src/managed-agents/BYOK.test.ts
+++ b/web/src/managed-agents/BYOK.test.ts
@@ -1,11 +1,18 @@
import { describe, expect, it } from 'vitest'
import {
+ hasBYOKPlanAccess,
hasProjectCodexAccess,
modelAccessCLICommand,
projectCodexBindingUpdates,
} from './BYOK'
describe('project BYOK presentation', () => {
+ it('limits BYOK to Pro and Max plans', () => {
+ expect(hasBYOKPlanAccess('base')).toBe(false)
+ expect(hasBYOKPlanAccess('pro')).toBe(true)
+ expect(hasBYOKPlanAccess('max')).toBe(true)
+ })
+
it('uses an install-free production CLI command', () => {
expect(
modelAccessCLICommand('test', {
diff --git a/web/src/managed-agents/BYOK.tsx b/web/src/managed-agents/BYOK.tsx
index 406d2358..aa5b8b50 100644
--- a/web/src/managed-agents/BYOK.tsx
+++ b/web/src/managed-agents/BYOK.tsx
@@ -1,13 +1,16 @@
import { useState } from 'react'
+import { Link } from 'react-router-dom'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import {
BrainCircuit,
Link2,
Link2Off,
+ LockKeyhole,
Loader2,
RefreshCw,
Unplug,
} from 'lucide-react'
+import { getAutumnBilling, getBilling } from '@/api/client'
import { ConfirmDialog } from '@/components/confirm-dialog'
import { CopyRow } from '@/components/copy-row'
import { EmptyState } from '@/components/empty-state'
@@ -80,6 +83,10 @@ export function projectCodexBindingUpdates(
}))
}
+export function hasBYOKPlanAccess(plan: string | undefined) {
+ return plan === 'pro' || plan === 'max'
+}
+
export function ManagedProjectBYOK({
projectId,
projectSlug,
@@ -94,13 +101,35 @@ export function ManagedProjectBYOK({
const cliCommand = modelAccessCLICommand(projectSlug, window.location)
const connectionQueryKey = ['managed-model-access-connections']
const bindingQueryKey = ['managed-model-access-bindings', projectId]
+ const billing = useQuery({
+ queryKey: ['billing'],
+ queryFn: getBilling,
+ })
+ const autumnBilling = useQuery({
+ queryKey: ['billing', 'autumn'],
+ queryFn: getAutumnBilling,
+ enabled: billing.data?.billingProvider === 'autumn',
+ })
+ const usagePlan =
+ billing.data?.billingProvider === 'autumn'
+ ? autumnBilling.data?.usagePlan
+ : billing.data?.plan
+ const planEligible = hasBYOKPlanAccess(usagePlan)
+ const billingLoading =
+ billing.isLoading ||
+ (billing.data?.billingProvider === 'autumn' && autumnBilling.isLoading)
+ const billingError =
+ billing.isError ||
+ (billing.data?.billingProvider === 'autumn' && autumnBilling.isError)
const connections = useQuery({
queryKey: connectionQueryKey,
queryFn: getManagedModelAccessConnections,
+ enabled: planEligible,
})
const bindings = useQuery({
queryKey: bindingQueryKey,
queryFn: () => getManagedModelAccessBindings(projectId),
+ enabled: planEligible,
})
const codex = connections.data?.find(
(connection) => connection.provider === 'openai',
@@ -151,7 +180,10 @@ export function ManagedProjectBYOK({
onError: (error) =>
notifyError("Couldn't disconnect the Codex account.", error),
})
- if (connections.isLoading || bindings.isLoading) {
+ if (
+ billingLoading ||
+ (planEligible && (connections.isLoading || bindings.isLoading))
+ ) {
return (
<Panel>
<PanelContent className="text-muted-foreground flex items-center gap-2 text-sm">
@@ -161,7 +193,10 @@ export function ManagedProjectBYOK({
)
}
- if (connections.isError || bindings.isError) {
+ if (
+ billingError ||
+ (planEligible && (connections.isError || bindings.isError))
+ ) {
return (
<Panel>
<EmptyState
@@ -172,6 +207,10 @@ export function ManagedProjectBYOK({
<Button
variant="outline"
onClick={() => {
+ void billing.refetch()
+ if (billing.data?.billingProvider === 'autumn') {
+ void autumnBilling.refetch()
+ }
void connections.refetch()
}}
>
@@ -183,6 +222,23 @@ export function ManagedProjectBYOK({
)
}
+ if (!planEligible) {
+ return (
+ <Panel>
+ <EmptyState
+ icon={LockKeyhole}
+ title="BYOK is available on Pro"
+ description="Upgrade to Pro to connect a Codex account and enable it for this project's development and production environments."
+ action={
+ <Button asChild>
+ <Link to="/billing">Upgrade to Pro</Link>
+ </Button>
+ }
+ />
+ </Panel>
+ )
+ }
+
return (
<div className="space-y-5">
<Panel>