An open-source, faster Devin alternative
TypeScript
feat: BYO Claude/Codex subscription — public API contracts, Autumn entitlement, dashboard, CLI (#680)
Mohamed Habib18faab908bbe
diff --git a/agent/README.md b/agent/README.mdindex 5929e883..7178109b 100644--- a/agent/README.md+++ b/agent/README.md@@ -21,6 +21,8 @@ describe that call; they do not perform I/O or run the durable agent loop.human-in-the-loop prompt; interactive clarification remains a tool action.- `useModel()` chooses a model. A string uses OpenRouter and retains its normal`provider/model` spelling.+- To select an OpenAI-native model that can use a project Codex subscription,+ use an explicit provider: `useModel({ provider: "openai", model: "gpt-5" })`.- `useTool()` and `useSubagent()` select declared capabilities.- `useSessionData()` reads the current durable session-data snapshot.- `useMcpServer()` conditionally selects a declared MCP server.diff --git a/cli/src/api.ts b/cli/src/api.tsindex c6458528..cf800726 100644--- a/cli/src/api.ts+++ b/cli/src/api.ts@@ -57,6 +57,34 @@ export interface ManagedSecretMetadata {updatedAt: string;}+// Model access (work 011). The provider token is write-only; these shapes+// carry only normalized metadata.+export interface ModelAccessConnection {+ id: string;+ organizationId: string;+ connectedByUserId: string;+ provider: "anthropic" | "openai";+ kind: "claude_subscription" | "codex_subscription";+ label: string;+ externalAccountHint?: string;+ status: string;+ checkedAt?: string;+ createdAt?: string;+ updatedAt?: string;+}++export interface ModelAccessBinding {+ organizationId: string;+ projectId: string;+ environment: "development" | "production";+ provider: "anthropic" | "openai";+ connectionId: string;+ enabled: boolean;+ enabledByUserId?: string;+ createdAt?: string;+ updatedAt?: string;+}+export interface AgentRuntimeVariableMetadata {name: string;projectId: string;@@ -285,6 +313,79 @@ export class OpenComputerClient {);}+ // ── Model access (work 011) ──────────────────────────────────────────────+ async modelAccessConnections(): Promise<ModelAccessConnection[]> {+ const result = await this.request<{ data: ModelAccessConnection[] }>(+ "/api/managed-agents/model-access/connections",+ );+ return result.data;+ }++ // Starts the personal Codex subscription OAuth flow. No token is given or+ // accepted; returns a pending intent with an authorize_url.+ connectModelAccess(input: { provider: "openai"; label?: string }) {+ return this.request<{+ connection: ModelAccessConnection;+ status: "pending";+ authorize_url: string;+ expires_at: string;+ }>("/api/managed-agents/model-access/connections", {+ method: "POST",+ body: JSON.stringify(input),+ });+ }++ // Relays a credential the local CLI obtained through the authorized Codex+ // OAuth flow into a connected subscription (encrypted custody server-side).+ relayModelAccess(+ id: string,+ credential: {+ access_token: string;+ refresh_token?: string;+ token_type: string;+ expires_at: number;+ },+ ) {+ return this.request<ModelAccessConnection>(+ `/api/managed-agents/model-access/connections/${encodeURIComponent(id)}/complete`,+ {+ method: "POST",+ body: JSON.stringify({+ access_token: credential.access_token,+ refresh_token: credential.refresh_token,+ token_type: credential.token_type,+ expires_at: credential.expires_at,+ }),+ },+ );+ }++ disconnectModelAccess(id: string) {+ return this.request<ModelAccessConnection>(+ `/api/managed-agents/model-access/connections/${encodeURIComponent(id)}`,+ { method: "DELETE" },+ );+ }++ async modelAccessBindings(projectId: string): Promise<ModelAccessBinding[]> {+ const result = await this.request<{ data: ModelAccessBinding[] }>(+ `/api/managed-agents/projects/${encodeURIComponent(projectId)}/model-access/bindings`,+ );+ return result.data;+ }++ putModelAccessBinding(input: {+ projectId: string;+ provider: "anthropic" | "openai";+ environment: "development" | "production";+ enabled: boolean;+ }) {+ return this.request<ModelAccessBinding>(+ `/api/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-access/bindings/${input.provider}/${input.environment}`,+ { method: "PUT", body: JSON.stringify({ enabled: input.enabled }) },+ );+ }+async runtimeVariables(input: {projectId: string;environment?: "development" | "production";diff --git a/cli/src/codex-oauth.test.ts b/cli/src/codex-oauth.test.tsnew file mode 100644index 00000000..ea6c5742--- /dev/null+++ b/cli/src/codex-oauth.test.ts@@ -0,0 +1,39 @@+import assert from "node:assert/strict";+import http from "node:http";+import type { AddressInfo } from "node:net";+import test from "node:test";++import { exchangeCodeOnCallback } from "./codex-oauth.js";++async function availablePort(): Promise<number> {+ const server = http.createServer();+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const port = (server.address() as AddressInfo).port;+ await new Promise<void>((resolve, reject) =>+ server.close((error) => (error ? reject(error) : resolve())),+ );+ return port;+}++test("Codex OAuth callback closes its listener before resolving", async () => {+ const port = await availablePort();+ const code = await exchangeCodeOnCallback(+ "https://auth.openai.com/oauth/authorize",+ "expected-state",+ port,+ () => {+ void fetch(+ `http://127.0.0.1:${port}/auth/callback?code=test-code&state=expected-state`,+ );+ },+ );+ assert.equal(code, "test-code");++ const rebound = http.createServer();+ await new Promise<void>((resolve) =>+ rebound.listen(port, "127.0.0.1", resolve),+ );+ await new Promise<void>((resolve, reject) =>+ rebound.close((error) => (error ? reject(error) : resolve())),+ );+});diff --git a/cli/src/codex-oauth.ts b/cli/src/codex-oauth.tsnew file mode 100644index 00000000..0c7a4639--- /dev/null+++ b/cli/src/codex-oauth.ts@@ -0,0 +1,213 @@+import http from "node:http";+import { randomBytes } from "node:crypto";+import { spawn } from "node:child_process";+import { platform } from "node:os";++// Local personal-Codex-subscription OAuth (work 011). The CLI performs the+// OAuth exchange on the user's machine against the authorized Codex endpoints,+// then relays the resulting credential to OpenComputer as a connected+// subscription. Nothing sensitive is ever shown or written to the repo.++// Observed Codex/OpenAI endpoints (see work 011 "Provider authorization").+const AUTHORIZE_URL = "https://auth.openai.com/oauth/authorize";+const TOKEN_URL = "https://auth.openai.com/oauth/token";+const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";+const SCOPE = "openid profile email offline_access";+const CALLBACK_PORT = 1455;+const CALLBACK_PATH = "/auth/callback";++export interface RelayedCodexCredential {+ access_token: string;+ refresh_token?: string;+ token_type: string;+ expires_at: number;+}++interface TokenResponse {+ access_token: string;+ refresh_token?: string;+ token_type?: string;+ expires_in: number;+}++function base64url(bytes: Uint8Array): string {+ return Buffer.from(bytes)+ .toString("base64")+ .replaceAll("+", "-")+ .replaceAll("/", "_")+ .replace(/=+$/, "");+}++export async function codexLogin(): Promise<{+ credential: RelayedCodexCredential;+ accountHint: string;+}> {+ const codeVerifier = base64url(randomBytes(32));+ const challengeBytes = await crypto.subtle.digest(+ "SHA-256",+ new TextEncoder().encode(codeVerifier),+ );+ const codeChallenge = base64url(new Uint8Array(challengeBytes));+ const state = base64url(randomBytes(24));+ const redirectUri = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;++ const authorizeUrl = new URL(AUTHORIZE_URL);+ authorizeUrl.searchParams.set("client_id", CLIENT_ID);+ authorizeUrl.searchParams.set("redirect_uri", redirectUri);+ authorizeUrl.searchParams.set("response_type", "code");+ authorizeUrl.searchParams.set("prompt", "consent");+ authorizeUrl.searchParams.set("scope", SCOPE);+ authorizeUrl.searchParams.set("state", state);+ authorizeUrl.searchParams.set("code_challenge", codeChallenge);+ authorizeUrl.searchParams.set("code_challenge_method", "S256");+ authorizeUrl.searchParams.set("id_token_add_organizations", "true");+ authorizeUrl.searchParams.set("codex_cli_simplified_flow", "true");+ authorizeUrl.searchParams.set("originator", "opencode");++ const authCode = await exchangeCodeOnCallback(+ authorizeUrl.toString(),+ state,+ CALLBACK_PORT,+ );++ const token = await exchangeToken({+ tokenUrl: TOKEN_URL,+ clientId: CLIENT_ID,+ code: authCode,+ codeVerifier,+ redirectUri,+ });++ return {+ credential: {+ access_token: token.access_token,+ refresh_token: token.refresh_token,+ token_type: token.token_type ?? "Bearer",+ expires_at: Date.now() + token.expires_in * 1_000,+ },+ accountHint: token.access_token.slice(0, 8),+ };+}++// Starts a temporary localhost callback server, opens the browser to the+// authorize URL, and resolves the one-time authorization code.+export function exchangeCodeOnCallback(+ authorizeUrl: string,+ expectedState: string,+ port: number,+ launchBrowser: (url: string) => void = openBrowser,+): Promise<string> {+ return new Promise((resolve, reject) => {+ let settled = false;+ const server = http.createServer((req, res) => {+ const url = new URL(req.url ?? "/", `http://localhost:${port}`);+ if (url.pathname !== CALLBACK_PATH) {+ res.writeHead(404).end();+ return;+ }+ if (settled) {+ res.writeHead(409, { connection: "close" }).end();+ return;+ }+ settled = true;+ const finish = (+ status: number,+ message: string,+ result: { code: string } | { error: Error },+ ): void => {+ res.writeHead(status, {+ "content-type": "text/plain",+ connection: "close",+ });+ res.end(message, () => {+ server.close((closeError) => {+ if (closeError) reject(closeError);+ else if ("code" in result) resolve(result.code);+ else reject(result.error);+ });+ server.closeAllConnections();+ });+ };+ const code = url.searchParams.get("code");+ const state = url.searchParams.get("state");+ if (!state || !secureEqual(state, expectedState)) {+ finish(+ 401,+ "OAuth state mismatch. Please close this window and retry.",+ { error: new Error("OAuth state mismatch") },+ );+ return;+ }+ if (!code) {+ const error = url.searchParams.get("error") ?? "missing code";+ finish(400, `Authorization failed: ${error}`, {+ error: new Error(`Authorization failed: ${error}`),+ });+ return;+ }+ finish(200, "Authorized. You can close this window.", { code });+ });++ server.on("error", (error) => {+ reject(error);+ });++ server.listen(port, "127.0.0.1", () => {+ launchBrowser(authorizeUrl);+ });+ });+}++async function exchangeToken(input: {+ tokenUrl: string;+ clientId: string;+ code: string;+ codeVerifier: string;+ redirectUri: string;+}): Promise<TokenResponse> {+ const body = new URLSearchParams({+ client_id: input.clientId,+ code: input.code,+ code_verifier: input.codeVerifier,+ grant_type: "authorization_code",+ redirect_uri: input.redirectUri,+ });+ const response = await fetch(input.tokenUrl, {+ method: "POST",+ headers: { "content-type": "application/x-www-form-urlencoded" },+ body,+ });+ const value: unknown = await response.json().catch(() => null);+ if (!response.ok) {+ throw new Error(`Codex token exchange failed (${String(response.status)})`);+ }+ const token = value as TokenResponse;+ if (typeof token?.access_token !== "string" || typeof token.expires_in !== "number") {+ throw new Error("Codex returned an invalid token response");+ }+ return token;+}++export function openBrowser(url: string): void {+ const command =+ platform() === "darwin"+ ? ["open", url]+ : platform() === "win32"+ ? ["rundll32", "url.dll,FileProtocolHandler", url]+ : ["xdg-open", url];+ const child = spawn(command[0]!, command.slice(1), {+ detached: true,+ stdio: "ignore",+ });+ child.once("error", () => undefined);+ child.unref();+}++function secureEqual(left: string, right: string): boolean {+ const a = Buffer.from(left);+ const b = Buffer.from(right);+ if (a.length !== b.length) return false;+ let diff = 0;+ for (let i = 0; i < a.length; i++) diff |= a[i]! ^ b[i]!;+ return diff === 0;+}diff --git a/cli/src/commands.test.ts b/cli/src/commands.test.tsnew file mode 100644index 00000000..894c3ac1--- /dev/null+++ b/cli/src/commands.test.ts@@ -0,0 +1,10 @@+import assert from "node:assert/strict";+import test from "node:test";++import { deploymentAlias } from "./commands.js";++test("one-shot deploy defaults to development and production stays explicit", () => {+ assert.equal(deploymentAlias(), "development");+ assert.equal(deploymentAlias("development"), "development");+ assert.equal(deploymentAlias("production"), "production");+});diff --git a/cli/src/commands.ts b/cli/src/commands.tsindex 3f4389df..bdfc1f57 100644--- a/cli/src/commands.ts+++ b/cli/src/commands.ts@@ -5,6 +5,7 @@ import {type ManagedSessionSnapshot,} from "./api.js";import { login, logout } from "./auth.js";+import { codexLogin } from "./codex-oauth.js";import { resolveConfig } from "./config.js";import {publishProjectDeployment,@@ -35,6 +36,10 @@ export interface GlobalOptions {verbose?: boolean;}+export function deploymentAlias(requestedAlias?: string): string {+ return requestedAlias ?? "development";+}+function printJSON(value: unknown): void {process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);}@@ -74,6 +79,13 @@ function environmentOption(throw new Error("--environment must be development or production");}+function consumeModelAccessProvider(args: string[]): "claude" | "codex" {+ if (args[0] === "claude" || args[0] === "codex") {+ return args.shift() as "claude" | "codex";+ }+ return "codex";+}+async function readSecretValue(): Promise<string> {if (!process.stdin.isTTY) {const chunks: Buffer[] = [];@@ -511,12 +523,16 @@ export async function runCommand(`Directory: ${initialized.root}\n` +`Project: choose or create one on the first watched deployment\n` +`Agents: opencomputer/\n` +- (spa ? `Web app: src/ (separate lifecycle)\n\n` : `App: agent only\n\n`) ++ (spa+ ? `Web app: src/ (separate lifecycle)\n\n`+ : `App: agent only\n\n`) +`Next:\n` +enterDirectory +` npm install\n` +` npm run deploy -- --watch # deploy changes to Development\n` +- (spa ? ` npm run dev:web # optional local web app\n` : ""),+ (spa+ ? ` npm run dev:web # optional local web app\n`+ : ""),);}return;@@ -587,7 +603,7 @@ export async function runCommand(if (project || createProjectName) {throw new Error("--project and --create-project require --watch");}- const alias = requestedAlias ?? "production";+ const alias = deploymentAlias(requestedAlias);const binding = await ensureProjectBinding(client, config, root, {interactive: !globals.json,select: true,@@ -752,6 +768,108 @@ export async function runCommand(throw new Error("Use `opencomputer secrets set`, `list`, or `remove`.");}+ if (command === "model-access") {+ const action = args.shift();+ if (action === "connect") {+ // Local Codex-account OAuth: open a localhost callback+ // server, complete the flow in the user's browser, then relay the+ // credential to OpenComputer as a connected account. Nothing secret+ // is echoed or persisted locally.+ const provider = consumeModelAccessProvider(args);+ if (provider !== "codex") {+ throw new Error(+ "Claude account BYOK is not supported. Connect a Codex account instead.",+ );+ }+ const projectReference = option(args, "--project");+ const legacyEnvironment = option(args, "--environment");+ if (legacyEnvironment && !projectReference)+ throw new Error("--environment requires --project <id|slug>");+ if (+ legacyEnvironment &&+ !["development", "production", "both"].includes(legacyEnvironment)+ )+ throw new Error("--environment must be development, production, or both");+ const environments = projectReference+ ? (["development", "production"] as const)+ : [];+ if (args.length) throw new Error(`Unexpected argument: ${args[0]}`);+ const project = projectReference+ ? await selectedProject(client, config, projectReference, false)+ : undefined;+ const receipt = await client.connectModelAccess({ provider: "openai" });+ process.stdout.write(+ "Opening a local callback and your browser to authorize your Codex account…\n",+ );+ const { credential, accountHint } = await codexLogin();+ const connection = await client.relayModelAccess(receipt.connection.id, {+ access_token: credential.access_token,+ refresh_token: credential.refresh_token,+ token_type: credential.token_type,+ expires_at: credential.expires_at,+ });+ const bindings = project+ ? await Promise.all(+ environments.map((environment) =>+ client.putModelAccessBinding({+ projectId: project.projectId,+ provider: "openai",+ environment,+ enabled: true,+ }),+ ),+ )+ : [];+ if (globals.json)+ printJSON({+ ...connection,+ external_account_hint: accountHint,+ bindings,+ });+ else {+ process.stdout.write(+ `Connected Codex account as ${connection.label}; status ${connection.status}.\n`,+ );+ if (project) {+ process.stdout.write(+ `Enabled Codex for ${project.projectId} (development and production).\n`,+ );+ }+ }+ return;+ }+ if (action === "list" || action === "ls" || action === undefined) {+ const connections = await client.modelAccessConnections();+ if (globals.json) printJSON(connections);+ else if (!connections.length)+ process.stdout.write("No model access connections.\n");+ else {+ for (const connection of connections) {+ process.stdout.write(+ `${connection.provider.padEnd(10)} ${connection.status.padEnd(18)} ` ++ `${connection.label}${connection.externalAccountHint ? ` (${connection.externalAccountHint})` : ""}\n`,+ );+ }+ }+ return;+ }+ if (action === "disconnect") {+ 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 connection = connections.find((c) => c.provider === apiProvider);+ if (!connection) throw new Error(`No ${provider} connection found.`);+ const updated = await client.disconnectModelAccess(connection.id);+ if (globals.json) printJSON(updated);+ else process.stdout.write(`Disconnected ${connection.label}.\n`);+ return;+ }+ throw new Error(+ "Use `opencomputer model-access connect|list|disconnect`.",+ );+ }+if (command === "env") {const action = args.shift();const projectReference = option(args, "--project");diff --git a/cli/src/index.ts b/cli/src/index.tsindex 97ab5ea7..3dd77669 100644--- a/cli/src/index.ts+++ b/cli/src/index.ts@@ -64,6 +64,9 @@ Usage:opencomputer env set <name> [--environment development|production] [--agent <agent>|current]opencomputer env list [--environment development|production] [--agent <agent>|current]opencomputer env remove <name> [--environment development|production] [--agent <agent>|current]+ opencomputer model-access connect codex [--project <id|slug>]+ opencomputer model-access list+ opencomputer model-access disconnect codexopencomputer 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>]@@ -71,7 +74,7 @@ Usage:opencomputer webhooks rotate-token <webhook-id> [--project <id|slug>]opencomputer webhooks remove <webhook-id> [--project <id|slug>]opencomputer logs [--agent <agent>] [--session <session-id>] [--environment development|production] [--follow]- opencomputer deploy [--alias <alias>] [--watch]+ opencomputer deploy [--alias development|production] [--watch]opencomputer run <agent> <prompt> [--keep]Global options:diff --git a/cli/src/project.test.ts b/cli/src/project.test.tsindex 27c1bb3f..ca56ab70 100644--- a/cli/src/project.test.ts+++ b/cli/src/project.test.ts@@ -347,6 +347,7 @@ export default function Agent() {url: string;connection?: string;}>;+ models: Array<{ provider: string; model: string }>;};assert.deepEqual(manifest, {version: 2,@@ -360,7 +361,21 @@ export default function Agent() {mcpServerDefinitions: [{ id: "docs", url: "https://mcp.example.com/" },],+ models: [+ {+ provider: "openrouter",+ model: "anthropic/claude-sonnet-4.6",+ },+ ],});+ assert.equal(+ (+ JSON.parse(+ await readFile(resolve(runtime, "opencode.json"), "utf8"),+ ) as { model: string }+ ).model,+ "openrouter/anthropic/claude-sonnet-4.6",+ );await assert.rejects(stat(resolve(initialized.agentRoot, "opencomputer.toml")),);@@ -369,6 +384,43 @@ export default function Agent() {}});+test("the compiler preserves an explicit OpenAI model selection for Codex routing", async () => {+ const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-openai-model-"));+ const root = resolve(parent, "app");+ try {+ const initialized = await initializeAgentProject(root);+ await writeFile(+ resolve(initialized.agentRoot, "agent.ts"),+ `import { useModel } from "@opencomputer/agent";++export default function Agent() {+ useModel({ provider: "openai", model: "gpt-5" });+ return "Help with the request.";+}+`,+ );++ const runtime = await prepareAgent(initialized.agentRoot);+ const manifest = JSON.parse(+ await readFile(+ resolve(runtime, ".opencomputer", "reactive.json"),+ "utf8",+ ),+ ) as { models: Array<{ provider: string; model: string }> };+ assert.deepEqual(manifest.models, [{ provider: "openai", model: "gpt-5" }]);+ assert.equal(+ (+ JSON.parse(+ await readFile(resolve(runtime, "opencode.json"), "utf8"),+ ) as { model: string }+ ).model,+ "openai/gpt-5",+ );+ } finally {+ await rm(parent, { recursive: true, force: true });+ }+});+test("the compiler records secret-backed HTTP connections without secret values", async () => {const parent = await mkdtemp(resolve(tmpdir(), "opencomputer-egress-"));const root = resolve(parent, "app");diff --git a/cli/src/project.ts b/cli/src/project.tsindex 688c9e28..6076a509 100644--- a/cli/src/project.ts+++ b/cli/src/project.ts@@ -1582,6 +1582,56 @@ function definedToolIds(source: string): string[] {.sort();}+function staticModelSelections(+ source: string,+): Array<{ provider: string; model: string }> {+ const file = ts.createSourceFile(+ "agent.ts",+ source,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TS,+ );+ const selections: Array<{ provider: string; model: string }> = [];+ const visit = (node: ts.Node): void => {+ if (+ ts.isCallExpression(node) &&+ ts.isIdentifier(node.expression) &&+ node.expression.text === "useModel"+ ) {+ const value = node.arguments[0];+ if (value && ts.isStringLiteralLike(value)) {+ selections.push({ provider: "openrouter", model: value.text });+ } else if (value && ts.isObjectLiteralExpression(value)) {+ let provider: string | undefined;+ let model: string | undefined;+ for (const property of value.properties) {+ if (!ts.isPropertyAssignment(property)) continue;+ const name = ts.isIdentifier(property.name)+ ? property.name.text+ : ts.isStringLiteralLike(property.name)+ ? property.name.text+ : undefined;+ if (!name || !ts.isStringLiteralLike(property.initializer)) continue;+ if (name === "provider") provider = property.initializer.text;+ if (name === "model") model = property.initializer.text;+ }+ if (provider && model) selections.push({ provider, model });+ }+ }+ ts.forEachChild(node, visit);+ };+ visit(file);+ return selections.filter(+ (selection, index) =>+ selections.findIndex(+ (candidate) =>+ candidate.provider === selection.provider &&+ candidate.model === selection.model,+ ) === index,+ );+}+function agentApiRuntimeSource(): string {return `function hooks() {const value = globalThis[Symbol.for("opencomputer.agent-hooks")];@@ -1708,13 +1758,21 @@ the product or support surface presented to users.`,);+ const declaredModels = staticModelSelections(agentSource);const openCodeConfig = resolve(root, "opencode.json");- if (await exists(openCodeConfig)) {- const parsed: unknown = JSON.parse(await readFile(openCodeConfig, "utf8"));+ const hasOpenCodeConfig = await exists(openCodeConfig);+ if (hasOpenCodeConfig || declaredModels.length === 1) {+ const parsed: unknown = hasOpenCodeConfig+ ? JSON.parse(await readFile(openCodeConfig, "utf8"))+ : {};if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {throw new Error("opencode.json must contain a JSON object");}const config = parsed as Record<string, unknown>;+ const inferredModel =+ declaredModels.length === 1+ ? `${declaredModels[0]!.provider}/${declaredModels[0]!.model}`+ : undefined;const configuredTools =config.tools &&typeof config.tools === "object" &&@@ -1735,6 +1793,9 @@ the product or support surface presented to users.`${JSON.stringify({...config,+ ...(config.model === undefined && inferredModel+ ? { model: inferredModel }+ : {}),tools: { ...configuredTools, question: !questionDenied },permission: {...configuredPermission,@@ -1937,6 +1998,7 @@ the product or support surface presented to users.]),].sort(),mcpServerDefinitions,+ models: declaredModels,},null,2,diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.tsindex 0e318c76..946c84f0 100644--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts@@ -37,8 +37,16 @@ class FakeStatement {if (!this.db.user) return null;return this.db.user as T;}- if (this.sql.includes("FROM api_keys WHERE key_hash")) {- return { org_id: orgID, created_by: userID, expires_at: null } as T;+ if (+ this.sql.includes("FROM api_keys WHERE key_hash") ||+ this.sql.includes("FROM api_keys k")+ ) {+ return {+ org_id: orgID,+ created_by: userID,+ expires_at: null,+ role: "admin",+ } as T;}if (this.sql.includes("SELECT o.name AS org_name")) {return { org_name: "Igor's workspace", email: "[email protected]" } as T;diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.tsindex 04482a19..da5bcdfb 100644--- a/cloudflare-workers/api-edge/src/dashboard.ts+++ b/cloudflare-workers/api-edge/src/dashboard.ts@@ -976,10 +976,20 @@ export async function handleDashboard(return json({ error: "managed model billing is unavailable" }, 503);}}+ const membership = await env.OPENCOMPUTER_DB.prepare(+ `SELECT role FROM org_memberships WHERE org_id = ?1 AND user_id = ?2`,+ ).bind(caller.orgID, caller.userID).first<{ role: string }>();return proxyManagedAgents(req,env,- caller,+ {+ orgID: caller.orgID,+ userID: caller.userID,+ role:+ membership?.role === "owner" || membership?.role === "admin"+ ? "admin"+ : membership?.role,+ },"/api/dashboard/managed-agents",);}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 39ad031b..ea6a301f 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -307,6 +307,7 @@ async function mintSandboxToken(interface Caller {orgID: string;userID: string | null;+ role?: string;// Set only for act-as-org provisioning tokens (sessions-api). Least-privilege:// the dispatch gates these to sandbox + secret-store routes (provisionScopeGate).scope?: "sandbox-provision";@@ -508,14 +509,28 @@ async function authenticate(req: Request, env: Env): Promise<Caller | null> {}const row = await env.OPENCOMPUTER_DB.prepare(- "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1",+ `SELECT k.org_id, k.created_by, k.expires_at,+ CASE WHEN m.role IN ('owner', 'admin') THEN 'admin' ELSE m.role END AS role+ FROM api_keys k+ LEFT JOIN org_memberships m+ ON m.org_id = k.org_id AND m.user_id = k.created_by+ WHERE k.key_hash = ?1`,).bind(hash)- .first<{ org_id: string; created_by: string | null; expires_at: number | null }>();+ .first<{+ org_id: string;+ created_by: string | null;+ expires_at: number | null;+ role: string | null;+ }>();if (!row) return null; // never cache negatives — a freshly-created key must work at onceif (row.expires_at && row.expires_at < nowSec) return null;- const caller: Caller = { orgID: row.org_id, userID: row.created_by };+ const caller: Caller = {+ orgID: row.org_id,+ userID: row.created_by,+ ...(row.role ? { role: row.role } : {}),+ };if (authCache.size >= CACHE_MAX) authCache.clear();const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };authCache.set(hash, entry);diff --git a/cloudflare-workers/api-edge/src/managed_agents.test.ts b/cloudflare-workers/api-edge/src/managed_agents.test.tsindex 500ff269..4b880e23 100644--- a/cloudflare-workers/api-edge/src/managed_agents.test.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.test.ts@@ -23,6 +23,7 @@ describe("managed agents proxy", () => {const token = await mintManagedAgentsAssertion("test-secret", {orgID: "org_test",userID: "user_test",+ role: "admin",});const payload = decodePayload(token);@@ -32,10 +33,104 @@ describe("managed agents proxy", () => {sub: "org_test",org_id: "org_test",user_id: "user_test",+ role: "admin",});expect(Number(payload.exp) - Number(payload.iat)).toBe(120);});+ it("returns the public model-access OAuth receipt without custody fields", async () => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({+ connection: {+ id: "mac_test",+ organizationId: "org_test",+ connectedByUserId: "user_test",+ provider: "openai",+ kind: "codex_subscription",+ label: "Codex subscription",+ status: "connecting",+ credentialCiphertext: "must-not-leak",+ oauthCodeVerifier: "must-not-leak",+ },+ status: "pending",+ authorize_url: "https://auth.openai.com/oauth/authorize?state=test",+ expires_at: "2026-08-24T00:15:00.000Z",+ }),+ ),+ );++ 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" }),+ },+ ),+ {+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ },+ { 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({+ status: "pending",+ authorize_url: "https://auth.openai.com/oauth/authorize?state=test",+ connection: {+ id: "mac_test",+ organizationId: "org_test",+ connectedByUserId: "user_test",+ provider: "openai",+ status: "connecting",+ },+ });+ expect(JSON.stringify(body)).not.toMatch(+ /credentialCiphertext|oauthCodeVerifier|must-not-leak/,+ );+ });++ it("rejects unsupported Claude account connection", async () => {+ const fetchSpy = vi.fn();+ vi.stubGlobal("fetch", fetchSpy);++ 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: "anthropic",+ token: "must-not-be-returned",+ }),+ },+ ),+ {+ OC_MANAGED_AGENTS_SECRET: "test-secret",+ MANAGED_AGENTS_API_URL: "https://managedagents.test",+ },+ { orgID: "org_test", userID: "user_test", role: "admin" },+ "/api/managed-agents",+ );++ expect(response.status).toBe(400);+ const body = await response.json<Record<string, unknown>>();+ expect(body).toMatchObject({+ error: {+ code: "unsupported_provider",+ message: "Codex is the only supported BYOK account provider.",+ },+ });+ expect(fetchSpy).not.toHaveBeenCalled();+ });+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.tsindex ba8a827b..df90ef7e 100644--- a/cloudflare-workers/api-edge/src/managed_agents.ts+++ b/cloudflare-workers/api-edge/src/managed_agents.ts@@ -6,6 +6,7 @@ export interface ManagedAgentsEnv {export interface ManagedAgentsCaller {orgID: string;userID: string | null;+ role?: string;}const DEFAULT_MANAGED_AGENTS_API_URL = "https://managedagents.opencomputer.dev";@@ -36,6 +37,7 @@ export async function mintManagedAgentsAssertion(exp: now + 120,};if (caller.userID) payload.user_id = caller.userID;+ if (caller.role) payload.role = caller.role;const encoder = new TextEncoder();const signingInput =`${b64url(encoder.encode(JSON.stringify(header)))}.` +@@ -221,6 +223,43 @@ function publicConnection(value: unknown): Record<string, unknown> {};}+function publicModelAccessConnection(+ value: unknown,+ includeAdminMetadata: boolean,+): Record<string, unknown> {+ const connection = record(value) ?? {};+ return {+ id: connection.id,+ provider: connection.provider,+ kind: connection.kind,+ label: connection.label,+ status: connection.status,+ checkedAt: connection.checkedAt,+ createdAt: connection.createdAt,+ updatedAt: connection.updatedAt,+ ...(includeAdminMetadata+ ? {+ organizationId: connection.organizationId,+ connectedByUserId: connection.connectedByUserId,+ externalAccountHint: connection.externalAccountHint,+ }+ : {}),+ };+}++function publicModelAccessBinding(value: unknown): Record<string, unknown> {+ const binding = record(value) ?? {};+ return {+ projectId: binding.projectId,+ environment: binding.environment,+ provider: binding.provider,+ connectionId: binding.connectionId,+ enabled: binding.enabled,+ createdAt: binding.createdAt,+ updatedAt: binding.updatedAt,+ };+}+function publicChannel(value: unknown): Record<string, unknown> {const channel = record(value) ?? {};return {@@ -427,6 +466,7 @@ function publicSuccessBody(suffix: string,value: unknown,publicOrigin?: string,+ includeAdminMetadata = false,): unknown {const body = record(value) ?? {};if (method === "GET" && suffix === "/agents") {@@ -522,6 +562,53 @@ function publicSuccessBody(if (method === "GET" && suffix === "/me") {return stripPrivateValues(body);}+ 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),+ )+ : [],+ };+ }+ if (method === "POST" && suffix === "/model-access/connections") {+ if (!body.connection) {+ return publicModelAccessConnection(body, includeAdminMetadata);+ }+ return {+ connection: publicModelAccessConnection(+ body.connection,+ includeAdminMetadata,+ ),+ status: body.status,+ authorize_url: body.authorize_url,+ expires_at: body.expires_at,+ };+ }+ if (+ (method === "POST" || method === "DELETE") &&+ /^\/model-access\/connections\/[^/]+(\/validate|\/complete)?$/.test(suffix)+ ) {+ return publicModelAccessConnection(body, includeAdminMetadata);+ }+ if (+ method === "GET" &&+ /^\/projects\/[^/]+\/model-access\/bindings$/.test(suffix)+ ) {+ return {+ data: Array.isArray(body.data)+ ? body.data.map(publicModelAccessBinding)+ : [],+ };+ }+ if (+ method === "PUT" &&+ /^\/projects\/[^/]+\/model-access\/bindings\/[^/]+\/[^/]+$/.test(suffix)+ ) {+ return publicModelAccessBinding(body);+ }if (method === "POST" && suffix === "/deployments") {return publicDeployment(body);}@@ -674,6 +761,7 @@ async function publicSuccessResponse(method: string,suffix: string,publicOrigin?: string,+ includeAdminMetadata = false,): Promise<Response> {const value: unknown = await upstream.json();const headers = new Headers({ "content-type": "application/json" });@@ -681,7 +769,15 @@ async function publicSuccessResponse(if (cacheControl) headers.set("cache-control", cacheControl);if (suffix.includes("/webhooks")) headers.set("cache-control", "no-store");return new Response(- JSON.stringify(publicSuccessBody(method, suffix, value, publicOrigin)),+ JSON.stringify(+ publicSuccessBody(+ method,+ suffix,+ value,+ publicOrigin,+ includeAdminMetadata,+ ),+ ),{status: upstream.status,headers,@@ -864,6 +960,28 @@ function isAllowedManagedAgentsRoute(method: string, suffix: string): boolean {/^\/channels(?:\/.*)?$/.test(suffix))))return true;+ // Model access (work 011): org-owned Codex subscription connections and their+ // project-environment bindings.+ if (+ (method === "GET" || method === "POST") &&+ suffix === "/model-access/connections"+ ) {+ return true;+ }+ if (+ (method === "POST" || method === "DELETE") &&+ /^\/model-access\/connections\/[^/]+(\/validate|\/complete)?$/.test(suffix)+ ) {+ return true;+ }+ if (+ (method === "GET" || method === "PUT" || method === "DELETE") &&+ /^\/projects\/[^/]+\/model-access\/bindings(?:\/[^/]+\/[^/]+)?$/.test(+ suffix,+ )+ ) {+ return true;+ }if (suffix.startsWith("/openrouter/")) return true;if (method === "POST" && suffix === "/sessions") return true;if (method === "GET" && suffix === "/sessions") return true;@@ -1136,6 +1254,41 @@ export async function proxyManagedAgents({ status: 503 },);}+ if (+ request.method.toUpperCase() === "POST" &&+ suffix === "/model-access/connections"+ ) {+ const payload = record(await request.clone().json().catch(() => null));+ if (payload?.provider !== "openai") {+ return Response.json(+ {+ error: {+ code: "unsupported_provider",+ message: "Codex is the only supported BYOK account provider.",+ },+ },+ { status: 400 },+ );+ }+ }+ 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(/\/+$/, "");@@ -1188,6 +1341,7 @@ export async function proxyManagedAgents(request.method.toUpperCase(),suffix,requestURL.origin,+ caller.role === "admin",);} catch (error) {console.error(diff --git a/scripts/autumn/autumn.config.ts b/scripts/autumn/autumn.config.tsindex 67468f8d..d7ae3862 100644--- a/scripts/autumn/autumn.config.ts+++ b/scripts/autumn/autumn.config.ts@@ -74,6 +74,16 @@ export const agentRuntime = feature({consumable: true,});+// Entitlement gate for connecting an external Claude/Codex subscription+// (work 011). Boolean feature: present on a plan = allowed, absent = denied.+// Not metered and not part of the credit system; subscription-routed model+// inference carries no OpenComputer model charge by design.+export const byoModelSubscriptions = feature({+ id: "byo_model_subscriptions",+ name: "byo_model_subscriptions",+ type: "boolean",+});+export const credits = feature({id: "credits",name: "credits",@@ -165,6 +175,9 @@ export const pro = plan({included: 200,reset: { interval: "month" },}),+ item({+ featureId: byoModelSubscriptions.id,+ }),],});@@ -180,5 +193,8 @@ export const max = plan({included: 2_000,reset: { interval: "month" },}),+ item({+ featureId: byoModelSubscriptions.id,+ }),],});diff --git a/web/src/App.tsx b/web/src/App.tsxindex aacb6191..83f5a9ec 100644--- a/web/src/App.tsx+++ b/web/src/App.tsx@@ -31,6 +31,9 @@ const ManagedAgentDetail = lazy(() => import('./managed-agents/Detail'))const ManagedProjectDetail = lazy(() => import('./managed-agents/Project'))const ManagedSessionDetail = lazy(() => import('./managed-agents/Session'))const ManagedAgentChannels = lazy(() => import('./managed-agents/Channels'))+const ModelAccessCallback = lazy(+ () => import('./managed-agents/ModelAccessCallback'),+)export default function App() {return (@@ -65,6 +68,10 @@ export default function App() {path="managed-agents/channels"element={<ManagedAgentChannels />}/>+ <Route+ path="model-access/callback"+ element={<ModelAccessCallback />}+ /><Routepath="managed-agents/connections"element={<Navigate to="/" replace />}diff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 569dc981..6ea83ca3 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -59,6 +59,10 @@ export type {SandboxWebhook,SandboxWebhookDelivery,Credential,+ ModelAccessConnection,+ ModelAccessBinding,+ ModelAccessConnectResponse,+ EffectiveModelRoute,AgentSecurityNotification,AgentHook,AgentHookCreate,@@ -995,6 +999,86 @@ export const rotateCredential = (id: string, key: string) =>S.CredentialSchema,)+// ── Model access (work 011) — org-owned Claude/Codex subscription connections ──+// The provider token is write-only; every response is normalized metadata only.+// Secret-bearing provider callbacks terminate at the private credential boundary.+export const getModelAccessConnections = () =>+ apiFetch(+ '/v3/model-access/connections',+ {},+ S.ModelAccessConnectionListSchema,+ ).then((r) => r.data)++// Starts the personal Codex subscription OAuth flow. Returns a pending intent+// with an authorize_url the dashboard redirects to. No token is accepted here;+// the provider credential never crosses the browser.+export const connectModelAccess = (body: {+ provider: 'openai' | 'anthropic'+ token?: string+ label?: string+}) =>+ apiFetch(+ '/v3/model-access/connections',+ { method: 'POST', body: JSON.stringify(body) },+ S.ModelAccessConnectResponseSchema,+ )++// Completes the OAuth callback (exchanged server-side at the private credential+// boundary), returning the connected connection. The authorization code is a+// one-time exchange value, not a stored credential.+export const completeModelAccess = (id: string, code: string, state: string) =>+ apiFetch(+ `/v3/model-access/connections/${encodeURIComponent(id)}/complete`,+ { method: 'POST', body: JSON.stringify({ code, state }) },+ S.ModelAccessConnectionSchema,+ )++// Re-validate the held credential against the provider (refresh entitlement /+// account hint / status). Never returns the token.+export const validateModelAccessConnection = (id: string) =>+ apiFetch(+ `/v3/model-access/connections/${encodeURIComponent(id)}/validate`,+ { method: 'POST' },+ S.ModelAccessConnectionSchema,+ )++// Disconnect revokes at the provider when supported, then deletes local secret+// material even if remote revocation fails.+export const disconnectModelAccess = (id: string) =>+ apiFetch<void>(`/v3/model-access/connections/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ })++// Project-environment enablement of the single org connection for a provider.+export const getModelAccessBindings = (projectId: string) =>+ apiFetch(+ `/v3/projects/${encodeURIComponent(projectId)}/model-access/bindings`,+ {},+ S.ModelAccessBindingListSchema,+ ).then((r) => r.data)++export const putModelAccessBinding = (+ projectId: string,+ provider: 'anthropic' | 'openai',+ environment: 'development' | 'production',+ enabled: boolean,+) =>+ apiFetch(+ `/v3/projects/${encodeURIComponent(projectId)}/model-access/bindings/${provider}/${environment}`,+ { method: 'PUT', body: JSON.stringify({ enabled }) },+ S.ModelAccessBindingSchema,+ )++export const deleteModelAccessBinding = (+ projectId: string,+ provider: 'anthropic' | 'openai',+ environment: 'development' | 'production',+) =>+ apiFetch<void>(+ `/v3/projects/${encodeURIComponent(projectId)}/model-access/bindings/${provider}/${environment}`,+ { method: 'DELETE' },+ )+// Sessions — the durable runs.export const getSessions = (params: {diff --git a/web/src/api/mock.ts b/web/src/api/mock.tsindex 0844f1f9..3526d716 100644--- a/web/src/api/mock.ts+++ b/web/src/api/mock.ts@@ -1244,6 +1244,14 @@ const ROUTES: Array<[RegExp, Handler]> = [],[/^\/managed-agents\/agents$/, () => ({ agents: managedAgentItems })],[/^\/managed-agents\/projects$/, () => ({ projects: managedProjects })],+ [+ /^\/managed-agents\/model-access\/connections$/,+ () => ({ data: [] }),+ ],+ [+ /^\/managed-agents\/projects\/[^/]+\/model-access\/bindings$/,+ () => ({ data: [] }),+ ],[/^\/managed-agents\/projects\/[^/]+$/,() => ({diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.tsindex 32633d0f..03a0c1ae 100644--- a/web/src/api/schemas.ts+++ b/web/src/api/schemas.ts@@ -904,6 +904,129 @@ export const CredentialListSchema = z.object({next_cursor: z.string().nullish(),})+// ── Model access (work 011: bring-your-own Codex subscription) ──────────────+// An organization-owned connection to a Codex subscription. The provider token+// is write-only and never appears on this object; the API returns only+// normalized metadata. At most one Codex connection per organization is+// enforced server-side (unique (organization_id, provider)).+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']),+ label: z.string(),+ external_account_hint: z.string().nullish(),+ status: z.enum([+ 'connecting',+ 'connected',+ 'reauth_required',+ 'provider_limited',+ 'plan_ineligible',+ 'revoked',+ 'unavailable',+ ]),+ // Provider-reported entitlement/model snapshot, when a sanctioned capability+ // surface exists. Opaque to the dashboard; display hints only, never authz.+ entitlement_snapshot: z.unknown().nullish(),+ checked_at: z.string().nullish(),+ created_at: z.string().nullish(),+ updated_at: z.string().nullish(),+})+export const ModelAccessConnectionListSchema = z.object({+ data: z.array(ModelAccessConnectionSchema),+})++// Connect: starts the personal Codex subscription OAuth flow. Returns a pending+// intent the dashboard redirects to, with the authorize_url. `label` is a+// display override and defaults server-side.+export const ModelAccessConnectRequestSchema = z.discriminatedUnion(+ 'provider',+ [+ z.object({ provider: z.literal('openai'), label: z.string().optional() }),+ z.object({+ provider: z.literal('anthropic'),+ token: z.string(),+ label: z.string().optional(),+ }),+ ],+)+export const ModelAccessConnectResponseSchema = z.union([+ ModelAccessConnectionSchema,+ z.object({+ connection: ModelAccessConnectionSchema,+ status: z.literal('pending'),+ authorize_url: z.string(),+ expires_at: z.string(),+ }),+])++// A project-environment enablement of the single org connection for a provider.+// One binding per (project, environment, provider). Created disabled by default.+export const ModelAccessBindingSchema = z.object({+ organization_id: z.string(),+ project_id: z.string(),+ environment: z.enum(['development', 'production']),+ provider: z.enum(['anthropic', 'openai']),+ connection_id: z.string(),+ enabled: z.boolean(),+ enabled_by_user_id: z.string().nullish(),+ created_at: z.string().nullish(),+ updated_at: z.string().nullish(),+})+export const ModelAccessBindingListSchema = z.object({+ data: z.array(ModelAccessBindingSchema),+})+export const ModelAccessBindingPutRequestSchema = z.object({+ enabled: z.boolean(),+})++// Typed error for model-access failures (resolution + dispatch).+export const ModelAccessErrorSchema = z.object({+ error: z.object({+ code: z.enum([+ 'model_access_unavailable',+ 'plan_ineligible',+ 'provider_not_connected',+ 'model_not_in_subscription',+ 'reauth_required',+ 'provider_allowance_exhausted',+ 'subscription_unavailable',+ ]),+ message: z.string(),+ // Present when both the subscription and Managed reasons must be shown.+ subscription_reason: z.string().nullish(),+ managed_reason: z.string().nullish(),+ }),+})++// 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() }),+ effective: z.object({ provider: z.string(), model: z.string() }),+ runtime: z.enum(['claude', 'codex']),+ access: z.object({+ type: z.enum(['managed', 'external_subscription']),+ connection_id: z.string().nullish(),+ connection_kind: z+ .enum(['claude_subscription', 'codex_subscription'])+ .nullish(),+ }),+ fallback: z+ .object({+ from: z.literal('external_subscription'),+ reason: z.enum([+ 'provider_not_connected',+ 'model_not_in_subscription',+ 'reauth_required',+ 'provider_allowance_exhausted',+ 'subscription_unavailable',+ ]),+ })+ .nullish(),+ open_computer_model_charge_usd: z.number(),+})+// Slack connection (sessions-api `serializeSlackApp`) — an agent's BYO Slack app.// Never carries secrets (bot token / signing secret stay in the secret backend).// `handle` is the agent's name; slack_app_id/team_id/account_login fill in once@@ -1199,6 +1322,12 @@ export type RepositorySourceInspection = z.infer<typeof RepositorySourceInspectionSchema>export type Credential = z.infer<typeof CredentialSchema>+export type ModelAccessConnection = z.infer<typeof ModelAccessConnectionSchema>+export type ModelAccessBinding = z.infer<typeof ModelAccessBindingSchema>+export type ModelAccessConnectResponse = z.infer<+ typeof ModelAccessConnectResponseSchema+>+export type EffectiveModelRoute = z.infer<typeof EffectiveModelRouteSchema>export type SlackConnection = z.infer<typeof SlackConnectionSchema>export type SlackManifestResponse = z.infer<typeof SlackManifestResponseSchema>export type ManagedSlackAuthorizeResponse = z.infer<diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.tsindex ae9177fc..13287faa 100644--- a/web/src/components/app-shell-nav.ts+++ b/web/src/components/app-shell-nav.ts@@ -2,6 +2,7 @@ import {ArrowLeft,Bot,Boxes,+ BrainCircuit,CalendarClock,KeySquare,Layers,@@ -86,6 +87,11 @@ export function managedAgentsNav(options: {label: 'Secrets',icon: KeySquare,},+ {+ to: `${projectPath}/byok`,+ label: 'BYOK',+ icon: BrainCircuit,+ },{to: projectPath,label: 'Debug playground',diff --git a/web/src/components/app-shell.test.ts b/web/src/components/app-shell.test.tsindex 10e43a89..e7323008 100644--- a/web/src/components/app-shell.test.ts+++ b/web/src/components/app-shell.test.ts@@ -1,4 +1,5 @@import { describe, expect, it } from 'vitest'+import { BrainCircuit, KeySquare } from 'lucide-react'import { managedAgentsNav } from './app-shell-nav'describe('managed agents navigation', () => {@@ -25,11 +26,18 @@ describe('managed agents navigation', () => {'Schedules','Webhooks','Secrets',+ 'BYOK','Debug playground',])expect(nav[1]?.items[nav[1].items.length - 1]?.to).toBe('/projects/project%20one',)+ expect(nav[1]?.items.find((item) => item.label === 'Secrets')?.icon).toBe(+ KeySquare,+ )+ expect(nav[1]?.items.find((item) => item.label === 'BYOK')?.icon).toBe(+ BrainCircuit,+ )})it('reveals each advanced area independently', () => {diff --git a/web/src/managed-agents/BYOK.tsx b/web/src/managed-agents/BYOK.tsxnew file mode 100644index 00000000..037e15f2--- /dev/null+++ b/web/src/managed-agents/BYOK.tsx@@ -0,0 +1,288 @@+import { useState } from 'react'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { BrainCircuit, Loader2, RefreshCw, Unplug } from 'lucide-react'+import { useLocation } from 'react-router-dom'+import { ConfirmDialog } from '@/components/confirm-dialog'+import { CopyRow } from '@/components/copy-row'+import { EmptyState } from '@/components/empty-state'+import {+ Panel,+ PanelContent,+ PanelDescription,+ PanelHeader,+ PanelTitle,+} from '@/components/panel'+import { StatusBadge } from '@/components/status-badge'+import { Button } from '@/components/ui/button'+import { useAuth } from '@/hooks/useAuth'+import { notifyError, notifySuccess } from '@/lib/errors'+import {+ connectManagedModelAccess,+ disconnectManagedModelAccessConnection,+ getManagedModelAccessConnections,+ validateManagedModelAccessConnection,+} from './api'++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 ManagedProjectBYOK({+ projectId,+ projectSlug,+}: {+ projectId: string+ projectSlug: string+}) {+ const { user } = useAuth()+ const location = useLocation()+ const queryClient = useQueryClient()+ const [confirmReplace, setConfirmReplace] = useState(false)+ const [confirmDisconnect, setConfirmDisconnect] = useState(false)+ const canManageConnection = user?.capabilities?.manageMembers !== false+ const cliExecutable =+ window.location.hostname === 'mo-oc-dev.com' ? 'ocdev' : 'opencomputer'+ const connectionQueryKey = ['managed-model-access-connections']+ const connections = useQuery({+ queryKey: connectionQueryKey,+ queryFn: getManagedModelAccessConnections,+ })+ const codex = connections.data?.find(+ (connection) => connection.provider === 'openai',+ )++ const connect = useMutation({+ mutationFn: connectManagedModelAccess,+ onSuccess: (receipt) => {+ sessionStorage.setItem(+ MODEL_ACCESS_RETURN_TO_KEY,+ `${location.pathname}${location.search}`,+ )+ sessionStorage.setItem(MODEL_ACCESS_PROJECT_KEY, projectId)+ window.location.assign(receipt.authorize_url)+ },+ onError: (error) =>+ notifyError("Couldn't start Codex authorization.", error),+ })+ const validateConnection = useMutation({+ mutationFn: () => validateManagedModelAccessConnection(codex!.id),+ onSuccess: async () => {+ await queryClient.invalidateQueries({ queryKey: connectionQueryKey })+ notifySuccess('Codex account revalidated.')+ },+ onError: (error) =>+ notifyError("Couldn't revalidate the Codex account.", error),+ })+ const disconnectConnection = useMutation({+ mutationFn: () => disconnectManagedModelAccessConnection(codex!.id),+ onSuccess: async () => {+ setConfirmDisconnect(false)+ await queryClient.invalidateQueries({ queryKey: connectionQueryKey })+ notifySuccess('Codex account disconnected.')+ },+ onError: (error) =>+ notifyError("Couldn't disconnect the Codex account.", error),+ })+ const startConnect = () => {+ setConfirmReplace(false)+ connect.mutate()+ }+ if (connections.isLoading) {+ return (+ <Panel>+ <PanelContent className="text-muted-foreground flex items-center gap-2 text-sm">+ <Loader2 className="size-4 animate-spin" /> Loading BYOK status…+ </PanelContent>+ </Panel>+ )+ }++ if (connections.isError) {+ return (+ <Panel>+ <EmptyState+ icon={BrainCircuit}+ title="BYOK status is temporarily unavailable"+ description="Try loading the project again."+ action={+ <Button+ variant="outline"+ onClick={() => {+ void connections.refetch()+ }}+ >+ Try again+ </Button>+ }+ />+ </Panel>+ )+ }++ return (+ <div className="space-y-5">+ <Panel>+ <PanelHeader>+ <div>+ <PanelTitle>BYOK</PanelTitle>+ <PanelDescription className="mt-1 max-w-2xl">+ Link a Codex account to this project. Connecting it enables the+ account for both development and production. Managed usage-based+ inference remains the fallback. Runtime compute is still charged.+ </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 account${codex.checkedAt ? ` · checked ${new Date(codex.checkedAt).toLocaleString()}` : ''}`+ : 'No Codex account is linked.'}+ </p>+ </div>++ <div className="flex flex-wrap gap-2 border-t pt-5">+ {canManageConnection ? (+ <Button+ variant={codex ? 'outline' : 'default'}+ disabled={connect.isPending}+ onClick={() =>+ codex ? setConfirmReplace(true) : startConnect()+ }+ >+ {connect.isPending ? (+ <Loader2 className="animate-spin" />+ ) : (+ <BrainCircuit />+ )}+ {codex ? 'Replace Codex account' : 'Connect Codex account'}+ </Button>+ ) : null}+ {canManageConnection && codex ? (+ <>+ <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>+ </>+ ) : null}+ </div>++ {!canManageConnection && !codex ? (+ <p className="text-muted-foreground text-sm">+ Ask an organization admin to connect a model account.+ </p>+ ) : 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>Connect with the CLI</PanelTitle>+ <PanelDescription className="mt-1 max-w-2xl">+ The Codex command opens OAuth, links or replaces the account, and+ enables it for this project in both development and production.+ </PanelDescription>+ </div>+ </PanelHeader>+ <PanelContent className="space-y-4">+ <CopyRow+ value={`${cliExecutable} model-access connect codex --project ${projectSlug}`}+ />+ </PanelContent>+ </Panel>++ <ConfirmDialog+ open={confirmReplace}+ onOpenChange={setConfirmReplace}+ title="Replace the Codex account?"+ description="This reconnects the Codex account and enables it for both environments in this project."+ confirmLabel="Continue to OpenAI"+ onConfirm={startConnect}+ />+ <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()}+ />+ </div>+ )+}diff --git a/web/src/managed-agents/DebugInspector.tsx b/web/src/managed-agents/DebugInspector.tsxindex cc6ae7a7..e06342fa 100644--- a/web/src/managed-agents/DebugInspector.tsx+++ b/web/src/managed-agents/DebugInspector.tsx@@ -10,6 +10,7 @@ import {} from 'lucide-react'import { cn } from '@/lib/utils'import {+ managedAgentModelRoute,managedAgentRenderDebug,type ManagedAgentEvent,type ManagedAgentRenderDebug,@@ -173,6 +174,32 @@ 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 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'const activity = events.filter((event) =>@@ -240,6 +267,9 @@ export function DebugInspector({? `${selected.render.model.provider}/${selected.render.model.model}`: 'Default'}</p>+ <p className="text-muted-foreground mt-1 text-[10px]">+ {accessLabel}+ </p></div><div><p className="text-muted-foreground">Provider turn</p>diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsxindex 745fd63d..577bdae7 100644--- a/web/src/managed-agents/Detail.tsx+++ b/web/src/managed-agents/Detail.tsx@@ -67,6 +67,7 @@ import { ManagedSlackWizard } from './SlackWizard'import { ManagedAgentOutboxes } from './Outboxes'import { ManagedAgentSchedules } from './Schedules'import { ManagedAgentWebhooks } from './Webhooks'+import { ManagedProjectBYOK } from './BYOK'import { AgentMarkdown } from './AgentMarkdown'type DetailTab =@@ -78,6 +79,7 @@ type DetailTab =| 'schedules'| 'webhooks'| 'secrets'+ | 'byok'function formatDate(value: string) {return new Date(value).toLocaleString()@@ -483,6 +485,7 @@ export default function ManagedAgentDetail({'schedules','webhooks','secrets',+ 'byok',])const activeTab = project? routeTab && projectTabs.has(routeTab)@@ -652,6 +655,7 @@ export default function ManagedAgentDetail({...(project ? ([{ id: 'schedules', label: 'Schedules' }] as const) : []),...(project ? ([{ id: 'webhooks', label: 'Webhooks' }] as const) : []),...(project ? ([{ id: 'secrets', label: 'Secrets' }] as const) : []),+ ...(project ? ([{ id: 'byok', label: 'BYOK' }] as const) : []),]return (@@ -1045,6 +1049,13 @@ export default function ManagedAgentDetail({environment={environment}/>) : null}++ {activeTab === 'byok' && project ? (+ <ManagedProjectBYOK+ projectId={project.project.id}+ projectSlug={project.project.slug}+ />+ ) : null}</div>)}diff --git a/web/src/managed-agents/ModelAccessCallback.tsx b/web/src/managed-agents/ModelAccessCallback.tsxnew file mode 100644index 00000000..dfa968ba--- /dev/null+++ b/web/src/managed-agents/ModelAccessCallback.tsx@@ -0,0 +1,98 @@+import { useEffect, useRef, useState } from 'react'+import { CheckCircle2, CircleAlert, Loader2 } from 'lucide-react'+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'++type CallbackState = 'completing' | 'failed'++export default function ModelAccessCallback() {+ const navigate = useNavigate()+ const [searchParams] = useSearchParams()+ const started = useRef(false)+ const [status, setStatus] = useState<CallbackState>('completing')+ const [message, setMessage] = useState('Completing Codex authorization…')++ useEffect(() => {+ if (started.current) return+ started.current = true+ const providerError = searchParams.get('error')+ const code = searchParams.get('code')+ const state = searchParams.get('state')+ const connectionId = state?.split('.', 1)[0]+ if (providerError || !code || !state || !connectionId) {+ setStatus('failed')+ setMessage(+ providerError+ ? `OpenAI authorization failed: ${providerError}`+ : 'The OAuth callback was incomplete. Return to the project and try again.',+ )+ return+ }++ void completeManagedModelAccess(connectionId, code, state)+ .then(async () => {+ const projectId = sessionStorage.getItem(MODEL_ACCESS_PROJECT_KEY)+ if (projectId) {+ await Promise.all(+ (['development', 'production'] as const).map((environment) =>+ putManagedModelAccessBinding({+ projectId,+ provider: 'openai',+ environment,+ enabled: true,+ }),+ ),+ )+ }+ const storedReturnTo = sessionStorage.getItem(+ MODEL_ACCESS_RETURN_TO_KEY,+ )+ sessionStorage.removeItem(MODEL_ACCESS_RETURN_TO_KEY)+ sessionStorage.removeItem(MODEL_ACCESS_PROJECT_KEY)+ const returnTo = storedReturnTo?.startsWith('/projects/')+ ? storedReturnTo+ : '/'+ void navigate(returnTo, { replace: true })+ })+ .catch((error: unknown) => {+ setStatus('failed')+ setMessage(+ error instanceof Error+ ? error.message+ : 'The Codex account could not be connected.',+ )+ })+ }, [navigate, searchParams])++ return (+ <div className="mx-auto max-w-xl py-16">+ <Panel>+ <PanelContent className="flex flex-col items-center py-12 text-center">+ {status === 'completing' ? (+ <Loader2 className="text-muted-foreground mb-4 size-8 animate-spin" />+ ) : (+ <CircleAlert className="text-destructive mb-4 size-8" />+ )}+ <h1 className="text-lg font-semibold">+ {status === 'completing'+ ? 'Connecting Codex account'+ : 'Codex authorization failed'}+ </h1>+ <p className="text-muted-foreground mt-2 max-w-md text-sm">+ {message}+ </p>+ {status === 'failed' ? (+ <Button asChild className="mt-6" variant="outline">+ <Link to="/">+ <CheckCircle2 /> Return to projects+ </Link>+ </Button>+ ) : null}+ </PanelContent>+ </Panel>+ </div>+ )+}diff --git a/web/src/managed-agents/api.test.ts b/web/src/managed-agents/api.test.tsindex 86c6d89a..3d07f519 100644--- a/web/src/managed-agents/api.test.ts+++ b/web/src/managed-agents/api.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import {displayManagedAgentName,+ managedAgentModelRoute,managedAgentRenderDebug,nextAgentEventDeadline,} from './api'@@ -66,3 +67,38 @@ describe('managedAgentRenderDebug', () => {).toBeUndefined()})})++describe('managedAgentModelRoute', () => {+ it('parses Codex BYOK route attribution', () => {+ const event = {+ id: 'event-2',+ seq: 2,+ timestamp: '2026-08-24T00:00:00.000Z',+ sessionId: 'session-1',+ turnId: 'turn-1',+ type: 'model.route_resolved',+ data: {+ requested: { provider: 'openai', model: 'gpt-5.6-sol' },+ effective: { provider: 'openai', model: 'gpt-5.6-sol' },+ runtime: 'codex',+ access: {+ type: 'external_subscription',+ connectionId: 'mac_1',+ connectionKind: 'codex_subscription',+ },+ openComputerModelChargeUsd: 0,+ },+ }++ expect(managedAgentModelRoute(event)).toMatchObject({+ access: {+ type: 'external_subscription',+ connectionKind: 'codex_subscription',+ },+ openComputerModelChargeUsd: 0,+ })+ expect(+ managedAgentModelRoute({ ...event, type: 'agent.rendered' }),+ ).toBeUndefined()+ })+})diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.tsindex e25ad8e1..949f2159 100644--- a/web/src/managed-agents/api.ts+++ b/web/src/managed-agents/api.ts@@ -99,6 +99,53 @@ const secretSchema = z.object({const secretsResponseSchema = z.object({ secrets: z.array(secretSchema) })+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']),+ label: z.string(),+ externalAccountHint: z.string().nullish(),+ status: z.enum([+ 'connecting',+ 'connected',+ 'reauth_required',+ 'provider_limited',+ 'plan_ineligible',+ 'revoked',+ 'unavailable',+ ]),+ checkedAt: z.string().nullish(),+ createdAt: z.string().nullish(),+ updatedAt: z.string().nullish(),+})++const modelAccessConnectionsResponseSchema = z.object({+ data: z.array(modelAccessConnectionSchema),+})++const modelAccessConnectResponseSchema = z.object({+ connection: modelAccessConnectionSchema,+ status: z.literal('pending'),+ authorize_url: z.string().url(),+ expires_at: z.string(),+})++const modelAccessBindingSchema = z.object({+ projectId: z.string(),+ environment: z.enum(['development', 'production']),+ provider: z.enum(['anthropic', 'openai']),+ connectionId: z.string(),+ enabled: z.boolean(),+ createdAt: z.string().nullish(),+ updatedAt: z.string().nullish(),+})++const modelAccessBindingsResponseSchema = z.object({+ data: z.array(modelAccessBindingSchema),+})+const runtimeVariableSchema = z.object({name: z.string(),projectId: z.string(),@@ -307,6 +354,24 @@ const renderDebugSchema = z.object({renderedAt: z.string(),})+const modelRouteSchema = z.object({+ requested: z+ .object({ provider: z.string(), model: z.string() })+ .nullable()+ .optional(),+ effective: z+ .object({ provider: z.string(), model: z.string() })+ .nullable()+ .optional(),+ runtime: z.string(),+ access: z.object({+ type: z.enum(['managed', 'external_subscription']),+ connectionId: z.string().optional(),+ connectionKind: z.string().optional(),+ }),+ openComputerModelChargeUsd: z.number().nullable(),+})+const eventsResponseSchema = z.object({events: z.array(eventSchema),})@@ -367,6 +432,7 @@ export type ManagedProjectOverview = z.infer<typeof projectOverviewSchema>export type ManagedAgentDeployment = z.infer<typeof deploymentSchema>export type ManagedAgentEvent = z.infer<typeof eventSchema>export type ManagedAgentRenderDebug = z.infer<typeof renderDebugSchema>+export type ManagedAgentModelRoute = z.infer<typeof modelRouteSchema>export type ManagedAgentSession = z.infer<typeof sessionSchema>export type ManagedAgentConnection = z.infer<typeof connectionSchema>export type ManagedAgentChannel = z.infer<typeof channelSchema>@@ -377,6 +443,10 @@ export type ManagedAgentScheduleRun = z.infer<typeof scheduleRunSchema>export type ManagedAgentWebhook = z.infer<typeof webhookSchema>export type ManagedSlackManifest = z.infer<typeof slackManifestResponseSchema>export type ManagedProjectSecret = z.infer<typeof secretSchema>+export type ManagedModelAccessConnection = z.infer<+ typeof modelAccessConnectionSchema+>+export type ManagedModelAccessBinding = z.infer<typeof modelAccessBindingSchema>const UUID_NAME =/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i@@ -420,6 +490,75 @@ export async function getManagedProject(projectId: string) {)}+export async function getManagedModelAccessConnections() {+ return (+ await apiFetch(+ '/managed-agents/model-access/connections',+ undefined,+ modelAccessConnectionsResponseSchema,+ )+ ).data+}++export async function connectManagedModelAccess() {+ return apiFetch(+ '/managed-agents/model-access/connections',+ { method: 'POST', body: JSON.stringify({ provider: 'openai' }) },+ modelAccessConnectResponseSchema,+ )+}++export async function completeManagedModelAccess(+ id: string,+ code: string,+ state: string,+) {+ return apiFetch(+ `/managed-agents/model-access/connections/${encodeURIComponent(id)}/complete`,+ { method: 'POST', body: JSON.stringify({ code, state }) },+ modelAccessConnectionSchema,+ )+}++export async function validateManagedModelAccessConnection(id: string) {+ return apiFetch(+ `/managed-agents/model-access/connections/${encodeURIComponent(id)}/validate`,+ { method: 'POST' },+ modelAccessConnectionSchema,+ )+}++export async function disconnectManagedModelAccessConnection(id: string) {+ return apiFetch(+ `/managed-agents/model-access/connections/${encodeURIComponent(id)}`,+ { method: 'DELETE' },+ modelAccessConnectionSchema,+ )+}++export async function getManagedModelAccessBindings(projectId: string) {+ return (+ await apiFetch(+ `/managed-agents/projects/${encodeURIComponent(projectId)}/model-access/bindings`,+ undefined,+ modelAccessBindingsResponseSchema,+ )+ ).data+}++export async function putManagedModelAccessBinding(input: {+ projectId: string+ provider: 'anthropic' | 'openai'+ environment: 'development' | 'production'+ enabled: boolean+}) {+ return apiFetch(+ `/managed-agents/projects/${encodeURIComponent(input.projectId)}/model-access/bindings/${input.provider}/${input.environment}`,+ { method: 'PUT', body: JSON.stringify({ enabled: input.enabled }) },+ modelAccessBindingSchema,+ )+}+export async function getManagedProjectSecrets(projectId: string,environment: 'development' | 'production',@@ -823,6 +962,12 @@ export function managedAgentRenderDebug(event: ManagedAgentEvent) {return parsed.success ? parsed.data : undefined}+export function managedAgentModelRoute(event: ManagedAgentEvent) {+ if (event.type !== 'model.route_resolved') return undefined+ const parsed = modelRouteSchema.safeParse(event.data)+ return parsed.success ? parsed.data : undefined+}+export async function getManagedAgentSession(sessionId: string) {return apiFetch(`/managed-agents/sessions/${encodeURIComponent(sessionId)}`,