Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(codex): assign named ChatGPT grants per agent

Alfredo Lopezf6e606738cfc
diff --git a/charts/clerum-crds/crds/host.yaml b/charts/clerum-crds/crds/host.yaml
index 69ea59c14..63923e915 100644
--- a/charts/clerum-crds/crds/host.yaml
+++ b/charts/clerum-crds/crds/host.yaml
@@ -88,6 +88,16 @@ spec:
name:
type: string
description: Model name (e.g. gpt-5.4-mini, claude-opus-4-7, glm-5.1).
+ connectionRef:
+ type: string
+ maxLength: 63
+ pattern: '^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$'
+ description: >-
+ Named Codex subscription key this Host is assigned to.
+ Absent Codex Hosts default to deployment-default.
+ ROLLOUT ORDER — CRD FIRST: apiextensions/v1 prunes unknown
+ fields, so this property must be applied before control-api
+ or Control UI persist spec.model.connectionRef.
allowedModels:
# Per-host model allowlist subset (spec v2 Topic 3a). OPTIONAL,
# ADDITIVE: when absent or empty, the host offers the FULL global
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index d6782a6cb..e0697b7ef 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.488",
+ "version": "0.1.489",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.488",
+ "version": "0.1.489",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 895f64295..ed0cabcc0 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.488",
+ "version": "0.1.489",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/db.ts b/control-api/src/db.ts
index b18af5cd8..c448b0232 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -5,8 +5,10 @@ import {
createBoundedPgPoolForConnection,
} from './boundedPgPool.js'
import { config } from './config.js'
+import { applyCodexCatalogModelsSchema } from './services/codexSubscriptionCatalog.js'
import {
applyCodexChatgptAccountIdSchema,
+ applyCodexMultiConnectionSchema,
applyCodexSubscriptionConnectionSchema,
} from './services/codexSubscriptionConnection.js'
import { applyCodexSubscriptionOAuthStateSchema } from './services/codexSubscriptionOAuthState.js'
@@ -16,6 +18,7 @@ import {
applyGfsUploadSessionSchema,
} from './services/gfsUploadSchema.js'
import {
+ applyLlmProviderAttemptConnectionIdSchema,
applyLlmProviderAttemptSchema,
applyLlmProviderAttemptTicketSchema,
} from './services/llmProviderAttemptStore.js'
@@ -5961,6 +5964,18 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
`)
},
},
+ {
+ version: '0101_codex_multi_connection',
+ apply: applyCodexMultiConnectionSchema,
+ },
+ {
+ version: '0102_codex_catalog_models',
+ apply: applyCodexCatalogModelsSchema,
+ },
+ {
+ version: '0103_llm_provider_attempts_connection_id',
+ apply: applyLlmProviderAttemptConnectionIdSchema,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/routes/admin/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.ts
index df5a1206e..9e5ac8705 100644
--- a/control-api/src/routes/admin/codexSubscription.ts
+++ b/control-api/src/routes/admin/codexSubscription.ts
@@ -2,14 +2,23 @@ import { Router } from 'express'
import { config } from '../../config.js'
import { pool } from '../../db.js'
import { asyncHandler } from '../../http/asyncHandler.js'
+import type { K8sGateway } from '../../k8s.js'
import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
import { rootLogger } from '../../observability/logger.js'
import {
type CodexCatalogTransport,
createCodexCatalogTransportFromEnv,
+ listCodexCatalogModels,
syncCodexSubscriptionCatalog,
} from '../../services/codexSubscriptionCatalog.js'
-import { loadCodexSubscriptionSecrets } from '../../services/codexSubscriptionConnection.js'
+import {
+ CodexSubscriptionInvalidConnectionKeyError,
+ assertCodexConnectionKey,
+ createNamedCodexSubscriptionConnection,
+ listSafeCodexSubscriptionConnections,
+ loadCodexSubscriptionSecrets,
+ normalizeCodexConnectionKey,
+} from '../../services/codexSubscriptionConnection.js'
import {
type CodexOAuthDeps,
CodexSubscriptionOAuthError,
@@ -43,7 +52,8 @@ function oauthDeps(
req: {
get: (h: string) => string | undefined
},
- redirectUri = resolveBrowserRedirectUri(req)
+ redirectUri = resolveBrowserRedirectUri(req),
+ connectionKey?: string
): CodexOAuthDeps {
return {
db: dbClient(),
@@ -52,9 +62,14 @@ function oauthDeps(
clientId: config.codexOAuthClientId,
redirectUri,
enabled: config.codexSubscriptionEnabled,
+ connectionKey: normalizeCodexConnectionKey(connectionKey),
}
}
+function keyFromReq(req: { params?: { key?: string } }): string {
+ return normalizeCodexConnectionKey(req.params?.key)
+}
+
function parseIntent(value: unknown): CodexSubscriptionOAuthIntent {
return value === 'reconnect' || value === 'replace' ? value : 'connect'
}
@@ -67,7 +82,7 @@ function sendOAuthError(
const status =
err.code === 'disabled'
? 404
- : err.code === 'replacement_required'
+ : err.code === 'replacement_required' || err.code === 'fingerprint_in_use'
? 409
: err.code === 'refresh_in_flight' || err.code === 'stale_revision'
? 409
@@ -84,122 +99,247 @@ function sendOAuthError(
throw err
}
+function slugFromDisplayName(displayName: string): string {
+ const slug = displayName
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .slice(0, 63)
+ return slug || `codex-${Date.now().toString(36)}`
+}
+
+function hostConnectionRef(spec: unknown): string | null {
+ if (!spec || typeof spec !== 'object') return null
+ const model = (spec as { model?: { provider?: string; connectionRef?: string } }).model
+ if (!model || model.provider !== 'codex-subscription') return null
+ return normalizeCodexConnectionKey(model.connectionRef)
+}
+
export function createAdminCodexSubscriptionRouter(
- catalogTransport: CodexCatalogTransport = createCodexCatalogTransportFromEnv()
+ catalogTransport: CodexCatalogTransport = createCodexCatalogTransportFromEnv(),
+ gateway?: K8sGateway
): Router {
const router = Router()
- router.get(
- `${BASE}/connection`,
- asyncHandler(async (req, res) => {
- try {
- const connection = await getCodexSubscriptionConnection(oauthDeps(req))
- res.status(200).json(connection)
- } catch (err) {
- sendOAuthError(res, err)
- }
- })
- )
+ async function assignedHostsFor(connectionKey: string): Promise<Array<{ name: string }>> {
+ if (!gateway) return []
+ try {
+ const hosts = (await gateway.listResource('hosts', config.hostsNamespace)) as Array<{
+ metadata?: { name?: string }
+ spec?: unknown
+ }>
+ return hosts
+ .filter(host => hostConnectionRef(host.spec) === connectionKey)
+ .map(host => ({ name: String(host.metadata?.name ?? '') }))
+ .filter(host => host.name)
+ } catch (err) {
+ log.warn({ event: 'codex_assigned_hosts_list_failed', err }, 'failed to list assigned hosts')
+ return []
+ }
+ }
- router.post(
- `${BASE}/browser/start`,
- asyncHandler(async (req, res) => {
- try {
- const redirectUri = resolveBrowserRedirectUri(req)
- if (isPublicCodexCliClient(config.codexOAuthClientId)) {
- throw new CodexSubscriptionOAuthError(
- 'browser_oauth_unregistered',
- 'browser OAuth requires a deployment-registered OpenAI client'
- )
- }
- const started = await startCodexBrowserConnect(
- oauthDeps(req, redirectUri),
- parseIntent(req.body?.intent)
+ async function withAssignedHosts<T extends { connectionKey: string }>(connection: T) {
+ return {
+ ...connection,
+ assignedHosts: await assignedHostsFor(connection.connectionKey),
+ }
+ }
+
+ const getConnectionHandler = asyncHandler(async (req, res) => {
+ try {
+ const connection = await getCodexSubscriptionConnection(
+ oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req))
+ )
+ res.status(200).json(await withAssignedHosts(connection))
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+
+ const browserStartHandler = asyncHandler(async (req, res) => {
+ try {
+ const redirectUri = resolveBrowserRedirectUri(req)
+ if (isPublicCodexCliClient(config.codexOAuthClientId)) {
+ throw new CodexSubscriptionOAuthError(
+ 'browser_oauth_unregistered',
+ 'browser OAuth requires a deployment-registered OpenAI client'
)
- res.status(200).json(started)
- } catch (err) {
- sendOAuthError(res, err)
}
- })
- )
+ const started = await startCodexBrowserConnect(
+ oauthDeps(req, redirectUri, keyFromReq(req)),
+ parseIntent(req.body?.intent)
+ )
+ res.status(200).json(started)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
- router.post(
- `${BASE}/device/start`,
- asyncHandler(async (req, res) => {
- try {
- const started = await startCodexDeviceConnect(oauthDeps(req), parseIntent(req.body?.intent))
- res.status(200).json(started)
- } catch (err) {
- sendOAuthError(res, err)
+ const deviceStartHandler = asyncHandler(async (req, res) => {
+ try {
+ const started = await startCodexDeviceConnect(
+ oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req)),
+ parseIntent(req.body?.intent)
+ )
+ res.status(200).json(started)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+
+ const devicePollHandler = asyncHandler(async (req, res) => {
+ try {
+ const state = typeof req.query.state === 'string' ? req.query.state : ''
+ const result = await pollCodexDevice(
+ oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req)),
+ state
+ )
+ res.status(200).json(result)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+
+ const refreshHandler = asyncHandler(async (req, res) => {
+ try {
+ const connection = await refreshCodexSubscriptionConnection(
+ oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req))
+ )
+ res.status(200).json(connection)
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+
+ const catalogSyncHandler = asyncHandler(async (req, res) => {
+ try {
+ if (!config.codexSubscriptionEnabled) {
+ res.status(404).json({ error: 'disabled' })
+ return
}
- })
- )
+ const db = dbClient()
+ const connectionKey = normalizeCodexConnectionKey(
+ typeof req.params.key === 'string' ? req.params.key : undefined
+ )
+ const secrets = await loadCodexSubscriptionSecrets(
+ db,
+ deriveOAuthEncryptionKey(config.oauthEncryptionKey),
+ connectionKey
+ )
+ if (!secrets?.accessToken) {
+ res.status(404).json({ error: 'no_grant' })
+ return
+ }
+ const synced = await syncCodexSubscriptionCatalog(db, catalogTransport, secrets.accessToken, {
+ connectionKey,
+ })
+ res.status(200).json({
+ outcome: synced.outcome,
+ added: synced.added,
+ refreshed: synced.refreshed,
+ staled: synced.staled,
+ connection: synced.connection,
+ })
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+
+ const revokeHandler = asyncHandler(async (req, res) => {
+ try {
+ const connection = await revokeCodexSubscription(
+ oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req))
+ )
+ res.status(200).json(await withAssignedHosts(connection))
+ } catch (err) {
+ sendOAuthError(res, err)
+ }
+ })
+
+ router.get(`${BASE}/connection`, getConnectionHandler)
+ router.post(`${BASE}/browser/start`, browserStartHandler)
+ router.post(`${BASE}/device/start`, deviceStartHandler)
+ router.get(`${BASE}/device/poll`, devicePollHandler)
+ router.post(`${BASE}/refresh`, refreshHandler)
+ router.post(`${BASE}/catalog/sync`, catalogSyncHandler)
+ router.post(`${BASE}/revoke`, revokeHandler)
+ router.get(`${BASE}/connections/:key`, getConnectionHandler)
+ router.post(`${BASE}/connections/:key/browser/start`, browserStartHandler)
+ router.post(`${BASE}/connections/:key/device/start`, deviceStartHandler)
+ router.get(`${BASE}/connections/:key/device/poll`, devicePollHandler)
+ router.post(`${BASE}/connections/:key/refresh`, refreshHandler)
+ router.post(`${BASE}/connections/:key/catalog/sync`, catalogSyncHandler)
+ router.post(`${BASE}/connections/:key/revoke`, revokeHandler)
router.get(
- `${BASE}/device/poll`,
- asyncHandler(async (req, res) => {
- try {
- const state = typeof req.query.state === 'string' ? req.query.state : ''
- const result = await pollCodexDevice(oauthDeps(req), state)
- res.status(200).json(result)
- } catch (err) {
- sendOAuthError(res, err)
+ `${BASE}/connections`,
+ asyncHandler(async (_req, res) => {
+ if (!config.codexSubscriptionEnabled) {
+ res.status(404).json({ error: 'disabled' })
+ return
}
- })
- )
-
- router.post(
- `${BASE}/refresh`,
- asyncHandler(async (req, res) => {
- try {
- const connection = await refreshCodexSubscriptionConnection(oauthDeps(req))
- res.status(200).json(connection)
- } catch (err) {
- sendOAuthError(res, err)
+ const rows = await listSafeCodexSubscriptionConnections(dbClient())
+ const connections = []
+ for (const row of rows) {
+ connections.push(await withAssignedHosts(row))
}
+ res.status(200).json({ connections })
})
)
router.post(
- `${BASE}/catalog/sync`,
+ `${BASE}/connections`,
asyncHandler(async (req, res) => {
+ if (!config.codexSubscriptionEnabled) {
+ res.status(404).json({ error: 'disabled' })
+ return
+ }
try {
- if (!config.codexSubscriptionEnabled) {
- res.status(404).json({ error: 'disabled' })
+ const displayName =
+ typeof req.body?.displayName === 'string' && req.body.displayName.trim()
+ ? req.body.displayName.trim()
+ : 'Codex subscription'
+ const requestedKey =
+ typeof req.body?.connectionKey === 'string' && req.body.connectionKey.trim()
+ ? req.body.connectionKey.trim()
+ : slugFromDisplayName(displayName)
+ const created = await createNamedCodexSubscriptionConnection(dbClient(), {
+ connectionKey: assertCodexConnectionKey(requestedKey),
+ displayName,
+ })
+ res.status(201).json(await withAssignedHosts(created))
+ } catch (err) {
+ if (err instanceof CodexSubscriptionInvalidConnectionKeyError) {
+ res.status(400).json({ error: 'invalid_connection_key' })
return
}
- const db = dbClient()
- const secrets = await loadCodexSubscriptionSecrets(
- db,
- deriveOAuthEncryptionKey(config.oauthEncryptionKey)
- )
- if (!secrets?.accessToken) {
- res.status(404).json({ error: 'no_grant' })
+ const code = (err as { code?: string } | null)?.code
+ if (code === '23505') {
+ res.status(409).json({ error: 'connection_key_taken' })
return
}
- const synced = await syncCodexSubscriptionCatalog(db, catalogTransport, secrets.accessToken)
- res.status(200).json({
- outcome: synced.outcome,
- added: synced.added,
- refreshed: synced.refreshed,
- staled: synced.staled,
- connection: synced.connection,
- })
- } catch (err) {
- sendOAuthError(res, err)
+ throw err
}
})
)
- router.post(
- `${BASE}/revoke`,
+ router.get(
+ `${BASE}/connections/:key/models`,
asyncHandler(async (req, res) => {
- try {
- const connection = await revokeCodexSubscription(oauthDeps(req))
- res.status(200).json(connection)
- } catch (err) {
- sendOAuthError(res, err)
+ if (!config.codexSubscriptionEnabled) {
+ res.status(404).json({ error: 'disabled' })
+ return
+ }
+ const connection = await getCodexSubscriptionConnection(
+ oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req))
+ )
+ if (!('id' in connection)) {
+ res.status(200).json({ models: [] })
+ return
}
+ const models = await listCodexCatalogModels(dbClient(), connection.id)
+ res.status(200).json({ models })
})
)
diff --git a/control-api/src/routes/admin/hostSpecValidation.ts b/control-api/src/routes/admin/hostSpecValidation.ts
index 2f7bca67b..164eb026e 100644
--- a/control-api/src/routes/admin/hostSpecValidation.ts
+++ b/control-api/src/routes/admin/hostSpecValidation.ts
@@ -156,7 +156,7 @@ const HostApprovalSchema = z
.optional()
export interface HostSpecValidationDeps {
- isModelAllowed: (provider: string, model: string) => Promise<boolean>
+ isModelAllowed: (provider: string, model: string, connectionRef?: string) => Promise<boolean>
/**
* Full `{ enabled, stale }` allowlist state for a pair (Fase 6). OPTIONAL and
* defaulted so existing callers that inject only `isModelAllowed` keep working;
@@ -338,8 +338,29 @@ export async function validateHostSpec(
],
}
}
- const allowed = await deps.isModelAllowed(provider, name)
- if (!allowed && !toleratePair(provider, name, 'primary', tol)) {
+ const connectionRef =
+ provider === 'codex-subscription' && isPlainObject(model)
+ ? typeof model.connectionRef === 'string' && model.connectionRef.trim()
+ ? model.connectionRef.trim()
+ : 'deployment-default'
+ : undefined
+ if (provider === 'codex-subscription' && isPlainObject(model) && !model.connectionRef) {
+ model.connectionRef = 'deployment-default'
+ }
+ const allowed = await deps.isModelAllowed(provider, name, connectionRef)
+ // Switching connectionRef is a new assignment even when (provider, model)
+ // already lived on the Host. A revoked/unknown grant must not ride the
+ // identity/channels full-replace tolerance. An unchanged revoked ref stays
+ // tolerable so operators can still save unrelated fields.
+ const storedConnectionRef = storedCodexConnectionRef(context.stored)
+ const connectionAssignmentChanged =
+ provider === 'codex-subscription' &&
+ storedConnectionRef !== undefined &&
+ storedConnectionRef !== connectionRef
+ if (
+ !allowed &&
+ (connectionAssignmentChanged || !toleratePair(provider, name, 'primary', tol))
+ ) {
return {
errors: [
{
@@ -525,6 +546,15 @@ async function maybeWarnStale(
* audit event (not emitted until the whole write persists) and returns true so
* the gate skips its rejection.
*/
+function storedCodexConnectionRef(stored: Record<string, unknown> | undefined): string | undefined {
+ if (!isPlainObject(stored) || !isPlainObject(stored.model)) return undefined
+ const provider = typeof stored.model.provider === 'string' ? stored.model.provider.trim() : ''
+ if (provider !== 'codex-subscription') return undefined
+ return typeof stored.model.connectionRef === 'string' && stored.model.connectionRef.trim()
+ ? stored.model.connectionRef.trim()
+ : 'deployment-default'
+}
+
function toleratePair(
provider: string,
model: string,
diff --git a/control-api/src/routes/admin/index.ts b/control-api/src/routes/admin/index.ts
index 88491c831..d9ce14cc4 100644
--- a/control-api/src/routes/admin/index.ts
+++ b/control-api/src/routes/admin/index.ts
@@ -48,7 +48,7 @@ export function createAdminRouter(gateway: K8sGateway): Router {
router.use(createAdminUsageRouter())
router.use(createAdminLlmPricesRouter())
router.use(createAdminLlmModelsRouter(gateway))
- router.use(createAdminCodexSubscriptionRouter())
+ router.use(createAdminCodexSubscriptionRouter(undefined, gateway))
router.use(createAdminBudgetsRouter())
router.use(createAdminTracingRouter())
return router
diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.ts
index 2e72d2dad..2da067371 100644
--- a/control-api/src/routes/admin/resources.ts
+++ b/control-api/src/routes/admin/resources.ts
@@ -11,6 +11,7 @@ import { enforceNamespace } from '../../http/namespaceAudit.js'
import { validateCommunicationChannelSpec } from '../../http/validateCommunicationChannelSpec.js'
import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
+import { isCodexAssignmentAllowed } from '../../services/codexSubscriptionCatalog.js'
import { stripHookRefFromHosts } from '../../services/hostGuardrailRefs.js'
import { getModelAllowlistState, isModelAllowed } from '../../services/llmAllowedModels.js'
import {
@@ -467,7 +468,10 @@ function hostModelLockNames(spec: unknown): string[] {
// `maybeWarnStale` escape to the global pool under the lock (adenda A3).
function hostValidationDeps(db: DbClient): HostSpecValidationDeps {
return {
- isModelAllowed: (provider, model) => isModelAllowed(provider, model, db),
+ isModelAllowed: (provider, model, connectionRef) =>
+ provider === 'codex-subscription'
+ ? isCodexAssignmentAllowed(db, connectionRef ?? 'deployment-default', model)
+ : isModelAllowed(provider, model, db),
getModelAllowlistState: (provider, model) => getModelAllowlistState(provider, model, db),
}
}
diff --git a/control-api/src/routes/mcp-host/index.ts b/control-api/src/routes/mcp-host/index.ts
index 4327dc3d7..0d46b3aba 100644
--- a/control-api/src/routes/mcp-host/index.ts
+++ b/control-api/src/routes/mcp-host/index.ts
@@ -17,7 +17,7 @@ export function createMcpHostRoutes(
router.use(createUserApprovalRequestsRoutes(gateway, directRunAttributionBindingService))
router.use(createMcpHostWorkflowRoutes(gateway))
router.use(createMcpHostPluginWorkloadSdkRoutes())
- router.use(createMcpHostLlmProviderAttemptRoutes())
+ router.use(createMcpHostLlmProviderAttemptRoutes(gateway))
router.use(createMcpHostHostsHeartbeatRoutes(gateway))
return router
}
diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
index abc037e05..4bf7e48ab 100644
--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
@@ -1,7 +1,10 @@
import { type Request, type Response, Router } from 'express'
+import { config } from '../../config.js'
import { asyncHandler } from '../../http/asyncHandler.js'
+import type { K8sGateway } from '../../k8s.js'
import { requireMcpHostJwt } from '../../middleware/mcpHostJwtAuth.js'
import { rootLogger } from '../../observability/logger.js'
+import { normalizeCodexConnectionKey } from '../../services/codexSubscriptionConnection.js'
import {
LlmProviderAttemptAuthorizeError,
authorizeLlmProviderAttempt,
@@ -34,7 +37,24 @@ function sendAuthorizeError(res: Response, err: unknown): void {
throw err
}
-export function createMcpHostLlmProviderAttemptRoutes(): Router {
+export async function resolveHostAssignedConnectionKey(
+ gateway: Pick<K8sGateway, 'getResource'>,
+ hostRef: string
+): Promise<string> {
+ try {
+ const host = (await gateway.getResource('hosts', hostRef, config.hostsNamespace)) as {
+ spec?: { model?: { connectionRef?: string } }
+ }
+ return normalizeCodexConnectionKey(host?.spec?.model?.connectionRef)
+ } catch {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'host_binding_mismatch',
+ 'Host assignment could not be attested'
+ )
+ }
+}
+
+export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Router {
const router = Router()
router.post(
'/mcp-host/llm/provider-attempts/authorize',
@@ -46,7 +66,9 @@ export function createMcpHostLlmProviderAttemptRoutes(): Router {
return
}
try {
- const result = await authorizeLlmProviderAttempt(claims, req.body)
+ const result = await authorizeLlmProviderAttempt(claims, req.body, {
+ resolveConnectionKey: hostRef => resolveHostAssignedConnectionKey(gateway, hostRef),
+ })
res.status(200).json(result)
} catch (err) {
sendAuthorizeError(res, err)
diff --git a/control-api/src/services/codexSubscriptionCatalog.ts b/control-api/src/services/codexSubscriptionCatalog.ts
index a5ba45280..748efbaed 100644
--- a/control-api/src/services/codexSubscriptionCatalog.ts
+++ b/control-api/src/services/codexSubscriptionCatalog.ts
@@ -3,10 +3,12 @@ import { config } from '../config.js'
import type { DbClient } from '../db.js'
import { rootLogger } from '../observability/logger.js'
import {
+ CODEX_SUBSCRIPTION_CONNECTION_KEY,
type CodexSubscriptionCatalogStatus,
type CodexSubscriptionConnectionStatus,
type CodexSubscriptionSafeConnection,
getSafeCodexSubscriptionConnection,
+ normalizeCodexConnectionKey,
recordCodexCatalogOutcome,
} from './codexSubscriptionConnection.js'
@@ -96,11 +98,141 @@ export function planCodexCatalogReconcile(
}
}
+export async function applyCodexCatalogModelsSchema(db: DbClient): Promise<void> {
+ await db.query(`
+ CREATE TABLE IF NOT EXISTS codex_catalog_models (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ connection_id UUID NOT NULL REFERENCES codex_subscription_connections(id),
+ model TEXT NOT NULL,
+ display_name TEXT,
+ context_window_tokens INTEGER,
+ enabled BOOLEAN NOT NULL DEFAULT false,
+ source TEXT NOT NULL CHECK (source IN ('manual', 'discovery')),
+ stale BOOLEAN NOT NULL DEFAULT false,
+ discovered_at TIMESTAMPTZ,
+ last_seen_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ CONSTRAINT codex_catalog_models_connection_model_unique UNIQUE (connection_id, model)
+ );
+
+ REVOKE ALL PRIVILEGES ON TABLE codex_catalog_models FROM PUBLIC;
+ REVOKE ALL PRIVILEGES ON TABLE codex_catalog_models
+ FROM trace_maintenance_runtime, workflow_recipes_runtime;
+ GRANT SELECT, INSERT, UPDATE ON TABLE codex_catalog_models TO control_api_runtime;
+ REVOKE DELETE, TRUNCATE, REFERENCES, TRIGGER ON TABLE codex_catalog_models FROM control_api_runtime;
+
+ INSERT INTO codex_catalog_models (
+ connection_id, model, display_name, context_window_tokens, enabled, source, stale,
+ discovered_at, last_seen_at
+ )
+ SELECT c.id, m.model, m.display_name, m.context_window_tokens, m.enabled, m.source, m.stale,
+ m.discovered_at, m.last_seen_at
+ FROM llm_allowed_models m
+ JOIN codex_subscription_connections c
+ ON c.connection_key = '${CODEX_SUBSCRIPTION_CONNECTION_KEY}'
+ WHERE m.provider = '${PROVIDER}'
+ ON CONFLICT (connection_id, model) DO NOTHING;
+ `)
+}
+
+export async function getCodexCatalogModelState(
+ db: DbClient,
+ connectionId: string,
+ model: string
+): Promise<{ enabled: boolean; stale: boolean } | null> {
+ const result = await db.query(
+ `SELECT enabled, stale
+ FROM codex_catalog_models
+ WHERE connection_id = $1
+ AND model = $2
+ LIMIT 1`,
+ [connectionId, model]
+ )
+ const row = result.rows[0] as { enabled?: boolean; stale?: boolean } | undefined
+ if (!row) return null
+ return { enabled: row.enabled === true, stale: row.stale === true }
+}
+
+export async function isCodexAssignmentAllowed(
+ db: DbClient,
+ connectionRef: string,
+ model: string
+): Promise<boolean> {
+ const connection = await getSafeCodexSubscriptionConnection(
+ db,
+ normalizeCodexConnectionKey(connectionRef)
+ )
+ if (
+ !connection ||
+ connection.status !== 'connected' ||
+ connection.revokedAt ||
+ connection.catalogStatus !== 'ready'
+ ) {
+ return false
+ }
+ const state = await getCodexCatalogModelState(db, connection.id, model)
+ return Boolean(state?.enabled && !state.stale)
+}
+
+export async function listCodexCatalogModels(
+ db: DbClient,
+ connectionId: string
+): Promise<Array<{ model: string; enabled: boolean; stale: boolean }>> {
+ const result = await db.query(
+ `SELECT model, enabled, stale
+ FROM codex_catalog_models
+ WHERE connection_id = $1
+ ORDER BY model ASC`,
+ [connectionId]
+ )
+ return (result.rows as Array<Record<string, unknown>>).map(row => ({
+ model: String(row.model),
+ enabled: row.enabled === true,
+ stale: row.stale === true,
+ }))
+}
+
+export async function rebuildLiveCodexUnionAllowlist(db: DbClient): Promise<void> {
+ await db.query(
+ `INSERT INTO llm_allowed_models
+ (provider, model, enabled, source, stale, display_name, context_window_tokens, vendor, last_seen_at)
+ SELECT $1, m.model, true, 'discovery', false,
+ MIN(m.display_name), MAX(m.context_window_tokens), 'OpenAI', NOW()
+ FROM codex_catalog_models m
+ JOIN codex_subscription_connections c ON c.id = m.connection_id
+ WHERE c.revoked_at IS NULL
+ AND m.enabled
+ AND m.stale = false
+ GROUP BY m.model
+ ON CONFLICT (provider, model) DO UPDATE
+ SET enabled = true,
+ stale = false,
+ last_seen_at = NOW()`,
+ [PROVIDER]
+ )
+ await db.query(
+ `UPDATE llm_allowed_models
+ SET enabled = false,
+ stale = true
+ WHERE provider = $1
+ AND model NOT IN (
+ SELECT DISTINCT m.model
+ FROM codex_catalog_models m
+ JOIN codex_subscription_connections c ON c.id = m.connection_id
+ WHERE c.revoked_at IS NULL
+ AND m.enabled
+ AND m.stale = false
+ )`,
+ [PROVIDER]
+ )
+}
+
export async function syncCodexSubscriptionCatalog(
db: DbClient,
transport: CodexCatalogTransport,
accessToken: string,
- expected?: { credentialRevision: number; catalogRevision: number }
+ expected?: { credentialRevision: number; catalogRevision: number; connectionKey?: string }
): Promise<{
outcome: CodexCatalogOutcome
connection: CodexSubscriptionSafeConnection | null
@@ -108,28 +240,31 @@ export async function syncCodexSubscriptionCatalog(
refreshed: number
staled: number
}> {
- const connection = await getSafeCodexSubscriptionConnection(db)
+ const connectionKey = normalizeCodexConnectionKey(expected?.connectionKey)
+ const connection = await getSafeCodexSubscriptionConnection(db, connectionKey)
if (!connection || connection.status === 'revoked' || connection.status === 'disconnected') {
throw new Error('codex_subscription_not_connected')
}
const expectedCredentialRevision = expected?.credentialRevision ?? connection.credentialRevision
const expectedCatalogRevision = expected?.catalogRevision ?? connection.catalogRevision
const result = await transport.listModels({ accessToken })
- const existing = await loadCodexRows(db)
+ const existing = await loadCodexRows(db, connection.id)
const plan = planCodexCatalogReconcile(existing, result)
const recorded = await recordCodexCatalogOutcome(db, {
catalogStatus: plan.catalogStatus as CodexSubscriptionCatalogStatus,
connectionStatus: plan.connectionStatus,
expectedCredentialRevision,
expectedCatalogRevision,
+ connectionKey,
})
let added = 0
let refreshed = 0
let staled = 0
if (recorded && plan.mutateRows) {
- added = await insertDiscovered(db, plan.inserts)
- refreshed = await refreshDiscovered(db, plan.refresh)
- staled = await staleMissing(db, plan.stale)
+ added = await insertDiscovered(db, connection.id, plan.inserts)
+ refreshed = await refreshDiscovered(db, connection.id, plan.refresh)
+ staled = await staleMissing(db, connection.id, plan.stale)
+ await rebuildLiveCodexUnionAllowlist(db)
}
if (!recorded) {
log.warn(
@@ -229,12 +364,12 @@ export function createCodexCatalogTransportFromEnv(
return createCodexProxyCatalogTransport({ adminBaseUrl })
}
-async function loadCodexRows(db: DbClient): Promise<CodexCatalogRow[]> {
+async function loadCodexRows(db: DbClient, connectionId: string): Promise<CodexCatalogRow[]> {
const result = await db.query(
`SELECT model, source, enabled, stale
- FROM llm_allowed_models
- WHERE provider = $1`,
- [PROVIDER]
+ FROM codex_catalog_models
+ WHERE connection_id = $1`,
+ [connectionId]
)
return (result.rows as Array<Record<string, unknown>>).map(row => ({
model: String(row.model),
@@ -244,44 +379,54 @@ async function loadCodexRows(db: DbClient): Promise<CodexCatalogRow[]> {
}))
}
-async function insertDiscovered(db: DbClient, models: CodexDiscoveredModel[]): Promise<number> {
+async function insertDiscovered(
+ db: DbClient,
+ connectionId: string,
+ models: CodexDiscoveredModel[]
+): Promise<number> {
let added = 0
for (const model of models) {
const result = await db.query(
- `INSERT INTO llm_allowed_models
- (provider, model, enabled, source, discovered_at, last_seen_at, stale, display_name, context_window_tokens, vendor)
- VALUES ($1, $2, false, 'discovery', NOW(), NOW(), false, $3, $4, 'OpenAI')
- ON CONFLICT (provider, model) DO NOTHING`,
- [PROVIDER, model.model, model.displayName ?? null, model.contextWindowTokens ?? null]
+ `INSERT INTO codex_catalog_models
+ (connection_id, model, enabled, source, discovered_at, last_seen_at, stale, display_name, context_window_tokens)
+ VALUES ($1, $2, true, 'discovery', NOW(), NOW(), false, $3, $4)
+ ON CONFLICT (connection_id, model) DO NOTHING`,
+ [connectionId, model.model, model.displayName ?? null, model.contextWindowTokens ?? null]
)
added += result.rowCount ?? 0
}
return added
}
-async function refreshDiscovered(db: DbClient, models: string[]): Promise<number> {
+async function refreshDiscovered(
+ db: DbClient,
+ connectionId: string,
+ models: string[]
+): Promise<number> {
if (models.length === 0) return 0
const result = await db.query(
- `UPDATE llm_allowed_models
+ `UPDATE codex_catalog_models
SET last_seen_at = NOW(),
- stale = false
- WHERE provider = $1
+ stale = false,
+ updated_at = NOW()
+ WHERE connection_id = $1
AND source = 'discovery'
AND model = ANY($2::text[])`,
- [PROVIDER, models]
+ [connectionId, models]
)
return result.rowCount ?? 0
}
-async function staleMissing(db: DbClient, models: string[]): Promise<number> {
+async function staleMissing(db: DbClient, connectionId: string, models: string[]): Promise<number> {
if (models.length === 0) return 0
const result = await db.query(
- `UPDATE llm_allowed_models
- SET stale = true
- WHERE provider = $1
+ `UPDATE codex_catalog_models
+ SET stale = true,
+ updated_at = NOW()
+ WHERE connection_id = $1
AND source = 'discovery'
AND model = ANY($2::text[])`,
- [PROVIDER, models]
+ [connectionId, models]
)
return result.rowCount ?? 0
}
diff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.ts
index 6ce1f9a86..470fe4800 100644
--- a/control-api/src/services/codexSubscriptionConnection.ts
+++ b/control-api/src/services/codexSubscriptionConnection.ts
@@ -3,6 +3,39 @@ import { decryptOAuthSecret, encryptOAuthSecret } from '../oauth/encryption.js'
export const CODEX_SUBSCRIPTION_CONNECTION_KEY = 'deployment-default' as const
+const CONNECTION_KEY_RE = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
+
+export function normalizeCodexConnectionKey(value?: string | null): string {
+ const trimmed = typeof value === 'string' ? value.trim() : ''
+ return trimmed || CODEX_SUBSCRIPTION_CONNECTION_KEY
+}
+
+export function assertCodexConnectionKey(value: string): string {
+ const key = value.trim()
+ if (!CONNECTION_KEY_RE.test(key)) {
+ throw new CodexSubscriptionInvalidConnectionKeyError(key)
+ }
+ return key
+}
+
+export class CodexSubscriptionInvalidConnectionKeyError extends Error {
+ readonly code = 'invalid_connection_key'
+
+ constructor(key: string) {
+ super(`Codex subscription connection key is invalid: ${key}`)
+ this.name = 'CodexSubscriptionInvalidConnectionKeyError'
+ }
+}
+
+export class CodexSubscriptionFingerprintConflictError extends Error {
+ readonly code = 'fingerprint_in_use'
+
+ constructor() {
+ super('A live Codex subscription already uses this ChatGPT account')
+ this.name = 'CodexSubscriptionFingerprintConflictError'
+ }
+}
+
export type CodexSubscriptionConnectionStatus =
| 'disconnected'
| 'connecting'
@@ -17,7 +50,10 @@ export type CodexSubscriptionCatalogStatus =
| 'unavailable'
export type CodexSubscriptionSafeConnection = {
- connectionKey: typeof CODEX_SUBSCRIPTION_CONNECTION_KEY
+ id: string
+ connectionKey: string
+ displayName: string
+ createdBy: string | null
status: CodexSubscriptionConnectionStatus
credentialRevision: number
catalogRevision: number
@@ -50,7 +86,10 @@ export type CodexSubscriptionSecrets = {
}
type SafeConnectionRow = {
+ id: string
connection_key: string
+ display_name: string | null
+ created_by: string | null
status: CodexSubscriptionConnectionStatus
credential_revision: string | number
catalog_revision: string | number
@@ -67,7 +106,10 @@ type SafeConnectionRow = {
}
const SAFE_CONNECTION_COLUMNS = `
+ id,
connection_key,
+ display_name,
+ created_by,
status,
credential_revision,
catalog_revision,
@@ -152,63 +194,149 @@ export async function applyCodexChatgptAccountIdSchema(db: DbClient): Promise<vo
`)
}
+export async function applyCodexMultiConnectionSchema(db: DbClient): Promise<void> {
+ await db.query(`
+ ALTER TABLE codex_subscription_connections
+ DROP CONSTRAINT IF EXISTS codex_subscription_connections_key_check;
+
+ ALTER TABLE codex_subscription_connections
+ ADD COLUMN IF NOT EXISTS display_name TEXT;
+
+ ALTER TABLE codex_subscription_connections
+ ADD COLUMN IF NOT EXISTS created_by TEXT;
+
+ UPDATE codex_subscription_connections
+ SET display_name = COALESCE(NULLIF(display_name, ''), 'Default deployment')
+ WHERE connection_key = '${CODEX_SUBSCRIPTION_CONNECTION_KEY}'
+ AND display_name IS NULL;
+
+ ALTER TABLE codex_subscription_oauth_states
+ ADD COLUMN IF NOT EXISTS connection_key TEXT;
+
+ UPDATE codex_subscription_oauth_states
+ SET connection_key = '${CODEX_SUBSCRIPTION_CONNECTION_KEY}'
+ WHERE connection_key IS NULL;
+
+ CREATE UNIQUE INDEX IF NOT EXISTS codex_subscription_connections_active_fingerprint
+ ON codex_subscription_connections (account_fingerprint)
+ WHERE revoked_at IS NULL AND account_fingerprint IS NOT NULL;
+ `)
+}
+
export async function getSafeCodexSubscriptionConnection(
- db: DbClient
+ db: DbClient,
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
): Promise<CodexSubscriptionSafeConnection | null> {
const result = await db.query(
`SELECT ${SAFE_CONNECTION_COLUMNS}
FROM codex_subscription_connections
WHERE connection_key = $1`,
- [CODEX_SUBSCRIPTION_CONNECTION_KEY]
+ [normalizeCodexConnectionKey(connectionKey)]
)
const row = result.rows[0] as SafeConnectionRow | undefined
return row ? toSafeConnection(row) : null
}
-export async function insertInitialCodexSubscriptionConnection(
+export async function getSafeCodexSubscriptionConnectionById(
db: DbClient,
- encryptionKey: Buffer,
- input: CodexSubscriptionCredentialWrite
+ connectionId: string
+): Promise<CodexSubscriptionSafeConnection | null> {
+ const result = await db.query(
+ `SELECT ${SAFE_CONNECTION_COLUMNS}
+ FROM codex_subscription_connections
+ WHERE id = $1`,
+ [connectionId]
+ )
+ const row = result.rows[0] as SafeConnectionRow | undefined
+ return row ? toSafeConnection(row) : null
+}
+
+export async function listSafeCodexSubscriptionConnections(
+ db: DbClient
+): Promise<CodexSubscriptionSafeConnection[]> {
+ const result = await db.query(
+ `SELECT ${SAFE_CONNECTION_COLUMNS}
+ FROM codex_subscription_connections
+ ORDER BY created_at ASC, connection_key ASC`
+ )
+ return (result.rows as SafeConnectionRow[]).map(toSafeConnection)
+}
+
+export async function createNamedCodexSubscriptionConnection(
+ db: DbClient,
+ input: { connectionKey: string; displayName: string; createdBy?: string | null }
): Promise<CodexSubscriptionSafeConnection> {
- const refreshTokenEncrypted = encryptOAuthSecret(encryptionKey, input.refreshToken)
- const accessTokenEncrypted =
- input.accessToken == null || input.accessToken === ''
- ? null
- : encryptOAuthSecret(encryptionKey, input.accessToken)
- const chatgptAccountIdEncrypted = encryptOptionalSecret(encryptionKey, input.chatgptAccountId)
+ const connectionKey = assertCodexConnectionKey(input.connectionKey)
+ const displayName = input.displayName.trim() || connectionKey
const result = await db.query(
`INSERT INTO codex_subscription_connections (
connection_key,
+ display_name,
+ created_by,
status,
- refresh_token_encrypted,
- access_token_encrypted,
- access_token_expires_at,
- chatgpt_account_id_encrypted,
credential_revision,
catalog_revision,
- account_fingerprint,
- catalog_status,
- last_auth_at
- ) VALUES ($1, $2, $3, $4, $5, $6, 1, 0, $7, 'never_synced', now())
+ catalog_status
+ ) VALUES ($1, $2, $3, 'disconnected', 1, 0, 'never_synced')
RETURNING ${SAFE_CONNECTION_COLUMNS}`,
- [
- CODEX_SUBSCRIPTION_CONNECTION_KEY,
- input.status ?? 'connected',
- refreshTokenEncrypted,
- accessTokenEncrypted,
- input.accessTokenExpiresAt ?? null,
- chatgptAccountIdEncrypted,
- input.accountFingerprint,
- ]
+ [connectionKey, displayName, input.createdBy ?? null]
)
return toSafeConnection(result.rows[0] as SafeConnectionRow)
}
+export async function insertInitialCodexSubscriptionConnection(
+ db: DbClient,
+ encryptionKey: Buffer,
+ input: CodexSubscriptionCredentialWrite,
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
+): Promise<CodexSubscriptionSafeConnection> {
+ const key = assertCodexConnectionKey(normalizeCodexConnectionKey(connectionKey))
+ const refreshTokenEncrypted = encryptOAuthSecret(encryptionKey, input.refreshToken)
+ const accessTokenEncrypted =
+ input.accessToken == null || input.accessToken === ''
+ ? null
+ : encryptOAuthSecret(encryptionKey, input.accessToken)
+ const chatgptAccountIdEncrypted = encryptOptionalSecret(encryptionKey, input.chatgptAccountId)
+ try {
+ const result = await db.query(
+ `INSERT INTO codex_subscription_connections (
+ connection_key,
+ display_name,
+ status,
+ refresh_token_encrypted,
+ access_token_encrypted,
+ access_token_expires_at,
+ chatgpt_account_id_encrypted,
+ credential_revision,
+ catalog_revision,
+ account_fingerprint,
+ catalog_status,
+ last_auth_at
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, 1, 0, $8, 'never_synced', now())
+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,
+ [
+ key,
+ key === CODEX_SUBSCRIPTION_CONNECTION_KEY ? 'Default deployment' : key,
+ input.status ?? 'connected',
+ refreshTokenEncrypted,
+ accessTokenEncrypted,
+ input.accessTokenExpiresAt ?? null,
+ chatgptAccountIdEncrypted,
+ input.accountFingerprint,
+ ]
+ )
+ return toSafeConnection(result.rows[0] as SafeConnectionRow)
+ } catch (err) {
+ throw remapFingerprintConflict(err)
+ }
+}
+
export async function rotateCodexSubscriptionCredentials(
db: DbClient,
encryptionKey: Buffer,
expectedRevision: number,
- input: CodexSubscriptionCredentialWrite
+ input: CodexSubscriptionCredentialWrite,
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
): Promise<CodexSubscriptionSafeConnection> {
const refreshTokenEncrypted = encryptOAuthSecret(encryptionKey, input.refreshToken)
const accessTokenEncrypted =
@@ -216,41 +344,47 @@ export async function rotateCodexSubscriptionCredentials(
? null
: encryptOAuthSecret(encryptionKey, input.accessToken)
const chatgptAccountIdEncrypted = encryptOptionalSecret(encryptionKey, input.chatgptAccountId)
- const result = await db.query(
- `UPDATE codex_subscription_connections
- SET refresh_token_encrypted = $1,
- access_token_encrypted = $2,
- access_token_expires_at = $3,
- chatgpt_account_id_encrypted = COALESCE($4, chatgpt_account_id_encrypted),
- account_fingerprint = $5,
- status = $6,
- credential_revision = credential_revision + 1,
- last_refresh_at = now(),
- last_auth_at = now(),
- revoked_at = NULL,
- updated_at = now()
- WHERE connection_key = $7
- AND credential_revision = $8
- RETURNING ${SAFE_CONNECTION_COLUMNS}`,
- [
- refreshTokenEncrypted,
- accessTokenEncrypted,
- input.accessTokenExpiresAt ?? null,
- chatgptAccountIdEncrypted,
- input.accountFingerprint,
- input.status ?? 'connected',
- CODEX_SUBSCRIPTION_CONNECTION_KEY,
- expectedRevision,
- ]
- )
- const row = result.rows[0] as SafeConnectionRow | undefined
- if (!row) throw new CodexSubscriptionStaleRevisionError()
- return toSafeConnection(row)
+ try {
+ const result = await db.query(
+ `UPDATE codex_subscription_connections
+ SET refresh_token_encrypted = $1,
+ access_token_encrypted = $2,
+ access_token_expires_at = $3,
+ chatgpt_account_id_encrypted = COALESCE($4, chatgpt_account_id_encrypted),
+ account_fingerprint = $5,
+ status = $6,
+ credential_revision = credential_revision + 1,
+ last_refresh_at = now(),
+ last_auth_at = now(),
+ revoked_at = NULL,
+ updated_at = now()
+ WHERE connection_key = $7
+ AND credential_revision = $8
+ RETURNING ${SAFE_CONNECTION_COLUMNS}`,
+ [
+ refreshTokenEncrypted,
+ accessTokenEncrypted,
+ input.accessTokenExpiresAt ?? null,
+ chatgptAccountIdEncrypted,
+ input.accountFingerprint,
+ input.status ?? 'connected',
+ normalizeCodexConnectionKey(connectionKey),
+ expectedRevision,
+ ]
+ )
+ const row = result.rows[0] as SafeConnectionRow | undefined
+ if (!row) throw new CodexSubscriptionStaleRevisionError()
+ return toSafeConnection(row)
+ } catch (err) {
+ throw remapFingerprintConflict(err)
+ }
}
export async function revokeCodexSubscriptionConnection(
- db: DbClient
+ db: DbClient,
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
): Promise<CodexSubscriptionSafeConnection | null> {
+ const key = normalizeCodexConnectionKey(connectionKey)
const result = await db.query(
`UPDATE codex_subscription_connections
SET status = 'revoked',
@@ -267,16 +401,17 @@ export async function revokeCodexSubscriptionConnection(
WHERE connection_key = $1
AND revoked_at IS NULL
RETURNING ${SAFE_CONNECTION_COLUMNS}`,
- [CODEX_SUBSCRIPTION_CONNECTION_KEY]
+ [key]
)
const row = result.rows[0] as SafeConnectionRow | undefined
- return row ? toSafeConnection(row) : getSafeCodexSubscriptionConnection(db)
+ return row ? toSafeConnection(row) : getSafeCodexSubscriptionConnection(db, key)
}
export async function acquireCodexSubscriptionRefreshLock(
db: DbClient,
lockToken: string,
- ttlMs: number
+ ttlMs: number,
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
): Promise<boolean> {
const result = await db.query(
`UPDATE codex_subscription_connections
@@ -291,14 +426,15 @@ export async function acquireCodexSubscriptionRefreshLock(
OR refresh_lock_expires_at <= now()
)
RETURNING refresh_lock_token`,
- [lockToken, ttlMs, CODEX_SUBSCRIPTION_CONNECTION_KEY]
+ [lockToken, ttlMs, normalizeCodexConnectionKey(connectionKey)]
)
return (result.rowCount ?? 0) > 0
}
export async function releaseCodexSubscriptionRefreshLock(
db: DbClient,
- lockToken: string
+ lockToken: string,
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
): Promise<boolean> {
const result = await db.query(
`UPDATE codex_subscription_connections
@@ -307,14 +443,15 @@ export async function releaseCodexSubscriptionRefreshLock(
updated_at = now()
WHERE connection_key = $1
AND refresh_lock_token = $2`,
- [CODEX_SUBSCRIPTION_CONNECTION_KEY, lockToken]
+ [normalizeCodexConnectionKey(connectionKey), lockToken]
)
return (result.rowCount ?? 0) > 0
}
export async function loadCodexSubscriptionSecrets(
db: DbClient,
- encryptionKey: Buffer
+ encryptionKey: Buffer,
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
): Promise<CodexSubscriptionSecrets | null> {
const result = await db.query(
`SELECT refresh_token_encrypted,
@@ -325,7 +462,7 @@ export async function loadCodexSubscriptionSecrets(
FROM codex_subscription_connections
WHERE connection_key = $1
AND revoked_at IS NULL`,
- [CODEX_SUBSCRIPTION_CONNECTION_KEY]
+ [normalizeCodexConnectionKey(connectionKey)]
)
const row = result.rows[0] as
| {
@@ -359,7 +496,8 @@ export async function updateCodexAccessTokenInPlace(
accessTokenExpiresAt?: Date | null
refreshToken?: string | null
chatgptAccountId?: string | null
- }
+ },
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
): Promise<CodexSubscriptionSafeConnection> {
const result = await db.query(
`UPDATE codex_subscription_connections
@@ -378,7 +516,7 @@ export async function updateCodexAccessTokenInPlace(
input.accessTokenExpiresAt ?? null,
encryptOptionalSecret(encryptionKey, input.refreshToken),
encryptOptionalSecret(encryptionKey, input.chatgptAccountId),
- CODEX_SUBSCRIPTION_CONNECTION_KEY,
+ normalizeCodexConnectionKey(connectionKey),
expectedRevision,
]
)
@@ -390,7 +528,8 @@ export async function updateCodexAccessTokenInPlace(
export async function persistCodexChatgptAccountId(
db: DbClient,
encryptionKey: Buffer,
- chatgptAccountId: string
+ chatgptAccountId: string,
+ connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
): Promise<void> {
await db.query(
`UPDATE codex_subscription_connections
@@ -399,7 +538,10 @@ export async function persistCodexChatgptAccountId(
WHERE connection_key = $2
AND revoked_at IS NULL
AND chatgpt_account_id_encrypted IS NULL`,
- [encryptOAuthSecret(encryptionKey, chatgptAccountId), CODEX_SUBSCRIPTION_CONNECTION_KEY]
+ [
+ encryptOAuthSecret(encryptionKey, chatgptAccountId),
+ normalizeCodexConnectionKey(connectionKey),
+ ]
)
}
@@ -418,6 +560,7 @@ export async function recordCodexCatalogOutcome(
connectionStatus?: CodexSubscriptionConnectionStatus
expectedCredentialRevision: number
expectedCatalogRevision: number
+ connectionKey?: string
}
): Promise<CodexSubscriptionSafeConnection | null> {
const result = await db.query(
@@ -434,7 +577,7 @@ export async function recordCodexCatalogOutcome(
[
input.catalogStatus,
input.connectionStatus ?? null,
- CODEX_SUBSCRIPTION_CONNECTION_KEY,
+ normalizeCodexConnectionKey(input.connectionKey),
input.expectedCredentialRevision,
input.expectedCatalogRevision,
]
@@ -443,9 +586,18 @@ export async function recordCodexCatalogOutcome(
return row ? toSafeConnection(row) : null
}
+function remapFingerprintConflict(err: unknown): never | Error {
+ const code = (err as { code?: string } | null)?.code
+ if (code === '23505') return new CodexSubscriptionFingerprintConflictError()
+ throw err
+}
+
function toSafeConnection(row: SafeConnectionRow): CodexSubscriptionSafeConnection {
return {
- connectionKey: CODEX_SUBSCRIPTION_CONNECTION_KEY,
+ id: String(row.id),
+ connectionKey: row.connection_key,
+ displayName: row.display_name?.trim() || row.connection_key,
+ createdBy: row.created_by,
status: row.status,
credentialRevision: Number(row.credential_revision),
catalogRevision: Number(row.catalog_revision),
diff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.ts
index 8a7dd4890..d118f8f70 100644
--- a/control-api/src/services/codexSubscriptionOAuth.ts
+++ b/control-api/src/services/codexSubscriptionOAuth.ts
@@ -2,13 +2,16 @@ import { createHash, randomBytes } from 'node:crypto'
import type { DbClient } from '../db.js'
import { rootLogger } from '../observability/logger.js'
import { chatgptAccountIdFromJwt } from './chatgptAccountId.js'
+import { rebuildLiveCodexUnionAllowlist } from './codexSubscriptionCatalog.js'
import {
+ CodexSubscriptionFingerprintConflictError,
type CodexSubscriptionSafeConnection,
CodexSubscriptionStaleRevisionError,
acquireCodexSubscriptionRefreshLock,
getSafeCodexSubscriptionConnection,
insertInitialCodexSubscriptionConnection,
loadCodexSubscriptionSecrets,
+ normalizeCodexConnectionKey,
persistCodexChatgptAccountId,
releaseCodexSubscriptionRefreshLock,
revokeCodexSubscriptionConnection,
@@ -57,6 +60,7 @@ export type CodexOAuthErrorCode =
| 'no_grant'
| 'invalid_callback'
| 'browser_oauth_unregistered'
+ | 'fingerprint_in_use'
export class CodexSubscriptionOAuthError extends Error {
readonly code: CodexOAuthErrorCode
@@ -75,6 +79,11 @@ export type CodexOAuthDeps = {
clientId: string
redirectUri: string
enabled: boolean
+ connectionKey?: string
+}
+
+function connectionKeyOf(deps: CodexOAuthDeps): string {
+ return normalizeCodexConnectionKey(deps.connectionKey)
}
export type CodexBrowserStartResult = {
@@ -109,12 +118,10 @@ function requireEnabled(deps: CodexOAuthDeps): void {
export async function getCodexSubscriptionConnection(
deps: CodexOAuthDeps
-): Promise<
- CodexSubscriptionSafeConnection | { connectionKey: 'deployment-default'; status: 'disconnected' }
-> {
+): Promise<CodexSubscriptionSafeConnection | { connectionKey: string; status: 'disconnected' }> {
requireEnabled(deps)
- const row = await getSafeCodexSubscriptionConnection(deps.db)
- return row ?? { connectionKey: 'deployment-default', status: 'disconnected' }
+ const row = await getSafeCodexSubscriptionConnection(deps.db, connectionKeyOf(deps))
+ return row ?? { connectionKey: connectionKeyOf(deps), status: 'disconnected' }
}
export async function startCodexBrowserConnect(
@@ -131,6 +138,7 @@ export async function startCodexBrowserConnect(
intent,
pkceVerifier,
expiresAt,
+ connectionKey: connectionKeyOf(deps),
})
const challenge = createHash('sha256').update(pkceVerifier).digest('base64url')
const url = new URL(CODEX_OAUTH_AUTHORIZE_URL)
@@ -168,6 +176,7 @@ export async function startCodexDeviceConnect(
intent,
deviceCode: encodeDeviceAuthHandle({ deviceAuthId, userCode }),
expiresAt,
+ connectionKey: connectionKeyOf(deps),
})
log.info({ event: 'codex_oauth_device_start', intent: safe.intent }, 'device OAuth start')
return {
@@ -258,17 +267,23 @@ export async function refreshCodexSubscriptionConnection(
deps: CodexOAuthDeps
): Promise<CodexSubscriptionSafeConnection> {
requireEnabled(deps)
- const current = await getSafeCodexSubscriptionConnection(deps.db)
+ const key = connectionKeyOf(deps)
+ const current = await getSafeCodexSubscriptionConnection(deps.db, key)
if (!current || current.status === 'revoked' || current.status === 'disconnected') {
throw new CodexSubscriptionOAuthError('not_connected', 'no active Codex subscription')
}
const lockToken = randomBytes(16).toString('hex')
- const locked = await acquireCodexSubscriptionRefreshLock(deps.db, lockToken, REFRESH_LOCK_TTL_MS)
+ const locked = await acquireCodexSubscriptionRefreshLock(
+ deps.db,
+ lockToken,
+ REFRESH_LOCK_TTL_MS,
+ key
+ )
if (!locked) {
throw new CodexSubscriptionOAuthError('refresh_in_flight', 'another refresh holds the lock')
}
try {
- const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey)
+ const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey, key)
if (!secrets)
throw new CodexSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')
const token = await exchangeRefreshToken(deps, secrets.refreshToken)
@@ -283,27 +298,41 @@ export async function refreshCodexSubscriptionConnection(
accessTokenExpiresAt: token.expiresAt,
chatgptAccountId: token.chatgptAccountId,
accountFingerprint: token.accountFingerprint,
- }
+ },
+ key
)
} catch (err) {
if (err instanceof CodexSubscriptionStaleRevisionError) {
throw new CodexSubscriptionOAuthError('stale_revision', 'refresh lost the credential race')
}
+ if (err instanceof CodexSubscriptionFingerprintConflictError) {
+ throw new CodexSubscriptionOAuthError(
+ 'fingerprint_in_use',
+ 'a live Codex subscription already uses this ChatGPT account'
+ )
+ }
throw err
}
} finally {
- await releaseCodexSubscriptionRefreshLock(deps.db, lockToken)
+ await releaseCodexSubscriptionRefreshLock(deps.db, lockToken, key)
}
}
export async function revokeCodexSubscription(
deps: CodexOAuthDeps
-): Promise<
- CodexSubscriptionSafeConnection | { connectionKey: 'deployment-default'; status: 'disconnected' }
-> {
+): Promise<CodexSubscriptionSafeConnection | { connectionKey: string; status: 'disconnected' }> {
requireEnabled(deps)
- const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey)
- const local = await revokeCodexSubscriptionConnection(deps.db)
+ const key = connectionKeyOf(deps)
+ const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey, key)
+ const local = await revokeCodexSubscriptionConnection(deps.db, key)
+ try {
+ await rebuildLiveCodexUnionAllowlist(deps.db)
+ } catch (err) {
+ log.warn(
+ { event: 'codex_union_rebuild_after_revoke_failed', err },
+ 'union allowlist rebuild failed'
+ )
+ }
if (secrets?.refreshToken) {
try {
const revokePayload: Record<string, string> = {
@@ -317,7 +346,7 @@ export async function revokeCodexSubscription(
}
}
log.info({ event: 'codex_oauth_revoked_local' }, 'local Codex subscription revoked')
- return local ?? { connectionKey: 'deployment-default', status: 'disconnected' }
+ return local ?? { connectionKey: key, status: 'disconnected' }
}
async function persistGrantedTokens(
@@ -325,7 +354,8 @@ async function persistGrantedTokens(
intent: CodexSubscriptionOAuthIntent,
parsed: ParsedCodexToken
): Promise<CodexSubscriptionSafeConnection> {
- const existing = await getSafeCodexSubscriptionConnection(deps.db)
+ const key = connectionKeyOf(deps)
+ const existing = await getSafeCodexSubscriptionConnection(deps.db, key)
if (
existing?.accountFingerprint &&
existing.accountFingerprint !== parsed.accountFingerprint &&
@@ -351,14 +381,15 @@ async function persistGrantedTokens(
)
}
if (!existing) {
- return insertInitialCodexSubscriptionConnection(deps.db, deps.encryptionKey, write)
+ return insertInitialCodexSubscriptionConnection(deps.db, deps.encryptionKey, write, key)
}
try {
return await rotateCodexSubscriptionCredentials(
deps.db,
deps.encryptionKey,
existing.credentialRevision,
- write
+ write,
+ key
)
} catch (err) {
if (err instanceof CodexSubscriptionStaleRevisionError) {
@@ -367,6 +398,12 @@ async function persistGrantedTokens(
'connection was replaced concurrently'
)
}
+ if (err instanceof CodexSubscriptionFingerprintConflictError) {
+ throw new CodexSubscriptionOAuthError(
+ 'fingerprint_in_use',
+ 'a live Codex subscription already uses this ChatGPT account'
+ )
+ }
throw err
}
}
@@ -385,7 +422,8 @@ type ParsedCodexToken = {
*/
export async function ensureFreshCodexAccessToken(deps: CodexOAuthDeps): Promise<void> {
requireEnabled(deps)
- const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey)
+ const key = connectionKeyOf(deps)
+ const secrets = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey, key)
if (!secrets) {
throw new CodexSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')
}
@@ -395,30 +433,41 @@ export async function ensureFreshCodexAccessToken(deps: CodexOAuthDeps): Promise
secrets.accessTokenExpiresAt.getTime() - Date.now() < ACCESS_TOKEN_REFRESH_SKEW_MS
if (secrets.accessToken && !expiring && accountId) {
if (!secrets.chatgptAccountId) {
- await persistCodexChatgptAccountId(deps.db, deps.encryptionKey, accountId)
+ await persistCodexChatgptAccountId(deps.db, deps.encryptionKey, accountId, key)
}
return
}
const lockToken = randomBytes(16).toString('hex')
- const locked = await acquireCodexSubscriptionRefreshLock(deps.db, lockToken, REFRESH_LOCK_TTL_MS)
+ const locked = await acquireCodexSubscriptionRefreshLock(
+ deps.db,
+ lockToken,
+ REFRESH_LOCK_TTL_MS,
+ key
+ )
if (!locked) {
await new Promise(resolve => setTimeout(resolve, 400))
return
}
try {
- const latest = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey)
+ const latest = await loadCodexSubscriptionSecrets(deps.db, deps.encryptionKey, key)
if (!latest) {
throw new CodexSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')
}
const token = await exchangeRefreshToken(deps, latest.refreshToken)
accountId = token.chatgptAccountId || chatgptAccountIdFromJwt(token.accessToken) || accountId
- await updateCodexAccessTokenInPlace(deps.db, deps.encryptionKey, latest.credentialRevision, {
- accessToken: token.accessToken,
- accessTokenExpiresAt: token.expiresAt,
- refreshToken: token.refreshToken,
- chatgptAccountId: accountId,
- })
+ await updateCodexAccessTokenInPlace(
+ deps.db,
+ deps.encryptionKey,
+ latest.credentialRevision,
+ {
+ accessToken: token.accessToken,
+ accessTokenExpiresAt: token.expiresAt,
+ refreshToken: token.refreshToken,
+ chatgptAccountId: accountId,
+ },
+ key
+ )
} catch (err) {
if (err instanceof CodexSubscriptionStaleRevisionError) {
throw new CodexSubscriptionOAuthError(
@@ -428,7 +477,7 @@ export async function ensureFreshCodexAccessToken(deps: CodexOAuthDeps): Promise
}
throw err
} finally {
- await releaseCodexSubscriptionRefreshLock(deps.db, lockToken)
+ await releaseCodexSubscriptionRefreshLock(deps.db, lockToken, key)
}
}
diff --git a/control-api/src/services/codexSubscriptionOAuthState.ts b/control-api/src/services/codexSubscriptionOAuthState.ts
index 23173f4f4..c3103d17e 100644
--- a/control-api/src/services/codexSubscriptionOAuthState.ts
+++ b/control-api/src/services/codexSubscriptionOAuthState.ts
@@ -24,6 +24,7 @@ export type CodexSubscriptionOAuthStateWrite = {
/** Encrypted Codex device handle JSON: { deviceAuthId, userCode }. */
deviceCode?: string
expiresAt: Date
+ connectionKey?: string
}
export type CodexSubscriptionConsumedOAuthState = {
@@ -117,8 +118,9 @@ export async function insertCodexSubscriptionOAuthState(
pkce_verifier_encrypted,
device_code_encrypted,
status,
- expires_at
- ) VALUES ($1, $2, $3, $4, $5, 'pending', $6)
+ expires_at,
+ connection_key
+ ) VALUES ($1, $2, $3, $4, $5, 'pending', $6, $7)
RETURNING ${SAFE_OAUTH_STATE_COLUMNS}`,
[
input.state,
@@ -127,6 +129,7 @@ export async function insertCodexSubscriptionOAuthState(
input.pkceVerifier ? encryptOAuthSecret(encryptionKey, input.pkceVerifier) : null,
input.deviceCode ? encryptOAuthSecret(encryptionKey, input.deviceCode) : null,
input.expiresAt,
+ input.connectionKey ?? 'deployment-default',
]
)
return toSafeOAuthState(result.rows[0] as SafeOAuthStateRow)
diff --git a/control-api/src/services/llmAllowedModelsConfigMap.ts b/control-api/src/services/llmAllowedModelsConfigMap.ts
index 1cf14bb56..9788f2376 100644
--- a/control-api/src/services/llmAllowedModelsConfigMap.ts
+++ b/control-api/src/services/llmAllowedModelsConfigMap.ts
@@ -25,6 +25,7 @@ import { pool } from '../db.js'
import {
type CodexSubscriptionSafeConnection,
getSafeCodexSubscriptionConnection,
+ listSafeCodexSubscriptionConnections,
} from './codexSubscriptionConnection.js'
import { type AllowedModelEntry, listEnabledGroupedByProvider } from './llmAllowedModels.js'
@@ -38,6 +39,7 @@ export const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'
export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'
export const CODEX_CONNECTION_STATUS_ANNOTATION = 'clerum.io/codex-connection-status'
export const CODEX_ENABLED_ANNOTATION = 'clerum.io/codex-enabled'
+export const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
const KNOWN_CONNECTION_STATUSES = new Set([
'disconnected',
@@ -49,8 +51,9 @@ const KNOWN_CONNECTION_STATUSES = new Set([
export function mapCodexConnectionStatusForSnapshot(
connection: CodexSubscriptionSafeConnection | null
-): 'connected' | 'disconnected' | 'reauth-required' | 'unavailable' {
+): 'connected' | 'disconnected' | 'reauth-required' | 'unavailable' | 'revoked' {
if (!connection || !KNOWN_CONNECTION_STATUSES.has(connection.status)) return 'disconnected'
+ if (connection.status === 'revoked') return 'revoked'
if (connection.status === 'reauth_required' || connection.catalogStatus === 'auth-rejected') {
return 'reauth-required'
}
@@ -60,7 +63,8 @@ export function mapCodexConnectionStatusForSnapshot(
}
export function buildCodexReadinessAnnotations(
- connection: CodexSubscriptionSafeConnection | null
+ connection: CodexSubscriptionSafeConnection | null,
+ connections: CodexSubscriptionSafeConnection[] = []
): Record<string, string> {
const annotations: Record<string, string> = {
[CODEX_ENABLED_ANNOTATION]: config.codexSubscriptionEnabled ? 'true' : 'false',
@@ -75,6 +79,24 @@ export function buildCodexReadinessAnnotations(
annotations[CATALOG_REVISION_ANNOTATION] = String(connection.catalogRevision)
annotations[CONNECTION_REVISION_ANNOTATION] = String(connection.credentialRevision)
}
+ const map: Record<
+ string,
+ {
+ status: ReturnType<typeof mapCodexConnectionStatusForSnapshot>
+ catalogRevision: number
+ connectionRevision: number
+ }
+ > = {}
+ for (const row of connections) {
+ map[row.connectionKey] = {
+ status: mapCodexConnectionStatusForSnapshot(row),
+ catalogRevision: row.catalogRevision,
+ connectionRevision: row.credentialRevision,
+ }
+ }
+ if (Object.keys(map).length > 0) {
+ annotations[CODEX_CONNECTIONS_ANNOTATION] = JSON.stringify(map)
+ }
return annotations
}
@@ -134,7 +156,13 @@ export class LlmAllowedModelsConfigMapWriter implements AllowedModelsConfigMapMa
async materialize(db: DbClient = pool): Promise<void> {
const grouped = await listEnabledGroupedByProvider(db)
const { data, contentHash } = buildConfigMapData(grouped)
- const readiness = buildCodexReadinessAnnotations(await loadCodexConnection(db))
+ const connections = await listSafeCodexSubscriptionConnections(db).catch(() => [])
+ const readiness = buildCodexReadinessAnnotations(
+ connections.find(row => row.connectionKey === 'deployment-default') ??
+ connections[0] ??
+ (await loadCodexConnection(db)),
+ connections
+ )
let lastError: unknown
for (let attempt = 1; attempt <= this.maxAttempts; attempt++) {
try {
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index 4337d5006..43c66b180 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -11,8 +11,12 @@ import type { McpHostAccessClaims } from '../utils/auth/mcpHostJwtToken.js'
import { isPlainObject } from '../utils/isPlainObject.js'
import { evaluateBudgetCheck } from './budgets/check.js'
import { getActiveReservation } from './budgets/reservations.js'
-import { getSafeCodexSubscriptionConnection } from './codexSubscriptionConnection.js'
-import { getModelAllowlistState } from './llmAllowedModels.js'
+import { getCodexCatalogModelState } from './codexSubscriptionCatalog.js'
+import {
+ CODEX_SUBSCRIPTION_CONNECTION_KEY,
+ getSafeCodexSubscriptionConnection,
+ normalizeCodexConnectionKey,
+} from './codexSubscriptionConnection.js'
import {
getMaxLlmProviderAttemptGeneration,
insertLlmProviderAttempt,
@@ -74,7 +78,8 @@ export type LlmProviderAttemptAuthorizerDeps = {
db: DbClient
withTransaction: typeof withTransaction
getConnection: typeof getSafeCodexSubscriptionConnection
- getModelState: typeof getModelAllowlistState
+ getModelState: typeof getCodexCatalogModelState
+ resolveConnectionKey: (hostRef: string) => Promise<string>
evaluateBudget: typeof evaluateBudgetCheck
getActiveReservation: typeof getActiveReservation
getMaxGeneration: typeof getMaxLlmProviderAttemptGeneration
@@ -87,7 +92,8 @@ const defaultDeps = (): LlmProviderAttemptAuthorizerDeps => ({
db: { query: (text, values) => pool.query(text, values) },
withTransaction,
getConnection: getSafeCodexSubscriptionConnection,
- getModelState: getModelAllowlistState,
+ getModelState: getCodexCatalogModelState,
+ resolveConnectionKey: async () => CODEX_SUBSCRIPTION_CONNECTION_KEY,
evaluateBudget: evaluateBudgetCheck,
getActiveReservation,
getMaxGeneration: getMaxLlmProviderAttemptGeneration,
@@ -160,9 +166,10 @@ function assertClaimBinding(body: Record<string, unknown>, claims: McpHostAccess
export async function authorizeLlmProviderAttempt(
claims: McpHostAccessClaims,
body: unknown,
- deps: LlmProviderAttemptAuthorizerDeps = defaultDeps()
+ deps: LlmProviderAttemptAuthorizerDeps | Partial<LlmProviderAttemptAuthorizerDeps> = defaultDeps()
): Promise<AuthorizeAttemptSuccess> {
- if (!deps.enabled) {
+ const resolvedDeps: LlmProviderAttemptAuthorizerDeps = { ...defaultDeps(), ...deps }
+ if (!resolvedDeps.enabled) {
throw new LlmProviderAttemptAuthorizeError('disabled', 'Codex subscription is disabled')
}
if (!claims.workflowControlScopes.includes(CODEX_EXECUTE_SCOPE)) {
@@ -236,9 +243,12 @@ export async function authorizeLlmProviderAttempt(
)
}
- return deps.withTransaction(async tx => {
+ return resolvedDeps.withTransaction(async tx => {
const db: DbClient = tx
- const connection = await deps.getConnection(db)
+ const connectionKey = normalizeCodexConnectionKey(
+ await resolvedDeps.resolveConnectionKey(caller.hostRef)
+ )
+ const connection = await resolvedDeps.getConnection(db, connectionKey)
if (
!connection ||
connection.status !== 'connected' ||
@@ -257,7 +267,7 @@ export async function authorizeLlmProviderAttempt(
)
}
- const modelState = await deps.getModelState(PROVIDER, request.model, db)
+ const modelState = await resolvedDeps.getModelState(db, connection.id, request.model)
if (!modelState || !modelState.enabled || modelState.stale) {
throw new LlmProviderAttemptAuthorizeError(
'model_not_allowed',
@@ -269,6 +279,7 @@ export async function authorizeLlmProviderAttempt(
model: request.model,
catalogRevision: connection.catalogRevision,
credentialRevision: connection.credentialRevision,
+ connectionKey: connection.connectionKey,
})
if (policyRevision !== connection.catalogRevision || policyHash !== expectedPolicyHash) {
throw new LlmProviderAttemptAuthorizeError(
@@ -277,7 +288,7 @@ export async function authorizeLlmProviderAttempt(
)
}
- const maxGeneration = await deps.getMaxGeneration(db, invocationId)
+ const maxGeneration = await resolvedDeps.getMaxGeneration(db, invocationId)
if (attemptGeneration < maxGeneration) {
throw new LlmProviderAttemptAuthorizeError(
'stale_generation',
@@ -288,7 +299,7 @@ export async function authorizeLlmProviderAttempt(
const presentedReservationId =
typeof body.budgetReservationId === 'string' ? body.budgetReservationId.trim() : ''
if (presentedReservationId) {
- const active = await deps.getActiveReservation(db, {
+ const active = await resolvedDeps.getActiveReservation(db, {
reservationId: presentedReservationId,
hostRef: caller.hostRef,
})
@@ -300,7 +311,7 @@ export async function authorizeLlmProviderAttempt(
}
}
- const budget = await deps.evaluateBudget(
+ const budget = await resolvedDeps.evaluateBudget(
{
host_ref: caller.hostRef,
context_ref: null,
@@ -331,7 +342,7 @@ export async function authorizeLlmProviderAttempt(
budget.reservationIds?.[0] ?? (presentedReservationId || 'unbudgeted')
try {
- const attempt = await deps.insertAttempt(db, {
+ const attempt = await resolvedDeps.insertAttempt(db, {
callerKind: caller.callerKind,
hostRef: caller.hostRef,
recipeNamespace: caller.recipeNamespace,
@@ -345,8 +356,9 @@ export async function authorizeLlmProviderAttempt(
policyHash,
budgetReservationId,
connectionRevision: connection.credentialRevision,
+ connectionId: connection.id,
})
- const issued = await deps.issueTicket(db, {
+ const issued = await resolvedDeps.issueTicket(db, {
sub: claims.sub,
hostRef: caller.hostRef,
recipeNamespace: caller.recipeNamespace ?? undefined,
@@ -361,6 +373,7 @@ export async function authorizeLlmProviderAttempt(
policyHash,
budgetReservationId,
connectionRevision: connection.credentialRevision,
+ connectionId: connection.id,
})
log.info(
{
diff --git a/control-api/src/services/llmProviderAttemptRedemption.ts b/control-api/src/services/llmProviderAttemptRedemption.ts
index 60bc4a492..2d67ee96d 100644
--- a/control-api/src/services/llmProviderAttemptRedemption.ts
+++ b/control-api/src/services/llmProviderAttemptRedemption.ts
@@ -6,6 +6,7 @@ import { rootLogger } from '../observability/logger.js'
import { chatgptAccountIdFromJwt } from './chatgptAccountId.js'
import {
getSafeCodexSubscriptionConnection,
+ getSafeCodexSubscriptionConnectionById,
loadCodexSubscriptionSecrets,
} from './codexSubscriptionConnection.js'
import {
@@ -85,7 +86,7 @@ export type RedeemAttemptDeps = {
withTransaction: typeof withTransaction
loadSecrets: typeof loadCodexSubscriptionSecrets
encryptionKey: Buffer
- ensureFreshAccessToken?: () => Promise<void>
+ ensureFreshAccessToken?: (connectionKey?: string) => Promise<void>
}
const defaultRedeemDeps = (): RedeemAttemptDeps => ({
@@ -93,7 +94,7 @@ const defaultRedeemDeps = (): RedeemAttemptDeps => ({
withTransaction,
loadSecrets: loadCodexSubscriptionSecrets,
encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),
- ensureFreshAccessToken: () =>
+ ensureFreshAccessToken: connectionKey =>
ensureFreshCodexAccessToken({
db: { query: (text, values) => pool.query(text, values) },
encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),
@@ -101,6 +102,7 @@ const defaultRedeemDeps = (): RedeemAttemptDeps => ({
clientId: config.codexOAuthClientId,
redirectUri: 'http://127.0.0.1/codex/oauth/callback',
enabled: config.codexSubscriptionEnabled,
+ connectionKey,
}),
})
@@ -130,7 +132,15 @@ export async function redeemLlmProviderAttempt(
if (deps.ensureFreshAccessToken) {
try {
- await deps.ensureFreshAccessToken()
+ let refreshKey: string | undefined
+ if (claims.connectionId) {
+ const assigned = await getSafeCodexSubscriptionConnectionById(
+ { query: (text, values) => pool.query(text, values) },
+ claims.connectionId
+ )
+ refreshKey = assigned?.connectionKey
+ }
+ await deps.ensureFreshAccessToken(refreshKey)
} catch (err) {
if (err instanceof CodexSubscriptionOAuthError) {
throw new LlmProviderAttemptRedeemError(
@@ -183,12 +193,15 @@ export async function redeemLlmProviderAttempt(
)
}
- const connection = await getSafeCodexSubscriptionConnection(tx)
+ const connection = attempt.connectionId
+ ? await getSafeCodexSubscriptionConnectionById(tx, attempt.connectionId)
+ : await getSafeCodexSubscriptionConnection(tx)
if (
!connection ||
connection.status !== 'connected' ||
connection.revokedAt ||
- connection.credentialRevision !== attempt.connectionRevision
+ connection.credentialRevision !== attempt.connectionRevision ||
+ (attempt.connectionId && connection.id !== attempt.connectionId)
) {
throw new LlmProviderAttemptRedeemError(
'connection_unavailable',
@@ -201,7 +214,7 @@ export async function redeemLlmProviderAttempt(
throw new LlmProviderAttemptRedeemError('ticket_replayed', 'execution ticket already used')
}
- const secrets = await deps.loadSecrets(tx, deps.encryptionKey)
+ const secrets = await deps.loadSecrets(tx, deps.encryptionKey, connection.connectionKey)
if (!secrets?.accessToken) {
throw new LlmProviderAttemptRedeemError(
'connection_unavailable',
diff --git a/control-api/src/services/llmProviderAttemptStore.ts b/control-api/src/services/llmProviderAttemptStore.ts
index 60dbc0d52..2589af50d 100644
--- a/control-api/src/services/llmProviderAttemptStore.ts
+++ b/control-api/src/services/llmProviderAttemptStore.ts
@@ -20,6 +20,7 @@ export type LlmProviderAttemptInsert = {
policyHash: string
budgetReservationId: string
connectionRevision: number
+ connectionId?: string | null
correlationId?: string | null
}
@@ -76,6 +77,19 @@ export async function applyLlmProviderAttemptSchema(db: DbClient): Promise<void>
`)
}
+export async function applyLlmProviderAttemptConnectionIdSchema(db: DbClient): Promise<void> {
+ await db.query(`
+ ALTER TABLE llm_provider_attempts
+ ADD COLUMN IF NOT EXISTS connection_id UUID REFERENCES codex_subscription_connections(id);
+
+ UPDATE llm_provider_attempts a
+ SET connection_id = c.id
+ FROM codex_subscription_connections c
+ WHERE a.connection_id IS NULL
+ AND c.connection_key = 'deployment-default';
+ `)
+}
+
export async function applyLlmProviderAttemptTicketSchema(db: DbClient): Promise<void> {
await db.query(`
CREATE TABLE IF NOT EXISTS llm_provider_attempt_tickets (
@@ -106,15 +120,15 @@ export async function insertLlmProviderAttempt(
caller_kind, host_ref, recipe_namespace, recipe_name, invocation_id,
attempt_generation, provider_attempt_index, provider, model, request_hash,
policy_revision, policy_hash, budget_reservation_id, connection_revision,
- status, correlation_id
+ connection_id, status, correlation_id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, 'codex-subscription', $8, $9, $10, $11, $12, $13,
- 'authorized', $14
+ $14, 'authorized', $15
)
RETURNING id, caller_kind, host_ref, recipe_namespace, recipe_name, invocation_id,
attempt_generation, provider_attempt_index, provider, model, request_hash,
policy_revision, policy_hash, budget_reservation_id, connection_revision,
- status, outcome, created_at`,
+ connection_id, status, outcome, created_at`,
[
input.callerKind,
input.hostRef,
@@ -129,6 +143,7 @@ export async function insertLlmProviderAttempt(
input.policyHash,
input.budgetReservationId,
input.connectionRevision,
+ input.connectionId ?? null,
input.correlationId ?? null,
]
)
@@ -149,6 +164,7 @@ export async function insertLlmProviderAttempt(
policyHash: String(row.policy_hash),
budgetReservationId: String(row.budget_reservation_id),
connectionRevision: Number(row.connection_revision),
+ connectionId: row.connection_id ? String(row.connection_id) : null,
status: row.status as LlmProviderAttemptStatus,
outcome: (row.outcome as LlmProviderAttemptOutcome | null) ?? null,
createdAt: row.created_at instanceof Date ? row.created_at : new Date(String(row.created_at)),
@@ -183,7 +199,7 @@ export async function loadLlmProviderAttempt(
`SELECT id, caller_kind, host_ref, recipe_namespace, recipe_name, invocation_id,
attempt_generation, provider_attempt_index, provider, model, request_hash,
policy_revision, policy_hash, budget_reservation_id, connection_revision,
- status, outcome, created_at
+ connection_id, status, outcome, created_at
FROM llm_provider_attempts
WHERE id = $1`,
[id]
@@ -206,6 +222,7 @@ export async function loadLlmProviderAttempt(
policyHash: String(row.policy_hash),
budgetReservationId: String(row.budget_reservation_id),
connectionRevision: Number(row.connection_revision),
+ connectionId: row.connection_id ? String(row.connection_id) : null,
status: row.status as LlmProviderAttemptStatus,
outcome: (row.outcome as LlmProviderAttemptOutcome | null) ?? null,
createdAt: row.created_at instanceof Date ? row.created_at : new Date(String(row.created_at)),
diff --git a/control-api/src/services/llmProviderAttemptTicket.ts b/control-api/src/services/llmProviderAttemptTicket.ts
index 61dc232bc..884161525 100644
--- a/control-api/src/services/llmProviderAttemptTicket.ts
+++ b/control-api/src/services/llmProviderAttemptTicket.ts
@@ -26,6 +26,7 @@ export type CodexExecutionTicketClaims = {
policyHash: string
budgetReservationId: string
connectionRevision: number
+ connectionId?: string
}
export type IssuedCodexExecutionTicket = {
diff --git a/control-api/test/db.codexSubscriptionMigration.test.ts b/control-api/test/db.codexSubscriptionMigration.test.ts
index 928070d25..d90e5d192 100644
--- a/control-api/test/db.codexSubscriptionMigration.test.ts
+++ b/control-api/test/db.codexSubscriptionMigration.test.ts
@@ -45,6 +45,18 @@ describe('00a0/00a1 Codex subscription persistence', () => {
expect(dbSource.indexOf("version: '00a4_codex_chatgpt_account_id'")).toBeLessThan(
dbSource.indexOf("version: '0100_seed_minimax_allowed_model'")
)
+ expect(dbSource).toContain("version: '0101_codex_multi_connection'")
+ expect(dbSource).toContain("version: '0102_codex_catalog_models'")
+ expect(dbSource).toContain("version: '0103_llm_provider_attempts_connection_id'")
+ expect(dbSource.indexOf("version: '0100_seed_minimax_allowed_model'")).toBeLessThan(
+ dbSource.indexOf("version: '0101_codex_multi_connection'")
+ )
+ expect(dbSource.indexOf("version: '0101_codex_multi_connection'")).toBeLessThan(
+ dbSource.indexOf("version: '0102_codex_catalog_models'")
+ )
+ expect(dbSource.indexOf("version: '0102_codex_catalog_models'")).toBeLessThan(
+ dbSource.indexOf("version: '0103_llm_provider_attempts_connection_id'")
+ )
})
it('creates a single active deployment-default connection with ciphertext and revisions', () => {
@@ -123,5 +135,6 @@ describe('00a0/00a1 Codex subscription persistence', () => {
const profile = runtimeAccessProfile()
expect(profile.get('codex_subscription_connections')).toBe('upsert')
expect(profile.get('codex_subscription_oauth_states')).toBe('upsert')
+ expect(profile.get('codex_catalog_models')).toBe('upsert')
})
})
diff --git a/control-api/test/db.ready.test.ts b/control-api/test/db.ready.test.ts
index a9b5acf49..3d9d8c6b2 100644
--- a/control-api/test/db.ready.test.ts
+++ b/control-api/test/db.ready.test.ts
@@ -3,6 +3,7 @@ import { CONTROL_API_MIGRATIONS, assertDbReady } from '../src/db.js'
const LATEST_MIGRATION = CONTROL_API_MIGRATIONS.at(-1)!.version
const CODEX_ACCOUNT_ID_MIGRATION = '00a4_codex_chatgpt_account_id'
+const CODEX_MULTI_CONNECTION_MIGRATION = '0101_codex_multi_connection'
describe('assertDbReady', () => {
it('accepts a database that recorded every registered migration', async () => {
@@ -38,4 +39,17 @@ describe('assertDbReady', () => {
`missing migrations ${CODEX_ACCOUNT_ID_MIGRATION}`
)
})
+
+ it('fails closed when 0101 is absent after the catalog tail moved to 0100', async () => {
+ const query = vi.fn().mockResolvedValue({
+ rows: CONTROL_API_MIGRATIONS.filter(
+ migration => migration.version !== CODEX_MULTI_CONNECTION_MIGRATION
+ ).map(migration => ({ version: migration.version })),
+ rowCount: CONTROL_API_MIGRATIONS.length - 1,
+ })
+
+ await expect(assertDbReady({ query })).rejects.toThrow(
+ `missing migrations ${CODEX_MULTI_CONNECTION_MIGRATION}`
+ )
+ })
})
diff --git a/control-api/test/hostSpecValidation.codexSubscription.test.ts b/control-api/test/hostSpecValidation.codexSubscription.test.ts
index 1ff4faf25..5f683fc15 100644
--- a/control-api/test/hostSpecValidation.codexSubscription.test.ts
+++ b/control-api/test/hostSpecValidation.codexSubscription.test.ts
@@ -49,6 +49,101 @@ describe('codex-subscription Host admission', () => {
expect(res!.errors[0].field).toBe('spec.secretRef')
})
+ it('defaults a missing connectionRef to deployment-default and checks that grant', async () => {
+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'
+ const isModelAllowed = vi.fn().mockResolvedValue(true)
+ const spec = { model: { provider: 'codex-subscription', name: 'gpt-5.1' } }
+ const res = await validateHostSpec(spec, { isModelAllowed })
+ expect(res).toBeNull()
+ expect(isModelAllowed).toHaveBeenCalledWith(
+ 'codex-subscription',
+ 'gpt-5.1',
+ 'deployment-default'
+ )
+ expect((spec.model as { connectionRef?: string }).connectionRef).toBe('deployment-default')
+ })
+
+ it('does not tolerate switching to a revoked connectionRef with the same model', async () => {
+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'
+ const isModelAllowed = vi.fn(async (_provider, _model, connectionRef) => {
+ return connectionRef === 'personal-pro'
+ })
+ const tolerations: Array<Record<string, unknown>> = []
+ const res = await validateHostSpec(
+ {
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'team-plus',
+ },
+ },
+ { isModelAllowed },
+ {
+ stored: {
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'personal-pro',
+ },
+ },
+ hostRef: { namespace: 'mcp-host', name: 'agent-a' },
+ tolerations,
+ }
+ )
+ expect(res).not.toBeNull()
+ expect(res!.errors[0].message).toContain('model_not_allowed')
+ expect(tolerations).toEqual([])
+ })
+
+ it('tolerates an unchanged revoked connectionRef so identity/channels PUTs can persist', async () => {
+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'
+ const isModelAllowed = vi.fn().mockResolvedValue(false)
+ const tolerations: Array<Record<string, unknown>> = []
+ const spec = {
+ channels: ['telegram'],
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'team-plus',
+ },
+ }
+ const res = await validateHostSpec(
+ spec,
+ { isModelAllowed },
+ {
+ stored: {
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'team-plus',
+ },
+ },
+ hostRef: { namespace: 'mcp-host', name: 'agent-a' },
+ tolerations,
+ }
+ )
+ expect(res).toBeNull()
+ expect(tolerations).toHaveLength(1)
+ })
+
+ it('rejects a revoked or unknown connectionRef when the allowlist says no', async () => {
+ process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'
+ const isModelAllowed = vi.fn().mockResolvedValue(false)
+ const res = await validateHostSpec(
+ {
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'team-plus',
+ },
+ },
+ { isModelAllowed }
+ )
+ expect(res).not.toBeNull()
+ expect(res!.errors[0].field).toBe('spec.model.name')
+ expect(isModelAllowed).toHaveBeenCalledWith('codex-subscription', 'gpt-5.1', 'team-plus')
+ })
+
it('rejects credentialSlot on a broker fallback', async () => {
process.env.CONTROL_API_CODEX_SUBSCRIPTION_ENABLED = 'true'
const isModelAllowed = vi.fn().mockResolvedValue(true)
@@ -94,6 +189,15 @@ describe('codex-subscription CRD contract', () => {
}
const spec = doc.spec.versions[0].schema.openAPIV3Schema.properties.spec
expect(spec.required).not.toContain('secretRef')
+ const modelProps = (
+ spec as {
+ properties?: {
+ model?: { properties?: { connectionRef?: { type?: string; pattern?: string } } }
+ }
+ }
+ ).properties?.model?.properties
+ expect(modelProps?.connectionRef?.type).toBe('string')
+ expect(modelProps?.connectionRef?.pattern).toContain('a-z0-9')
const rules = spec['x-kubernetes-validations'] ?? []
expect(
rules.some(r => r.rule.includes('secretRef') && r.rule.includes('codex-subscription'))
diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.ts
index e527c6143..f7bf3c552 100644
--- a/control-api/test/routes.admin.codexSubscription.test.ts
+++ b/control-api/test/routes.admin.codexSubscription.test.ts
@@ -158,6 +158,22 @@ describe('admin Codex subscription routes', () => {
assertNoLeak(refresh.body)
})
+ it('maps a live fingerprint collision on a keyed device start to 409', async () => {
+ oauth.startDevice.mockRejectedValue(
+ new CodexSubscriptionOAuthError('fingerprint_in_use', 'account already connected')
+ )
+ const res = await request(app)
+ .post('/admin/llm/providers/codex-subscription/connections/team-plus/device/start')
+ .send({ intent: 'connect' })
+ expect(res.status).toBe(409)
+ expect(res.body).toEqual({ error: 'fingerprint_in_use' })
+ expect(oauth.startDevice).toHaveBeenCalledWith(
+ expect.objectContaining({ connectionKey: 'team-plus' }),
+ 'connect'
+ )
+ assertNoLeak(res.body)
+ })
+
it('revokes without returning secrets', async () => {
oauth.revoke.mockResolvedValue({
connectionKey: 'deployment-default',
diff --git a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
index 4f5c70825..4e21ed934 100644
--- a/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
+++ b/control-api/test/routes.mcp-host.llmProviderAttempts.test.ts
@@ -1,7 +1,10 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
-import { createMcpHostLlmProviderAttemptRoutes } from '../src/routes/mcp-host/llmProviderAttempts.routes.js'
+import {
+ createMcpHostLlmProviderAttemptRoutes,
+ resolveHostAssignedConnectionKey,
+} from '../src/routes/mcp-host/llmProviderAttempts.routes.js'
import { LlmProviderAttemptAuthorizeError } from '../src/services/llmProviderAttemptAuthorizer.js'
import * as authorizer from '../src/services/llmProviderAttemptAuthorizer.js'
import * as mcpHostJwt from '../src/utils/auth/mcpHostJwtToken.js'
@@ -23,7 +26,11 @@ function buildApp() {
const app = express()
app.use(express.json({ limit: '1mb' }))
const api = express.Router()
- api.use(createMcpHostLlmProviderAttemptRoutes())
+ api.use(
+ createMcpHostLlmProviderAttemptRoutes({
+ getResource: vi.fn(),
+ } as never)
+ )
app.use('/api/v1', api)
return app
}
@@ -108,3 +115,30 @@ describe('POST /api/v1/mcp-host/llm/provider-attempts/authorize', () => {
expect(JSON.stringify(res.body)).not.toMatch(/refresh|access_token|Authorization/i)
})
})
+
+describe('resolveHostAssignedConnectionKey', () => {
+ it('reads the Host connectionRef and defaults a Phase 1 Host', async () => {
+ const gateway = {
+ getResource: vi.fn().mockResolvedValue({
+ spec: { model: { provider: 'codex-subscription', connectionRef: 'team-plus' } },
+ }),
+ }
+ await expect(resolveHostAssignedConnectionKey(gateway, 'agent-a')).resolves.toBe('team-plus')
+
+ gateway.getResource.mockResolvedValueOnce({
+ spec: { model: { provider: 'codex-subscription' } },
+ })
+ await expect(resolveHostAssignedConnectionKey(gateway, 'agent-b')).resolves.toBe(
+ 'deployment-default'
+ )
+ })
+
+ it('fails closed when the Host cannot be attested', async () => {
+ const gateway = {
+ getResource: vi.fn().mockRejectedValue(Object.assign(new Error('nf'), { code: 404 })),
+ }
+ await expect(resolveHostAssignedConnectionKey(gateway, 'ghost')).rejects.toMatchObject({
+ code: 'host_binding_mismatch',
+ })
+ })
+})
diff --git a/control-api/test/services.codexSubscriptionConnection.test.ts b/control-api/test/services.codexSubscriptionConnection.test.ts
index 76ff27339..00a44c26f 100644
--- a/control-api/test/services.codexSubscriptionConnection.test.ts
+++ b/control-api/test/services.codexSubscriptionConnection.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'
import {
+ CodexSubscriptionFingerprintConflictError,
CodexSubscriptionStaleRevisionError,
getSafeCodexSubscriptionConnection,
insertInitialCodexSubscriptionConnection,
@@ -25,7 +26,10 @@ describe('codex subscription connection repository', () => {
query.mockResolvedValueOnce({
rows: [
{
+ id: '11111111-1111-1111-1111-111111111111',
connection_key: 'deployment-default',
+ display_name: 'Default deployment',
+ created_by: null,
status: 'connected',
refresh_token_encrypted: ciphertext,
access_token_encrypted: encryptOAuthSecret(KEY, 'access-secret'),
@@ -71,7 +75,10 @@ describe('codex subscription connection repository', () => {
query.mockResolvedValueOnce({
rows: [
{
+ id: '11111111-1111-1111-1111-111111111111',
connection_key: 'deployment-default',
+ display_name: 'Default deployment',
+ created_by: null,
status: 'connected',
credential_revision: '1',
catalog_revision: '0',
@@ -100,8 +107,23 @@ describe('codex subscription connection repository', () => {
const [, params] = query.mock.calls[0] as [string, unknown[]]
expect(params).not.toContain('plain-refresh')
expect(params).not.toContain('plain-access')
- expect(String(params[2])).toMatch(/^v1\./)
expect(String(params[3])).toMatch(/^v1\./)
+ expect(String(params[4])).toMatch(/^v1\./)
+ })
+
+ it('maps a unique active fingerprint violation to fingerprint_in_use', async () => {
+ query.mockRejectedValueOnce(Object.assign(new Error('duplicate'), { code: '23505' }))
+ await expect(
+ insertInitialCodexSubscriptionConnection(
+ { query },
+ KEY,
+ {
+ refreshToken: 'plain-refresh',
+ accountFingerprint: 'fp_dup',
+ },
+ 'team-plus'
+ )
+ ).rejects.toBeInstanceOf(CodexSubscriptionFingerprintConflictError)
})
it('rejects a stale credential_revision writer', async () => {
diff --git a/control-api/test/services.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.ts
index c9c731ed7..548f05759 100644
--- a/control-api/test/services.codexSubscriptionOAuth.test.ts
+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts
@@ -452,7 +452,8 @@ describe('codex subscription OAuth broker', () => {
expect.anything(),
KEY,
3,
- expect.objectContaining({ accessToken: 'access-secret', chatgptAccountId: 'acct_live_9' })
+ expect.objectContaining({ accessToken: 'access-secret', chatgptAccountId: 'acct_live_9' }),
+ 'deployment-default'
)
expect(repos.rotate).not.toHaveBeenCalled()
expect(repos.releaseLock).toHaveBeenCalled()
diff --git a/control-api/test/services.llmAllowedModelsConfigMap.test.ts b/control-api/test/services.llmAllowedModelsConfigMap.test.ts
index 4a79e3cc8..55f347e14 100644
--- a/control-api/test/services.llmAllowedModelsConfigMap.test.ts
+++ b/control-api/test/services.llmAllowedModelsConfigMap.test.ts
@@ -212,7 +212,10 @@ describe('LlmAllowedModelsConfigMapWriter', () => {
describe('Codex readiness annotations', () => {
it('maps only connected+ready to the snapshot-facing connected status', () => {
const base = {
+ id: '11111111-1111-1111-1111-111111111111',
connectionKey: 'deployment-default',
+ displayName: 'Default deployment',
+ createdBy: null,
credentialRevision: 1,
catalogRevision: 2,
accountFingerprint: null,
@@ -248,6 +251,45 @@ describe('Codex readiness annotations', () => {
expect(mapCodexConnectionStatusForSnapshot(null)).toBe('disconnected')
})
+ it('maps revoked to a snapshot-facing revoked status and lists every key', () => {
+ const base = {
+ id: '11111111-1111-1111-1111-111111111111',
+ displayName: 'Default deployment',
+ createdBy: null,
+ credentialRevision: 1,
+ catalogRevision: 2,
+ accountFingerprint: null,
+ catalogSyncedAt: null,
+ lastRefreshAt: null,
+ lastAuthAt: null,
+ refreshLockHeld: false,
+ revokedAt: null,
+ createdAt: new Date(0),
+ updatedAt: new Date(0),
+ } as Omit<CodexSubscriptionSafeConnection, 'connectionKey' | 'status' | 'catalogStatus'>
+ const revoked = {
+ ...base,
+ connectionKey: 'team-plus',
+ status: 'revoked' as const,
+ catalogStatus: 'ready' as const,
+ revokedAt: new Date(),
+ }
+ const live = {
+ ...base,
+ connectionKey: 'personal-pro',
+ status: 'connected' as const,
+ catalogStatus: 'ready' as const,
+ }
+ expect(mapCodexConnectionStatusForSnapshot(revoked)).toBe('revoked')
+ const annotations = buildCodexReadinessAnnotations(live, [revoked, live])
+ const map = JSON.parse(annotations['clerum.io/codex-connections'] as string) as Record<
+ string,
+ { status: string }
+ >
+ expect(map['team-plus'].status).toBe('revoked')
+ expect(map['personal-pro'].status).toBe('connected')
+ })
+
it('omits revision annotations when the connection row is absent', () => {
const annotations = buildCodexReadinessAnnotations(null)
expect(annotations[CODEX_CONNECTION_STATUS_ANNOTATION]).toBe('disconnected')
diff --git a/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts b/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts
index 6f8c038b6..ba99a383a 100644
--- a/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorization.realPostgres.integration.test.ts
@@ -5,12 +5,12 @@ import { initDb } from '../src/db.js'
import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
import { evaluateBudgetCheck } from '../src/services/budgets/check.js'
import { getActiveReservation } from '../src/services/budgets/reservations.js'
+import { getCodexCatalogModelState } from '../src/services/codexSubscriptionCatalog.js'
import {
getSafeCodexSubscriptionConnection,
insertInitialCodexSubscriptionConnection,
recordCodexCatalogOutcome,
} from '../src/services/codexSubscriptionConnection.js'
-import { getModelAllowlistState } from '../src/services/llmAllowedModels.js'
import {
type LlmProviderAttemptAuthorizerDeps,
authorizeLlmProviderAttempt,
@@ -100,7 +100,8 @@ describeRealPostgres('Codex provider-attempt authorization on real PostgreSQL',
}
},
getConnection: getSafeCodexSubscriptionConnection,
- getModelState: getModelAllowlistState,
+ getModelState: getCodexCatalogModelState,
+ resolveConnectionKey: async () => 'deployment-default',
evaluateBudget: evaluateBudgetCheck,
getActiveReservation,
getMaxGeneration: getMaxLlmProviderAttemptGeneration,
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
index bd7103cf7..34a4ff199 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
@@ -35,7 +35,10 @@ function claims(overrides: Partial<McpHostAccessClaims> = {}): McpHostAccessClai
function connection(overrides: Record<string, unknown> = {}) {
return {
+ id: '11111111-1111-1111-1111-111111111111',
connectionKey: 'deployment-default',
+ displayName: 'Default deployment',
+ createdBy: null,
status: 'connected',
credentialRevision: 3,
catalogRevision: 4,
@@ -225,6 +228,56 @@ describe('authorizeLlmProviderAttempt', () => {
).rejects.toMatchObject({ code: 'invalid_request' })
})
+ it('fails closed for every Host on a revoked grant and leaves another grant usable', async () => {
+ const teamPlus = connection({
+ id: '22222222-2222-4222-8222-222222222222',
+ connectionKey: 'team-plus',
+ status: 'revoked',
+ revokedAt: new Date(),
+ credentialRevision: 8,
+ })
+ const personal = connection({
+ id: '33333333-3333-4333-8333-333333333333',
+ connectionKey: 'personal-pro',
+ })
+ const getConnection = vi.fn(async (_db: unknown, key: string) => {
+ if (key === 'team-plus') return teamPlus
+ if (key === 'personal-pro') return personal
+ return null
+ })
+ const resolveConnectionKey = vi.fn(async (hostRef: string) =>
+ hostRef === 'agent-c' ? 'personal-pro' : 'team-plus'
+ )
+ const shared = deps({
+ getConnection: getConnection as never,
+ resolveConnectionKey,
+ })
+
+ await expect(
+ authorizeLlmProviderAttempt(claims({ hostRefs: ['agent-a'] }), body(), shared)
+ ).rejects.toMatchObject({ code: 'connection_unavailable' })
+ await expect(
+ authorizeLlmProviderAttempt(claims({ hostRefs: ['agent-b'] }), body(), shared)
+ ).rejects.toMatchObject({ code: 'connection_unavailable' })
+
+ const live = await authorizeLlmProviderAttempt(
+ claims({ hostRefs: ['agent-c'] }),
+ body({
+ policyHash: computeCodexPolicyHash({
+ model: REQUEST.model,
+ catalogRevision: 4,
+ credentialRevision: 3,
+ connectionKey: 'personal-pro',
+ }),
+ }),
+ shared
+ )
+ expect(live.executionTicket).toBe('ticket.jwt')
+ expect(resolveConnectionKey).toHaveBeenCalledWith('agent-a')
+ expect(resolveConnectionKey).toHaveBeenCalledWith('agent-b')
+ expect(resolveConnectionKey).toHaveBeenCalledWith('agent-c')
+ })
+
it('is disabled when the feature flag is off', async () => {
await expect(
authorizeLlmProviderAttempt(claims(), body(), { ...current, enabled: false })
diff --git a/control-api/test/services.llmProviderAttemptRedemption.test.ts b/control-api/test/services.llmProviderAttemptRedemption.test.ts
index a36c42eab..4c8ec1a69 100644
--- a/control-api/test/services.llmProviderAttemptRedemption.test.ts
+++ b/control-api/test/services.llmProviderAttemptRedemption.test.ts
@@ -59,13 +59,17 @@ describe('redeemLlmProviderAttempt', () => {
policyHash: CLAIMS.policyHash,
budgetReservationId: CLAIMS.budgetReservationId,
connectionRevision: CLAIMS.connectionRevision,
+ connectionId: null,
status: 'authorized',
outcome: null,
createdAt: new Date(),
})
vi.spyOn(store, 'markLlmProviderAttemptTicketRedeemed').mockResolvedValue(true)
vi.spyOn(connection, 'getSafeCodexSubscriptionConnection').mockResolvedValue({
+ id: '11111111-1111-1111-1111-111111111111',
connectionKey: 'deployment-default',
+ displayName: 'Default deployment',
+ createdBy: null,
status: 'connected',
credentialRevision: 3,
catalogRevision: 4,
@@ -135,6 +139,40 @@ describe('redeemLlmProviderAttempt', () => {
).rejects.toBeInstanceOf(LlmProviderAttemptRedeemError)
})
+ it('refuses to redeem a pre-revoke ticket after the grant is revoked', async () => {
+ vi.mocked(connection.getSafeCodexSubscriptionConnection).mockResolvedValueOnce({
+ id: '11111111-1111-1111-1111-111111111111',
+ connectionKey: 'team-plus',
+ displayName: 'Team Plus',
+ createdBy: null,
+ status: 'revoked',
+ credentialRevision: 4,
+ catalogRevision: 4,
+ accountFingerprint: null,
+ catalogStatus: 'ready',
+ catalogSyncedAt: new Date(),
+ lastRefreshAt: null,
+ lastAuthAt: new Date(),
+ refreshLockHeld: false,
+ revokedAt: new Date(),
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ })
+ await expect(
+ redeemLlmProviderAttempt(
+ { executionTicket: 'ticket', requestHash: CLAIMS.requestHash },
+ {
+ enabled: true,
+ withTransaction: async work => work({ query: vi.fn() } as never),
+ loadSecrets: async () => {
+ throw new Error('should not load secrets after revoke')
+ },
+ encryptionKey: Buffer.alloc(32),
+ }
+ )
+ ).rejects.toMatchObject({ code: 'connection_unavailable' })
+ })
+
it('is disabled when the flag is off', async () => {
await expect(
redeemLlmProviderAttempt(
diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.ts
index b2419a3ea..6c0920e00 100644
--- a/control-ui/app/constants/routes.ts
+++ b/control-ui/app/constants/routes.ts
@@ -71,7 +71,6 @@ export const CONTROL_ROUTES = {
discovery: '/llm-models/discovery',
new: '/llm-models/new',
edit: (id: string) => `/llm-models/${segment(id)}/edit`,
- codexSubscription: '/llm-models/providers/codex-subscription',
},
marketplace: {
root: '/marketplace',
diff --git a/control-ui/app/globals.css b/control-ui/app/globals.css
index 98f07e1f8..fa790f2b9 100644
--- a/control-ui/app/globals.css
+++ b/control-ui/app/globals.css
@@ -7801,6 +7801,11 @@ textarea.cu-input {
gap: 0.75rem;
}
+.cu-llm-config__credential-kind,
+.cu-llm-config__after-provider {
+ grid-column: 1 / -1;
+}
+
.cu-llm-provider-icon {
display: inline-grid;
place-items: center;
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsx
index ff93f3d5b..b7c88f719 100644
--- a/control-ui/app/hosts/[name]/page.tsx
+++ b/control-ui/app/hosts/[name]/page.tsx
@@ -7,6 +7,7 @@ import { DetailPageShell } from '@components/DetailPageShell'
import { useToast } from '@components/Toast'
import { HOST_DEFAULT_TAB, HOST_TABS } from '@constants/hostDetails'
import { CONTROL_ROUTES } from '@constants/routes'
+import { CodexAgentAssignment } from '../../../components/CodexAgentAssignment'
import { HostAccessTab } from '../../../components/HostAccessTab'
import { HostAdvancedTab } from '../../../components/HostAdvancedTab'
import { HostGuardrailsSection } from '../../../components/HostGuardrailsSection'
@@ -27,6 +28,7 @@ import {
getActiveCredentialKeys,
getModelOptions,
getProviderLabel,
+ isOpenAiFamily,
isProviderUsable,
llmChainRequiresSecret,
normalizeAllowedModels,
@@ -124,6 +126,26 @@ export default function HostDetailsPage() {
error: modelsError,
} = useLlmAllowedModels()
const [modelNameDraft, setModelNameDraft] = useState('')
+ const [connectionRefDraft, setConnectionRefDraft] = useState('deployment-default')
+ const [codexModels, setCodexModels] = useState<string[]>([])
+ const catalogForEditor = useMemo(() => {
+ if (providerDraft !== 'codex-subscription' || codexModels.length === 0) return allowedCatalog
+ const others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')
+ return [
+ ...others,
+ ...codexModels.map(model => ({
+ id: `codex:${model}`,
+ provider: 'codex-subscription',
+ model,
+ vendor: 'OpenAI',
+ display_name: model,
+ context_window_tokens: null,
+ enabled: true,
+ source: 'discovery' as const,
+ stale: false,
+ })),
+ ]
+ }, [allowedCatalog, providerDraft, codexModels])
const [secretRefDraft, setSecretRefDraft] = useState('')
// Fallback policy (spec §3-R5). `undefined` = the Host has no llmPolicy.
const [llmPolicyDraft, setLlmPolicyDraft] = useState<LlmPolicy | undefined>(undefined)
@@ -156,8 +178,8 @@ export default function HostDetailsPage() {
const [availableSecrets, setAvailableSecrets] = useState<string[]>([])
const providerModelOptions = useMemo(
- () => getModelOptions(allowedCatalog, providerDraft),
- [allowedCatalog, providerDraft]
+ () => getModelOptions(catalogForEditor, providerDraft),
+ [catalogForEditor, providerDraft]
)
// The EFFECTIVE per-host subset to persist (Topic 3a): the raw draft pruned to
// the providers actually in this host's domain (primary + fallbacks — so a
@@ -260,6 +282,11 @@ export default function HostDetailsPage() {
currentModel ||
resolveDefaultModel(nextProvider, getModelOptions(allowedCatalog, nextProvider))
)
+ setConnectionRefDraft(
+ String(
+ (spec.model as { connectionRef?: string } | undefined)?.connectionRef || ''
+ ).trim() || 'deployment-default'
+ )
setSecretRefDraft(String(spec.secretRef || ''))
setLlmPolicyDraft(normalizeLlmPolicy(spec.llmPolicy))
// Hydrate the per-host model subset from the saved spec (Topic 3a); absent
@@ -522,6 +549,9 @@ export default function HostDetailsPage() {
model: {
provider: providerDraft,
name: modelNameDraft.trim(),
+ ...(providerDraft === 'codex-subscription'
+ ? { connectionRef: connectionRefDraft.trim() || 'deployment-default' }
+ : {}),
},
}
// Host identity is metadata.name / the route slug. Never persist
@@ -931,6 +961,22 @@ export default function HostDetailsPage() {
<label htmlFor="model-provider">Model provider</label>
<div className="cu-field__readonly">{getProviderLabel(providerDraft)}</div>
</div>
+ {isOpenAiFamily(providerDraft) ? (
+ <div className="cu-field">
+ <label htmlFor="model-openai-credential">OpenAI credential</label>
+ <div className="cu-field__readonly">
+ {providerDraft === 'codex-subscription' ? 'ChatGPT subscription' : 'API key'}
+ </div>
+ </div>
+ ) : null}
+ {providerDraft === 'codex-subscription' ? (
+ <div className="cu-field">
+ <label htmlFor="model-subscription">Subscription</label>
+ <div className="cu-field__readonly">
+ {connectionRefDraft || 'deployment-default'}
+ </div>
+ </div>
+ ) : null}
<div className="cu-field">
<label htmlFor="model-allowed">Allowed models</label>
{allowedModelsSummary.length > 0 ? (
@@ -1018,6 +1064,17 @@ export default function HostDetailsPage() {
<LlmProviderConfig
provider={providerDraft}
model={modelNameDraft}
+ subscriptionCredentialEnabled
+ afterPrimaryProvider={
+ providerDraft === 'codex-subscription' ? (
+ <CodexAgentAssignment
+ connectionRef={connectionRefDraft}
+ onConnectionRefChange={setConnectionRefDraft}
+ onModelsChange={setCodexModels}
+ disabled={busy}
+ />
+ ) : null
+ }
onPrimaryChange={next => {
setProviderDraft(next.provider)
setModelNameDraft(next.model)
@@ -1026,7 +1083,7 @@ export default function HostDetailsPage() {
onPolicyChange={handlePolicyChange}
allowedModels={allowedModelsDraft}
onAllowedModelsChange={setAllowedModelsDraft}
- catalog={allowedCatalog}
+ catalog={catalogForEditor}
catalogLoading={modelsLoading}
catalogError={modelsError}
replacePrimaryModelWithAllowedModels
diff --git a/control-ui/app/llm-models/providers/codex-subscription/page.tsx b/control-ui/app/llm-models/providers/codex-subscription/page.tsx
index 3e6ae804b..c38cc2f14 100644
--- a/control-ui/app/llm-models/providers/codex-subscription/page.tsx
+++ b/control-ui/app/llm-models/providers/codex-subscription/page.tsx
@@ -1,15 +1,13 @@
'use client'
-import { AuthGate } from '@components/AuthGate'
-import { CodexSubscriptionConnection } from '@components/CodexSubscriptionConnection'
-import { DashboardLayout } from '@components/DashboardLayout'
+import { useEffect } from 'react'
+import { useRouter } from 'next/navigation'
+import { CONTROL_ROUTES } from '@constants/routes'
export default function CodexSubscriptionProviderPage() {
- return (
- <AuthGate>
- <DashboardLayout isDetailPage>
- <CodexSubscriptionConnection />
- </DashboardLayout>
- </AuthGate>
- )
+ const router = useRouter()
+ useEffect(() => {
+ router.replace(CONTROL_ROUTES.agents.root)
+ }, [router])
+ return null
}
diff --git a/control-ui/components/CodexAgentAssignment/index.tsx b/control-ui/components/CodexAgentAssignment/index.tsx
new file mode 100644
index 000000000..02c551e7d
--- /dev/null
+++ b/control-ui/components/CodexAgentAssignment/index.tsx
@@ -0,0 +1,275 @@
+'use client'
+
+import React, { useCallback, useEffect, useState } from 'react'
+import { useConfirmDialog } from '@components/ConfirmDialog'
+import { useToast } from '@components/Toast'
+import {
+ type CodexSubscriptionConnectionView,
+ createCodexSubscriptionConnection,
+ listCodexConnectionModels,
+ listCodexSubscriptionConnections,
+ pollCodexDevice,
+ revokeCodexSubscription,
+ startCodexDeviceConnect,
+ syncCodexSubscriptionCatalog,
+} from '@lib/codexSubscription'
+import { isCodexSubscriptionUiEnabled } from '@lib/codexSubscriptionFeature'
+import {
+ mapConnectionStatus,
+ statusLabel,
+ statusTagClass,
+} from '../CodexSubscriptionConnection/types'
+
+export type CodexAgentAssignmentProps = {
+ connectionRef: string
+ onConnectionRefChange: (connectionKey: string) => void
+ onModelsChange?: (models: string[]) => void
+ disabled?: boolean
+}
+
+function assignedHostNames(connection: CodexSubscriptionConnectionView): string[] {
+ return (connection.assignedHosts ?? []).map(host => host.name).filter(Boolean)
+}
+
+export function CodexAgentAssignment({
+ connectionRef,
+ onConnectionRefChange,
+ onModelsChange,
+ disabled = false,
+}: CodexAgentAssignmentProps) {
+ const { showToast } = useToast()
+ const { confirm, confirmDialog } = useConfirmDialog()
+ const [connections, setConnections] = useState<CodexSubscriptionConnectionView[]>([])
+ const [selected, setSelected] = useState<CodexSubscriptionConnectionView | null>(null)
+ const [userCode, setUserCode] = useState<string | null>(null)
+ const [verificationUri, setVerificationUri] = useState<string | null>(null)
+ const [creating, setCreating] = useState(false)
+ const [displayName, setDisplayName] = useState('')
+ const [busy, setBusy] = useState(false)
+
+ const load = useCallback(async () => {
+ if (!isCodexSubscriptionUiEnabled()) return
+ const rows = await listCodexSubscriptionConnections()
+ setConnections(rows)
+ const current =
+ rows.find(row => row.connectionKey === connectionRef) ??
+ rows.find(row => row.connectionKey === 'deployment-default') ??
+ rows[0] ??
+ null
+ setSelected(current)
+ if (current && current.connectionKey !== connectionRef) {
+ onConnectionRefChange(current.connectionKey)
+ }
+ if (current?.status === 'connected') {
+ const models = await listCodexConnectionModels(current.connectionKey)
+ onModelsChange?.(models.filter(row => row.enabled && !row.stale).map(row => row.model))
+ } else {
+ onModelsChange?.([])
+ }
+ }, [connectionRef, onConnectionRefChange, onModelsChange])
+
+ useEffect(() => {
+ void load().catch(() => undefined)
+ }, [load])
+
+ const assignable = connections.filter(
+ row => row.status !== 'revoked' || row.connectionKey === connectionRef
+ )
+
+ async function handleCreate() {
+ setBusy(true)
+ try {
+ const created = await createCodexSubscriptionConnection({
+ displayName: displayName.trim() || 'Codex subscription',
+ })
+ setCreating(false)
+ setDisplayName('')
+ onConnectionRefChange(created.connectionKey)
+ await load()
+ } catch (err) {
+ showToast({
+ type: 'error',
+ title: 'Could not create subscription',
+ message: err instanceof Error ? err.message : 'Request failed',
+ })
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function handleConnect() {
+ if (!selected) return
+ setBusy(true)
+ try {
+ const started = await startCodexDeviceConnect(
+ selected.status === 'connected' ? 'reconnect' : 'connect',
+ selected.connectionKey
+ )
+ setUserCode(started.userCode)
+ setVerificationUri(started.verificationUri)
+ const deadline = Date.now() + started.intervalSeconds * 1000 * 40
+ while (Date.now() < deadline) {
+ await new Promise(resolve => setTimeout(resolve, started.intervalSeconds * 1000))
+ const polled = await pollCodexDevice(started.state, selected.connectionKey)
+ if (polled.status === 'connected') {
+ setUserCode(null)
+ setVerificationUri(null)
+ await load()
+ return
+ }
+ if (polled.status === 'expired' || polled.status === 'denied') break
+ }
+ } catch (err) {
+ showToast({
+ type: 'error',
+ title: 'ChatGPT sign-in failed',
+ message: err instanceof Error ? err.message : 'Request failed',
+ })
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function handleSync() {
+ if (!selected || selected.status !== 'connected') return
+ setBusy(true)
+ try {
+ await syncCodexSubscriptionCatalog(selected.connectionKey)
+ await load()
+ showToast({
+ type: 'success',
+ title: 'Catalog synced',
+ message: selected.displayName ?? selected.connectionKey,
+ })
+ } catch (err) {
+ const code = (err as { code?: string } | null)?.code
+ showToast({
+ type: 'error',
+ title: code === 'no_grant' ? 'Connect ChatGPT first' : 'Catalog sync failed',
+ message: err instanceof Error ? err.message : 'Request failed',
+ })
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ async function handleRevoke() {
+ if (!selected) return
+ const names = assignedHostNames(selected)
+ const confirmed = await confirm({
+ title: 'Revoke this ChatGPT subscription?',
+ message:
+ names.length > 0
+ ? `This subscription is used by ${names.length} agent(s): ${names.join(', ')}. Revoke disconnects all of them.${
+ selected.connectionKey === 'deployment-default'
+ ? ' Workflow recipes that use a ChatGPT subscription also fail closed on this grant.'
+ : ''
+ }`
+ : 'Revoke disconnects this ChatGPT grant. Assigned agents keep the reference and stop authorizing.',
+ confirmLabel: 'Revoke',
+ })
+ if (!confirmed) return
+ setBusy(true)
+ try {
+ await revokeCodexSubscription(selected.connectionKey)
+ await load()
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ if (!isCodexSubscriptionUiEnabled()) return null
+
+ const uiStatus = selected ? mapConnectionStatus(selected.status) : 'disconnected'
+
+ return (
+ <div className="cu-form-stack" data-testid="codex-agent-assignment">
+ {confirmDialog}
+ <div className="cu-field">
+ <label htmlFor="codex-subscription">ChatGPT subscription</label>
+ <select
+ id="codex-subscription"
+ value={selected?.connectionKey ?? ''}
+ disabled={disabled || busy}
+ onChange={event => onConnectionRefChange(event.target.value)}
+ >
+ {assignable.map(row => (
+ <option
+ key={row.connectionKey}
+ value={row.connectionKey}
+ disabled={row.status === 'revoked'}
+ >
+ {row.displayName || row.connectionKey}
+ {row.status === 'revoked' ? ' (revoked)' : ''}
+ </option>
+ ))}
+ </select>
+ </div>
+ <div className="cu-field">
+ <span className="cu-settings-row__label">Status</span>
+ <span className={statusTagClass(uiStatus)} data-testid="codex-connection-status">
+ {statusLabel(uiStatus)}
+ </span>
+ </div>
+ {creating ? (
+ <div className="cu-field">
+ <label htmlFor="codex-new-name">New subscription name</label>
+ <input
+ id="codex-new-name"
+ value={displayName}
+ onChange={event => setDisplayName(event.target.value)}
+ disabled={disabled || busy}
+ />
+ <button
+ type="button"
+ className="cu-btn cu-btn--primary"
+ onClick={() => void handleCreate()}
+ disabled={busy}
+ >
+ Create
+ </button>
+ </div>
+ ) : (
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost cu-btn--sm"
+ onClick={() => setCreating(true)}
+ disabled={disabled || busy}
+ >
+ New subscription
+ </button>
+ )}
+ <div className="cu-form-actions">
+ <button
+ type="button"
+ className="cu-btn cu-btn--primary"
+ onClick={() => void handleConnect()}
+ disabled={disabled || busy || !selected}
+ >
+ Sign in with ChatGPT
+ </button>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost"
+ onClick={() => void handleSync()}
+ disabled={disabled || busy || selected?.status !== 'connected'}
+ >
+ Sync catalog
+ </button>
+ <button
+ type="button"
+ className="cu-btn cu-btn--ghost"
+ onClick={() => void handleRevoke()}
+ disabled={disabled || busy || !selected || selected.status === 'revoked'}
+ >
+ Revoke
+ </button>
+ </div>
+ {userCode ? (
+ <div className="cu-banner" data-testid="codex-device-code">
+ Enter {userCode} at {verificationUri ?? 'https://auth.openai.com/codex/device'}
+ </div>
+ ) : null}
+ </div>
+ )
+}
diff --git a/control-ui/components/CodexSubscriptionConnection/index.tsx b/control-ui/components/CodexSubscriptionConnection/index.tsx
index 57a1fa6fd..1bb810302 100644
--- a/control-ui/components/CodexSubscriptionConnection/index.tsx
+++ b/control-ui/components/CodexSubscriptionConnection/index.tsx
@@ -135,9 +135,8 @@ export function CodexSubscriptionConnection() {
if (!enabled) return null
return (
<LlmModelsTabBar
- activeTab="codex-subscription"
+ activeTab="catalog"
catalogCount={tabModels.length}
- codexEnabled
discoveryReviewCount={discoveryReviewCount}
/>
)
@@ -160,7 +159,7 @@ export function CodexSubscriptionConnection() {
useEffect(() => {
const outcome = readCodexOAuthQueryParam(searchParams)
if (!outcome) return
- router.replace(CONTROL_ROUTES.llmModels.codexSubscription)
+ router.replace(CONTROL_ROUTES.agents.root)
if (outcome === 'connected') {
void loadConnection().then(() => {
showToast('Codex subscription connected.', { tone: 'success' })
diff --git a/control-ui/components/CodexSubscriptionConnection/types.ts b/control-ui/components/CodexSubscriptionConnection/types.ts
index 05ffc1424..37e16635f 100644
--- a/control-ui/components/CodexSubscriptionConnection/types.ts
+++ b/control-ui/components/CodexSubscriptionConnection/types.ts
@@ -12,6 +12,7 @@ export type CodexSubscriptionUiStatus =
| 'connected'
| 'reauth-required'
| 'revoking'
+ | 'revoked'
| 'unavailable'
export type CodexSubscriptionConnectionProps = {
@@ -30,7 +31,7 @@ export function mapConnectionStatus(status: CodexConnectionStatus): CodexSubscri
if (status === 'reauth_required') return 'reauth-required'
if (status === 'connecting') return 'connecting'
if (status === 'connected') return 'connected'
- if (status === 'revoked') return 'disconnected'
+ if (status === 'revoked') return 'revoked'
return 'disconnected'
}
@@ -44,6 +45,8 @@ export function statusLabel(status: CodexSubscriptionUiStatus): string {
return 'Device code pending'
case 'reauth-required':
return 'Reauthorization required'
+ case 'revoked':
+ return 'Revoked'
case 'revoking':
return 'Revoking'
case 'unavailable':
@@ -60,6 +63,7 @@ export function statusTagClass(status: CodexSubscriptionUiStatus): string {
case 'connecting':
case 'device-pending':
return 'cu-llm-config__block-tag cu-llm-config__block-tag--warning'
+ case 'revoked':
case 'reauth-required':
case 'unavailable':
return 'cu-llm-config__block-tag cu-llm-config__block-tag--danger'
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsx
index 06e85ad26..97b15f6fa 100644
--- a/control-ui/components/HostWizard/index.tsx
+++ b/control-ui/components/HostWizard/index.tsx
@@ -1,6 +1,7 @@
'use client'
import React, { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { CodexAgentAssignment } from '@/components/CodexAgentAssignment'
import { CreateFlowPanel } from '@/components/CreateFlowPanel'
import { CreateStepFlow } from '@/components/CreateStepFlow'
import { LlmProviderConfig } from '@/components/LlmProviderConfig'
@@ -246,6 +247,7 @@ function isStepValid(
llmPolicy: LlmPolicy | undefined
provider: LlmProvider
modelName: string
+ connectionRef?: string
selectedUserIds: string[]
selectedTeamIds: string[]
directoryLoadFailed: boolean
@@ -262,6 +264,7 @@ function isStepValid(
// catalog model and no Secret. Any static primary/fallback still requires
// the exact credential slots (existing Secret or a complete new one).
if (!state.modelName.trim()) return false
+ if (state.provider === 'codex-subscription' && !state.connectionRef?.trim()) return false
if (!llmChainRequiresSecret(state.provider, state.llmPolicy?.fallbacks)) return true
// New secret: the PRIMARY provider must be usable (asymmetric gate — a
// fallback missing its key only warns). Cross-slot mistakes (half Bedrock
@@ -339,6 +342,8 @@ export function HostWizard({
error: modelsError,
} = useLlmAllowedModels()
const [modelName, setModelName] = useState('')
+ const [connectionRef, setConnectionRef] = useState('deployment-default')
+ const [codexModels, setCodexModels] = useState<string[]>([])
const [stateless, setStateless] = useState(false)
const [users, setUsers] = useState<
Array<{ id: string; email: string; name: string | null; displayName: string | null }>
@@ -392,9 +397,27 @@ export function HostWizard({
null,
[existingContexts, selectedExistingContext]
)
+ const catalogForEditor = useMemo(() => {
+ if (provider !== 'codex-subscription' || codexModels.length === 0) return allowedCatalog
+ const others = allowedCatalog.filter(row => row.provider !== 'codex-subscription')
+ return [
+ ...others,
+ ...codexModels.map(model => ({
+ id: `codex:${model}`,
+ provider: 'codex-subscription',
+ model,
+ vendor: 'OpenAI',
+ display_name: model,
+ context_window_tokens: null,
+ enabled: true,
+ source: 'discovery' as const,
+ stale: false,
+ })),
+ ]
+ }, [allowedCatalog, provider, codexModels])
const providerModelOptions = useMemo(
- () => getModelOptions(allowedCatalog, provider),
- [allowedCatalog, provider]
+ () => getModelOptions(catalogForEditor, provider),
+ [catalogForEditor, provider]
)
const chainRequiresSecret = llmChainRequiresSecret(provider, llmPolicy?.fallbacks)
const handleExistingSecretChange = useCallback(
@@ -479,6 +502,7 @@ export function HostWizard({
llmPolicy,
provider,
modelName,
+ connectionRef,
selectedUserIds,
selectedTeamIds,
directoryLoadFailed: directoryLoadError.length > 0,
@@ -497,6 +521,7 @@ export function HostWizard({
llmPolicy,
provider,
modelName,
+ connectionRef,
selectedUserIds,
selectedTeamIds,
directoryLoadError,
@@ -778,6 +803,7 @@ export function HostWizard({
model: {
provider,
name: modelName,
+ ...(provider === 'codex-subscription' ? { connectionRef } : {}),
},
// Opt-in fallback policy (spec §3-R5): only set when at least one
// fallback is configured, so a Host without fallbacks behaves as today.
@@ -1068,6 +1094,45 @@ export function HostWizard({
{step === 2 && (
<div className="cu-form-stack cu-agent-form-stack">
+ <LlmProviderConfig
+ provider={provider}
+ model={modelName}
+ subscriptionCredentialEnabled
+ afterPrimaryProvider={
+ provider === 'codex-subscription' ? (
+ <CodexAgentAssignment
+ connectionRef={connectionRef}
+ onConnectionRefChange={setConnectionRef}
+ onModelsChange={setCodexModels}
+ />
+ ) : null
+ }
+ onPrimaryChange={next => {
+ setProvider(next.provider)
+ setModelName(next.model)
+ }}
+ policy={llmPolicy}
+ onPolicyChange={setLlmPolicy}
+ allowedModels={allowedModels}
+ onAllowedModelsChange={setAllowedModels}
+ catalog={catalogForEditor}
+ catalogLoading={modelsLoading}
+ catalogError={modelsError}
+ modelLabel="Default model"
+ showAllowedModels={false}
+ credentials={
+ chainRequiresSecret && secretMode === 'new'
+ ? {
+ draft: llmKeyDraft,
+ onChange: (dataKey, value) =>
+ setLlmKeyDraft(prev => ({ ...prev, [dataKey]: value })),
+ }
+ : undefined
+ }
+ secretKeys={chainRequiresSecret && secretMode === 'new' ? llmSecretKeys : []}
+ fallbackProvidersInitiallyCollapsed
+ disabled={busy}
+ />
{chainRequiresSecret ? (
<div className="cu-agent-access-section">
<strong>Credentials</strong>
@@ -1143,39 +1208,10 @@ export function HostWizard({
</div>
) : (
<p className="cu-muted cu-agent-access-hint">
- This provider authenticates through the Codex subscription. No LLM secret is
- required unless you add a static-credentials fallback.
+ This OpenAI credential authenticates through a ChatGPT subscription. No LLM secret
+ is required unless you add a static-credentials fallback.
</p>
)}
- <LlmProviderConfig
- provider={provider}
- model={modelName}
- onPrimaryChange={next => {
- setProvider(next.provider)
- setModelName(next.model)
- }}
- policy={llmPolicy}
- onPolicyChange={setLlmPolicy}
- allowedModels={allowedModels}
- onAllowedModelsChange={setAllowedModels}
- catalog={allowedCatalog}
- catalogLoading={modelsLoading}
- catalogError={modelsError}
- modelLabel="Default model"
- showAllowedModels={false}
- credentials={
- chainRequiresSecret && secretMode === 'new'
- ? {
- draft: llmKeyDraft,
- onChange: (dataKey, value) =>
- setLlmKeyDraft(prev => ({ ...prev, [dataKey]: value })),
- }
- : undefined
- }
- secretKeys={chainRequiresSecret && secretMode === 'new' ? llmSecretKeys : []}
- fallbackProvidersInitiallyCollapsed
- disabled={busy}
- />
</div>
)}
diff --git a/control-ui/components/LlmModelTable.tsx b/control-ui/components/LlmModelTable.tsx
index eb46ef7ff..6726b9711 100644
--- a/control-ui/components/LlmModelTable.tsx
+++ b/control-ui/components/LlmModelTable.tsx
@@ -2,7 +2,7 @@
import React, { useEffect, useMemo, useState } from 'react'
import type { LlmAllowedModel } from '@lib/api'
-import { formatContextWindow, getProviderDisplayLabel } from '@lib/llm'
+import { catalogGroupKey, formatContextWindow, getProviderDisplayLabel } from '@lib/llm'
import { isUnpricedAllowedModel } from '@lib/llmModelUnpriced'
import { type SortDirection, TableSortHeader, compareNullsLast, toggleSort } from '@lib/tableSort'
import { FilterSelect } from './FilterSelect'
@@ -50,6 +50,29 @@ function compareModel(a: LlmAllowedModel, b: LlmAllowedModel): number {
const ALL_PROVIDERS = '__all__'
+type DisplayModel = LlmAllowedModel & { credentialLabel: string }
+
+function collapseFamilyRows(family: string, models: LlmAllowedModel[]): DisplayModel[] {
+ if (family !== 'openai') {
+ return models.map(row => ({ ...row, credentialLabel: '' }))
+ }
+ const byName = new Map<string, LlmAllowedModel[]>()
+ for (const row of models) {
+ const list = byName.get(row.model) ?? []
+ list.push(row)
+ byName.set(row.model, list)
+ }
+ return Array.from(byName.entries()).map(([, rows]) => {
+ const apiKey = rows.find(row => row.provider === 'openai')
+ const subscription = rows.find(row => row.provider === 'codex-subscription')
+ const primary = apiKey ?? subscription ?? rows[0]
+ const parts: string[] = []
+ if (apiKey) parts.push('API key')
+ if (subscription) parts.push('Subscription')
+ return { ...primary, credentialLabel: parts.join(' · ') }
+ })
+}
+
type EnabledFilter = 'all' | 'enabled' | 'disabled'
type SourceFilter = 'all' | 'manual' | 'discovery'
@@ -75,8 +98,8 @@ export function LlmModelTable({
const normalizedSearch = searchQuery.trim().toLowerCase()
const providerOptions = useMemo(() => {
- return Array.from(new Set(items.map(model => model.provider))).sort((left, right) =>
- getProviderDisplayLabel(left).localeCompare(getProviderDisplayLabel(right))
+ return Array.from(new Set(items.map(model => catalogGroupKey(model.provider)))).sort(
+ (left, right) => getProviderDisplayLabel(left).localeCompare(getProviderDisplayLabel(right))
)
}, [items])
@@ -122,7 +145,9 @@ export function LlmModelTable({
const filteredItems = useMemo(() => {
return items.filter(model => {
- if (providerFilter !== ALL_PROVIDERS && model.provider !== providerFilter) return false
+ if (providerFilter !== ALL_PROVIDERS && catalogGroupKey(model.provider) !== providerFilter) {
+ return false
+ }
if (enabledFilter === 'enabled' && !model.enabled) return false
if (enabledFilter === 'disabled' && model.enabled) return false
if (sourceFilter !== 'all' && model.source !== sourceFilter) return false
@@ -143,25 +168,30 @@ export function LlmModelTable({
const groupedItems = useMemo(() => {
const groups = new Map<string, LlmAllowedModel[]>()
for (const model of filteredItems) {
- const group = groups.get(model.provider)
+ const family = catalogGroupKey(model.provider)
+ const group = groups.get(family)
if (group) group.push(model)
- else groups.set(model.provider, [model])
+ else groups.set(family, [model])
}
- for (const group of groups.values()) {
- if (!sortKey) continue
- const direction = sortDir === 'asc' ? 1 : -1
- const byKey = compareModelByKey(sortKey)
- group.sort((a, b) => {
- if (sortKey === 'contextWindow') {
- const nullOrder = compareNullsLast(a.context_window_tokens, b.context_window_tokens)
- if (nullOrder !== null) return nullOrder
- }
- const diff = byKey(a, b) * direction
- if (diff !== 0) return diff
- return compareModel(a, b)
- })
+ const collapsed: Array<[string, DisplayModel[]]> = []
+ for (const [family, rows] of groups.entries()) {
+ const display = collapseFamilyRows(family, rows)
+ if (sortKey) {
+ const direction = sortDir === 'asc' ? 1 : -1
+ const byKey = compareModelByKey(sortKey)
+ display.sort((a, b) => {
+ if (sortKey === 'contextWindow') {
+ const nullOrder = compareNullsLast(a.context_window_tokens, b.context_window_tokens)
+ if (nullOrder !== null) return nullOrder
+ }
+ const diff = byKey(a, b) * direction
+ if (diff !== 0) return diff
+ return compareModel(a, b)
+ })
+ }
+ collapsed.push([family, display])
}
- return Array.from(groups.entries()).sort(([left], [right]) =>
+ return collapsed.sort(([left], [right]) =>
getProviderDisplayLabel(left).localeCompare(getProviderDisplayLabel(right))
)
}, [filteredItems, sortDir, sortKey])
@@ -216,6 +246,7 @@ export function LlmModelTable({
const modelColumns: TableHeaderColumn[] = [
{ key: 'model', label: renderSortHeader('model', 'Model'), minWidth: '15rem' },
+ { key: 'credential', label: 'Credential', width: '11rem' },
{ key: 'vendor', label: renderSortHeader('vendor', 'Vendor'), width: '10rem' },
{
key: 'displayName',
@@ -333,7 +364,10 @@ export function LlmModelTable({
</thead>
{groupedItems.map(([provider, models]) => {
const providerLabel = getProviderDisplayLabel(provider)
- const providerModels = items.filter(model => model.provider === provider)
+ const providerModels = collapseFamilyRows(
+ provider,
+ items.filter(model => catalogGroupKey(model.provider) === provider)
+ )
const enabledCount = providerModels.filter(model => model.enabled).length
const staleCount = providerModels.filter(model => model.stale).length
const hasFilteredModels = models.length !== providerModels.length
@@ -374,7 +408,7 @@ export function LlmModelTable({
</td>
</tr>
{expanded
- ? models.map((model: LlmAllowedModel) => (
+ ? models.map((model: DisplayModel) => (
<tr key={model.id} className="cu-table__row cu-llm-model-row">
<td className="cu-px-model">
<span className="cu-px-model-content">
@@ -387,6 +421,7 @@ export function LlmModelTable({
) : null}
</span>
</td>
+ <td>{model.credentialLabel || '—'}</td>
<td>{model.vendor || '—'}</td>
<td>{model.display_name || '—'}</td>
<td className="cu-px-num">
diff --git a/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsx b/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsx
index 6894d053f..8f3e5879f 100644
--- a/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsx
+++ b/control-ui/components/LlmModelsSurface/LlmModelsTabBar.tsx
@@ -5,12 +5,11 @@ import { TabBar } from '@components/TabBar'
import type { TabBarOption } from '@components/TabBar/types'
import { CONTROL_ROUTES } from '@constants/routes'
-export type LlmModelsTabValue = 'catalog' | 'discovery' | 'codex-subscription'
+export type LlmModelsTabValue = 'catalog' | 'discovery'
export type LlmModelsTabBarProps = {
activeTab: LlmModelsTabValue
catalogCount?: number
- codexEnabled?: boolean
discoveryReviewCount?: number
}
@@ -21,7 +20,6 @@ export type LlmModelsTabBarProps = {
export function LlmModelsTabBar({
activeTab,
catalogCount,
- codexEnabled = false,
discoveryReviewCount = 0,
}: LlmModelsTabBarProps) {
const options: TabBarOption<LlmModelsTabValue>[] = [
@@ -41,14 +39,6 @@ export function LlmModelsTabBar({
},
]
- if (codexEnabled) {
- options.push({
- value: 'codex-subscription' as const,
- href: CONTROL_ROUTES.llmModels.codexSubscription,
- label: 'Codex subscription',
- })
- }
-
return (
<TabBar<LlmModelsTabValue>
activeValue={activeTab}
diff --git a/control-ui/components/LlmModelsSurface/index.tsx b/control-ui/components/LlmModelsSurface/index.tsx
index a9af9b4c3..1cfa6c987 100644
--- a/control-ui/components/LlmModelsSurface/index.tsx
+++ b/control-ui/components/LlmModelsSurface/index.tsx
@@ -21,10 +21,6 @@ import {
isLlmModelConfigMapDeferred,
isSilentApiError,
} from '@lib/api'
-import {
- isCodexSubscriptionUiEnabled,
- loadCodexSubscriptionCapability,
-} from '@lib/codexSubscriptionFeature'
import { getProviderDisplayLabel } from '@lib/llm'
import { buildUnpricedKeys } from '@lib/llmModelUnpriced'
import { CatalogAttentionBanner } from './CatalogAttentionBanner'
@@ -48,7 +44,6 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {
// Bumped after each successful mutation so the attention banner re-fetches
// and drops any item the operator just resolved (on demand, no polling).
const [attentionRefreshKey, setAttentionRefreshKey] = useState(0)
- const [codexEnabled, setCodexEnabled] = useState(false)
const unpricedKeys = useMemo(() => buildUnpricedKeys(unpriced), [unpriced])
@@ -144,9 +139,6 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {
useEffect(() => {
if (authState.isLoggedIn && !authState.isLoading) {
void loadAll()
- void loadCodexSubscriptionCapability().then(capability => {
- setCodexEnabled(isCodexSubscriptionUiEnabled(capability))
- })
}
}, [activeTab, authState.isLoggedIn, authState.isLoading])
@@ -160,7 +152,6 @@ function LlmModelsContent({ activeTab }: LlmModelsSurfaceProps) {
<LlmModelsTabBar
activeTab={activeTab}
catalogCount={models.length}
- codexEnabled={codexEnabled}
discoveryReviewCount={discoveryReviewCount}
/>
)
diff --git a/control-ui/components/LlmPolicyEditor/index.tsx b/control-ui/components/LlmPolicyEditor/index.tsx
index a1a7dee66..0d911637b 100644
--- a/control-ui/components/LlmPolicyEditor/index.tsx
+++ b/control-ui/components/LlmPolicyEditor/index.tsx
@@ -5,13 +5,14 @@ import { IconTrash } from '@/components/icons'
import { Button, CheckboxField, Field, SelectInput, TextInput } from '@/components/ui'
import {
LLM_DEFAULT_COOLDOWN_SECONDS,
- LLM_PROVIDER_OPTIONS,
LLM_TRIGGER_CLASSES,
LLM_TRIGGER_LABELS,
type LlmFallbackEntry,
type LlmPolicy,
type LlmProvider,
type LlmTriggerClass,
+ OPENAI_SUBSCRIPTION_PROVIDER,
+ OPERATOR_PROVIDER_OPTIONS,
constrainModelOptions,
getCredentialSlotOptions,
getProviderDisplayLabel,
@@ -310,11 +311,14 @@ function FallbackRow({
})
}}
>
- {LLM_PROVIDER_OPTIONS.map(option => (
+ {OPERATOR_PROVIDER_OPTIONS.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
+ {entry.provider === OPENAI_SUBSCRIPTION_PROVIDER ? (
+ <option value={OPENAI_SUBSCRIPTION_PROVIDER}>OpenAI (ChatGPT subscription)</option>
+ ) : null}
</SelectInput>
</Field>
diff --git a/control-ui/components/LlmProviderConfig/index.tsx b/control-ui/components/LlmProviderConfig/index.tsx
index 19cb5bde5..8f40f4258 100644
--- a/control-ui/components/LlmProviderConfig/index.tsx
+++ b/control-ui/components/LlmProviderConfig/index.tsx
@@ -15,6 +15,8 @@ import {
type LlmCredentialField,
type LlmCredentialGroup,
type LlmProvider,
+ OPENAI_SUBSCRIPTION_PROVIDER,
+ OPERATOR_PROVIDER_OPTIONS,
allowedModelsForProvider,
constrainModelOptions,
describeLlmCompleteness,
@@ -22,6 +24,7 @@ import {
getModelOptions,
getProviderLabel,
getProviderSlotKeys,
+ isOpenAiFamily,
isProviderAllowUnrestricted,
mintFallbackSlot,
normalizeProvider,
@@ -101,6 +104,8 @@ export function LlmProviderConfig({
secretKeys = [],
fallbackProvidersInitiallyCollapsed = false,
disabled = false,
+ subscriptionCredentialEnabled = false,
+ afterPrimaryProvider,
}: LlmProviderConfigProps) {
const [fallbackProvidersOpen, setFallbackProvidersOpen] = useState(
!fallbackProvidersInitiallyCollapsed
@@ -123,14 +128,18 @@ export function LlmProviderConfig({
[catalog, allowedModels, provider]
)
const primaryModelOutOfAllowlist = Boolean(model) && !primaryModelOptions.includes(model)
+ const pickerOptions = subscriptionCredentialEnabled
+ ? OPERATOR_PROVIDER_OPTIONS
+ : LLM_PROVIDER_OPTIONS
const primaryProviderOptions = useMemo(
() =>
- LLM_PROVIDER_OPTIONS.map(option => ({
+ pickerOptions.map(option => ({
...option,
icon: <LlmProviderIcon provider={option.value} label={option.label} />,
})),
- []
+ [pickerOptions]
)
+ const providerPickerValue = isOpenAiFamily(provider) ? 'openai' : provider
const primaryModelSelectOptions = useMemo(() => {
const options: SelectionDropdownOption[] = primaryModelOptions.map(option => ({
value: option,
@@ -238,7 +247,7 @@ export function LlmProviderConfig({
<SelectionDropdown
id="llm-primary-provider"
className="cu-llm-config__primary-select cu-llm-config__provider-select"
- value={[provider]}
+ value={[providerPickerValue]}
options={primaryProviderOptions}
placeholder="Select provider…"
searchPlaceholder="Search providers…"
@@ -250,19 +259,77 @@ export function LlmProviderConfig({
const nextProviderValue = next[0]
if (!nextProviderValue) return
const nextProvider = normalizeProvider(nextProviderValue)
- // Default within this provider's per-host subset when it has one
- // (matches the fallback rows), so switching to a provider that is
- // already restricted never auto-selects an out-of-subset model.
+ const resolved =
+ nextProvider === 'openai' && provider === OPENAI_SUBSCRIPTION_PROVIDER
+ ? OPENAI_SUBSCRIPTION_PROVIDER
+ : nextProvider
onPrimaryChange({
- provider: nextProvider,
+ provider: resolved,
model: resolveDefaultModel(
- nextProvider,
- constrainModelOptions(catalog, allowedModels, nextProvider)
+ resolved,
+ constrainModelOptions(catalog, allowedModels, resolved)
),
})
}}
/>
</Field>
+ {subscriptionCredentialEnabled && isOpenAiFamily(provider) ? (
+ <fieldset
+ className="cu-field cu-llm-config__credential-kind"
+ data-testid="openai-credential-kind"
+ >
+ <legend className="cu-field__label">OpenAI credential</legend>
+ <div
+ className="cu-agent-radio-group"
+ role="radiogroup"
+ aria-label="OpenAI credential"
+ >
+ <label className="cu-agent-radio">
+ <input
+ type="radio"
+ name="openai-credential-kind"
+ checked={provider === 'openai'}
+ disabled={disabled}
+ onChange={() =>
+ onPrimaryChange({
+ provider: 'openai',
+ model: resolveDefaultModel(
+ 'openai',
+ constrainModelOptions(catalog, allowedModels, 'openai')
+ ),
+ })
+ }
+ />
+ API key
+ </label>
+ <label className="cu-agent-radio">
+ <input
+ type="radio"
+ name="openai-credential-kind"
+ checked={provider === OPENAI_SUBSCRIPTION_PROVIDER}
+ disabled={disabled}
+ onChange={() =>
+ onPrimaryChange({
+ provider: OPENAI_SUBSCRIPTION_PROVIDER,
+ model: resolveDefaultModel(
+ OPENAI_SUBSCRIPTION_PROVIDER,
+ constrainModelOptions(
+ catalog,
+ allowedModels,
+ OPENAI_SUBSCRIPTION_PROVIDER
+ )
+ ),
+ })
+ }
+ />
+ ChatGPT subscription
+ </label>
+ </div>
+ </fieldset>
+ ) : null}
+ {afterPrimaryProvider ? (
+ <div className="cu-llm-config__after-provider">{afterPrimaryProvider}</div>
+ ) : null}
{replacePrimaryModelWithAllowedModels && showAllowedModels ? (
<AllowedModelsField
@@ -302,7 +369,9 @@ export function LlmProviderConfig({
<p className="cu-field__error">Couldn&apos;t load the model allowlist: {catalogError}</p>
) : !catalogLoading && primaryModelOptions.length === 0 ? (
<p className="cu-field__error">
- No enabled models for this provider. Add one under LLM Models first.
+ {provider === OPENAI_SUBSCRIPTION_PROVIDER
+ ? 'No enabled models for this subscription. Connect and sync the grant first.'
+ : 'No enabled models for this provider. Add one under LLM Models first.'}
</p>
) : null}
diff --git a/control-ui/components/LlmProviderConfig/types.ts b/control-ui/components/LlmProviderConfig/types.ts
index 645b39fd3..d077708a7 100644
--- a/control-ui/components/LlmProviderConfig/types.ts
+++ b/control-ui/components/LlmProviderConfig/types.ts
@@ -1,3 +1,4 @@
+import type { ReactNode } from 'react'
import type { HostAllowedModel, LlmModelCatalogEntry, LlmPolicy, LlmProvider } from '@/lib/llm'
// Write-only credential wiring. Values are NEVER read back from the server; the
@@ -58,4 +59,9 @@ export type LlmProviderConfigProps = {
fallbackProvidersInitiallyCollapsed?: boolean
disabled?: boolean
+
+ /** When true, OpenAI offers API key vs ChatGPT subscription. Runtime id stays separate. */
+ subscriptionCredentialEnabled?: boolean
+ /** Rendered after the OpenAI credential radios (grant picker). */
+ afterPrimaryProvider?: ReactNode
}
diff --git a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx
index 6823280c7..fb6b786df 100644
--- a/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx
+++ b/control-ui/components/__tests__/CodexSubscriptionConnection.test.tsx
@@ -174,7 +174,7 @@ describe('CodexSubscriptionConnection', () => {
searchParams = new URLSearchParams('codex_oauth=connected')
renderSurface()
await waitFor(() => {
- expect(replaceMock).toHaveBeenCalledWith('/llm-models/providers/codex-subscription')
+ expect(replaceMock).toHaveBeenCalledWith(expect.stringMatching(/\/(hosts|agents)/))
})
expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Connected')
})
@@ -246,7 +246,7 @@ describe('CodexSubscriptionConnection', () => {
await waitFor(() => {
expect(revokeCodexSubscription).toHaveBeenCalled()
})
- expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Disconnected')
+ expect(await screen.findByTestId('codex-connection-status')).toHaveTextContent('Revoked')
})
it('anti-false-positive: a leaked accessToken never reaches the DOM', async () => {
diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
index ebfc2b4eb..46a293f0b 100644
--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
@@ -31,6 +31,10 @@ vi.mock('../HostIdentityTab', () => ({
),
}))
+vi.mock('../CodexAgentAssignment', () => ({
+ CodexAgentAssignment: () => <div data-testid="codex-agent-assignment" />,
+}))
+
vi.mock('../HostAccessTab', () => ({
HostAccessTab: ({ hostName }: { hostName: string }) => (
<div data-testid="access-tab">Access editor for {hostName}</div>
@@ -360,6 +364,8 @@ describe('HostDetailsPage identity integration', () => {
render(<HostDetailsPage />)
expect(await screen.findByText('Broker-backed — no LLM secret required')).toBeInTheDocument()
+ expect(screen.getByText('ChatGPT subscription')).toBeInTheDocument()
+ expect(screen.queryByText('OpenAI Codex Subscription')).not.toBeInTheDocument()
fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
@@ -370,7 +376,11 @@ describe('HostDetailsPage identity integration', () => {
c => c[0] === 'PUT' && c[1] === '/api/v1/admin/hosts/foo'
)
const payload = putCall![2]
- expect(payload.spec.model).toEqual({ provider: 'codex-subscription', name: 'gpt-5.1' })
+ expect(payload.spec.model).toEqual({
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'deployment-default',
+ })
expect(payload.spec.secretRef).toBeUndefined()
expect(payload.spec.hostRef).toBeUndefined()
expect(payload.spec.userId).toBeUndefined()
diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsx
index d782196f1..0af60fb3d 100644
--- a/control-ui/components/__tests__/HostWizard.test.tsx
+++ b/control-ui/components/__tests__/HostWizard.test.tsx
@@ -22,6 +22,10 @@ import { ToastProvider } from '../Toast'
* These tests lock the new behavior so it cannot regress.
*/
+vi.mock('../CodexAgentAssignment', () => ({
+ CodexAgentAssignment: () => <div data-testid="codex-agent-assignment" />,
+}))
+
// Mock lib/api BEFORE importing the component. vi.mock is hoisted.
vi.mock('../../lib/api', () => ({
apiGet: vi.fn().mockResolvedValue({ items: [] }),
@@ -785,10 +789,14 @@ async function walkToModelStep(opts?: { agentName?: string }) {
async function selectCodexSubscription(model = 'gpt-5.1') {
fireEvent.click(screen.getByLabelText('Provider', { selector: '#llm-primary-provider' }))
- fireEvent.click(screen.getByRole('option', { name: /OpenAI Codex Subscription/i }))
+ fireEvent.click(screen.getByRole('option', { name: /^OpenAI$/i }))
+ fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))
await waitFor(() => {
expect(screen.queryByText(/Use an existing secret/i)).not.toBeInTheDocument()
})
+ expect(
+ screen.queryByRole('option', { name: /OpenAI Codex Subscription/i })
+ ).not.toBeInTheDocument()
fireEvent.click(screen.getByLabelText('Default model', { selector: '#llm-primary-model' }))
fireEvent.click(screen.getByRole('option', { name: model }))
}
@@ -811,7 +819,11 @@ describe('HostWizard — broker-backed Codex authoring', () => {
expect.objectContaining({
metadata: { name: 'codex-only' },
spec: expect.objectContaining({
- model: { provider: 'codex-subscription', name: 'gpt-5.1' },
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'deployment-default',
+ },
}),
})
)
diff --git a/control-ui/components/__tests__/LlmModelTable.test.tsx b/control-ui/components/__tests__/LlmModelTable.test.tsx
index 34fe79066..85fec060d 100644
--- a/control-ui/components/__tests__/LlmModelTable.test.tsx
+++ b/control-ui/components/__tests__/LlmModelTable.test.tsx
@@ -79,6 +79,42 @@ describe('LlmModelTable catalog-lifecycle columns', () => {
expect(screen.queryByText('Discovered')).not.toBeInTheDocument()
expect(screen.queryByText('Stale', { selector: '.cu-px-badge--warn' })).toBeNull()
})
+
+ it('groups OpenAI API-key and subscription rows under one family', () => {
+ renderTable([
+ {
+ ...baseModel,
+ id: 'oa-key',
+ provider: 'openai',
+ model: 'gpt-5.1',
+ vendor: 'OpenAI',
+ display_name: 'GPT-5.1',
+ },
+ {
+ ...baseModel,
+ id: 'oa-sub',
+ provider: 'codex-subscription',
+ model: 'gpt-5.1',
+ vendor: 'OpenAI',
+ display_name: 'GPT-5.1',
+ },
+ {
+ ...baseModel,
+ id: 'oa-sub-only',
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ vendor: 'OpenAI',
+ display_name: 'GPT-5.3 Codex',
+ },
+ ])
+ expect(
+ screen.queryByRole('button', { name: /OpenAI Codex Subscription/i })
+ ).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Expand OpenAI models' }))
+ expect(screen.getByText('gpt-5.1')).toBeInTheDocument()
+ expect(screen.getByText('API key · Subscription')).toBeInTheDocument()
+ expect(screen.getByText('gpt-5.3-codex').closest('tr')).toHaveTextContent('Subscription')
+ })
})
describe('LlmModelTable filters', () => {
diff --git a/control-ui/components/__tests__/LlmModelsSurface.test.tsx b/control-ui/components/__tests__/LlmModelsSurface.test.tsx
index 0a23e4be7..992055157 100644
--- a/control-ui/components/__tests__/LlmModelsSurface.test.tsx
+++ b/control-ui/components/__tests__/LlmModelsSurface.test.tsx
@@ -94,16 +94,14 @@ describe('LlmModelsSurface', () => {
expect(screen.queryByRole('tab', { name: 'Codex subscription' })).not.toBeInTheDocument()
})
- it('shows the Codex subscription tab only after Control API proves the flag', async () => {
- vi.mocked(loadCodexSubscriptionCapability).mockResolvedValue({ enabled: true })
+ it('never shows a Codex subscription tab on LLM Models', async () => {
render(
<ToastProvider>
<LlmModelsSurface activeTab="catalog" />
</ToastProvider>
)
- const tab = await screen.findByRole('tab', { name: 'Codex subscription' })
- expect(tab).toHaveAttribute('href', '/llm-models/providers/codex-subscription')
- expect(screen.queryByTestId('codex-subscription-catalog-link')).not.toBeInTheDocument()
+ expect(await screen.findByText('Model catalog')).toBeInTheDocument()
+ expect(screen.queryByRole('tab', { name: 'Codex subscription' })).not.toBeInTheDocument()
})
})
diff --git a/control-ui/components/__tests__/LlmProviderConfig.test.tsx b/control-ui/components/__tests__/LlmProviderConfig.test.tsx
index fc9e53202..5ad44408d 100644
--- a/control-ui/components/__tests__/LlmProviderConfig.test.tsx
+++ b/control-ui/components/__tests__/LlmProviderConfig.test.tsx
@@ -21,6 +21,7 @@ function Harness({
withCredentials = true,
existingKeys,
replacePrimaryModelWithAllowedModels = false,
+ subscriptionCredentialEnabled = false,
}: {
initialProvider?: LlmProvider
initialModel?: string
@@ -29,6 +30,7 @@ function Harness({
withCredentials?: boolean
existingKeys?: string[]
replacePrimaryModelWithAllowedModels?: boolean
+ subscriptionCredentialEnabled?: boolean
}) {
const [provider, setProvider] = useState<LlmProvider>(initialProvider)
const [model, setModel] = useState(initialModel)
@@ -58,6 +60,7 @@ function Harness({
: undefined
}
replacePrimaryModelWithAllowedModels={replacePrimaryModelWithAllowedModels}
+ subscriptionCredentialEnabled={subscriptionCredentialEnabled}
secretKeys={existingKeys}
/>
)
@@ -172,6 +175,18 @@ describe('LlmProviderConfig (spec Topic 1b — domain projection + usable gate)'
).toHaveTextContent('OpenAI')
expect(screen.getByLabelText('Model', { selector: '#llm-primary-model' })).toBeInTheDocument()
})
+
+ it('offers OpenAI plus a credential type instead of a Codex provider option', () => {
+ render(<Harness subscriptionCredentialEnabled />)
+ fireEvent.click(screen.getByLabelText('Provider', { selector: '#llm-primary-provider' }))
+ expect(screen.getByRole('option', { name: /^OpenAI$/i })).toBeInTheDocument()
+ expect(
+ screen.queryByRole('option', { name: /OpenAI Codex Subscription/i })
+ ).not.toBeInTheDocument()
+ fireEvent.click(screen.getByRole('radio', { name: /ChatGPT subscription/i }))
+ expect(screen.getByRole('radio', { name: /ChatGPT subscription/i })).toBeChecked()
+ expect(screen.getByText(/Connect and sync the grant first/i)).toBeInTheDocument()
+ })
})
describe('LlmProviderConfig (spec Topic 3a — per-host allowed-models subset)', () => {
diff --git a/control-ui/lib/__tests__/llm.test.ts b/control-ui/lib/__tests__/llm.test.ts
index e11509bdc..acd0dc983 100644
--- a/control-ui/lib/__tests__/llm.test.ts
+++ b/control-ui/lib/__tests__/llm.test.ts
@@ -5,13 +5,19 @@ import {
LLM_CREDENTIAL_GROUPS,
LLM_DEFAULT_MODEL_BY_PROVIDER,
type LlmModelCatalogEntry,
+ OPERATOR_PROVIDER_OPTIONS,
brokerBackedRecipeAuthoringError,
budgetUnitAllowedForProviders,
+ catalogGroupKey,
getAllModelOptions,
getLlmGroupCompleteness,
getModelOptions,
+ getProviderDisplayLabel,
+ getProviderLabel,
inferProviderFromModels,
+ isOpenAiFamily,
llmChainRequiresSecret,
+ openAiCredentialSources,
providerRequiresLlmSecret,
resolveDefaultModel,
validateLlmSecretData,
@@ -62,6 +68,44 @@ describe('getModelOptions', () => {
})
})
+describe('OpenAI family presentation', () => {
+ it('does not offer Codex as a second provider in operator pickers', () => {
+ expect(OPERATOR_PROVIDER_OPTIONS.some(option => option.value === 'codex-subscription')).toBe(
+ false
+ )
+ expect(OPERATOR_PROVIDER_OPTIONS.some(option => option.value === 'openai')).toBe(true)
+ })
+
+ it('labels the subscription runtime id as OpenAI for operators', () => {
+ expect(getProviderLabel('codex-subscription')).toBe('OpenAI')
+ expect(getProviderDisplayLabel('codex-subscription')).toBe('OpenAI')
+ expect(getProviderLabel('openai')).toBe('OpenAI')
+ })
+
+ it('groups subscription catalog rows under OpenAI', () => {
+ expect(catalogGroupKey('codex-subscription')).toBe('openai')
+ expect(catalogGroupKey('openai')).toBe('openai')
+ expect(catalogGroupKey('claude')).toBe('claude')
+ expect(isOpenAiFamily('codex-subscription')).toBe(true)
+ })
+
+ it('marks a model as API key, subscription, or both', () => {
+ const catalog: LlmModelCatalogEntry[] = [
+ { provider: 'openai', model: 'gpt-5.1', enabled: true },
+ { provider: 'codex-subscription', model: 'gpt-5.1', enabled: true },
+ { provider: 'codex-subscription', model: 'gpt-5.3-codex', enabled: true },
+ ]
+ expect(openAiCredentialSources(catalog, 'gpt-5.1')).toEqual({
+ apiKey: true,
+ subscription: true,
+ })
+ expect(openAiCredentialSources(catalog, 'gpt-5.3-codex')).toEqual({
+ apiKey: false,
+ subscription: true,
+ })
+ })
+})
+
describe('getAllModelOptions', () => {
it('flattens and de-duplicates enabled models across providers', () => {
const all = getAllModelOptions(CATALOG)
diff --git a/control-ui/lib/__tests__/routes.test.ts b/control-ui/lib/__tests__/routes.test.ts
index 8eb786baa..31450dba9 100644
--- a/control-ui/lib/__tests__/routes.test.ts
+++ b/control-ui/lib/__tests__/routes.test.ts
@@ -28,9 +28,7 @@ describe('CONTROL_ROUTES', () => {
expect(CONTROL_ROUTES.globalFileSystem).toBe('/global-file-system')
})
- it('exposes the Codex subscription provider path without query tabs', () => {
- expect(CONTROL_ROUTES.llmModels.codexSubscription).toBe(
- '/llm-models/providers/codex-subscription'
- )
+ it('does not expose an LLM Models Codex subscription owner path', () => {
+ expect('codexSubscription' in CONTROL_ROUTES.llmModels).toBe(false)
})
})
diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.ts
index 78991d813..c663e41bb 100644
--- a/control-ui/lib/codexSubscription.ts
+++ b/control-ui/lib/codexSubscription.ts
@@ -13,8 +13,12 @@ export type CodexCatalogStatus = 'never_synced' | 'ready' | 'auth-rejected' | 'u
export type CodexOAuthIntent = 'connect' | 'reconnect' | 'replace'
+export type CodexAssignedHost = { name: string }
+
export type CodexSubscriptionConnectionView = {
- connectionKey: 'deployment-default'
+ id?: string
+ connectionKey: string
+ displayName?: string
status: CodexConnectionStatus
credentialRevision: number
catalogRevision: number
@@ -24,6 +28,7 @@ export type CodexSubscriptionConnectionView = {
lastRefreshAt: string | null
lastAuthAt: string | null
refreshLockHeld: boolean
+ assignedHosts?: CodexAssignedHost[]
}
export type CodexBrowserStartView = {
@@ -111,7 +116,19 @@ export function sanitizeCodexConnection(raw: unknown): CodexSubscriptionConnecti
? catalogStatus
: 'never_synced'
return {
- connectionKey: 'deployment-default',
+ connectionKey:
+ typeof raw.connectionKey === 'string' && raw.connectionKey.trim()
+ ? raw.connectionKey.trim()
+ : 'deployment-default',
+ displayName: pickString(raw.displayName) ?? undefined,
+ assignedHosts: Array.isArray(raw.assignedHosts)
+ ? raw.assignedHosts
+ .filter(
+ (entry): entry is { name: string } =>
+ Boolean(entry) && typeof (entry as { name?: unknown }).name === 'string'
+ )
+ .map(entry => ({ name: entry.name }))
+ : undefined,
status,
credentialRevision: pickNumber(raw.credentialRevision),
catalogRevision: pickNumber(raw.catalogRevision),
@@ -195,44 +212,96 @@ export function sanitizeCodexCatalogSync(raw: unknown): CodexCatalogSyncView {
}
}
-export async function getCodexSubscriptionConnection(): Promise<CodexSubscriptionConnectionView> {
- return sanitizeCodexConnection(await apiGet(`${CODEX_SUBSCRIPTION_API_BASE}/connection`))
+export async function listCodexSubscriptionConnections(): Promise<
+ CodexSubscriptionConnectionView[]
+> {
+ const raw = (await apiGet(`${CODEX_SUBSCRIPTION_API_BASE}/connections`)) as {
+ connections?: unknown
+ }
+ return Array.isArray(raw.connections) ? raw.connections.map(sanitizeCodexConnection) : []
+}
+
+export async function createCodexSubscriptionConnection(input: {
+ displayName: string
+ connectionKey?: string
+}): Promise<CodexSubscriptionConnectionView> {
+ return sanitizeCodexConnection(
+ await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/connections`, input)
+ )
+}
+
+export async function listCodexConnectionModels(
+ connectionKey: string
+): Promise<Array<{ model: string; enabled: boolean; stale: boolean }>> {
+ const raw = (await apiGet(
+ `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}/models`
+ )) as { models?: Array<{ model?: string; enabled?: boolean; stale?: boolean }> }
+ return Array.isArray(raw.models)
+ ? raw.models
+ .filter(row => typeof row.model === 'string' && row.model.trim())
+ .map(row => ({
+ model: String(row.model),
+ enabled: row.enabled === true,
+ stale: row.stale === true,
+ }))
+ : []
+}
+
+export async function getCodexSubscriptionConnection(
+ connectionKey?: string
+): Promise<CodexSubscriptionConnectionView> {
+ const path = connectionKey
+ ? `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}`
+ : `${CODEX_SUBSCRIPTION_API_BASE}/connection`
+ return sanitizeCodexConnection(await apiGet(path))
+}
+
+function keyedPath(connectionKey: string | undefined, action: string): string {
+ if (!connectionKey) return `${CODEX_SUBSCRIPTION_API_BASE}/${action}`
+ return `${CODEX_SUBSCRIPTION_API_BASE}/connections/${encodeURIComponent(connectionKey)}/${action}`
}
export async function startCodexBrowserConnect(
- intent: CodexOAuthIntent
+ intent: CodexOAuthIntent,
+ connectionKey?: string
): Promise<CodexBrowserStartView> {
return sanitizeCodexBrowserStart(
- await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/browser/start`, { intent })
+ await apiSend('POST', keyedPath(connectionKey, 'browser/start'), { intent })
)
}
export async function startCodexDeviceConnect(
- intent: CodexOAuthIntent
+ intent: CodexOAuthIntent,
+ connectionKey?: string
): Promise<CodexDeviceStartView> {
return sanitizeCodexDeviceStart(
- await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/device/start`, { intent })
+ await apiSend('POST', keyedPath(connectionKey, 'device/start'), { intent })
)
}
-export async function pollCodexDevice(state: string): Promise<CodexDevicePollView> {
- return sanitizeCodexDevicePoll(
- await apiGet(`${CODEX_SUBSCRIPTION_API_BASE}/device/poll`, { state })
- )
+export async function pollCodexDevice(
+ state: string,
+ connectionKey?: string
+): Promise<CodexDevicePollView> {
+ return sanitizeCodexDevicePoll(await apiGet(keyedPath(connectionKey, 'device/poll'), { state }))
}
-export async function refreshCodexSubscriptionConnection(): Promise<CodexSubscriptionConnectionView> {
- return sanitizeCodexConnection(await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/refresh`))
+export async function refreshCodexSubscriptionConnection(
+ connectionKey?: string
+): Promise<CodexSubscriptionConnectionView> {
+ return sanitizeCodexConnection(await apiSend('POST', keyedPath(connectionKey, 'refresh')))
}
-export async function syncCodexSubscriptionCatalog(): Promise<CodexCatalogSyncView> {
- return sanitizeCodexCatalogSync(
- await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/catalog/sync`)
- )
+export async function syncCodexSubscriptionCatalog(
+ connectionKey?: string
+): Promise<CodexCatalogSyncView> {
+ return sanitizeCodexCatalogSync(await apiSend('POST', keyedPath(connectionKey, 'catalog/sync')))
}
-export async function revokeCodexSubscription(): Promise<CodexSubscriptionConnectionView> {
- return sanitizeCodexConnection(await apiSend('POST', `${CODEX_SUBSCRIPTION_API_BASE}/revoke`))
+export async function revokeCodexSubscription(
+ connectionKey?: string
+): Promise<CodexSubscriptionConnectionView> {
+ return sanitizeCodexConnection(await apiSend('POST', keyedPath(connectionKey, 'revoke')))
}
const CODEX_OAUTH_QUERY_PARAM = 'codex_oauth'
diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.ts
index e1b9d7ae6..45bda62fe 100644
--- a/control-ui/lib/llm.ts
+++ b/control-ui/lib/llm.ts
@@ -45,6 +45,41 @@ export const LLM_PROVIDER_OPTIONS: Array<{ value: LlmProvider; label: string }>
id => ({ value: id, label: PROVIDER_DISPLAY_LABELS[id] })
)
+/** Runtime broker id. Never offer this as a second Provider row in operator pickers. */
+export const OPENAI_SUBSCRIPTION_PROVIDER = 'codex-subscription' as const
+
+export function isOpenAiFamily(provider: string | undefined | null): boolean {
+ return provider === 'openai' || provider === OPENAI_SUBSCRIPTION_PROVIDER
+}
+
+/** Provider dropdown: one OpenAI entry. Runtime still persists `codex-subscription`. */
+export const OPERATOR_PROVIDER_OPTIONS: Array<{ value: LlmProvider; label: string }> =
+ LLM_PROVIDER_OPTIONS.filter(option => option.value !== OPENAI_SUBSCRIPTION_PROVIDER)
+
+export function catalogGroupKey(provider: string): string {
+ return provider === OPENAI_SUBSCRIPTION_PROVIDER ? 'openai' : provider
+}
+
+export type OpenAiCredentialSource = 'api-key' | 'subscription'
+
+export function openAiCredentialSources(
+ catalog: LlmModelCatalogEntry[],
+ model: string
+): { apiKey: boolean; subscription: boolean } {
+ return {
+ apiKey: catalog.some(
+ row => row.provider === 'openai' && row.model === model && row.enabled && !row.stale
+ ),
+ subscription: catalog.some(
+ row =>
+ row.provider === OPENAI_SUBSCRIPTION_PROVIDER &&
+ row.model === model &&
+ row.enabled &&
+ !row.stale
+ ),
+ }
+}
+
// The list of usable models per provider is no longer a static catalog: it is
// the operator-declared allowlist served by control-api (`/admin/llm-models`,
// spec §3-R3). Fetch it with `useLlmAllowedModels()` and pass the rows to the
@@ -417,6 +452,8 @@ export function normalizeProvider(value: string | undefined | null): LlmProvider
export function getProviderLabel(provider: string | undefined | null): string {
const normalized = normalizeProvider(provider)
+ // Operator presentation: one OpenAI family. Runtime id stays codex-subscription.
+ if (normalized === OPENAI_SUBSCRIPTION_PROVIDER) return 'OpenAI'
const match = LLM_PROVIDER_OPTIONS.find(option => option.value === normalized)
return match?.label || 'OpenAI'
}
@@ -431,6 +468,7 @@ export function isKnownProvider(provider: string | undefined | null): boolean {
// unrecognized provider — important where free-form providers surface, e.g.
// the LLM-prices table and the unpriced-model chips.
export function getProviderDisplayLabel(provider: string): string {
+ if (provider === OPENAI_SUBSCRIPTION_PROVIDER) return 'OpenAI'
return isKnownProvider(provider) ? getProviderLabel(provider) : provider
}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 314c50b2c..c6b258943 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.445",
+ "version": "0.1.446",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.445",
+ "version": "0.1.446",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
diff --git a/control-ui/package.json b/control-ui/package.json
index b26a1c932..73e7bf984 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.445",
+ "version": "0.1.446",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/deploy/scripts/control-api-runtime-access-profiles.tsv b/deploy/scripts/control-api-runtime-access-profiles.tsv
index 2217662cc..07c4f9c27 100644
--- a/deploy/scripts/control-api-runtime-access-profiles.tsv
+++ b/deploy/scripts/control-api-runtime-access-profiles.tsv
@@ -4,6 +4,7 @@ agent_run_events append
budget_pending_reservations legacy_dml
codex_subscription_connections upsert
codex_subscription_oauth_states upsert
+codex_catalog_models upsert
control_admin_deletion_audit legacy_dml
control_admin_email_change_requests legacy_dml
control_admin_invitations legacy_dml
diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.md
index f24e6357a..a342dbca9 100644
--- a/docs/architecture/codex-subscription-transport-contract.md
+++ b/docs/architecture/codex-subscription-transport-contract.md
@@ -76,3 +76,8 @@ and must not weaken this allowlist. Account identifiers stay redacted.
The focused drift from spec SHA `7d56b10849458a67b15f7d9a0991fa62604913a3` to
current `HEAD` did not change credential owner, data path, trust boundary,
namespace/workload shape, gateway count, mTLS stance, or access-token recipient.
+
+Phase 2 grant binding hashes `{ catalogRevision, connectionKey,
+credentialRevision, model, provider }` so two named subscriptions with the
+same integer revisions do not collide. Host `spec.model.connectionRef` selects
+the grant; revoke of one key fail-closes only that assignment.
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 50434a9be..470d48e14 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.232",
+ "version": "0.1.233",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.232",
+ "version": "0.1.233",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index d2d6ee4e2..bebc9f50a 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.232",
+ "version": "0.1.233",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/src/codexExecutionProjection.ts b/host-context-controller/src/codexExecutionProjection.ts
index be22c7e75..371b69712 100644
--- a/host-context-controller/src/codexExecutionProjection.ts
+++ b/host-context-controller/src/codexExecutionProjection.ts
@@ -15,7 +15,13 @@ export type CodexSnapshotError = 'missing' | 'forbidden' | 'timeout' | 'malforme
export type CodexCatalogSnapshot = {
flagEnabled: boolean
- connectionStatus?: 'connected' | 'disconnected' | 'reauth-required' | 'unavailable' | null
+ connectionStatus?:
+ | 'connected'
+ | 'disconnected'
+ | 'reauth-required'
+ | 'unavailable'
+ | 'revoked'
+ | null
catalogContentHash?: string | null
catalogRevision?: number | null
connectionRevision?: number | null
@@ -25,7 +31,7 @@ export type CodexCatalogSnapshot = {
}
export type CodexHostSpec = {
- model?: { provider?: string; name?: string }
+ model?: { provider?: string; name?: string; connectionRef?: string }
allowedModels?: Array<{ provider?: string; model?: string }>
llmPolicy?: { fallbacks?: Array<{ provider?: string; model?: string }> }
}
diff --git a/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts b/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts
index 8f959eff9..3d8e8a5fb 100644
--- a/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts
+++ b/host-context-controller/src/hostReconciler.codexScopeProvenance.test.ts
@@ -92,6 +92,15 @@ function eligibleCodexConfigMap(stale = false) {
'clerum.io/connection-revision': '1',
'clerum.io/codex-connection-status': 'connected',
'clerum.io/codex-enabled': 'true',
+ 'clerum.io/codex-connections': JSON.stringify({
+ 'deployment-default': {
+ status: 'connected',
+ catalogRevision: 1,
+ connectionRevision: 1,
+ },
+ 'team-plus': { status: 'revoked', catalogRevision: 3, connectionRevision: 8 },
+ 'personal-pro': { status: 'connected', catalogRevision: 4, connectionRevision: 2 },
+ }),
},
},
data: {
@@ -252,6 +261,36 @@ describe('HostReconciler Codex scope provenance', () => {
expect(proxyPolicyBodies(networkingApi)).toEqual([])
})
+ it('keeps a Host on a live grant eligible when another assigned grant is revoked', async () => {
+ const { reconciler, coreApi, networkingApi } = createReconciler()
+ wireAllowlist(coreApi, eligibleCodexConfigMap())
+
+ await reconciler.reconcile(
+ makeCodexHost({
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.3-codex',
+ connectionRef: 'personal-pro',
+ },
+ })
+ )
+ expect(issuedScopes()).toContain('llm:codex:execute')
+ expect(proxyPolicyBodies(networkingApi)).toHaveLength(1)
+
+ vi.mocked(issueMcpHostRuntimeTokens).mockClear()
+ await reconciler.reconcile(
+ makeCodexHost({
+ host: 'revoked-host',
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.3-codex',
+ connectionRef: 'team-plus',
+ },
+ })
+ )
+ expect(issuedScopes()).not.toContain('llm:codex:execute')
+ })
+
it('does not mint Codex scope or egress when the allowlist ConfigMap times out', async () => {
const { reconciler, coreApi, networkingApi } = createReconciler()
wireAllowlist(
diff --git a/host-context-controller/src/hostReconciler.ts b/host-context-controller/src/hostReconciler.ts
index 74198b3f9..4869ca0d5 100644
--- a/host-context-controller/src/hostReconciler.ts
+++ b/host-context-controller/src/hostReconciler.ts
@@ -466,6 +466,7 @@ export class HostReconciler {
private readonly newTelemetryOccurrenceId: () => string
private readonly statusMap: Map<string, HostRuntimeStatus> = new Map()
private codexSnapshot: CodexCatalogSnapshot = { flagEnabled: false }
+ private lastCodexConfigMap: k8s.V1ConfigMap | undefined
private readonly readinessTimers: Map<string, ReturnType<typeof setTimeout>> = new Map()
/**
* host.name → image whose pull-policy refusal was already error-logged.
@@ -1376,7 +1377,11 @@ export class HostReconciler {
}
private projectCodexForHost(host: HostCRD): CodexExecutionProjection {
- return projectCodexExecution(host.spec, this.codexSnapshot)
+ const connectionKey = host.spec.model?.connectionRef?.trim() || 'deployment-default'
+ const snapshot = this.lastCodexConfigMap
+ ? parseAllowedModelsSnapshot(this.lastCodexConfigMap, connectionKey)
+ : this.codexSnapshot
+ return projectCodexExecution(host.spec, snapshot)
}
private resolveEffectiveControlScopesForHost(
@@ -1407,12 +1412,14 @@ export class HostReconciler {
name: ALLOWED_MODELS_CONFIGMAP_NAME,
namespace: config.hccTargetNamespace,
})
+ this.lastCodexConfigMap = cm
this.codexSnapshot = parseAllowedModelsSnapshot(cm)
} catch (err) {
const timeout =
err instanceof HostK8sRequestTimeoutError ||
(err as { code?: string }).code === HOST_K8S_REQUEST_TIMEOUT_CODE
if (timeout) {
+ this.lastCodexConfigMap = undefined
this.codexSnapshot = snapshotFromConfigMapError('timeout')
log.warn('Codex allowlist ConfigMap read timed out; failing closed', {
configMap: ALLOWED_MODELS_CONFIGMAP_NAME,
@@ -1422,6 +1429,7 @@ export class HostReconciler {
}
const code = getErrorCode(err)
if (code === 401 || code === 403) {
+ this.lastCodexConfigMap = undefined
this.codexSnapshot = snapshotFromConfigMapError('forbidden')
log.warn('Codex allowlist ConfigMap read forbidden; failing closed', {
configMap: ALLOWED_MODELS_CONFIGMAP_NAME,
@@ -1430,6 +1438,7 @@ export class HostReconciler {
})
return
}
+ this.lastCodexConfigMap = undefined
this.codexSnapshot = snapshotFromConfigMapError('missing')
log.warn('Codex allowlist ConfigMap unavailable; failing closed', {
configMap: ALLOWED_MODELS_CONFIGMAP_NAME,
diff --git a/host-context-controller/src/llmAllowedModelsSnapshot.test.ts b/host-context-controller/src/llmAllowedModelsSnapshot.test.ts
new file mode 100644
index 000000000..22de5fbd8
--- /dev/null
+++ b/host-context-controller/src/llmAllowedModelsSnapshot.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest'
+import { projectCodexExecution } from './codexExecutionProjection'
+import { parseAllowedModelsSnapshot } from './llmAllowedModelsSnapshot'
+
+function multiGrantConfigMap() {
+ return {
+ metadata: {
+ annotations: {
+ 'clerum.io/content-hash': 'aa',
+ 'clerum.io/catalog-revision': '1',
+ 'clerum.io/connection-revision': '1',
+ 'clerum.io/codex-connection-status': 'connected',
+ 'clerum.io/codex-enabled': 'true',
+ 'clerum.io/codex-connections': JSON.stringify({
+ 'deployment-default': {
+ status: 'connected',
+ catalogRevision: 1,
+ connectionRevision: 1,
+ },
+ 'team-plus': { status: 'revoked', catalogRevision: 3, connectionRevision: 8 },
+ 'personal-pro': { status: 'connected', catalogRevision: 4, connectionRevision: 2 },
+ }),
+ },
+ },
+ data: {
+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex', stale: false }]),
+ },
+ }
+}
+
+describe('parseAllowedModelsSnapshot per assigned connection', () => {
+ it('marks the assigned revoked grant ineligible and leaves another Host eligible', () => {
+ const cm = multiGrantConfigMap()
+ const revoked = parseAllowedModelsSnapshot(cm, 'team-plus')
+ const live = parseAllowedModelsSnapshot(cm, 'personal-pro')
+ expect(revoked.connectionStatus).toBe('revoked')
+ expect(revoked.connectionRevision).toBe(8)
+ expect(live.connectionStatus).toBe('connected')
+ expect(live.catalogRevision).toBe(4)
+
+ const spec = { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } }
+ expect(projectCodexExecution(spec, revoked).eligibility).toBe('ineligible')
+ expect(projectCodexExecution(spec, revoked).reason).toBe('connection_revoked')
+ expect(projectCodexExecution(spec, live).eligibility).toBe('eligible')
+ })
+
+ it('defaults a Phase 1 Host without connectionRef to deployment-default', () => {
+ const snapshot = parseAllowedModelsSnapshot(multiGrantConfigMap())
+ expect(snapshot.connectionStatus).toBe('connected')
+ expect(snapshot.catalogRevision).toBe(1)
+ })
+})
diff --git a/host-context-controller/src/llmAllowedModelsSnapshot.ts b/host-context-controller/src/llmAllowedModelsSnapshot.ts
index 589a453e7..61ce30148 100644
--- a/host-context-controller/src/llmAllowedModelsSnapshot.ts
+++ b/host-context-controller/src/llmAllowedModelsSnapshot.ts
@@ -7,6 +7,7 @@ export const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'
export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'
export const CODEX_CONNECTION_STATUS_ANNOTATION = 'clerum.io/codex-connection-status'
export const CODEX_ENABLED_ANNOTATION = 'clerum.io/codex-enabled'
+export const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCatalogSnapshot {
return { flagEnabled: false, snapshotError: error }
@@ -21,7 +22,10 @@ function parseOptionalIntegerAnnotation(
return Number.isInteger(parsed) ? parsed : 'invalid'
}
-export function parseAllowedModelsSnapshot(cm: V1ConfigMap | undefined): CodexCatalogSnapshot {
+export function parseAllowedModelsSnapshot(
+ cm: V1ConfigMap | undefined,
+ connectionKey = 'deployment-default'
+): CodexCatalogSnapshot {
if (!cm) return snapshotFromConfigMapError('missing')
const annotations = cm.metadata?.annotations ?? {}
const enabledModels = new Set<string>()
@@ -41,20 +45,44 @@ export function parseAllowedModelsSnapshot(cm: V1ConfigMap | undefined): CodexCa
return snapshotFromConfigMapError('malformed')
}
}
- const catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
- const connectionRevision = parseOptionalIntegerAnnotation(
+ let catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
+ let connectionRevision = parseOptionalIntegerAnnotation(
annotations,
CONNECTION_REVISION_ANNOTATION
)
if (catalogRevision === 'invalid' || connectionRevision === 'invalid') {
return snapshotFromConfigMapError('malformed')
}
+ let connectionStatus =
+ (annotations[CODEX_CONNECTION_STATUS_ANNOTATION] as CodexCatalogSnapshot['connectionStatus']) ??
+ null
+ const rawMap = annotations[CODEX_CONNECTIONS_ANNOTATION]
+ if (rawMap) {
+ try {
+ const parsed = JSON.parse(rawMap) as Record<
+ string,
+ { status?: string; catalogRevision?: number; connectionRevision?: number }
+ >
+ const assigned = parsed[connectionKey]
+ if (assigned) {
+ connectionStatus =
+ (assigned.status as CodexCatalogSnapshot['connectionStatus']) ?? connectionStatus
+ if (Number.isInteger(assigned.catalogRevision)) {
+ catalogRevision = assigned.catalogRevision as number
+ }
+ if (Number.isInteger(assigned.connectionRevision)) {
+ connectionRevision = assigned.connectionRevision as number
+ }
+ } else if (connectionKey !== 'deployment-default') {
+ connectionStatus = 'disconnected'
+ }
+ } catch {
+ return snapshotFromConfigMapError('malformed')
+ }
+ }
return {
flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',
- connectionStatus:
- (annotations[
- CODEX_CONNECTION_STATUS_ANNOTATION
- ] as CodexCatalogSnapshot['connectionStatus']) ?? null,
+ connectionStatus,
catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] ?? null,
catalogRevision,
connectionRevision,
diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.ts
index 73ed9d548..be518db34 100644
--- a/host-context-controller/src/types.ts
+++ b/host-context-controller/src/types.ts
@@ -361,6 +361,7 @@ export interface ContextCRD {
export interface HostModelSpec {
provider?: LlmProviderId
name?: string
+ connectionRef?: string
}
export interface HostAllowedModel {
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 70e701bcf..b09432d2f 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.278",
+ "version": "0.1.279",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.278",
+ "version": "0.1.279",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index b34ffdd5f..0888f4e9a 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.278",
+ "version": "0.1.279",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/config/configStore.test.ts b/mcp-host/src/config/configStore.test.ts
index 935a6d296..1b2aa7145 100644
--- a/mcp-host/src/config/configStore.test.ts
+++ b/mcp-host/src/config/configStore.test.ts
@@ -578,6 +578,7 @@ describe('ConfigStore — allowlist tier (R3)', () => {
expect(store.codexPolicyBinding()).toEqual({
catalogRevision: 7,
credentialRevision: 3,
+ connectionKey: 'deployment-default',
})
const handle = built.watch.active.get(ALLOWLIST_WATCH_KEY)
@@ -595,6 +596,7 @@ describe('ConfigStore — allowlist tier (R3)', () => {
expect(store.codexPolicyBinding()).toEqual({
catalogRevision: 8,
credentialRevision: 3,
+ connectionKey: 'deployment-default',
})
handle!.emit('DELETED', { metadata: { name: ALLOWLIST_CM } })
diff --git a/mcp-host/src/config/configStore.ts b/mcp-host/src/config/configStore.ts
index 6bd4c7e1d..fe952bc39 100644
--- a/mcp-host/src/config/configStore.ts
+++ b/mcp-host/src/config/configStore.ts
@@ -116,10 +116,12 @@ export interface AllowedModelEntry {
export type CodexPolicyBinding = {
catalogRevision: number
credentialRevision: number
+ connectionKey: string
}
export const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'
export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'
+export const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
export type ConfigStoreChangeHandler = (change: ConfigStoreChange) => void
@@ -132,6 +134,8 @@ export interface ConfigStoreOptions {
llmSecretRef: string | null
/** Configured LLM provider — selects which key inside the LLM Secret is exposed. */
provider: LlmProvider | null
+ /** Assigned Codex grant; defaults to deployment-default. */
+ connectionRef?: string | null
/**
* Name of the operator-managed LLM allowlist ConfigMap to watch (R3). When
* null/undefined the fourth tier is disabled entirely (no watch, no bootstrap)
@@ -555,7 +559,10 @@ export class ConfigStore {
metadata?: { annotations?: Record<string, string> }
}): boolean {
const modelsChanged = this.applyAllowlistData(cm.data ?? {})
- const nextBinding = parseCodexPolicyBinding(cm.metadata?.annotations)
+ const nextBinding = parseCodexPolicyBinding(
+ cm.metadata?.annotations,
+ this.opts.connectionRef?.trim() || 'deployment-default'
+ )
const bindingChanged = !codexBindingsEqual(this.codexBinding, nextBinding)
this.codexBinding = nextBinding
return modelsChanged || bindingChanged
@@ -912,14 +919,35 @@ function parseOptionalIntegerAnnotation(
}
function parseCodexPolicyBinding(
- annotations: Record<string, string> | undefined
+ annotations: Record<string, string> | undefined,
+ connectionKey = 'deployment-default'
): CodexPolicyBinding | null {
if (!annotations) return null
- const catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
- const credentialRevision = parseOptionalIntegerAnnotation(
+ let catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
+ let credentialRevision = parseOptionalIntegerAnnotation(
annotations,
CONNECTION_REVISION_ANNOTATION
)
+ const rawMap = annotations[CODEX_CONNECTIONS_ANNOTATION]
+ if (rawMap) {
+ try {
+ const parsed = JSON.parse(rawMap) as Record<
+ string,
+ { catalogRevision?: number; connectionRevision?: number }
+ >
+ const assigned = parsed[connectionKey]
+ if (
+ assigned &&
+ Number.isInteger(assigned.catalogRevision) &&
+ Number.isInteger(assigned.connectionRevision)
+ ) {
+ catalogRevision = assigned.catalogRevision as number
+ credentialRevision = assigned.connectionRevision as number
+ }
+ } catch {
+ return null
+ }
+ }
if (
catalogRevision === null ||
catalogRevision === 'invalid' ||
@@ -928,13 +956,17 @@ function parseCodexPolicyBinding(
) {
return null
}
- return { catalogRevision, credentialRevision }
+ return { catalogRevision, credentialRevision, connectionKey }
}
function codexBindingsEqual(a: CodexPolicyBinding | null, b: CodexPolicyBinding | null): boolean {
if (a === b) return true
if (!a || !b) return false
- return a.catalogRevision === b.catalogRevision && a.credentialRevision === b.credentialRevision
+ return (
+ a.catalogRevision === b.catalogRevision &&
+ a.credentialRevision === b.credentialRevision &&
+ a.connectionKey === b.connectionKey
+ )
}
/**
diff --git a/mcp-host/src/llm/codexPolicyBinding.ts b/mcp-host/src/llm/codexPolicyBinding.ts
index f560f5fee..36a19d8bc 100644
--- a/mcp-host/src/llm/codexPolicyBinding.ts
+++ b/mcp-host/src/llm/codexPolicyBinding.ts
@@ -5,6 +5,7 @@ const POLICY_HASH_RE = /^[a-f0-9]{64}$/
export type CodexPolicyBinding = {
catalogRevision: number
credentialRevision: number
+ connectionKey?: string
}
export type CodexAttemptPolicy = {
@@ -62,6 +63,7 @@ export function resolveCodexAttemptPolicy(input: {
model: input.model,
catalogRevision: binding.catalogRevision,
credentialRevision: binding.credentialRevision,
+ connectionKey: binding.connectionKey,
}),
}
}
diff --git a/mcp-host/src/llm/hostLlmBinding.test.ts b/mcp-host/src/llm/hostLlmBinding.test.ts
new file mode 100644
index 000000000..98af2abf2
--- /dev/null
+++ b/mcp-host/src/llm/hostLlmBinding.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest'
+import { assignedConnectionRef, hostPrimaryLlmBindingChanged } from './hostLlmBinding'
+
+describe('hostPrimaryLlmBindingChanged', () => {
+ it('treats a connectionRef swap as a credential-surface change', () => {
+ const change = hostPrimaryLlmBindingChanged(
+ {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'deployment-default',
+ secretRef: undefined,
+ },
+ {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'team-plus',
+ secretRef: undefined,
+ }
+ )
+ expect(change.providerChanged).toBe(false)
+ expect(change.modelChanged).toBe(false)
+ expect(change.secretRefChanged).toBe(false)
+ expect(change.connectionRefChanged).toBe(true)
+ })
+
+ it('does not treat a Phase 1 missing ref as a change from deployment-default', () => {
+ const change = hostPrimaryLlmBindingChanged(
+ {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: undefined,
+ },
+ {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'deployment-default',
+ }
+ )
+ expect(change.connectionRefChanged).toBe(false)
+ expect(assignedConnectionRef(undefined)).toBe('deployment-default')
+ })
+})
diff --git a/mcp-host/src/llm/hostLlmBinding.ts b/mcp-host/src/llm/hostLlmBinding.ts
new file mode 100644
index 000000000..ecc2148cc
--- /dev/null
+++ b/mcp-host/src/llm/hostLlmBinding.ts
@@ -0,0 +1,28 @@
+export type HostPrimaryLlmBinding = {
+ provider?: string | null
+ name?: string | null
+ connectionRef?: string | null
+ secretRef?: string | null
+}
+
+export function assignedConnectionRef(connectionRef?: string | null): string {
+ return connectionRef?.trim() || 'deployment-default'
+}
+
+export function hostPrimaryLlmBindingChanged(
+ previous: HostPrimaryLlmBinding | null | undefined,
+ next: HostPrimaryLlmBinding
+): {
+ providerChanged: boolean
+ modelChanged: boolean
+ secretRefChanged: boolean
+ connectionRefChanged: boolean
+} {
+ return {
+ providerChanged: previous?.provider !== next.provider,
+ modelChanged: previous?.name !== next.name,
+ secretRefChanged: previous?.secretRef !== next.secretRef,
+ connectionRefChanged:
+ assignedConnectionRef(previous?.connectionRef) !== assignedConnectionRef(next.connectionRef),
+ }
+}
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 5a2a5be62..14c63a7c8 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -67,6 +67,7 @@ import { FailoverEngine } from './llm/failover/engine'
import { llmFallbackTotal } from './llm/failover/metrics'
import { parseLlmPolicy } from './llm/failover/policy'
import type { FailoverSwitchEvent, FallbackEntry, LlmPolicy } from './llm/failover/types'
+import { hostPrimaryLlmBindingChanged } from './llm/hostLlmBinding'
import { PromptCache } from './llm/promptCache'
import { clerumPromptCacheInvalidationsTotal } from './llm/promptCacheMetrics'
import { ALL_PROVIDERS, type LlmProvider, descriptorFor, isLlmProvider } from './llm/registryCore'
@@ -631,6 +632,7 @@ async function ensureConfigStore(host: HostCRD): Promise<ConfigStore> {
hostRef: host.name,
llmSecretRef: host.spec.secretRef ?? null,
provider,
+ connectionRef: host.spec.model?.connectionRef ?? null,
allowlistConfigMapName: config.llmAllowlistConfigMapName,
// R5 — load the failover policy's referenced credential slots from the same
// LLM Secret (kept out of the effective env; read via fallbackSlotValue).
@@ -1156,9 +1158,23 @@ async function onHostChange(host: HostCRD): Promise<void> {
const contextChanged =
currentHost !== null && currentHost.spec.contextRef !== host.spec.contextRef
- const providerChanged = currentHost?.spec.model?.provider !== host.spec.model?.provider
- const secretRefChanged = currentHost?.spec.secretRef !== host.spec.secretRef
- const modelChanged = currentHost?.spec.model?.name !== host.spec.model?.name
+ const { providerChanged, secretRefChanged, modelChanged, connectionRefChanged } =
+ hostPrimaryLlmBindingChanged(
+ currentHost
+ ? {
+ provider: currentHost.spec.model?.provider,
+ name: currentHost.spec.model?.name,
+ connectionRef: currentHost.spec.model?.connectionRef,
+ secretRef: currentHost.spec.secretRef,
+ }
+ : null,
+ {
+ provider: host.spec.model?.provider,
+ name: host.spec.model?.name,
+ connectionRef: host.spec.model?.connectionRef,
+ secretRef: host.spec.secretRef,
+ }
+ )
if (contextChanged) {
// The old Context's authority must disappear before any asynchronous Host
@@ -1179,17 +1195,25 @@ async function onHostChange(host: HostCRD): Promise<void> {
refreshFailoverPolicy(host)
const fallbackSlotsChanged =
JSON.stringify(prevFallbackSlots) !== JSON.stringify(fallbackCredentialSlotsFor(currentPolicy))
- if (!configStore || providerChanged || secretRefChanged || fallbackSlotsChanged) {
- console.log('[Main] Rebuilding ConfigStore (provider/secretRef/failover slots changed)')
+ if (
+ !configStore ||
+ providerChanged ||
+ secretRefChanged ||
+ connectionRefChanged ||
+ fallbackSlotsChanged
+ ) {
+ console.log(
+ '[Main] Rebuilding ConfigStore (provider/secretRef/connectionRef/failover slots changed)'
+ )
await ensureConfigStore(host)
}
currentKeys = apiKeysFromConfigStore(configStore!)
- // R5.10 — only a primary credential-surface change (secretRef/provider) may
- // clear a sticky runtime cooldown; unrelated CR edits must not (see
+ // R5.10 — only a primary credential-surface change (secretRef/provider/grant)
+ // may clear a sticky runtime cooldown; unrelated CR edits must not (see
// initializeProvider). A `secretRefChanged` rebuilds the ConfigStore fresh, so
// the store.onChange clearCooldown path never fires for it — this covers it.
await initializeProvider(host, currentKeys, {
- llmConfigChanged: secretRefChanged || providerChanged,
+ llmConfigChanged: secretRefChanged || providerChanged || connectionRefChanged,
})
// PMC-2 — the cached `stable` tier embeds the model+provider runtime line
@@ -1198,7 +1222,7 @@ async function onHostChange(host: HostCRD): Promise<void> {
// keeps serving the OLD model:/provider: line until eviction (generation is
// correct — it uses the live provider — but the system prompt mislabels the
// model). This is deliberately OUTSIDE the personalization branch below.
- if (providerChanged || secretRefChanged || modelChanged) {
+ if (providerChanged || secretRefChanged || modelChanged || connectionRefChanged) {
promptCache?.invalidateAll('model_change')
}
diff --git a/mcp-host/src/types.ts b/mcp-host/src/types.ts
index 8f32a32e9..838673eda 100644
--- a/mcp-host/src/types.ts
+++ b/mcp-host/src/types.ts
@@ -11,6 +11,7 @@ import type { LlmProvider } from './llm/registryCore'
export interface ModelConfig {
provider: LlmProvider
name: string
+ connectionRef?: string
}
/** Phase 7–8: Workspace memory configuration. */
diff --git a/packages/llm-provider-attempt-contract/index.cjs b/packages/llm-provider-attempt-contract/index.cjs
index 8f2260d63..953bdb591 100644
--- a/packages/llm-provider-attempt-contract/index.cjs
+++ b/packages/llm-provider-attempt-contract/index.cjs
@@ -62,6 +62,7 @@ const CLAIMS_KEYS = new Set([
'policyHash',
'budgetReservationId',
'connectionRevision',
+ 'connectionId',
])
const AUTHORIZE_KEYS = new Set([
'providerAttemptId',
@@ -362,13 +363,14 @@ function hashCodexCompletionRequestV1(request) {
/**
* Grant-binding digest for a Codex authorize attempt. Must match
* control-api's expected hash: SHA-256 of lexicographic stableStringify of
- * { catalogRevision, credentialRevision, model, provider }.
+ * { catalogRevision, connectionKey, credentialRevision, model, provider }.
*/
function computeCodexPolicyHash(input) {
return createHash('sha256')
.update(
stableStringify({
catalogRevision: input.catalogRevision,
+ connectionKey: input.connectionKey || 'deployment-default',
credentialRevision: input.credentialRevision,
model: input.model,
provider: PROVIDER_ID,
@@ -432,6 +434,10 @@ function parseCodexExecutionTicketClaims(input) {
budgetReservationId: input.budgetReservationId,
connectionRevision: input.connectionRevision,
}
+ if (input.connectionId !== undefined) {
+ if (!isBoundedId(input.connectionId)) return fail('invalid', 'connectionId is invalid')
+ claims.connectionId = input.connectionId
+ }
if (input.recipeNamespace !== undefined) {
if (!isBoundedId(input.recipeNamespace)) return fail('invalid', 'recipeNamespace is invalid')
claims.recipeNamespace = input.recipeNamespace
diff --git a/packages/llm-provider-attempt-contract/index.d.ts b/packages/llm-provider-attempt-contract/index.d.ts
index 9878bf2e0..a984ba5be 100644
--- a/packages/llm-provider-attempt-contract/index.d.ts
+++ b/packages/llm-provider-attempt-contract/index.d.ts
@@ -91,6 +91,7 @@ export type CodexExecutionTicketClaims = {
policyHash: string
budgetReservationId: string
connectionRevision: number
+ connectionId?: string
}
export type AuthorizeAttemptResponse = {
@@ -141,6 +142,7 @@ export declare function computeCodexPolicyHash(input: {
model: string
catalogRevision: number
credentialRevision: number
+ connectionKey?: string
}): string
export declare function parseCodexExecutionTicketClaims(
input: unknown
diff --git a/packages/llm-provider-attempt-contract/index.test.cjs b/packages/llm-provider-attempt-contract/index.test.cjs
index 402a29ef7..4fcff9392 100644
--- a/packages/llm-provider-attempt-contract/index.test.cjs
+++ b/packages/llm-provider-attempt-contract/index.test.cjs
@@ -114,6 +114,7 @@ test('hash is SHA-256 of lexicographic stableStringify of the projection', () =>
test('computeCodexPolicyHash is SHA-256 of lexicographic stableStringify of the binding', () => {
const binding = {
catalogRevision: 4,
+ connectionKey: 'deployment-default',
credentialRevision: 3,
model: 'gpt-5.1',
provider: 'codex-subscription',
@@ -135,6 +136,7 @@ test('computeCodexPolicyHash is SHA-256 of lexicographic stableStringify of the
credentialRevision: 3,
catalogRevision: 4,
model: 'gpt-5.1',
+ connectionKey: 'deployment-default',
}),
expected
)
@@ -146,6 +148,15 @@ test('computeCodexPolicyHash is SHA-256 of lexicographic stableStringify of the
}),
expected
)
+ assert.notEqual(
+ contract.computeCodexPolicyHash({
+ model: 'gpt-5.1',
+ catalogRevision: 4,
+ credentialRevision: 3,
+ connectionKey: 'team-plus',
+ }),
+ expected
+ )
})
test('stableStringify sorts object keys and drops undefined like control-api', () => {
diff --git a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts
index c398f46d5..4ea716153 100644
--- a/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts
+++ b/tests/e2e/playwright/control-ui/codex-subscription-admission.spec.ts
@@ -2,46 +2,30 @@
* Codex subscription — Control UI admission and route guards.
*
* Contract:
- * - Entry point: application root `/` for authenticated journeys.
- * - Negative guard: unauthenticated deep link must not expose broker controls.
- * - UI: Codex subscription nav link appears only after capability is proven.
- * - Business signal: GET /connection succeeds with disconnected status when enabled.
+ * - Unauthenticated deep link to an agent model tab must not expose Connect.
+ * - LLM Models no longer owns ChatGPT assignment; the old URL has no Connect owner.
*/
import { expect, test } from '@playwright/test'
import { loginControlUiVisible } from '../helpers/visible-login'
test.describe('Codex subscription admission', () => {
- test('unauthenticated deep link is blocked by AuthGate', async ({ page }) => {
- // route guard: unauthenticated deep link must not expose broker controls
- await page.goto('/llm-models/providers/codex-subscription')
+ test('unauthenticated agent model deep link is blocked by AuthGate', async ({ page }) => {
+ await page.goto('/agents/e2e-codex-authoring/model')
await expect(page.getByLabel('Username or email')).toBeVisible({ timeout: 20_000 })
- await expect(page.getByTestId('codex-connection-status')).toHaveCount(0)
+ await expect(page.getByTestId('codex-agent-assignment')).toHaveCount(0)
await expect(page.getByRole('button', { name: 'Sign in with ChatGPT' })).toHaveCount(0)
})
- test('catalog surface exposes Codex subscription only after capability is proven', async ({
- page,
- }) => {
- // E2E_GUARDIAN_ENTRY_POINT
+ test('LLM Models no longer owns Codex assignment', async ({ page }) => {
await page.goto('/')
await loginControlUiVisible(page)
- const capability = page.waitForResponse(
- response =>
- response.url().includes('/api/v1/admin/llm/providers/codex-subscription/connection') &&
- response.request().method() === 'GET'
- )
await page.getByRole('link', { name: 'LLM Models' }).click()
await expect(page).toHaveURL(/\/llm-models/)
- const capabilityResponse = await capability
- expect(
- capabilityResponse.ok(),
- `capability probe must succeed, got ${capabilityResponse.status()}`
- ).toBe(true)
-
- const body = (await capabilityResponse.json()) as { status?: string }
- expect(body.status).toBe('disconnected')
+ await expect(page.getByRole('tab', { name: 'Codex subscription' })).toHaveCount(0)
- await expect(page.getByRole('tab', { name: 'Codex subscription' })).toBeVisible()
+ await page.goto('/llm-models/providers/codex-subscription')
+ await expect(page.getByRole('button', { name: 'Sign in with ChatGPT' })).toHaveCount(0)
+ await expect(page.getByTestId('codex-connection-status')).toHaveCount(0)
})
})
diff --git a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
index 9c5a21646..e0772f2be 100644
--- a/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
+++ b/tests/e2e/playwright/control-ui/codex-subscription-connection.spec.ts
@@ -1,66 +1,283 @@
/**
- * Codex subscription — Control UI connection journey.
+ * Codex subscription — assign, connect, sync, reuse, and revoke from the
+ * agent model page.
*
- * Contract:
- * - Entry point: application root `/` (E2E_GUARDIAN_ENTRY_POINT).
- * - Actions: visible login, open LLM Models, open the Codex subscription surface.
- * - Route/state: `/llm-models/providers/codex-subscription` after UI navigation.
- * - UI: Connect controls and Disconnected status; no tokens or account ids.
- * - Business signal: waitForResponse on GET /connection (capability + status).
- *
- * This journey does not complete ChatGPT OAuth. That is the real-upstream lane.
+ * Guardian: prove the route, not the destination. ChatGPT OAuth is the only
+ * mocked external boundary. Happy path starts at `/` and clicks through Agents.
+ * Direct `goto` of an agent model tab is not the happy-path entry.
*/
-import { expect, test } from '@playwright/test'
+import { type Page, expect, test } from '@playwright/test'
import { loginControlUiVisible } from '../helpers/visible-login'
+type CodexConnection = {
+ connectionKey: string
+ displayName?: string
+ status: string
+ catalogRevision: number
+ assignedHosts?: Array<{ name: string }>
+}
+
+async function openAgents(page: Page) {
+ await page.getByRole('link', { name: 'Agents', exact: true }).click()
+ await expect(page).toHaveURL(/\/(?:hosts|agents)$/)
+}
+
+async function openNamedAgent(page: Page, name: string) {
+ await page.getByRole('link', { name, exact: true }).click()
+ await expect(page).toHaveURL(new RegExp(`/((?:hosts|agents))/${name}(?:/|$)`))
+}
+
+async function openFirstAgent(page: Page): Promise<string> {
+ const named = page.locator('a[href*="/agents/"], a[href*="/hosts/"]').filter({
+ hasNotText: /Create|new/i,
+ })
+ await expect(named.first()).toBeVisible()
+ const href = (await named.first().getAttribute('href')) ?? ''
+ const match = href.match(/\/(?:hosts|agents)\/([^/]+)/)
+ const name = match?.[1] ?? ''
+ await named.first().click()
+ await expect(page).toHaveURL(/\/(?:hosts|agents)\/[^/]+/)
+ return decodeURIComponent(name)
+}
+
+async function openModelEditor(page: Page) {
+ await page.getByRole('tab', { name: /Model/i }).click()
+ await expect(page).toHaveURL(/\/(?:hosts|agents)\/[^/]+\/model/)
+ await expect(page.getByRole('heading', { name: /Model/i })).toBeVisible()
+ const edit = page.getByRole('button', { name: 'Edit', exact: true })
+ if (await edit.isVisible().catch(() => false)) {
+ await edit.click()
+ }
+ await expect(page.getByLabel('Provider')).toBeVisible()
+}
+
+async function chooseSubscriptionCredential(page: Page) {
+ await page.getByLabel('Provider').click()
+ await page.getByRole('option', { name: 'OpenAI', exact: true }).click()
+ await expect(page.getByRole('option', { name: 'OpenAI Codex Subscription' })).toHaveCount(0)
+ await page.getByRole('radio', { name: 'ChatGPT subscription' }).check()
+ await expect(page.getByTestId('codex-agent-assignment')).toBeVisible()
+}
+
+async function listConnections(page: Page): Promise<CodexConnection[]> {
+ const res = await page.request.get('/api/v1/admin/llm/providers/codex-subscription/connections')
+ expect(res.ok(), `list connections must succeed, got ${res.status()}`).toBe(true)
+ const body = (await res.json()) as { connections?: CodexConnection[] }
+ return body.connections ?? []
+}
+
test.describe('Codex subscription connection', () => {
- test('operator can open the Codex subscription connection surface', async ({ page }) => {
- // E2E_GUARDIAN_ENTRY_POINT
+ test('operator assigns a subscription from the agent model tab', async ({ page }) => {
await page.goto('/')
await loginControlUiVisible(page)
+ await openAgents(page)
+ const agentName = await openFirstAgent(page)
+ await openModelEditor(page)
+ await chooseSubscriptionCredential(page)
- await page.getByRole('link', { name: 'LLM Models' }).click()
- await expect(page).toHaveURL(/\/llm-models/)
+ const picker = page.getByLabel('ChatGPT subscription')
+ await expect(picker).toBeVisible()
+ await expect(page.getByLabel(/OpenAI API key/i)).toHaveCount(0)
- const connection = page.waitForResponse(
+ const connections = await listConnections(page)
+ const selectedKey = await picker.inputValue()
+ expect(selectedKey.length).toBeGreaterThan(0)
+ expect(connections.some(row => row.connectionKey === selectedKey)).toBe(true)
+ const selected = connections.find(row => row.connectionKey === selectedKey)
+ test.skip(
+ selected?.status !== 'connected',
+ 'assign+save requires a live ChatGPT grant as fixture setup'
+ )
+
+ const put = page.waitForResponse(
response =>
- response.url().includes('/api/v1/admin/llm/providers/codex-subscription/connection') &&
- response.request().method() === 'GET'
+ new RegExp(`/api/v1/admin/hosts/${agentName}$`).test(new URL(response.url()).pathname) &&
+ response.request().method() === 'PUT'
)
- await page.getByRole('tab', { name: 'Codex subscription' }).click()
- const response = await connection
- expect(response.ok(), `connection read must succeed, got ${response.status()}`).toBe(true)
- const body = (await response.json()) as { status?: string }
- expect(body.status).toBe('disconnected')
- await expect(page).toHaveURL(/\/llm-models\/providers\/codex-subscription/)
- await expect(page.getByRole('heading', { name: 'Codex subscription' })).toBeVisible()
- await expect(page.getByTestId('codex-connection-status')).toContainText(/Disconnected/)
- await expect(page.getByRole('button', { name: 'Sign in with ChatGPT' })).toBeVisible()
- await expect(page.getByText(/sk-|access token|account id/i)).toHaveCount(0)
+ const modelSelect = page.getByLabel(/^Model$/i)
+ const optionCount = await modelSelect
+ .locator('option')
+ .count()
+ .catch(() => 0)
+ if (optionCount > 1) {
+ await modelSelect.selectOption({ index: 1 })
+ }
+ await page.getByRole('button', { name: 'Save', exact: true }).click()
+ const response = await put
+ expect(response.ok(), `assign save must succeed, got ${response.status()}`).toBe(true)
+ const body = (await response.json()) as {
+ spec?: { model?: { provider?: string; connectionRef?: string } }
+ }
+ expect(body.spec?.model?.provider).toBe('codex-subscription')
+ expect(body.spec?.model?.connectionRef).toBe(selectedKey)
+
+ const echoed = await page.request.get(`/api/v1/admin/hosts/${encodeURIComponent(agentName)}`)
+ expect(echoed.ok()).toBe(true)
+ const host = (await echoed.json()) as {
+ spec?: { model?: { connectionRef?: string } }
+ }
+ expect(host.spec?.model?.connectionRef).toBe(selectedKey)
})
- test('Sign in with ChatGPT starts the ChatGPT device login and stays on control-ui', async ({
- page,
- }) => {
+ test('Sign in with ChatGPT starts device login from the agent page', async ({ page }) => {
await page.goto('/')
await loginControlUiVisible(page)
- await page.getByRole('link', { name: 'LLM Models' }).click()
- await page.getByRole('tab', { name: 'Codex subscription' }).click()
- await expect(page).toHaveURL(/\/llm-models\/providers\/codex-subscription/)
+ await openAgents(page)
+ await openFirstAgent(page)
+ await openModelEditor(page)
+ await chooseSubscriptionCredential(page)
const deviceStart = page.waitForResponse(
response =>
- response.url().includes('/api/v1/admin/llm/providers/codex-subscription/device/start') &&
- response.request().method() === 'POST'
+ /\/api\/v1\/admin\/llm\/providers\/codex-subscription\/(connections\/[^/]+\/)?device\/start$/.test(
+ new URL(response.url()).pathname
+ ) && response.request().method() === 'POST'
)
await page.getByRole('button', { name: 'Sign in with ChatGPT' }).click()
const response = await deviceStart
expect(response.ok(), `device start must succeed, got ${response.status()}`).toBe(true)
const body = (await response.json()) as { userCode?: string; verificationUri?: string }
- expect(body.userCode, 'ChatGPT sign-in must return a user code').toEqual(expect.any(String))
+ expect(body.userCode).toEqual(expect.any(String))
expect(body.verificationUri).toMatch(/^https:\/\/auth\.openai\.com\/codex\/device/)
await expect(page.getByTestId('codex-device-code')).toContainText(String(body.userCode))
- await expect(page).toHaveURL(/\/llm-models\/providers\/codex-subscription/)
+ await expect(page).toHaveURL(/\/(?:hosts|agents)\/[^/]+\/model/)
await expect(page).not.toHaveURL(/oauth\/authorize/)
})
+
+ test('Sync catalog is disabled until that grant is connected', async ({ page }) => {
+ await page.goto('/')
+ await loginControlUiVisible(page)
+ await openAgents(page)
+ await openFirstAgent(page)
+ await openModelEditor(page)
+ await chooseSubscriptionCredential(page)
+
+ const connections = await listConnections(page)
+ const picker = page.getByLabel('ChatGPT subscription')
+ const disconnected = connections.find(row => row.status !== 'connected')
+ if (disconnected) {
+ await picker.selectOption(disconnected.connectionKey)
+ await expect(page.getByRole('button', { name: 'Sync catalog' })).toBeDisabled()
+ }
+
+ const connected = connections.find(row => row.status === 'connected')
+ if (!connected) {
+ await expect(page.getByRole('button', { name: 'Sync catalog' })).toBeDisabled()
+ return
+ }
+
+ await picker.selectOption(connected.connectionKey)
+ const sync = page.waitForResponse(
+ response =>
+ new RegExp(
+ `/api/v1/admin/llm/providers/codex-subscription/connections/${connected.connectionKey}/catalog/sync$`
+ ).test(new URL(response.url()).pathname) && response.request().method() === 'POST'
+ )
+ await page.getByRole('button', { name: 'Sync catalog' }).click()
+ const response = await sync
+ expect(response.ok(), `catalog sync must succeed, got ${response.status()}`).toBe(true)
+ const body = (await response.json()) as {
+ added?: number
+ refreshed?: number
+ connection?: { catalogRevision?: number; connectionKey?: string }
+ }
+ expect(body.connection?.connectionKey).toBe(connected.connectionKey)
+ expect(typeof body.connection?.catalogRevision).toBe('number')
+ expect((body.added ?? 0) + (body.refreshed ?? 0)).toBeGreaterThanOrEqual(0)
+ })
+
+ test('operator reuses the same grant on a second agent', async ({ page }) => {
+ await page.goto('/')
+ await loginControlUiVisible(page)
+ await openAgents(page)
+ await openFirstAgent(page)
+ await openModelEditor(page)
+ await chooseSubscriptionCredential(page)
+
+ await page.getByRole('button', { name: 'New subscription' }).click()
+ const displayName = `e2e-shared-${Date.now().toString(36)}`
+ await page.getByLabel('New subscription name').fill(displayName)
+ const created = page.waitForResponse(
+ response =>
+ /\/api\/v1\/admin\/llm\/providers\/codex-subscription\/connections$/.test(
+ new URL(response.url()).pathname
+ ) && response.request().method() === 'POST'
+ )
+ await page.getByRole('button', { name: 'Create', exact: true }).click()
+ const createRes = await created
+ expect(createRes.ok()).toBe(true)
+ const createdBody = (await createRes.json()) as { connectionKey?: string }
+ const sharedKey = createdBody.connectionKey
+ expect(sharedKey).toEqual(expect.any(String))
+ await expect(page.getByLabel('ChatGPT subscription')).toHaveValue(String(sharedKey))
+
+ await openAgents(page)
+ const agents = page.locator('a[href*="/agents/"], a[href*="/hosts/"]').filter({
+ hasNotText: /Create|new/i,
+ })
+ const count = await agents.count()
+ test.skip(count < 2, 'reuse requires a second agent in the list')
+ await agents.nth(1).click()
+ await expect(page).toHaveURL(/\/(?:hosts|agents)\/[^/]+/)
+ await openModelEditor(page)
+ await chooseSubscriptionCredential(page)
+ await page.getByLabel('ChatGPT subscription').selectOption(String(sharedKey))
+ await expect(page.getByLabel('ChatGPT subscription')).toHaveValue(String(sharedKey))
+ await expect(page.getByRole('option', { name: displayName })).toHaveCount(1)
+ })
+
+ test('revoking a shared grant from the agent page fail-closes that key only', async ({
+ page,
+ }) => {
+ await page.goto('/')
+ await loginControlUiVisible(page)
+ await openAgents(page)
+ const firstName = await openFirstAgent(page)
+ await openModelEditor(page)
+ await chooseSubscriptionCredential(page)
+
+ await page.getByRole('button', { name: 'New subscription' }).click()
+ const displayName = `e2e-revoke-${Date.now().toString(36)}`
+ await page.getByLabel('New subscription name').fill(displayName)
+ const created = page.waitForResponse(
+ response =>
+ /\/api\/v1\/admin\/llm\/providers\/codex-subscription\/connections$/.test(
+ new URL(response.url()).pathname
+ ) && response.request().method() === 'POST'
+ )
+ await page.getByRole('button', { name: 'Create', exact: true }).click()
+ const createRes = await created
+ expect(createRes.ok()).toBe(true)
+ const createdBody = (await createRes.json()) as { connectionKey?: string }
+ const revokeKey = String(createdBody.connectionKey)
+
+ const revoke = page.waitForResponse(
+ response =>
+ new RegExp(
+ `/api/v1/admin/llm/providers/codex-subscription/connections/${revokeKey}/revoke$`
+ ).test(new URL(response.url()).pathname) && response.request().method() === 'POST'
+ )
+ await page.getByRole('button', { name: 'Revoke', exact: true }).click()
+ await expect(page.getByRole('alertdialog')).toBeVisible()
+ await expect(page.getByRole('alertdialog')).toContainText(/agent/i)
+ await page.getByRole('alertdialog').getByRole('button', { name: 'Revoke', exact: true }).click()
+ const response = await revoke
+ expect(response.ok(), `revoke must succeed, got ${response.status()}`).toBe(true)
+ const body = (await response.json()) as { status?: string; connectionKey?: string }
+ expect(body.status).toBe('revoked')
+ expect(body.connectionKey).toBe(revokeKey)
+ await expect(page).toHaveURL(new RegExp(`/((?:hosts|agents))/${firstName}/model`))
+ await expect(page.getByTestId('codex-connection-status')).toHaveText(/Revoked/i)
+ await expect(page.getByRole('button', { name: 'Sync catalog' })).toBeDisabled()
+
+ const after = await listConnections(page)
+ const revoked = after.find(row => row.connectionKey === revokeKey)
+ expect(revoked?.status).toBe('revoked')
+ const otherLive = after.find(
+ row => row.connectionKey !== revokeKey && row.status === 'connected'
+ )
+ if (otherLive) {
+ expect(otherLive.status).toBe('connected')
+ }
+ })
})
diff --git a/tests/e2e/playwright/control-ui/codex-subscription-host-workflow.spec.ts b/tests/e2e/playwright/control-ui/codex-subscription-host-workflow.spec.ts
index 7c6f5912d..ae808f918 100644
--- a/tests/e2e/playwright/control-ui/codex-subscription-host-workflow.spec.ts
+++ b/tests/e2e/playwright/control-ui/codex-subscription-host-workflow.spec.ts
@@ -5,7 +5,7 @@
* - Entry point: application root `/` (E2E_GUARDIAN_ENTRY_POINT).
* - Actions: visible login, open Agents, start Create agent, choose Codex.
* - Route/state: `/agents/new` Model & credentials step.
- * - UI: OpenAI Codex Subscription is selectable and requires no LLM secret.
+ * - UI: OpenAI + ChatGPT subscription is selectable and requires no LLM secret.
* - Business signal: waitForResponse on the allowlist catalog used to populate models.
*
* A live catalog model is not asserted: Sync/enable is the connection lane.
@@ -43,12 +43,15 @@ test.describe('Codex subscription host and workflow authoring', () => {
await expect(page.getByText('Model & credentials', { exact: true })).toBeVisible()
await page.getByLabel('Provider').click()
- await page.getByRole('option', { name: 'OpenAI Codex Subscription' }).click()
+ await page.getByRole('option', { name: 'OpenAI', exact: true }).click()
+ await expect(page.getByRole('option', { name: 'OpenAI Codex Subscription' })).toHaveCount(0)
+ await page.getByRole('radio', { name: 'ChatGPT subscription' }).check()
await expect(
page.getByText(/This provider authenticates through the Codex subscription/)
).toBeVisible()
await expect(page.getByLabel('Secret name')).toHaveCount(0)
await expect(page.getByLabel(/OpenAI API key/i)).toHaveCount(0)
+ await expect(page.getByTestId('codex-agent-assignment')).toBeVisible()
await expect(page.getByRole('button', { name: 'Next' })).toBeDisabled()
})
})
diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.json
index d42a06d2f..96d46d24d 100644
--- a/tests/e2e/playwright/package-lock.json
+++ b/tests/e2e/playwright/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.27",
+ "version": "0.1.28",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-playwright-tests",
- "version": "0.1.27",
+ "version": "0.1.28",
"devDependencies": {
"@playwright/test": "^1.50.0",
"@types/node": "^22.0.0"
diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.json
index 54f627fc8..6ee755903 100644
--- a/tests/e2e/playwright/package.json
+++ b/tests/e2e/playwright/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.27",
+ "version": "0.1.28",
"private": true,
"description": "Playwright E2E tests for Control UI and Desktop App",
"scripts": {
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 10c3a511b..d0b7c8711 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.302",
+ "version": "0.1.303",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.302",
+ "version": "0.1.303",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index a71d166fb..0aa0dc5f4 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.302",
+ "version": "0.1.303",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
new file mode 100644
index 000000000..1b32272f5
--- /dev/null
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest'
+import { parseAllowedModelsSnapshot } from './llmAllowedModelsSnapshot'
+
+function multiGrantConfigMap() {
+ return {
+ metadata: {
+ annotations: {
+ 'clerum.io/content-hash': 'aa',
+ 'clerum.io/catalog-revision': '1',
+ 'clerum.io/connection-revision': '1',
+ 'clerum.io/codex-connection-status': 'connected',
+ 'clerum.io/codex-enabled': 'true',
+ 'clerum.io/codex-connections': JSON.stringify({
+ 'deployment-default': {
+ status: 'revoked',
+ catalogRevision: 1,
+ connectionRevision: 9,
+ },
+ 'personal-pro': { status: 'connected', catalogRevision: 4, connectionRevision: 2 },
+ }),
+ },
+ },
+ data: {
+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex', stale: false }]),
+ },
+ }
+}
+
+describe('WRC parseAllowedModelsSnapshot per assigned connection', () => {
+ it('reads clerum.io/codex-connections instead of the flat status annotation', () => {
+ const snapshot = parseAllowedModelsSnapshot(multiGrantConfigMap())
+ expect(snapshot.connectionStatus).toBe('revoked')
+ expect(snapshot.connectionRevision).toBe(9)
+ })
+
+ it('can project a non-default grant when a recipe is later bound to one', () => {
+ const snapshot = parseAllowedModelsSnapshot(multiGrantConfigMap(), 'personal-pro')
+ expect(snapshot.connectionStatus).toBe('connected')
+ expect(snapshot.catalogRevision).toBe(4)
+ })
+})
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
index 26c3e63d1..06c018cac 100644
--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
@@ -7,6 +7,7 @@ export const CATALOG_REVISION_ANNOTATION = 'clerum.io/catalog-revision'
export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'
export const CODEX_CONNECTION_STATUS_ANNOTATION = 'clerum.io/codex-connection-status'
export const CODEX_ENABLED_ANNOTATION = 'clerum.io/codex-enabled'
+export const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'
export const ALLOWLIST_CONFIGMAP_NAMESPACE = process.env.CLERUM_MODEL_CONFIG_NAMESPACE ?? 'mcp-host'
export function snapshotFromConfigMapError(error: CodexSnapshotError): CodexCatalogSnapshot {
@@ -22,7 +23,10 @@ function parseOptionalIntegerAnnotation(
return Number.isInteger(parsed) ? parsed : 'invalid'
}
-export function parseAllowedModelsSnapshot(cm: V1ConfigMap | undefined): CodexCatalogSnapshot {
+export function parseAllowedModelsSnapshot(
+ cm: V1ConfigMap | undefined,
+ connectionKey = 'deployment-default'
+): CodexCatalogSnapshot {
if (!cm) return snapshotFromConfigMapError('missing')
const annotations = cm.metadata?.annotations ?? {}
const enabledModels = new Set<string>()
@@ -42,20 +46,44 @@ export function parseAllowedModelsSnapshot(cm: V1ConfigMap | undefined): CodexCa
return snapshotFromConfigMapError('malformed')
}
}
- const catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
- const connectionRevision = parseOptionalIntegerAnnotation(
+ let catalogRevision = parseOptionalIntegerAnnotation(annotations, CATALOG_REVISION_ANNOTATION)
+ let connectionRevision = parseOptionalIntegerAnnotation(
annotations,
CONNECTION_REVISION_ANNOTATION
)
if (catalogRevision === 'invalid' || connectionRevision === 'invalid') {
return snapshotFromConfigMapError('malformed')
}
+ let connectionStatus =
+ (annotations[CODEX_CONNECTION_STATUS_ANNOTATION] as CodexCatalogSnapshot['connectionStatus']) ??
+ null
+ const rawMap = annotations[CODEX_CONNECTIONS_ANNOTATION]
+ if (rawMap) {
+ try {
+ const parsed = JSON.parse(rawMap) as Record<
+ string,
+ { status?: string; catalogRevision?: number; connectionRevision?: number }
+ >
+ const assigned = parsed[connectionKey]
+ if (assigned) {
+ connectionStatus =
+ (assigned.status as CodexCatalogSnapshot['connectionStatus']) ?? connectionStatus
+ if (Number.isInteger(assigned.catalogRevision)) {
+ catalogRevision = assigned.catalogRevision as number
+ }
+ if (Number.isInteger(assigned.connectionRevision)) {
+ connectionRevision = assigned.connectionRevision as number
+ }
+ } else if (connectionKey !== 'deployment-default') {
+ connectionStatus = 'disconnected'
+ }
+ } catch {
+ return snapshotFromConfigMapError('malformed')
+ }
+ }
return {
flagEnabled: annotations[CODEX_ENABLED_ANNOTATION] === 'true',
- connectionStatus:
- (annotations[
- CODEX_CONNECTION_STATUS_ANNOTATION
- ] as CodexCatalogSnapshot['connectionStatus']) ?? null,
+ connectionStatus,
catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] ?? null,
catalogRevision,
connectionRevision,