An open-source, faster Devin alternative
TypeScript
Add project BYOC model routing (#763)
Mohamed Habibbfe975f00494
diff --git a/cli/src/api.test.ts b/cli/src/api.test.tsindex 8f8f8841..86418fe0 100644--- a/cli/src/api.test.ts+++ b/cli/src/api.test.ts@@ -134,6 +134,77 @@ test("memory precondition failures surface the API's code", async (context) => {);});+test("model connections and routes use write-only connection input and project route endpoints", async (context) => {+ const requests: Request[] = [];+ context.mock.method(+ globalThis,+ "fetch",+ async (input: string | URL | Request, init?: RequestInit) => {+ const request = new Request(input, init);+ requests.push(request);+ if (request.method === "DELETE") return new Response(null, { status: 204 });+ if (request.url.endsWith("/model-access/connections")) {+ return Response.json({+ id: "mac_scx",+ organizationId: "org_test",+ connectedByUserId: "user_test",+ provider: "openai_compatible",+ kind: "openai_compatible_api",+ label: "SCX",+ baseUrl: "https://api.scx.ai/v1",+ status: "connected",+ });+ }+ return Response.json({+ id: "mr_test",+ projectId: "prj_test",+ environment: "development",+ connectionId: "mac_scx",+ model: "GLM-5.3",+ fallback: "fail",+ revision: 1,+ });+ },+ );+ const client = new OpenComputerClient({+ apiUrl: "https://app.opencomputer.dev",+ apiKey: "test",+ });++ await client.connectModelAccessApiKey({+ provider: "openai_compatible",+ api_key: "secret-key",+ base_url: "https://api.scx.ai/v1",+ });+ await client.putModelRoute({+ projectId: "prj_test",+ environment: "development",+ connectionId: "mac_scx",+ model: "GLM-5.3",+ fallback: "fail",+ });+ await client.deleteModelRoute({+ projectId: "prj_test",+ environment: "production",+ });++ assert.deepEqual(await requests[0]!.json(), {+ provider: "openai_compatible",+ api_key: "secret-key",+ base_url: "https://api.scx.ai/v1",+ });+ assert.equal(+ requests[1]!.url,+ "https://app.opencomputer.dev/api/managed-agents/projects/prj_test/model-routes/development",+ );+ assert.deepEqual(await requests[1]!.json(), {+ connection_id: "mac_scx",+ model: "GLM-5.3",+ fallback: "fail",+ });+ assert.equal(requests[2]!.method, "DELETE");+});+test("database queries use the project read endpoint with positional parameters", async (context) => {let request: Request | undefined;context.mock.method(globalThis, "fetch", async (input: string | URL | Request, init?: RequestInit) => {diff --git a/cli/src/api.ts b/cli/src/api.tsindex 1f86b22c..e8f8ace4 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -109,9 +109,14 @@ export interface ModelAccessConnection {id: string;organizationId: string;connectedByUserId: string;- provider: "anthropic" | "openai";- kind: "claude_subscription" | "codex_subscription";+ provider: "anthropic" | "openai" | "openrouter" | "openai_compatible";+ kind:+ | "claude_subscription"+ | "codex_subscription"+ | "openrouter_api_key"+ | "openai_compatible_api";label: string;+ baseUrl?: string;externalAccountHint?: string;status: string;checkedAt?: string;@@ -131,6 +136,19 @@ export interface ModelAccessBinding {updatedAt?: string;}+export interface ModelRoute {+ id: string;+ projectId: string;+ environment: "development" | "production";+ agentId?: string;+ connectionId: string;+ model: string;+ fallback: "fail" | "managed";+ revision: number;+ createdAt?: string;+ updatedAt?: string;+}+export interface AgentRuntimeVariableMetadata {name: string;projectId: string;@@ -759,6 +777,61 @@ export class OpenComputerClient {});}+ connectModelAccessApiKey(input: {+ provider: "openrouter" | "openai_compatible";+ api_key: string;+ base_url?: string;+ label?: string;+ }) {+ return this.request<ModelAccessConnection>(+ "/api/managed-agents/model-access/connections",+ { method: "POST", body: JSON.stringify(input) },+ );+ }++ async modelRoutes(projectId: string): Promise<ModelRoute[]> {+ const result = await this.request<{ data: ModelRoute[] }>(+ `/api/managed-agents/projects/${encodeURIComponent(projectId)}/model-routes`,+ );+ return result.data;+ }++ putModelRoute(input: {+ projectId: string;+ environment: "development" | "production";+ connectionId: string;+ model: string;+ agentId?: string;+ fallback: "fail" | "managed";+ }) {+ return this.request<ModelRoute>(+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-routes/${input.environment}`,+ {+ method: "PUT",+ body: JSON.stringify({+ connection_id: input.connectionId,+ model: input.model,+ fallback: input.fallback,+ ...(input.agentId ? { agent_id: input.agentId } : {}),+ }),+ },+ );+ }++ deleteModelRoute(input: {+ projectId: string;+ environment: "development" | "production";+ agentId?: string;+ }) {+ return this.request<void>(+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-routes/${input.environment}`,+ {+ method: "DELETE",+ body: JSON.stringify(input.agentId ? { agent_id: input.agentId } : {}),+ },+ );+ }+// Relays a credential the local CLI obtained through the authorized Codex// OAuth flow into a connected subscription (encrypted custody server-side).relayModelAccess(diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex d08c8a7e..10596abb 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -155,9 +155,20 @@ function printDatabaseResult(result: {if (result.truncated) process.stdout.write("Result truncated; add LIMIT and paginate the query.\n");}-function consumeModelAccessProvider(args: string[]): "claude" | "codex" {- if (args[0] === "claude" || args[0] === "codex") {- return args.shift() as "claude" | "codex";+function consumeModelAccessProvider(+ args: string[],+): "claude" | "codex" | "openrouter" | "openai-compatible" {+ if (+ args[0] === "claude" ||+ args[0] === "codex" ||+ args[0] === "openrouter" ||+ args[0] === "openai-compatible"+ ) {+ return args.shift() as+ | "claude"+ | "codex"+ | "openrouter"+ | "openai-compatible";}return "codex";}@@ -1562,11 +1573,40 @@ function serviceOfConnection(connection: {// credential to OpenComputer as a connected account. Nothing secret// is echoed or persisted locally.const provider = consumeModelAccessProvider(args);- if (provider !== "codex") {+ if (provider === "claude") {throw new Error("Claude account BYOK is not supported. Connect a Codex account instead.",);}+ if (provider === "openrouter" || provider === "openai-compatible") {+ const projectReference = option(args, "--project");+ const baseUrl = option(args, "--base-url");+ const label = option(args, "--label");+ const apiKeyStdin = flag(args, "--api-key-stdin");+ if (provider === "openai-compatible" && !baseUrl) {+ throw new Error("--base-url is required for openai-compatible");+ }+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const apiKey = apiKeyStdin+ ? await readStdinValue(true)+ : await readTemplateSecretValue();+ const connection = await client.connectModelAccessApiKey({+ provider: provider === "openrouter" ? "openrouter" : "openai_compatible",+ api_key: apiKey,+ ...(baseUrl ? { base_url: baseUrl } : {}),+ ...(label ? { label } : {}),+ });+ if (globals.json) printJSON(connection);+ else {+ process.stdout.write(`Connected ${connection.label}; status ${connection.status}.\n`);+ if (projectReference) {+ process.stdout.write(+ `Next: opencomputer model-route set --project ${projectReference} --connection ${connection.id} --model <model>\n`,+ );+ }+ }+ return;+ }const projectReference = option(args, "--project");const legacyEnvironment = option(args, "--environment");if (legacyEnvironment && !projectReference)@@ -1647,7 +1687,14 @@ function serviceOfConnection(connection: {const provider = consumeModelAccessProvider(args);if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);const connections = await client.modelAccessConnections();- const apiProvider = provider === "claude" ? "anthropic" : "openai";+ const apiProvider =+ provider === "claude"+ ? "anthropic"+ : provider === "openrouter"+ ? "openrouter"+ : provider === "openai-compatible"+ ? "openai_compatible"+ : "openai";const connection = connections.find((c) => c.provider === apiProvider);if (!connection) throw new Error(`No ${provider} connection found.`);const updated = await client.disconnectModelAccess(connection.id);@@ -1655,7 +1702,69 @@ function serviceOfConnection(connection: {else process.stdout.write(`Disconnected ${connection.label}.\n`);return;}- throw new Error("Use `opencomputer model-access connect|list|disconnect`.");+ throw new Error(+ "Use `opencomputer model-access connect|list|disconnect` with codex, openrouter, or openai-compatible.",+ );+ }++ if (command === "model-route") {+ const action = args.shift();+ const projectReference = option(args, "--project");+ const project = await selectedProject(client, config, projectReference);+ if (action === "list" || action === "ls" || action === undefined) {+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const routes = await client.modelRoutes(project.projectId);+ if (globals.json) printJSON(routes);+ else if (!routes.length) process.stdout.write("No model routes.\n");+ else for (const route of routes) {+ process.stdout.write(+ `${route.environment.padEnd(11)} ${(route.agentId ?? "project").padEnd(20)} ${route.model} via ${route.connectionId} (${route.fallback}) r${route.revision}\n`,+ );+ }+ return;+ }+ const agentId = option(args, "--agent");+ if (action === "set") {+ const connectionId = option(args, "--connection");+ const model = option(args, "--model");+ const fallback = option(args, "--fallback") ?? "fail";+ if (!connectionId || !model) throw new Error("--connection and --model are required");+ if (fallback !== "fail" && fallback !== "managed") {+ throw new Error("--fallback must be fail or managed");+ }+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const routes = await Promise.all(+ (["development", "production"] as const).map((environment) =>+ client.putModelRoute({+ projectId: project.projectId,+ environment,+ connectionId,+ model,+ ...(agentId ? { agentId } : {}),+ fallback,+ }),+ ),+ );+ if (globals.json) printJSON(routes);+ else process.stdout.write(`Set ${agentId ? `agent ${agentId}` : "project"} route for development and production.\n`);+ return;+ }+ if (action === "delete" || action === "remove") {+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ await Promise.all(+ (["development", "production"] as const).map((environment) =>+ client.deleteModelRoute({+ projectId: project.projectId,+ environment,+ ...(agentId ? { agentId } : {}),+ }),+ ),+ );+ if (globals.json) printJSON({ deleted: true });+ else process.stdout.write("Removed model route from development and production.\n");+ return;+ }+ throw new Error("Use `opencomputer model-route set|list|delete`.");}if (command === "env") {diff --git a/cli/src/index.ts b/cli/src/index.tsindex beab7b41..fce11710 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -79,8 +79,13 @@ Usage:opencomputer connection listopencomputer connection remove <alias|connection-id> [--service <name>]opencomputer model-access connect codex [--project <id|slug>]+ opencomputer model-access connect openrouter [--api-key-stdin] [--project <id|slug>]+ opencomputer model-access connect openai-compatible --base-url <url> [--api-key-stdin] [--project <id|slug>]opencomputer model-access listopencomputer model-access disconnect codex+ opencomputer model-route set --project <id|slug> --connection <id> --model <model> [--agent <agent>] [--fallback fail|managed]+ opencomputer model-route list --project <id|slug>+ opencomputer model-route delete --project <id|slug> [--agent <agent>]opencomputer webhooks list [--environment development|production] [--agent <agent>|current]opencomputer webhooks create <name> [--environment development|production] [--agent <agent>|current]opencomputer webhooks enable <webhook-id> [--project <id|slug>]diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 47c360b0..68fe14be 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -357,9 +357,26 @@ describe("managed agents proxy", () => {);});- it("rejects unsupported Claude account connection", async () => {- const fetchSpy = vi.fn();- vi.stubGlobal("fetch", fetchSpy);+ it("accepts a Claude setup token and strips it from the response", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (_input, init) => {+ expect(await new Response(init?.body).json()).toMatchObject({+ provider: "anthropic",+ token: "sk-ant-oat01-write-only-setup-token-value",+ });+ return Response.json({+ id: "mac_claude",+ organizationId: "org_test",+ connectedByUserId: "user_test",+ provider: "anthropic",+ kind: "claude_subscription",+ label: "Claude account",+ status: "connected",+ credentialCiphertext: "must-not-leak",+ });+ }),+ );const response = await proxyManagedAgents(new Request(@@ -369,27 +386,156 @@ describe("managed agents proxy", () => {headers: { "content-type": "application/json" },body: JSON.stringify({provider: "anthropic",- token: "must-not-be-returned",+ token: "sk-ant-oat01-write-only-setup-token-value",}),},),{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",);- expect(response.status).toBe(400);+ expect(response.status).toBe(200);const body = await response.json<Record<string, unknown>>();expect(body).toMatchObject({- error: {- code: "unsupported_provider",- message: "Codex is the only supported BYOK account provider.",+ id: "mac_claude",+ provider: "anthropic",+ kind: "claude_subscription",+ status: "connected",+ });+ expect(JSON.stringify(body)).not.toMatch(/credentialCiphertext|setup-token/);+ });++ it("accepts an OpenAI-compatible connection and strips custody fields", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async (_input, init) => {+ expect(await new Response(init?.body).json()).toMatchObject({+ provider: "openai_compatible",+ api_key: "write-only-key",+ base_url: "https://api.scx.ai/v1",+ });+ return Response.json({+ id: "mac_scx",+ organizationId: "org_test",+ connectedByUserId: "user_test",+ provider: "openai_compatible",+ kind: "openai_compatible_api",+ label: "SCX",+ baseUrl: "https://api.scx.ai/v1",+ status: "connected",+ credentialCiphertext: "must-not-leak",+ });+ }),+ );+ const response = 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_compatible",+ api_key: "write-only-key",+ base_url: "https://api.scx.ai/v1",+ }),+ }),+ {+ 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",+ );+ expect(response.status).toBe(200);+ const body = await response.json<Record<string, unknown>>();+ expect(body).toMatchObject({+ id: "mac_scx",+ provider: "openai_compatible",+ kind: "openai_compatible_api",+ baseUrl: "https://api.scx.ai/v1",});- expect(fetchSpy).not.toHaveBeenCalled();+ expect(JSON.stringify(body)).not.toMatch(/write-only-key|credentialCiphertext|must-not-leak/);+ });++ it("proxies project model routes without exposing private audit metadata", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({+ id: "mr_test",+ organizationId: "org_test",+ projectId: "prj_test",+ environment: "development",+ connectionId: "mac_scx",+ model: "GLM-5.3",+ fallback: "fail",+ revision: 2,+ updatedByUserId: "user_test",+ }),+ ),+ );+ const response = await proxyManagedAgents(+ new Request("https://mo-oc-dev.com/api/managed-agents/projects/prj_test/model-routes/development", {+ method: "PUT",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({+ connection_id: "mac_scx",+ model: "GLM-5.3",+ fallback: "fail",+ }),+ }),+ {+ 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",+ );+ expect(response.status).toBe(200);+ const body = await response.json<Record<string, unknown>>();+ expect(body).toMatchObject({+ id: "mr_test",+ projectId: "prj_test",+ model: "GLM-5.3",+ revision: 2,+ });+ expect(body).not.toHaveProperty("organizationId");+ expect(body).not.toHaveProperty("updatedByUserId");+ });++ it("removes a project model route without deleting its connection", async () => {+ const fetchSpy = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit) => {+ expect(init?.method).toBe("DELETE");+ expect(await new Response(init?.body).text()).toBe("{}");+ return new Response(null, { status: 204 });+ });+ vi.stubGlobal("fetch", fetchSpy);++ const response = await proxyManagedAgents(+ new Request("https://mo-oc-dev.com/api/managed-agents/projects/prj_test/model-routes/development", {+ method: "DELETE",+ headers: { "content-type": "application/json" },+ body: "{}",+ }),+ {+ 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",+ );++ expect(response.status).toBe(204);+ expect(fetchSpy).toHaveBeenCalledOnce();+ expect(String(fetchSpy.mock.calls[0]?.[0])).toBe(+ "https://managedagents.test/v1/projects/prj_test/model-routes/development",+ );});it("rejects BYOK connection and enablement on the base plan", async () => {diff --git a/cloudflare-workers/api-edge/src/managed_agents.ts b/cloudflare-workers/api-edge/src/managed_agents.tsindex 93377667..dc976b6e 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -539,6 +539,7 @@ function publicModelAccessConnection(provider: connection.provider,kind: connection.kind,label: connection.label,+ baseUrl: connection.baseUrl,status: connection.status,checkedAt: connection.checkedAt,createdAt: connection.createdAt,@@ -553,6 +554,22 @@ function publicModelAccessConnection(};}+function publicModelRoute(value: unknown): Record<string, unknown> {+ const route = record(value) ?? {};+ return {+ id: route.id,+ projectId: route.projectId,+ environment: route.environment,+ agentId: route.agentId,+ connectionId: route.connectionId,+ model: route.model,+ fallback: route.fallback,+ revision: route.revision,+ createdAt: route.createdAt,+ updatedAt: route.updatedAt,+ };+}+function publicModelAccessBinding(value: unknown): Record<string, unknown> {const binding = record(value) ?? {};return {@@ -1551,11 +1568,9 @@ function publicSuccessBody(if (method === "GET" && suffix === "/model-access/connections") {return {data: Array.isArray(body.data)- ? body.data- .filter((value) => record(value)?.provider === "openai")- .map((value) =>- publicModelAccessConnection(value, includeAdminMetadata),- )+ ? body.data.map((value) =>+ publicModelAccessConnection(value, includeAdminMetadata),+ ): [],};}@@ -1595,6 +1610,14 @@ function publicSuccessBody() {return publicModelAccessBinding(body);}+ if (method === "GET" && /^\/projects\/[^/]+\/model-routes$/.test(suffix)) {+ return {+ data: Array.isArray(body.data) ? body.data.map(publicModelRoute) : [],+ };+ }+ if (method === "PUT" && /^\/projects\/[^/]+\/model-routes\/[^/]+$/.test(suffix)) {+ return publicModelRoute(body);+ }if (method === "POST" && suffix === "/deployments") {return publicDeployment(body);}@@ -2035,6 +2058,12 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {) {return true;}+ if (+ (method === "GET" || method === "PUT" || method === "DELETE") &&+ /^\/projects\/[^/]+\/model-routes(?:\/[^/]+)?$/.test(suffix)+ ) {+ return true;+ }if ((method === "GET" || method === "POST") &&/^\/projects\/[^/]+\/webhooks$/.test(suffix)@@ -2541,12 +2570,17 @@ export async function proxyManagedAgents(.json().catch(() => null),);- if (payload?.provider !== "openai") {+ if (+ payload?.provider !== "openai" &&+ payload?.provider !== "anthropic" &&+ payload?.provider !== "openrouter" &&+ payload?.provider !== "openai_compatible"+ ) {return Response.json({error: {code: "unsupported_provider",- message: "Codex is the only supported BYOK account provider.",+ message: "Supported providers are Codex, Claude, OpenRouter, and OpenAI-compatible APIs.",},},{ status: 400 },@@ -2567,7 +2601,10 @@ export async function proxyManagedAgents(.json().catch(() => null),)?.enabled === true;- if (modelAccessConnectionWrite || modelAccessBindingEnable) {+ const modelRouteWrite =+ (method === "PUT" || method === "DELETE") &&+ /^\/projects\/[^/]+\/model-routes\/[^/]+$/.test(suffix);+ if (modelAccessConnectionWrite || modelAccessBindingEnable || modelRouteWrite) {try {if (!(await hasBYOKPlanAccess(env, caller.orgID))) {return byokPlanRequired();@@ -2592,24 +2629,6 @@ export async function proxyManagedAgents();}}- const bindingProvider = suffix.match(- /^\/projects\/[^/]+\/model-access\/bindings\/([^/]+)\/[^/]+$/,- )?.[1];- if (- request.method.toUpperCase() === "PUT" &&- bindingProvider &&- bindingProvider !== "openai"- ) {- return Response.json(- {- error: {- code: "unsupported_provider",- message: "Codex is the only supported BYOK account provider.",- },- },- { status: 400 },- );- }const base = (env.MANAGED_AGENTS_API_URL ?? DEFAULT_MANAGED_AGENTS_API_URL).replace(/\/+$/, "");diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex 03a0c1ae..2faf7541 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -913,9 +913,15 @@ export const ModelAccessConnectionSchema = z.object({id: z.string(),organization_id: z.string(),connected_by_user_id: z.string(),- provider: z.enum(['anthropic', 'openai']),- kind: z.enum(['claude_subscription', 'codex_subscription']),+ provider: z.enum(['anthropic', 'openai', 'openrouter', 'openai_compatible']),+ kind: z.enum([+ 'claude_subscription',+ 'codex_subscription',+ 'openrouter_api_key',+ 'openai_compatible_api',+ ]),label: z.string(),+ base_url: z.string().url().nullish(),external_account_hint: z.string().nullish(),status: z.enum(['connecting',@@ -1002,14 +1008,19 @@ export const ModelAccessErrorSchema = z.object({// The immutable record of how one provider call was routed and billed.export const EffectiveModelRouteSchema = z.object({- requested: z.object({ provider: z.string(), model: z.string() }),+ requested: z.object({ provider: z.string(), model: z.string() }).nullable(),effective: z.object({ provider: z.string(), model: z.string() }),- runtime: z.enum(['claude', 'codex']),+ runtime: z.enum(['claude', 'codex', 'opencode']),access: z.object({- type: z.enum(['managed', 'external_subscription']),+ type: z.enum(['managed', 'external_subscription', 'external_api_key']),connection_id: z.string().nullish(),connection_kind: z- .enum(['claude_subscription', 'codex_subscription'])+ .enum([+ 'claude_subscription',+ 'codex_subscription',+ 'openrouter_api_key',+ 'openai_compatible_api',+ ]).nullish(),}),fallback: zdiff --git a/web/src/managed-agents/BYOK.test.ts b/web/src/managed-agents/BYOK.test.tsindex 3e96278c..4bf17a98 100644--- a/web/src/managed-agents/BYOK.test.ts+++ b/web/src/managed-agents/BYOK.test.ts@@ -1,95 +1,52 @@import { describe, expect, it } from 'vitest'import {+ DEFAULT_MODEL_ROUTE_PROVIDER,hasBYOKPlanAccess,- hasProjectCodexAccess,- modelAccessCLICommand,- projectCodexBindingUpdates,-} from './BYOK'+ MODEL_ROUTE_MODEL_SUGGESTIONS,+ MODEL_ROUTE_PROVIDER_DEFAULTS,+ modelConnectionLabel,+ SUBSCRIPTION_ROUTE_AVAILABILITY,+} from './byok-config'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', {- hostname: 'app.opencomputer.dev',- origin: 'https://app.opencomputer.dev',- }),- ).toBe(- 'npx --yes --package=@opencomputer/cli@latest -- opencomputer model-access connect codex --project test',+ it('uses mainstream defaults and leaves custom providers explicit', () => {+ expect(DEFAULT_MODEL_ROUTE_PROVIDER).toBe('openrouter')+ expect(MODEL_ROUTE_PROVIDER_DEFAULTS.openrouter.model).toBe('openai/gpt-5')+ expect(MODEL_ROUTE_PROVIDER_DEFAULTS.openai_compatible.model).toBe('')+ expect(JSON.stringify(MODEL_ROUTE_PROVIDER_DEFAULTS)).not.toContain(+ 'scx.ai',)- })-- it('targets the current API outside production', () => {- expect(- modelAccessCLICommand('test', {- hostname: 'mo-oc-dev.com',- origin: 'https://mo-oc-dev.com',- }),- ).toContain('opencomputer --api-url https://mo-oc-dev.com model-access')- })-- it('requires enabled Codex bindings in both project environments', () => {- expect(- hasProjectCodexAccess([- {- provider: 'openai',- environment: 'development',- enabled: true,- },- ]),- ).toBe(false)- expect(- hasProjectCodexAccess([- {- provider: 'openai',- environment: 'development',- enabled: true,- },- {- provider: 'openai',- environment: 'production',- enabled: true,- },- ]),- ).toBe(true)- })-- it('enables development and production together without reconnecting', () => {- expect(projectCodexBindingUpdates('prj_test', true)).toEqual([+ expect(MODEL_ROUTE_PROVIDER_DEFAULTS).not.toHaveProperty('claude')+ expect(MODEL_ROUTE_MODEL_SUGGESTIONS.openrouter).toContain(+ 'anthropic/claude-sonnet-4.6',+ )+ expect(SUBSCRIPTION_ROUTE_AVAILABILITY).toEqual([{- projectId: 'prj_test',- provider: 'openai',- environment: 'development',- enabled: true,+ id: 'codex',+ label: 'Codex subscription — Coming soon',+ disabled: true,},{- projectId: 'prj_test',- provider: 'openai',- environment: 'production',- enabled: true,+ id: 'claude',+ label: 'Claude subscription — Coming soon',+ disabled: true,},])})- it('disables both environments without disconnecting the account', () => {- expect(projectCodexBindingUpdates('prj_test', false)).toEqual([- {- projectId: 'prj_test',- provider: 'openai',- environment: 'development',- enabled: false,- },- {- projectId: 'prj_test',- provider: 'openai',- environment: 'production',- enabled: false,- },- ])+ it('shows a safe custom-provider origin instead of an opaque id', () => {+ expect(+ modelConnectionLabel({+ id: 'mac_1',+ label: 'OpenAI-compatible API',+ baseUrl: 'https://api.example.com/v1',+ }),+ ).toBe('OpenAI-compatible API · api.example.com')+ })++ it('limits BYOK to Pro and Max plans', () => {+ expect(hasBYOKPlanAccess('base')).toBe(false)+ expect(hasBYOKPlanAccess('pro')).toBe(true)+ expect(hasBYOKPlanAccess('max')).toBe(true)})})diff --git a/web/src/managed-agents/BYOK.tsx b/web/src/managed-agents/BYOK.tsxindex aa5b8b50..1255c379 100644--- a/web/src/managed-agents/BYOK.tsx+++ b/web/src/managed-agents/BYOK.tsx@@ -1,18 +1,9 @@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 { BrainCircuit, Link2, LockKeyhole, Loader2, Trash2 } 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'import {Panel,@@ -26,81 +17,38 @@ import { Button } from '@/components/ui/button'import { useAuth } from '@/hooks/useAuth'import { notifyError, notifySuccess } from '@/lib/errors'import {- disconnectManagedModelAccessConnection,+ connectManagedModelApiKey,+ deleteManagedModelRoute,getManagedModelAccessConnections,- getManagedModelAccessBindings,- putManagedModelAccessBinding,- validateManagedModelAccessConnection,+ getManagedModelRoutes,+ putManagedModelRoute,} from './api'+import {+ DEFAULT_MODEL_ROUTE_PROVIDER,+ hasBYOKPlanAccess,+ MODEL_ROUTE_MODEL_SUGGESTIONS,+ MODEL_ROUTE_PROVIDER_DEFAULTS,+ modelConnectionLabel,+ SUBSCRIPTION_ROUTE_AVAILABILITY,+ type ModelRouteProviderChoice,+} from './byok-config'-export const MODEL_ACCESS_RETURN_TO_KEY = 'opencomputer:model-access:return-to'-export const MODEL_ACCESS_PROJECT_KEY = 'opencomputer:model-access:project'--function connectionTone(status: string) {- if (status === 'connected') return 'running'- if (status === 'revoked' || status === 'unavailable') return 'stopped'- return 'pending'-}--export function modelAccessCLICommand(- projectSlug: string,- location: Pick<Location, 'hostname' | 'origin'>,-) {- const apiArgument =- location.hostname === 'app.opencomputer.dev'- ? ''- : ` --api-url ${location.origin}`- return `npx --yes --package=@opencomputer/cli@latest -- opencomputer${apiArgument} model-access connect codex --project ${projectSlug}`-}--export function hasProjectCodexAccess(- bindings:- | Array<{- enabled: boolean- environment: string- provider: string- }>- | undefined,-) {- const enabled = bindings?.filter(- (binding) => binding.provider === 'openai' && binding.enabled,- )- return (- enabled?.some((binding) => binding.environment === 'development') ===- true && enabled.some((binding) => binding.environment === 'production')- )-}--export function projectCodexBindingUpdates(- projectId: string,- enabled: boolean,-) {- return (['development', 'production'] as const).map((environment) => ({- projectId,- provider: 'openai' as const,- environment,- enabled,- }))-}--export function hasBYOKPlanAccess(plan: string | undefined) {- return plan === 'pro' || plan === 'max'-}--export function ManagedProjectBYOK({- projectId,- projectSlug,-}: {- projectId: string- projectSlug: string-}) {+export function ManagedProjectBYOK({ projectId }: { projectId: string }) {const { user } = useAuth()const queryClient = useQueryClient()- const [confirmDisconnect, setConfirmDisconnect] = useState(false)+ const [confirmRemoveRoute, setConfirmRemoveRoute] = useState(false)+ const [apiProvider, setApiProvider] = useState<ModelRouteProviderChoice>(+ DEFAULT_MODEL_ROUTE_PROVIDER,+ )+ const [apiKey, setApiKey] = useState('')+ const [baseUrl, setBaseUrl] = useState('')+ const [routeModel, setRouteModel] = useState(+ MODEL_ROUTE_PROVIDER_DEFAULTS[DEFAULT_MODEL_ROUTE_PROVIDER].model,+ )+ const [routeFallback, setRouteFallback] = useState<'fail' | 'managed'>('fail')const canManageConnection = user?.capabilities?.manageMembers !== false- const cliCommand = modelAccessCLICommand(projectSlug, window.location)const connectionQueryKey = ['managed-model-access-connections']- const bindingQueryKey = ['managed-model-access-bindings', projectId]+ const routeQueryKey = ['managed-model-routes', projectId]const billing = useQuery({queryKey: ['billing'],queryFn: getBilling,@@ -126,63 +74,59 @@ export function ManagedProjectBYOK({queryFn: getManagedModelAccessConnections,enabled: planEligible,})- const bindings = useQuery({- queryKey: bindingQueryKey,- queryFn: () => getManagedModelAccessBindings(projectId),+ const routes = useQuery({+ queryKey: routeQueryKey,+ queryFn: () => getManagedModelRoutes(projectId),enabled: planEligible,})- const codex = connections.data?.find(- (connection) => connection.provider === 'openai',- )- const projectEnabled = hasProjectCodexAccess(bindings.data)- const updateProjectAccess = useMutation({- mutationFn: (enabled: boolean) =>+ const removeRoute = useMutation({+ mutationFn: () =>Promise.all(- projectCodexBindingUpdates(projectId, enabled).map((binding) =>- putManagedModelAccessBinding(binding),+ (['development', 'production'] as const).map((environment) =>+ deleteManagedModelRoute({ projectId, environment }),),),- onSuccess: async (_bindings, enabled) => {- await queryClient.invalidateQueries({ queryKey: bindingQueryKey })- notifySuccess(- enabled- ? 'Codex enabled for this project.'- : 'Codex disabled for this project.',- )- },- onError: (error, enabled) =>- notifyError(- enabled- ? "Couldn't enable Codex for this project."- : "Couldn't disable Codex for this project.",- error,- ),- })- const validateConnection = useMutation({- mutationFn: () => validateManagedModelAccessConnection(codex!.id),onSuccess: async () => {- await queryClient.invalidateQueries({ queryKey: connectionQueryKey })- notifySuccess('Codex account revalidated.')+ setConfirmRemoveRoute(false)+ await queryClient.invalidateQueries({ queryKey: routeQueryKey })+ notifySuccess('Project model route removed.')},onError: (error) =>- notifyError("Couldn't revalidate the Codex account.", error),+ notifyError("Couldn't remove the project model route.", error),})- const disconnectConnection = useMutation({- mutationFn: () => disconnectManagedModelAccessConnection(codex!.id),+ const configureApiRoute = useMutation({+ mutationFn: async () => {+ const connection = await connectManagedModelApiKey({+ provider: apiProvider,+ apiKey,+ ...(apiProvider === 'openai_compatible' ? { baseUrl } : {}),+ })+ return Promise.all(+ (['development', 'production'] as const).map((environment) =>+ putManagedModelRoute({+ projectId,+ environment,+ connectionId: connection.id,+ model: routeModel,+ fallback: routeFallback,+ }),+ ),+ )+ },onSuccess: async () => {- setConfirmDisconnect(false)+ setApiKey('')await Promise.all([queryClient.invalidateQueries({ queryKey: connectionQueryKey }),- queryClient.invalidateQueries({ queryKey: bindingQueryKey }),+ queryClient.invalidateQueries({ queryKey: routeQueryKey }),])- notifySuccess('Codex account disconnected.')+ notifySuccess('Model connection and project route configured.')},onError: (error) =>- notifyError("Couldn't disconnect the Codex account.", error),+ notifyError("Couldn't configure the model route.", error),})if (billingLoading ||- (planEligible && (connections.isLoading || bindings.isLoading))+ (planEligible && (connections.isLoading || routes.isLoading))) {return (<Panel>@@ -195,7 +139,7 @@ export function ManagedProjectBYOK({if (billingError ||- (planEligible && (connections.isError || bindings.isError))+ (planEligible && (connections.isError || routes.isError))) {return (<Panel>@@ -228,7 +172,7 @@ export function ManagedProjectBYOK({<EmptyStateicon={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."+ description="Upgrade to Pro to connect your model provider and configure a project model route."action={<Button asChild><Link to="/billing">Upgrade to Pro</Link>@@ -244,194 +188,178 @@ export function ManagedProjectBYOK({<Panel><PanelHeader><div>- <PanelTitle>BYOK</PanelTitle>+ <PanelTitle>Bring your own model</PanelTitle><PanelDescription className="mt-1 max-w-2xl">- Connect one Codex account to your organization, then enable it for- the projects that should use it. Project enablement always covers- both development and production. Managed usage-based inference- remains the fallback. Runtime compute is still charged.+ Send every new session through your OpenRouter or+ OpenAI-compatible API key. This project route overrides useModel()+ and also works when agent code selects no model.</PanelDescription></div></PanelHeader>- <PanelContent className="space-y-6">- <div>- <p className="text-muted-foreground text-xs font-medium uppercase">- Connected accounts- </p>- <div className="mt-2 flex flex-wrap items-center gap-2">- <span className="text-sm font-medium">Codex account</span>- {codex ? (- <StatusBadge- status={connectionTone(codex.status)}- label={codex.status.replace(/_/g, ' ')}- />- ) : (- <StatusBadge status="stopped" label="Not connected" />- )}- </div>- <p className="text-muted-foreground mt-2 text-sm">- {codex- ? `Connected to your organization${codex.checkedAt ? ` · checked ${new Date(codex.checkedAt).toLocaleString()}` : ''}`- : 'No Codex account is linked.'}- </p>- <div className="mt-4">- <p className="text-muted-foreground text-xs font-medium uppercase">- Project access- </p>- <div className="mt-2 flex flex-wrap items-center gap-2">- <StatusBadge- status={projectEnabled ? 'running' : 'stopped'}- label={- projectEnabled- ? 'Enabled for development and production'- : 'Not enabled for this project'- }- />- </div>- {codex && !projectEnabled ? (- <div className="mt-3 space-y-3">- <p className="text-muted-foreground text-sm">- The organization account is connected, but this project will- use Managed inference until it is enabled.- </p>- {canManageConnection && codex.status === 'connected' ? (- <Button- variant="outline"- disabled={updateProjectAccess.isPending}- onClick={() => updateProjectAccess.mutate(true)}+ <PanelContent className="space-y-4">+ {routes.data?.length ? (+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="space-y-2">+ {routes.data.map((route) => {+ const connection = connections.data?.find(+ (candidate) => candidate.id === route.connectionId,+ )+ return (+ <div+ key={route.id}+ className="flex flex-wrap items-center gap-2 text-sm">- {updateProjectAccess.isPending ? (- <Loader2 className="animate-spin" />- ) : (- <Link2 />- )}- Enable for this project- </Button>- ) : null}- </div>- ) : null}- {canManageConnection && projectEnabled ? (- <div className="mt-3 space-y-3">- <p className="text-muted-foreground text-sm">- Disable Codex here to return this project to Managed- inference without disconnecting the organization account.- </p>- <Button- variant="outline"- disabled={updateProjectAccess.isPending}- onClick={() => updateProjectAccess.mutate(false)}- >- {updateProjectAccess.isPending ? (- <Loader2 className="animate-spin" />- ) : (- <Link2Off />- )}- Disable for this project- </Button>- </div>+ <StatusBadge status="running" label={route.environment} />+ <span>{route.model}</span>+ <span className="text-muted-foreground">+ via{' '}+ {connection+ ? modelConnectionLabel(connection)+ : route.connectionId}{' '}+ · {route.fallback} · r{route.revision}+ </span>+ </div>+ )+ })}+ </div>+ {canManageConnection ? (+ <Button+ type="button"+ variant="outline"+ disabled={removeRoute.isPending}+ onClick={() => setConfirmRemoveRoute(true)}+ >+ {removeRoute.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <Trash2 />+ )}+ Remove route+ </Button>) : null}</div>- </div>-- {canManageConnection && codex ? (- <div className="flex flex-wrap gap-2 border-t pt-5">- <Button- variant="outline"- disabled={validateConnection.isPending}- onClick={() => validateConnection.mutate()}- >- {validateConnection.isPending ? (- <Loader2 className="animate-spin" />- ) : (- <RefreshCw />- )}- Revalidate- </Button>- <Button- variant="outline"- disabled={disconnectConnection.isPending}- onClick={() => setConfirmDisconnect(true)}- >- <Unplug /> Disconnect- </Button>- </div>- ) : null}-- {!canManageConnection && !codex ? (+ ) : (<p className="text-muted-foreground text-sm">- Ask an organization admin to connect a model account.+ No project override. Agent code and the platform default determine+ the model.</p>+ )}+ {canManageConnection ? (+ <div className="grid gap-3 border-t pt-4 md:grid-cols-2">+ <label className="space-y-1 text-sm">+ <span className="font-medium">Provider</span>+ <select+ className="border-input bg-background h-9 w-full rounded-md border px-3"+ value={apiProvider}+ onChange={(event) => {+ setApiKey('')+ setApiProvider(+ event.target.value as ModelRouteProviderChoice,+ )+ setRouteModel(+ MODEL_ROUTE_PROVIDER_DEFAULTS[+ event.target.value as ModelRouteProviderChoice+ ].model,+ )+ }}+ >+ <option value="openrouter">OpenRouter API key</option>+ <option value="openai_compatible">+ Custom OpenAI-compatible API+ </option>+ {SUBSCRIPTION_ROUTE_AVAILABILITY.map((provider) => (+ <option+ key={provider.id}+ value={provider.id}+ disabled={provider.disabled}+ >+ {provider.label}+ </option>+ ))}+ </select>+ <span className="text-muted-foreground block text-xs">+ Codex and Claude subscription connections are coming soon.+ </span>+ </label>+ <label className="space-y-1 text-sm">+ <span className="font-medium">Provider model ID</span>+ <input+ className="border-input bg-background h-9 w-full rounded-md border px-3"+ value={routeModel}+ list={`model-route-${apiProvider}-models`}+ autoComplete="off"+ onChange={(event) => setRouteModel(event.target.value)}+ />+ <datalist id={`model-route-${apiProvider}-models`}>+ {MODEL_ROUTE_MODEL_SUGGESTIONS[apiProvider].map((model) => (+ <option key={model} value={model} />+ ))}+ </datalist>+ </label>+ {apiProvider === 'openai_compatible' ? (+ <label className="space-y-1 text-sm">+ <span className="font-medium">Base URL</span>+ <input+ className="border-input bg-background h-9 w-full rounded-md border px-3"+ type="url"+ value={baseUrl}+ placeholder="https://api.example.com/v1"+ onChange={(event) => setBaseUrl(event.target.value)}+ />+ </label>+ ) : null}+ <label className="space-y-1 text-sm">+ <span className="font-medium">API key</span>+ <input+ className="border-input bg-background h-9 w-full rounded-md border px-3"+ type="password"+ autoComplete="off"+ value={apiKey}+ onChange={(event) => setApiKey(event.target.value)}+ />+ </label>+ <label className="space-y-1 text-sm">+ <span className="font-medium">If unavailable</span>+ <select+ className="border-input bg-background h-9 w-full rounded-md border px-3"+ value={routeFallback}+ onChange={(event) =>+ setRouteFallback(event.target.value as 'fail' | 'managed')+ }+ >+ <option value="fail">Fail closed</option>+ <option value="managed">Use Managed</option>+ </select>+ </label>+ <div className="flex items-end">+ <Button+ disabled={+ !routeModel ||+ (apiProvider === 'openai_compatible' && !baseUrl) ||+ !apiKey ||+ configureApiRoute.isPending+ }+ onClick={() => configureApiRoute.mutate()}+ >+ {configureApiRoute.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <Link2 />+ )}+ Connect and save route+ </Button>+ </div>+ </div>) : null}</PanelContent></Panel>-- <Panel>- <PanelHeader>- <div>- <PanelTitle>Use the account in agent code</PanelTitle>- <PanelDescription className="mt-1 max-w-2xl">- Select the model-access provider explicitly. Connected accounts- use their native provider; Managed models use OpenRouter.- </PanelDescription>- </div>- </PanelHeader>- <PanelContent className="space-y-4">- <div>- <p className="mb-2 text-sm font-medium">Codex account eligible</p>- <CopyRow- value={'useModel({ provider: "openai", model: "gpt-5.6-sol" })'}- />- </div>- <div>- <p className="mb-2 text-sm font-medium">- Managed OpenRouter · OpenAI- </p>- <CopyRow- value={- 'useModel({ provider: "openrouter", model: "openai/gpt-5" })'- }- />- </div>- <div>- <p className="mb-2 text-sm font-medium">- Managed OpenRouter · Anthropic- </p>- <CopyRow- value={- 'useModel({ provider: "openrouter", model: "anthropic/claude-sonnet-4.6" })'- }- />- </div>- </PanelContent>- </Panel>-- <Panel>- <PanelHeader>- <div>- <PanelTitle>- {codex- ? 'Replace the organization account with the CLI'- : 'Connect an organization account with the CLI'}- </PanelTitle>- <PanelDescription className="mt-1 max-w-2xl">- The Codex command opens OAuth, links or replaces the organization- account, and enables it for this project. If the account is- already connected, use the button above to enable this project- without repeating OAuth.- </PanelDescription>- </div>- </PanelHeader>- <PanelContent className="space-y-4">- <CopyRow value={cliCommand} />- </PanelContent>- </Panel><ConfirmDialog- open={confirmDisconnect}- onOpenChange={setConfirmDisconnect}- title="Disconnect the Codex account?"- description="Projects using this account will return to Managed inference."- confirmLabel="Disconnect account"- onConfirm={() => disconnectConnection.mutate()}+ open={confirmRemoveRoute}+ onOpenChange={setConfirmRemoveRoute}+ title="Remove this project route?"+ description="New sessions will use the model selected by agent code or the platform default. The provider connection remains available to other projects."+ confirmLabel="Remove route"+ onConfirm={() => removeRoute.mutate()}/></div>)diff --git a/web/src/managed-agents/DebugInspector.test.ts b/web/src/managed-agents/DebugInspector.test.tsnew file mode 100644index 00000000..eee74b7c--- /dev/null+++ b/web/src/managed-agents/DebugInspector.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it } from 'vitest'+import { modelRouteForRender } from './DebugInspector'+import type { ManagedAgentEvent } from './api'++function event(+ seq: number,+ type: string,+ data: Record<string, unknown>,+): ManagedAgentEvent {+ return { seq, type, data }+}++describe('modelRouteForRender', () => {+ it('associates a gateway resolution emitted immediately before its render', () => {+ const events = [+ event(1, 'turn.started', {}),+ event(2, 'model.route_resolved', {+ requested: {+ provider: 'openrouter',+ model: 'anthropic/claude-sonnet-4.6',+ },+ effective: { provider: 'connection', model: 'GLM-5.3' },+ runtime: 'opencode',+ access: {+ type: 'external_api_key',+ connectionKind: 'openai_compatible_api',+ },+ source: 'project_route',+ routeId: 'mr_1',+ routeRevision: 1,+ fallback: 'fail',+ openComputerModelChargeUsd: 0,+ }),+ event(3, 'agent.rendered', {}),+ event(4, 'turn.completed', {}),+ ]++ expect(modelRouteForRender(events, events[2]!)).toMatchObject({+ effective: { provider: 'connection', model: 'GLM-5.3' },+ source: 'project_route',+ routeRevision: 1,+ })+ })++ it('does not reuse a previous turn route for the next render', () => {+ const events = [+ event(1, 'model.route_resolved', {+ effective: { provider: 'connection', model: 'GLM-5.3' },+ runtime: 'opencode',+ access: { type: 'external_api_key' },+ openComputerModelChargeUsd: 0,+ }),+ event(2, 'agent.rendered', {}),+ event(3, 'agent.rendered', {}),+ ]++ expect(modelRouteForRender(events, events[2]!)).toBeUndefined()+ })+})diff --git a/web/src/managed-agents/DebugInspector.tsx b/web/src/managed-agents/DebugInspector.tsxindex f28f190d..b452cd95 100644--- a/web/src/managed-agents/DebugInspector.tsx+++ b/web/src/managed-agents/DebugInspector.tsx@@ -16,6 +16,32 @@ import {type ManagedAgentRenderDebug,} from './api'+export function modelRouteForRender(+ events: ManagedAgentEvent[],+ renderEvent: ManagedAgentEvent,+) {+ const renderIndex = events.indexOf(renderEvent)+ if (renderIndex < 0) return undefined+ let previousRenderIndex = -1+ for (let index = renderIndex - 1; index >= 0; index -= 1) {+ if (events[index]?.type === 'agent.rendered') {+ previousRenderIndex = index+ break+ }+ }+ const nextRenderIndex = events.findIndex(+ (event, index) => index > renderIndex && event.type === 'agent.rendered',+ )+ const routes = events+ .slice(+ previousRenderIndex + 1,+ nextRenderIndex < 0 ? undefined : nextRenderIndex,+ )+ .map(managedAgentModelRoute)+ .filter((route) => route !== undefined)+ return routes[routes.length - 1]+}+function eventSummary(event: ManagedAgentEvent) {if (event.type === 'runtime.log') {return typeof event.data.message === 'string'@@ -188,32 +214,21 @@ export function DebugInspector({: -1const previous =actualIndex > 0 ? renders[actualIndex - 1]?.render : undefined- const selectedEventIndex = selected ? events.indexOf(selected.event) : -1- const nextRenderIndex =- selectedEventIndex >= 0- ? events.findIndex(- (event, index) =>- index > selectedEventIndex && event.type === 'agent.rendered',- )- : -1- const route =- selectedEventIndex >= 0- ? events- .slice(- selectedEventIndex + 1,- nextRenderIndex < 0 ? undefined : nextRenderIndex,- )- .map(managedAgentModelRoute)- .find(Boolean)- : undefined+ const route = selected+ ? modelRouteForRender(events, selected.event)+ : undefinedconst accessLabel =route?.access.type === 'external_subscription'? route.access.connectionKind === 'codex_subscription'? 'Codex account · BYOK': 'Connected account · BYOK'- : route?.access.type === 'managed'- ? 'Managed · usage-based'- : 'Not resolved yet'+ : route?.access.type === 'external_api_key'+ ? route.access.connectionKind === 'openrouter_api_key'+ ? 'OpenRouter API key · BYOK'+ : 'OpenAI-compatible API · BYOK'+ : route?.access.type === 'managed'+ ? 'Managed · usage-based'+ : 'Not resolved yet'const activity = events.filter((event) =>@@ -275,23 +290,40 @@ export function DebugInspector({<div className="bg-background grid grid-cols-2 gap-3 rounded-md border p-3 text-xs"><div>- <p className="text-muted-foreground">Model</p>+ <p className="text-muted-foreground">Requested model</p><p className="mt-1 font-mono text-[10px] break-all">- {selected.render.model- ? `${selected.render.model.provider}/${selected.render.model.model}`- : 'Default'}+ {route?.requested+ ? `${route.requested.provider}/${route.requested.model}`+ : selected.render.model+ ? `${selected.render.model.provider}/${selected.render.model.model}`+ : 'Default'}</p>- <p className="text-muted-foreground mt-1 text-[10px]">- {accessLabel}+ </div>+ <div>+ <p className="text-muted-foreground">Effective model</p>+ <p className="mt-1 font-mono text-[10px] break-all">+ {route?.effective+ ? `${route.effective.provider}/${route.effective.model}`+ : 'Not resolved yet'}</p></div><div>- <p className="text-muted-foreground">Provider turn</p>- <p className="mt-1 font-mono">{selected.render.providerTurn}</p>+ <p className="text-muted-foreground">Access</p>+ <p className="mt-1 text-[10px]">{accessLabel}</p>+ </div>+ <div>+ <p className="text-muted-foreground">Route</p>+ <p className="mt-1 text-[10px]">+ {route?.source+ ? `${route.source.replace(/_/g, ' ')}${route.routeRevision ? ` · r${route.routeRevision}` : ''}`+ : route?.routeId+ ? `Project override${route.routeRevision ? ` · r${route.routeRevision}` : ''}`+ : 'Code or platform default'}+ </p></div><div>- <p className="text-muted-foreground">State version</p>- <p className="mt-1 font-mono">{selected.render.stateVersion}</p>+ <p className="text-muted-foreground">Provider turn</p>+ <p className="mt-1 font-mono">{selected.render.providerTurn}</p></div><div><p className="text-muted-foreground">Rendered</p>diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex 03d4c5bd..2e46fcc7 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -1287,10 +1287,7 @@ export default function ManagedAgentDetail({) : null}{activeTab === 'byok' && project ? (- <ManagedProjectBYOK- projectId={project.project.id}- projectSlug={project.project.slug}- />+ <ManagedProjectBYOK projectId={project.project.id} />) : null}{activeTab === 'connections' && project ? (diff --git a/web/src/managed-agents/ModelAccessCallback.tsx b/web/src/managed-agents/ModelAccessCallback.tsxindex dfa968ba..8550b77c 100644--- a/web/src/managed-agents/ModelAccessCallback.tsx+++ b/web/src/managed-agents/ModelAccessCallback.tsx@@ -4,7 +4,10 @@ import { Link, useNavigate, useSearchParams } from 'react-router-dom'import { Panel, PanelContent } from '@/components/panel'import { Button } from '@/components/ui/button'import { completeManagedModelAccess, putManagedModelAccessBinding } from './api'-import { MODEL_ACCESS_PROJECT_KEY, MODEL_ACCESS_RETURN_TO_KEY } from './BYOK'+import {+ MODEL_ACCESS_PROJECT_KEY,+ MODEL_ACCESS_RETURN_TO_KEY,+} from './byok-config'type CallbackState = 'completing' | 'failed'diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex ae92c375..170a6ce8 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -222,9 +222,15 @@ const modelAccessConnectionSchema = z.object({id: z.string(),organizationId: z.string().optional(),connectedByUserId: z.string().optional(),- provider: z.enum(['anthropic', 'openai']),- kind: z.enum(['claude_subscription', 'codex_subscription']),+ provider: z.enum(['anthropic', 'openai', 'openrouter', 'openai_compatible']),+ kind: z.enum([+ 'claude_subscription',+ 'codex_subscription',+ 'openrouter_api_key',+ 'openai_compatible_api',+ ]),label: z.string(),+ baseUrl: z.string().url().nullish(),externalAccountHint: z.string().nullish(),status: z.enum(['connecting',@@ -265,6 +271,23 @@ const modelAccessBindingsResponseSchema = z.object({data: z.array(modelAccessBindingSchema),})+const projectModelRouteSchema = z.object({+ id: z.string(),+ projectId: z.string(),+ environment: z.enum(['development', 'production']),+ agentId: z.string().nullish(),+ connectionId: z.string(),+ model: z.string(),+ fallback: z.enum(['fail', 'managed']),+ revision: z.number(),+ createdAt: z.string().nullish(),+ updatedAt: z.string().nullish(),+})++const modelRoutesResponseSchema = z.object({+ data: z.array(projectModelRouteSchema),+})+const runtimeVariableSchema = z.object({name: z.string(),projectId: z.string(),@@ -593,10 +616,16 @@ const modelRouteSchema = z.object({.optional(),runtime: z.string(),access: z.object({- type: z.enum(['managed', 'external_subscription']),+ type: z.enum(['managed', 'external_subscription', 'external_api_key']),connectionId: z.string().optional(),connectionKind: z.string().optional(),}),+ source: z+ .enum(['agent_route', 'project_route', 'use_model', 'platform_default'])+ .optional(),+ routeId: z.string().optional(),+ routeRevision: z.number().optional(),+ fallback: z.enum(['fail', 'managed']).optional(),openComputerModelChargeUsd: z.number().nullable(),})@@ -800,6 +829,7 @@ export type ManagedModelAccessConnection = z.infer<typeof modelAccessConnectionSchema>export type ManagedModelAccessBinding = z.infer<typeof modelAccessBindingSchema>+export type ManagedProjectModelRoute = z.infer<typeof projectModelRouteSchema>export type TemplateInspection = z.infer<typeof templateInspectionSchema>export type TemplateInstallation = z.infer<typeof templateInstallationSchema>@@ -1006,6 +1036,85 @@ export async function connectManagedModelAccess() {)}+export async function connectManagedModelApiKey(input: {+ provider: 'openrouter' | 'openai_compatible'+ apiKey: string+ baseUrl?: string+ label?: string+}) {+ return apiFetch(+ '/managed-agents/model-access/connections',+ {+ method: 'POST',+ body: JSON.stringify({+ provider: input.provider,+ api_key: input.apiKey,+ base_url: input.baseUrl,+ label: input.label,+ }),+ },+ modelAccessConnectionSchema,+ )+}++export async function connectManagedClaudeSetupToken(token: string) {+ return apiFetch(+ '/managed-agents/model-access/connections',+ {+ method: 'POST',+ body: JSON.stringify({ provider: 'anthropic', token }),+ },+ modelAccessConnectionSchema,+ )+}++export async function getManagedModelRoutes(projectId: string) {+ return (+ await apiFetch(+ `/managed-agents/projects/${encodeURIComponent(projectId)}/model-routes`,+ undefined,+ modelRoutesResponseSchema,+ )+ ).data+}++export async function putManagedModelRoute(input: {+ projectId: string+ environment: 'development' | 'production'+ connectionId: string+ model: string+ fallback: 'fail' | 'managed'+ agentId?: string+}) {+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-routes/${input.environment}`,+ {+ method: 'PUT',+ body: JSON.stringify({+ connection_id: input.connectionId,+ model: input.model,+ fallback: input.fallback,+ agent_id: input.agentId,+ }),+ },+ projectModelRouteSchema,+ )+}++export async function deleteManagedModelRoute(input: {+ projectId: string+ environment: 'development' | 'production'+ agentId?: string+}) {+ return apiFetch<void>(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-routes/${input.environment}`,+ {+ method: 'DELETE',+ body: JSON.stringify(input.agentId ? { agent_id: input.agentId } : {}),+ },+ )+}+export async function completeManagedModelAccess(id: string,code: string,diff --git a/web/src/managed-agents/byok-config.ts b/web/src/managed-agents/byok-config.tsnew file mode 100644index 00000000..c57d9a4a--- /dev/null+++ b/web/src/managed-agents/byok-config.ts@@ -0,0 +1,55 @@+export const MODEL_ACCESS_RETURN_TO_KEY = 'opencomputer:model-access:return-to'+export const MODEL_ACCESS_PROJECT_KEY = 'opencomputer:model-access:project'++export type ModelRouteProviderChoice = 'openrouter' | 'openai_compatible'++export const MODEL_ROUTE_PROVIDER_DEFAULTS: Record<+ ModelRouteProviderChoice,+ { model: string }+> = {+ openrouter: { model: 'openai/gpt-5' },+ openai_compatible: { model: '' },+}++export const DEFAULT_MODEL_ROUTE_PROVIDER: ModelRouteProviderChoice =+ 'openrouter'++export const SUBSCRIPTION_ROUTE_AVAILABILITY = [+ {+ id: 'codex',+ label: 'Codex subscription — Coming soon',+ disabled: true,+ },+ {+ id: 'claude',+ label: 'Claude subscription — Coming soon',+ disabled: true,+ },+] as const++export const MODEL_ROUTE_MODEL_SUGGESTIONS: Record<+ ModelRouteProviderChoice,+ string[]+> = {+ openrouter: ['openai/gpt-5', 'anthropic/claude-sonnet-4.6'],+ openai_compatible: [],+}++export function modelConnectionLabel(connection: {+ id: string+ label: string+ baseUrl?: string | null+}) {+ if (connection.baseUrl) {+ try {+ return `${connection.label} · ${new URL(connection.baseUrl).hostname}`+ } catch {+ // The API validates URLs; retain the safe label if older data does not.+ }+ }+ return connection.label || connection.id+}++export function hasBYOKPlanAccess(plan: string | undefined) {+ return plan === 'pro' || plan === 'max'+}