Skip to content

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

TypeScript

fix(codex): persist recipe grant identity and close remaining review gaps

Alfredo Lopezae8ed558aebf
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index ab31d8f4d..6cfd7a2e4 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.511",
+ "version": "0.1.512",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.511",
+ "version": "0.1.512",
"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 fedc85b94..49f561047 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.511",
+ "version": "0.1.512",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index c57c74db8..23374cd77 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -252,7 +252,7 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
const provider = typeof raw.provider === 'string' ? raw.provider.trim() : ''
const model = typeof raw.model === 'string' ? raw.model.trim() : ''
const credentialSlot = typeof raw.credentialSlot === 'string' ? raw.credentialSlot.trim() : ''
- const connectionRef = typeof raw.connectionRef === 'string' ? raw.connectionRef.trim() : ''
+ let connectionRef = typeof raw.connectionRef === 'string' ? raw.connectionRef.trim() : ''
if (!targetRef || targetRef.length > MAX_ALLOWLIST_ENTRY_LENGTH || targetRef.includes('*')) {
res
.status(400)
@@ -281,20 +281,21 @@ function parsePromptTargets(value: unknown, res: Response): PluginWorkloadSdkPro
})
return null
}
- // The target only CHOOSES an existing Codex grant. Reject the missing /
- // unassigned / malformed key here; existence, connection status, and
- // model offer are re-validated against the catalog inside the upsert
- // transaction (fail closed on every unknown/revoked/not-offered case).
- try {
- if (!connectionRef || isCodexUnassignedConnectionKey(connectionRef)) {
- throw new Error('missing_connection_ref')
+ // Named keys must be well-formed. Missing or `unassigned` is allowed so
+ // a previously stored Codex target can be edited without inventing a
+ // grant. Spend still fail-closes at authorize until the operator picks
+ // a live connection. Malformed keys stay rejected.
+ if (connectionRef && !isCodexUnassignedConnectionKey(connectionRef)) {
+ try {
+ assertCodexConnectionKey(connectionRef)
+ } catch {
+ res.status(400).json({
+ error: `promptTargets[${index}].connectionRef must name an existing Codex subscription connection`,
+ })
+ return null
}
- assertCodexConnectionKey(connectionRef)
- } catch {
- res.status(400).json({
- error: `promptTargets[${index}].connectionRef must name an existing Codex subscription connection`,
- })
- return null
+ } else {
+ connectionRef = ''
}
} else {
if (connectionRef) {
@@ -561,17 +562,17 @@ export function createAdminPluginWorkloadSdkRouter(
// Codex (oauth-broker) targets are validated against the chosen
// grant's per-connection catalog, not the flat `llm_allowed_models`
// union: only a model offered AND enabled (non-stale) on that
- // exact connected grant may be authorized. Unknown, unassigned,
- // revoked, and not-offered all fail closed with a stable error.
- // No Pieza D toleration applies — a Codex grant that lost a model
- // must be re-pointed explicitly, never silently kept.
+ // exact connected grant may be authorized. Missing/unassigned is
+ // allowed so a stored target remains editable; spend still
+ // fail-closes at authorize. Named unknown/revoked/not-offered
+ // keys fail closed. No Pieza D silent keep.
for (const target of promptTargets) {
if (!isBrokerBackedProvider(target.provider)) continue
- const allowed = await isCodexAssignmentAllowed(
- db,
- target.connectionRef ?? '',
- target.model
- )
+ const connectionRef = target.connectionRef ?? ''
+ if (!connectionRef || isCodexUnassignedConnectionKey(connectionRef)) {
+ continue
+ }
+ const allowed = await isCodexAssignmentAllowed(db, connectionRef, target.model)
if (!allowed) {
throw new GrantModelGateError({
error: 'codex_connection_not_allowed',
diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.ts
index 78fcfcc06..c446fb731 100644
--- a/control-api/src/routes/admin/recipes.ts
+++ b/control-api/src/routes/admin/recipes.ts
@@ -15,6 +15,12 @@ import {
type SecretOwnership,
parseSecretOwnership,
} from '../../secretOwnership.js'
+import {
+ CODEX_CONNECTION_REF_ANNOTATION,
+ assertCodexConnectionKey,
+ isCodexUnassignedConnectionKey,
+ readHostCodexConnectionRef,
+} from '../../services/codexSubscriptionConnection.js'
import {
ensureRegistryPullSecrets,
platformWorkloadNamespaces,
@@ -159,7 +165,12 @@ function parseWorkflowSecretOwnershipBody(
}
export interface RecipeBody {
- metadata?: { name?: string; namespace?: string; labels?: Record<string, unknown> }
+ metadata?: {
+ name?: string
+ namespace?: string
+ labels?: Record<string, unknown>
+ annotations?: Record<string, unknown>
+ }
spec?: Record<string, unknown>
}
@@ -1234,11 +1245,60 @@ function validateRecipeBody(body: RecipeBody): ValidationError[] {
return errors
}
+function recipeUsesCodexBroker(spec?: Record<string, unknown>): boolean {
+ const agent = spec?.agent
+ if (!agent || typeof agent !== 'object' || Array.isArray(agent)) return false
+ return (agent as { provider?: unknown }).provider === 'codex-subscription'
+}
+
+function readRequestedCodexRecipeGrant(body: RecipeBody): string {
+ const raw = body.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
+ return readHostCodexConnectionRef(typeof raw === 'string' ? raw : '')
+}
+
+function validateCodexRecipeGrant(body: RecipeBody): ValidationError[] {
+ if (!recipeUsesCodexBroker(body.spec)) return []
+ const key = readRequestedCodexRecipeGrant(body)
+ if (isCodexUnassignedConnectionKey(key)) {
+ return [
+ {
+ field: `metadata.annotations.${CODEX_CONNECTION_REF_ANNOTATION}`,
+ rule: 'codexRecipeGrantRequired',
+ message: 'Codex subscription recipes must choose an existing ChatGPT grant',
+ },
+ ]
+ }
+ try {
+ assertCodexConnectionKey(key)
+ } catch {
+ return [
+ {
+ field: `metadata.annotations.${CODEX_CONNECTION_REF_ANNOTATION}`,
+ rule: 'codexRecipeGrantInvalid',
+ message: 'clerum.io/codex-connection-ref is not a valid connection key',
+ },
+ ]
+ }
+ return []
+}
+
+function sanitizeRecipeCodexAnnotation(body: RecipeBody): Record<string, string> {
+ if (!recipeUsesCodexBroker(body.spec)) {
+ // Explicit empty value so mergeAnnotationsForReplace does not keep a
+ // leftover clerum.io/codex-connection-ref from a previous Codex write.
+ return { [CODEX_CONNECTION_REF_ANNOTATION]: '' }
+ }
+ const key = readRequestedCodexRecipeGrant(body)
+ return {
+ [CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(key) ? '' : key,
+ }
+}
+
function sanitizeRecipeBody(
body: RecipeBody,
currentLabels?: Record<string, string>
): {
- metadata: { name: string; labels?: Record<string, string> }
+ metadata: { name: string; labels?: Record<string, string>; annotations: Record<string, string> }
spec: Record<string, unknown>
} {
const metadata = { ...(body.metadata ?? {}) }
@@ -1258,6 +1318,7 @@ function sanitizeRecipeBody(
metadata: {
name: metadata.name as string,
...(sanitizedLabels ? { labels: sanitizedLabels } : {}),
+ annotations: sanitizeRecipeCodexAnnotation(body),
},
spec: body.spec as Record<string, unknown>,
}
@@ -1391,7 +1452,10 @@ async function checkRecipeNameAvailable(
async function updateRecipeWithConflictRetry(
gateway: K8sGateway,
name: string,
- body: { metadata?: { labels?: Record<string, string> }; spec: Record<string, unknown> },
+ body: {
+ metadata?: { labels?: Record<string, string>; annotations?: Record<string, string> }
+ spec: Record<string, unknown>
+ },
namespace: string
): Promise<unknown> {
let lastConflict: unknown
@@ -1540,6 +1604,11 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {
res.status(422).json({ valid: false, errors })
return
}
+ const grantErrors = validateCodexRecipeGrant(body)
+ if (grantErrors.length > 0) {
+ res.status(422).json({ valid: false, errors: grantErrors })
+ return
+ }
const egressErrors = await validateWorkflowRecipeEgressPreflight(body.spec)
if (egressErrors.length > 0) {
res.status(422).json({ valid: false, errors: egressErrors })
@@ -1721,6 +1790,11 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {
res.status(422).json({ errors })
return
}
+ const grantErrors = validateCodexRecipeGrant(body)
+ if (grantErrors.length > 0) {
+ res.status(422).json({ errors: grantErrors })
+ return
+ }
const egressErrors = await validateWorkflowRecipeEgressPreflight(body.spec)
if (egressErrors.length > 0) {
res.status(422).json({ errors: egressErrors })
@@ -1826,6 +1900,11 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {
res.status(422).json({ errors })
return
}
+ const grantErrors = validateCodexRecipeGrant(body)
+ if (grantErrors.length > 0) {
+ res.status(422).json({ errors: grantErrors })
+ return
+ }
const egressErrors = await validateWorkflowRecipeEgressPreflight(body.spec)
if (egressErrors.length > 0) {
res.status(422).json({ errors: egressErrors })
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index 654c17e86..8753e72d4 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -257,18 +257,26 @@ export async function authorizeLlmProviderAttempt(
return resolvedDeps.withTransaction(async tx => {
const db: DbClient = tx
const connection = await resolvedDeps.getConnection(db, connectionKey)
+ // Terminal grant failures must not look like a retryable proxy outage.
+ // Missing, revoked, and auth-rejected rows require a new grant or
+ // operator re-auth — failover onto another provider is the wrong recovery.
if (
!connection ||
- connection.status !== 'connected' ||
connection.revokedAt ||
+ connection.status === 'revoked' ||
+ connection.status === 'reauth_required' ||
connection.catalogStatus === 'auth-rejected'
) {
throw new LlmProviderAttemptAuthorizeError(
- 'connection_unavailable',
- 'Codex subscription connection is not usable'
+ 'no_grant',
+ 'Codex subscription grant is missing, revoked, or requires re-authentication'
)
}
- if (connection.catalogStatus === 'unavailable' || connection.catalogStatus === 'never_synced') {
+ if (
+ connection.status !== 'connected' ||
+ connection.catalogStatus === 'unavailable' ||
+ connection.catalogStatus === 'never_synced'
+ ) {
throw new LlmProviderAttemptAuthorizeError(
'connection_unavailable',
'Codex subscription catalog is not ready'
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index 0a184c7dc..61524d097 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -659,27 +659,31 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
})
- it('rejects a Codex target without a connectionRef', async () => {
+ it('accepts a stored Codex target without connectionRef as unassigned', async () => {
+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g-legacy' } as never)
const { connectionRef: _omitted, ...targetWithoutConnection } =
codexGrantBody.promptTargets[0]!
const res = await request(buildApp())
.post('/admin/plugin-workload-sdk/grants')
.send({ ...codexGrantBody, promptTargets: [targetWithoutConnection] })
- expect(res.status).toBe(400)
- expect(res.body.error).toContain('connectionRef')
- expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ expect(res.status).toBe(200)
+ expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()
+ expect(patchResourceAnnotations).not.toHaveBeenCalled()
+ expect(sdkDb.upsertGrant).toHaveBeenCalled()
})
- it('rejects the unassigned sentinel as a Codex connection choice', async () => {
+ it('accepts the unassigned sentinel as a stored Codex target', async () => {
+ vi.mocked(sdkDb.upsertGrant).mockResolvedValue({ id: 'g-legacy' } as never)
const res = await request(buildApp())
.post('/admin/plugin-workload-sdk/grants')
.send({
...codexGrantBody,
promptTargets: [{ ...codexGrantBody.promptTargets[0]!, connectionRef: 'unassigned' }],
})
- expect(res.status).toBe(400)
- expect(res.body.error).toContain('connectionRef')
- expect(sdkDb.upsertGrant).not.toHaveBeenCalled()
+ expect(res.status).toBe(200)
+ expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()
+ expect(patchResourceAnnotations).not.toHaveBeenCalled()
+ expect(sdkDb.upsertGrant).toHaveBeenCalled()
})
it('rejects a static credentialSlot on a Codex (oauth-broker) target', async () => {
diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.ts
index 98d105ff8..28aeef9b6 100644
--- a/control-api/test/routes.adminRecipes.test.ts
+++ b/control-api/test/routes.adminRecipes.test.ts
@@ -248,6 +248,65 @@ describe.sequential('routes/admin/recipes', () => {
expect(res.body.metadata.namespace).toBe(SANDBOX_NS)
})
+ function codexSubscriptionRecipe(name: string, connectionRef?: string) {
+ return {
+ metadata: {
+ name,
+ ...(connectionRef !== undefined
+ ? { annotations: { 'clerum.io/codex-connection-ref': connectionRef } }
+ : {}),
+ },
+ spec: {
+ agent: { provider: 'codex-subscription', model: 'gpt-5.1' },
+ triggers: { onDemand: { allowedActors: ['user'] } },
+ steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],
+ },
+ }
+ }
+
+ it('POST /admin/recipes — stamps a named Codex grant annotation', async () => {
+ const res = await api
+ .post('/admin/recipes')
+ .send(codexSubscriptionRecipe('codex-granted', 'team-plus'))
+ .expect(201)
+ expect(res.body.metadata.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ })
+ })
+
+ it('POST /admin/recipes — rejects a Codex recipe without a named grant', async () => {
+ const res = await api
+ .post('/admin/recipes')
+ .send(codexSubscriptionRecipe('codex-missing'))
+ .expect(422)
+ expect(res.body.errors[0].rule).toBe('codexRecipeGrantRequired')
+ })
+
+ it('POST /admin/recipes/validate — rejects a Codex recipe with an unassigned grant', async () => {
+ const res = await api
+ .post('/admin/recipes/validate')
+ .send(codexSubscriptionRecipe('codex-unassigned', 'unassigned'))
+ .expect(422)
+ expect(res.body.valid).toBe(false)
+ expect(res.body.errors[0].rule).toBe('codexRecipeGrantRequired')
+ })
+
+ it('PUT /admin/recipes/:name — clears a leftover Codex grant when the agent is no longer Codex', async () => {
+ await api
+ .post('/admin/recipes')
+ .send(codexSubscriptionRecipe('codex-then-openai', 'team-plus'))
+ .expect(201)
+ const res = await api
+ .put('/admin/recipes/codex-then-openai')
+ .send({
+ spec: { workloads: [{ id: 'svc', type: 'deployment', image: 'my-image:latest' }] },
+ })
+ .expect(200)
+ expect(res.body.metadata.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': '',
+ })
+ })
+
it('POST /admin/recipes — accepts declared cluster-local sibling egressBindings', async () => {
const res = await api
.post('/admin/recipes')
diff --git a/control-api/test/services.codexSubscriptionCatalog.test.ts b/control-api/test/services.codexSubscriptionCatalog.test.ts
index 08b7bb0d8..2e111d5a1 100644
--- a/control-api/test/services.codexSubscriptionCatalog.test.ts
+++ b/control-api/test/services.codexSubscriptionCatalog.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest'
import {
createCodexCatalogTransportFromEnv,
createCodexProxyCatalogTransport,
+ isCodexAssignmentAllowed,
pickCodexGrantModel,
planCodexCatalogReconcile,
syncCodexSubscriptionCatalog,
@@ -216,3 +217,73 @@ describe('Codex proxy catalog transport', () => {
})
})
})
+
+describe('isCodexAssignmentAllowed', () => {
+ function connectionRow(overrides: Record<string, unknown> = {}) {
+ return {
+ id: '11111111-1111-4111-8111-111111111111',
+ connection_key: 'team-plus',
+ display_name: 'Team Plus',
+ default_model: 'gpt-5.1',
+ created_by: null,
+ status: 'connected',
+ credential_revision: 1,
+ catalog_revision: 4,
+ account_fingerprint: 'fp',
+ catalog_status: 'ready',
+ catalog_synced_at: new Date(),
+ last_refresh_at: new Date(),
+ last_auth_at: new Date(),
+ refresh_lock_token: null,
+ refresh_lock_expires_at: null,
+ revoked_at: null,
+ created_at: new Date(),
+ updated_at: new Date(),
+ ...overrides,
+ }
+ }
+
+ it('allows a connected ready grant that offers an enabled model', async () => {
+ const db = {
+ query: vi
+ .fn()
+ .mockResolvedValueOnce({ rows: [connectionRow()] })
+ .mockResolvedValueOnce({ rows: [{ enabled: true, stale: false }] }),
+ }
+ await expect(isCodexAssignmentAllowed(db as never, 'team-plus', 'gpt-5.1')).resolves.toBe(true)
+ })
+
+ it('rejects unassigned, revoked, stale, and not-ready grants', async () => {
+ await expect(
+ isCodexAssignmentAllowed({ query: vi.fn() } as never, 'unassigned', 'gpt-5.1')
+ ).resolves.toBe(false)
+
+ const revoked = {
+ query: vi.fn().mockResolvedValueOnce({
+ rows: [connectionRow({ status: 'revoked', revoked_at: new Date() })],
+ }),
+ }
+ await expect(isCodexAssignmentAllowed(revoked as never, 'team-plus', 'gpt-5.1')).resolves.toBe(
+ false
+ )
+
+ const stale = {
+ query: vi
+ .fn()
+ .mockResolvedValueOnce({ rows: [connectionRow()] })
+ .mockResolvedValueOnce({ rows: [{ enabled: true, stale: true }] }),
+ }
+ await expect(isCodexAssignmentAllowed(stale as never, 'team-plus', 'gpt-5.1')).resolves.toBe(
+ false
+ )
+
+ const unavailable = {
+ query: vi.fn().mockResolvedValueOnce({
+ rows: [connectionRow({ catalog_status: 'unavailable' })],
+ }),
+ }
+ await expect(
+ isCodexAssignmentAllowed(unavailable as never, 'team-plus', 'gpt-5.1')
+ ).resolves.toBe(false)
+ })
+})
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
index a407b4de0..176bae6dc 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
@@ -161,18 +161,31 @@ describe('authorizeLlmProviderAttempt', () => {
).rejects.toMatchObject({ code: 'invalid_request' })
})
- it('rejects disconnected and reauth connections as connection_unavailable', async () => {
+ it('rejects disconnected catalogs as connection_unavailable', async () => {
vi.mocked(current.getConnection).mockResolvedValueOnce(
connection({ status: 'disconnected' }) as never
)
await expect(authorizeLlmProviderAttempt(claims(), body(), current)).rejects.toMatchObject({
code: 'connection_unavailable',
})
+ })
+
+ it('rejects reauth and revoked grants as no_grant', async () => {
vi.mocked(current.getConnection).mockResolvedValueOnce(
connection({ status: 'reauth_required' }) as never
)
await expect(authorizeLlmProviderAttempt(claims(), body(), current)).rejects.toMatchObject({
- code: 'connection_unavailable',
+ code: 'no_grant',
+ })
+ vi.mocked(current.getConnection).mockResolvedValueOnce(
+ connection({ status: 'revoked', revokedAt: new Date() }) as never
+ )
+ await expect(authorizeLlmProviderAttempt(claims(), body(), current)).rejects.toMatchObject({
+ code: 'no_grant',
+ })
+ vi.mocked(current.getConnection).mockResolvedValueOnce(null)
+ await expect(authorizeLlmProviderAttempt(claims(), body(), current)).rejects.toMatchObject({
+ code: 'no_grant',
})
})
@@ -267,10 +280,10 @@ describe('authorizeLlmProviderAttempt', () => {
await expect(
authorizeLlmProviderAttempt(claims({ hostRefs: ['agent-a'] }), body(), shared)
- ).rejects.toMatchObject({ code: 'connection_unavailable' })
+ ).rejects.toMatchObject({ code: 'no_grant' })
await expect(
authorizeLlmProviderAttempt(claims({ hostRefs: ['agent-b'] }), body(), shared)
- ).rejects.toMatchObject({ code: 'connection_unavailable' })
+ ).rejects.toMatchObject({ code: 'no_grant' })
const live = await authorizeLlmProviderAttempt(
claims({ hostRefs: ['agent-c'] }),
diff --git a/control-ui/components/RecipeEditor.tsx b/control-ui/components/RecipeEditor.tsx
index 990188330..1ed943690 100644
--- a/control-ui/components/RecipeEditor.tsx
+++ b/control-ui/components/RecipeEditor.tsx
@@ -23,9 +23,17 @@ import {
updateRecipe,
validateRecipeServer,
} from '../lib/api'
+import {
+ CODEX_CONNECTION_REF_ANNOTATION,
+ CODEX_UNASSIGNED_CONNECTION_KEY,
+ type CodexSubscriptionConnectionView,
+ isAssignableCodexGrant,
+ listCodexSubscriptionConnections,
+} from '../lib/codexSubscription'
import { analyzeWorkflowRecipeEgress } from '../lib/egressModel'
import type { EgressBinding, EgressEditorStatus } from '../lib/egressModel'
-import { brokerBackedRecipeAuthoringError } from '../lib/llm'
+import { OPENAI_SUBSCRIPTION_PROVIDER, brokerBackedRecipeAuthoringError } from '../lib/llm'
+import { credentialSelectValue, parseCredentialSelect } from '../lib/llmCredentialSelect'
import { DEFAULT_OPERATOR_DEFAULTS, applyDefaults } from '../lib/recipeDefaults'
import {
type RecipeSecretNamespaces,
@@ -41,6 +49,7 @@ import { validateRecipe } from '../lib/recipeValidator'
import { CreateFlowPanel } from './CreateFlowPanel'
import { CreateStepFlow } from './CreateStepFlow'
import { EgressEditor } from './EgressEditor'
+import { LlmSecretSelect, type LlmSecretSelectOption } from './LlmSecretSelect'
import { RecipeDefaultsPanel } from './RecipeDefaultsPanel'
import { WorkflowAccessPanel } from './WorkflowAccessPanel'
@@ -80,6 +89,32 @@ function checkPolicyL1(parsed: { spec?: unknown } | null): ServerValidationError
return null
}
+function readRecipeAgentProvider(spec: unknown): string {
+ if (!spec || typeof spec !== 'object' || Array.isArray(spec)) return ''
+ const agent = (spec as { agent?: unknown }).agent
+ if (!agent || typeof agent !== 'object' || Array.isArray(agent)) return ''
+ return typeof (agent as { provider?: unknown }).provider === 'string'
+ ? (agent as { provider: string }).provider.trim()
+ : ''
+}
+
+function readRecipeCodexGrantAnnotation(
+ resource?: { metadata?: { annotations?: Record<string, string> } } | null
+): string {
+ const raw = resource?.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
+ return typeof raw === 'string' ? raw.trim() : ''
+}
+
+function recipeGrantAnnotations(provider: string, connectionRef: string): Record<string, string> {
+ if (provider !== OPENAI_SUBSCRIPTION_PROVIDER) {
+ return { [CODEX_CONNECTION_REF_ANNOTATION]: '' }
+ }
+ const parsed = parseCredentialSelect(credentialSelectValue('', connectionRef))
+ return {
+ [CODEX_CONNECTION_REF_ANNOTATION]: parsed.kind === 'subscription' ? parsed.connectionKey : '',
+ }
+}
+
type TransportWorkloadEditorTarget = {
index: number
id: string
@@ -1545,6 +1580,24 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
cancelled = true
}
}, [])
+
+ useEffect(() => {
+ let cancelled = false
+ void listCodexSubscriptionConnections()
+ .then(rows => {
+ if (!cancelled) setCodexConnections(rows)
+ })
+ .catch(() => {
+ if (!cancelled) setCodexConnections([])
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [])
+
+ useEffect(() => {
+ setCodexConnectionRef(readRecipeCodexGrantAnnotation(currentInitial))
+ }, [currentInitial])
const secretNamespaces = useMemo(
() =>
resolveRecipeSecretNamespaces({
@@ -1560,6 +1613,10 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
}
return EXAMPLE_JSON
})
+ const [codexConnections, setCodexConnections] = useState<CodexSubscriptionConnectionView[]>([])
+ const [codexConnectionRef, setCodexConnectionRef] = useState(() =>
+ readRecipeCodexGrantAnnotation(initial)
+ )
const [step, setStep] = useState<Step>('input')
const [validation, setValidation] = useState<ValidationResult | null>(null)
@@ -1603,6 +1660,43 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
}
}, [jsonInput])
+ const isCodexRecipe = useMemo(() => {
+ try {
+ const parsed = JSON.parse(jsonInput) as { spec?: unknown }
+ return readRecipeAgentProvider(parsed.spec) === OPENAI_SUBSCRIPTION_PROVIDER
+ } catch {
+ return false
+ }
+ }, [jsonInput])
+
+ const codexGrantOptions = useMemo<LlmSecretSelectOption[]>(() => {
+ const options: LlmSecretSelectOption[] = codexConnections
+ .filter(isAssignableCodexGrant)
+ .map(row => ({
+ group: 'ChatGPT subscriptions',
+ value: credentialSelectValue('', row.connectionKey),
+ label: row.displayName || row.connectionKey,
+ meta: 'ChatGPT subscription',
+ providers: [{ id: 'codex-subscription', label: 'ChatGPT' }],
+ }))
+ if (
+ codexConnectionRef &&
+ codexConnectionRef !== CODEX_UNASSIGNED_CONNECTION_KEY &&
+ !codexConnections.some(
+ row => row.connectionKey === codexConnectionRef && isAssignableCodexGrant(row)
+ )
+ ) {
+ options.unshift({
+ group: 'ChatGPT subscriptions',
+ value: credentialSelectValue('', codexConnectionRef),
+ label: `${codexConnectionRef} (unavailable)`,
+ meta: 'ChatGPT subscription',
+ providers: [{ id: 'codex-subscription', label: 'ChatGPT' }],
+ })
+ }
+ return options
+ }, [codexConnections, codexConnectionRef])
+
const deploying = deployPhase !== 'idle'
// If the resolved recipe-secret namespaces change after refs were detected
@@ -1675,6 +1769,10 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
name: string
namespace?: string
}
+ const grantAnnotations = recipeGrantAnnotations(
+ readRecipeAgentProvider(specToUse),
+ codexConnectionRef
+ )
try {
// Resolve namespaces before grants fallback below. Secret values are not
@@ -1692,7 +1790,7 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
// L2 decides if the CRD is structurally and policy-valid. Missing
// declarative Secret refs come back as pending credentials and do not
// block creation; real validation errors still fail closed here.
- const brokerError = brokerBackedRecipeAuthoringError(specToUse)
+ const brokerError = brokerBackedRecipeAuthoringError(specToUse, codexConnectionRef)
if (brokerError) {
setServerValidation({
valid: false,
@@ -1704,7 +1802,7 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
setDeployPhase('validating')
const l2 = await validateRecipeServer(
{
- metadata: { name: bodyMeta.name },
+ metadata: { name: bodyMeta.name, annotations: grantAnnotations },
spec: specToUse,
},
{ mode: isEdit ? 'edit' : 'create' }
@@ -1717,7 +1815,10 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
if (isEdit) {
setDeployPhase('creating')
- await updateRecipe(name, { spec: specToUse })
+ await updateRecipe(name, {
+ spec: specToUse,
+ metadata: { annotations: grantAnnotations },
+ })
setDetectedSecrets([])
// Edit-mode workflow access is already persisted live by the panel on
// each click; nothing to do here.
@@ -1730,7 +1831,10 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
// side (Phase 8 split). Response body carries the resolved namespace
// so the grants PUT can target it exactly without client inference.
setDeployPhase('creating')
- const created = await createRecipe({ metadata: { name }, spec: specToUse })
+ const created = await createRecipe({
+ metadata: { name, annotations: grantAnnotations },
+ spec: specToUse,
+ })
setDetectedSecrets([])
if (
@@ -2419,6 +2523,27 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)
/>
))}
+ {step === 'confirm' && isCodexRecipe ? (
+ <div className="cu-recipe-status-panel" data-testid="codex-recipe-grant">
+ <div style={{ fontWeight: 700, marginBottom: 8 }}>ChatGPT grant</div>
+ <p style={{ margin: '0 0 10px', color: 'var(--cu-text-muted)' }}>
+ Choose an existing ChatGPT grant. The recipe stores it as{' '}
+ <code>clerum.io/codex-connection-ref</code>.
+ </p>
+ <LlmSecretSelect
+ id="codex-recipe-grant"
+ ariaLabel="ChatGPT grant"
+ value={credentialSelectValue('', codexConnectionRef)}
+ onChange={value => {
+ const parsed = parseCredentialSelect(value)
+ setCodexConnectionRef(parsed.kind === 'subscription' ? parsed.connectionKey : '')
+ }}
+ options={codexGrantOptions}
+ placeholder="Choose a ChatGPT grant"
+ />
+ </div>
+ ) : null}
+
{/* Policy banner — appears when L1 (client) or L2 (server) rejects. */}
{step === 'confirm' && (l1Live || serverValidationMessages.length > 0) && (
<div className="cu-recipe-status-panel cu-recipe-status-panel--error" role="alert">
diff --git a/control-ui/components/__tests__/RecipeEditor.test.tsx b/control-ui/components/__tests__/RecipeEditor.test.tsx
index 8684afd9e..778a87b48 100644
--- a/control-ui/components/__tests__/RecipeEditor.test.tsx
+++ b/control-ui/components/__tests__/RecipeEditor.test.tsx
@@ -9,6 +9,28 @@ import { RecipeEditor } from '../RecipeEditor'
import { ToastProvider } from '../Toast'
// vi.mock is hoisted before imports, factory runs lazily
+vi.mock('../../lib/codexSubscription', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../lib/codexSubscription')>()
+ return {
+ ...actual,
+ listCodexSubscriptionConnections: vi.fn().mockResolvedValue([
+ {
+ connectionKey: 'team-plus',
+ displayName: 'Team Plus',
+ status: 'connected',
+ catalogStatus: 'ready',
+ credentialRevision: 1,
+ catalogRevision: 1,
+ accountFingerprint: 'fp',
+ catalogSyncedAt: '2026-08-01T00:00:00.000Z',
+ lastRefreshAt: null,
+ lastAuthAt: '2026-08-01T00:00:00.000Z',
+ refreshLockHeld: false,
+ },
+ ]),
+ }
+})
+
vi.mock('../../lib/api', () => ({
createRecipe: vi
.fn()
@@ -863,14 +885,20 @@ describe('RecipeEditor — deploy flow', () => {
await waitFor(() => expect(api.createRecipe).toHaveBeenCalled())
const validationPayload = vi.mocked(api.validateRecipeServer).mock.calls[0][0]
- expect(validationPayload.metadata).toEqual({ name: 'namespace-ignored' })
+ expect(validationPayload.metadata).toEqual({
+ name: 'namespace-ignored',
+ annotations: { 'clerum.io/codex-connection-ref': '' },
+ })
expect(validationPayload.spec.workloads[0]).toEqual(
expect.objectContaining({ id: 'api', type: 'deployment' })
)
expect(api.validateRecipeServer).toHaveBeenCalledWith(validationPayload, { mode: 'create' })
const createPayload = vi.mocked(api.createRecipe).mock.calls[0][0]
- expect(createPayload.metadata).toEqual({ name: 'namespace-ignored' })
+ expect(createPayload.metadata).toEqual({
+ name: 'namespace-ignored',
+ annotations: { 'clerum.io/codex-connection-ref': '' },
+ })
expect(createPayload.spec.workloads[0]).toEqual(
expect.objectContaining({ id: 'api', type: 'deployment' })
)
@@ -1689,9 +1717,12 @@ describe('RecipeEditor — grants in editor', () => {
target: { value: 'Agentic Workflow (Codex Subscription)' },
})
reviewAndProceedToDeploy()
+ fireEvent.click(await screen.findByRole('button', { name: 'ChatGPT grant' }))
+ fireEvent.click(await screen.findByRole('option', { name: /Team Plus/ }))
fireEvent.click(await screen.findByText('Deploy plugin'))
await waitFor(() => expect(api.createRecipe).toHaveBeenCalled())
const createPayload = vi.mocked(api.createRecipe).mock.calls[0][0] as {
+ metadata?: { annotations?: Record<string, string> }
spec: { agent?: { provider?: string; model?: string; secretRef?: unknown } }
}
expect(createPayload.spec.agent).toEqual({
@@ -1699,9 +1730,25 @@ describe('RecipeEditor — grants in editor', () => {
model: 'gpt-5.1',
})
expect(createPayload.spec.agent?.secretRef).toBeUndefined()
+ expect(createPayload.metadata?.annotations).toEqual({
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ })
expect(onSaved).toHaveBeenCalled()
})
+ it('blocks a Codex recipe that has not chosen a ChatGPT grant', async () => {
+ render(<RecipeEditor onSaved={vi.fn()} onCancel={vi.fn()} />)
+ fireEvent.change(screen.getByRole('combobox'), {
+ target: { value: 'Agentic Workflow (Codex Subscription)' },
+ })
+ reviewAndProceedToDeploy()
+ fireEvent.click(await screen.findByText('Deploy plugin'))
+ await waitFor(() => {
+ expect(screen.getByText(/must choose an existing ChatGPT grant/i)).toBeInTheDocument()
+ })
+ expect(api.createRecipe).not.toHaveBeenCalled()
+ })
+
it('blocks a Codex recipe that still declares an LLM secretRef', async () => {
render(<RecipeEditor onSaved={vi.fn()} onCancel={vi.fn()} />)
fireEvent.change(screen.getByRole('textbox'), {
diff --git a/control-ui/lib/__tests__/llm.test.ts b/control-ui/lib/__tests__/llm.test.ts
index 72e29f435..4d73fb288 100644
--- a/control-ui/lib/__tests__/llm.test.ts
+++ b/control-ui/lib/__tests__/llm.test.ts
@@ -300,11 +300,17 @@ describe('broker-backed authoring helpers', () => {
})
it('rejects Codex recipe authoring that omits the model, ships a secretRef, or uses cost', () => {
+ expect(
+ brokerBackedRecipeAuthoringError(
+ { agent: { provider: 'codex-subscription', model: 'gpt-5.1' } },
+ 'team-plus'
+ )
+ ).toBeNull()
expect(
brokerBackedRecipeAuthoringError({
agent: { provider: 'codex-subscription', model: 'gpt-5.1' },
})
- ).toBeNull()
+ ).toMatch(/ChatGPT grant/)
expect(
brokerBackedRecipeAuthoringError({
agent: { provider: 'codex-subscription' },
diff --git a/control-ui/lib/api.ts b/control-ui/lib/api.ts
index 8b8ae6689..522130379 100644
--- a/control-ui/lib/api.ts
+++ b/control-ui/lib/api.ts
@@ -2469,6 +2469,7 @@ export type WorkflowRecipeResource = {
namespace?: string
creationTimestamp?: string
labels?: Record<string, string>
+ annotations?: Record<string, string>
}
spec?: Record<string, unknown>
status?: WorkflowRecipeStatus
@@ -2500,7 +2501,7 @@ export async function getRecipe(name: string) {
}
export async function createRecipe(payload: {
- metadata: { name: string; namespace?: string }
+ metadata: { name: string; namespace?: string; annotations?: Record<string, string> }
spec: Record<string, unknown>
}) {
return apiSend(
@@ -2535,7 +2536,7 @@ export type ServerValidationResult =
// let the reconciler catch at L4.
export async function validateRecipeServer(
recipe: {
- metadata: { name: string; namespace?: string }
+ metadata: { name: string; namespace?: string; annotations?: Record<string, string> }
spec: Record<string, unknown>
},
opts: { mode?: 'create' | 'edit' } = {}
@@ -2558,7 +2559,13 @@ export async function validateRecipeServer(
throw new Error(`${res.status} ${res.statusText} - ${text}`)
}
-export async function updateRecipe(name: string, payload: { spec: Record<string, unknown> }) {
+export async function updateRecipe(
+ name: string,
+ payload: {
+ spec: Record<string, unknown>
+ metadata?: { annotations?: Record<string, string> }
+ }
+) {
return apiSend(
'PUT',
`/api/v1/admin/recipes/${encodeURIComponent(name)}`,
diff --git a/control-ui/lib/codexSubscription.ts b/control-ui/lib/codexSubscription.ts
index 2dc31fdc8..4ff61bc91 100644
--- a/control-ui/lib/codexSubscription.ts
+++ b/control-ui/lib/codexSubscription.ts
@@ -25,6 +25,9 @@ export type CodexAssignableHost = {
export const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned'
+/** Recipe grant identity. Recipes have no CRD `connectionRef` field. */
+export const CODEX_CONNECTION_REF_ANNOTATION = 'clerum.io/codex-connection-ref'
+
export function isAssignableCodexGrant(
row: Pick<CodexSubscriptionConnectionView, 'status' | 'catalogStatus'>
): boolean {
diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.ts
index d8bedc31a..142f5b1b4 100644
--- a/control-ui/lib/llm.ts
+++ b/control-ui/lib/llm.ts
@@ -7,6 +7,7 @@ import {
PROVIDER_NON_SECRET_ENV,
isLlmProviderId,
} from '@clerum/llm-providers'
+import { CODEX_UNASSIGNED_CONNECTION_KEY } from './codexSubscription'
// The canonical provider set, labels and credential slots live in the shared
// @clerum/llm-providers package (spec §3-R4) — this module derives its
@@ -273,8 +274,12 @@ export function budgetUnitAllowedForProviders(
}
// Recipe authoring guard: a broker-backed agent must name an explicit model
-// and must not carry an LLM secretRef or a cost-unit budget.
-export function brokerBackedRecipeAuthoringError(spec: Record<string, unknown>): string | null {
+// and must not carry an LLM secretRef or a cost-unit budget. The grant lives
+// on metadata.annotations[clerum.io/codex-connection-ref], not in spec.
+export function brokerBackedRecipeAuthoringError(
+ spec: Record<string, unknown>,
+ connectionRef?: string
+): string | null {
const agent = spec.agent
if (!agent || typeof agent !== 'object' || Array.isArray(agent)) return null
const record = agent as Record<string, unknown>
@@ -292,6 +297,10 @@ export function brokerBackedRecipeAuthoringError(spec: Record<string, unknown>):
const unit = (budget as Record<string, unknown>).unit
if (unit === 'cost') return 'Codex subscription budgets must use unit tokens, not cost.'
}
+ const grant = typeof connectionRef === 'string' ? connectionRef.trim() : ''
+ if (!grant || grant === CODEX_UNASSIGNED_CONNECTION_KEY) {
+ return 'Codex subscription recipes must choose an existing ChatGPT grant.'
+ }
return null
}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 8f496235a..a570e2b37 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.471",
+ "version": "0.1.472",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.471",
+ "version": "0.1.472",
"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 58b561486..3e1f94978 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.471",
+ "version": "0.1.472",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 667c8656a..553e0fd74 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.291",
+ "version": "0.1.292",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.291",
+ "version": "0.1.292",
"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 b2b3f621c..1377b2d93 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.291",
+ "version": "0.1.292",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/llm/__tests__/codexSubscription.test.ts b/mcp-host/src/llm/__tests__/codexSubscription.test.ts
index 8d7147c36..fef628868 100644
--- a/mcp-host/src/llm/__tests__/codexSubscription.test.ts
+++ b/mcp-host/src/llm/__tests__/codexSubscription.test.ts
@@ -248,6 +248,21 @@ describe('CodexSubscriptionProvider', () => {
expect(classified.retryable).toBe(false)
})
+ it('does not treat a revoked grant as a retryable provider outage', () => {
+ const provider = new CodexSubscriptionProvider('gpt-5.3-codex', deps() as never)
+ const revoked = provider.classifyError(new CodexAuthorizeError('no_grant', 'revoked'))
+ expect(revoked.code).toBe(LlmErrorCode.AuthenticationFailed)
+ expect(revoked.retryable).toBe(false)
+ expect(classifyFailoverClass(revoked.code, revoked.retryable)).toBe('auth')
+
+ const transient = provider.classifyError(
+ new CodexAuthorizeError('connection_unavailable', 'catalog unavailable')
+ )
+ expect(transient.code).toBe(LlmErrorCode.ModelOverloaded)
+ expect(transient.retryable).toBe(true)
+ expect(classifyFailoverClass(transient.code, transient.retryable)).toBe('provider_unavailable')
+ })
+
it('maps transient proxy failures onto failover-eligible classes', () => {
const provider = new CodexSubscriptionProvider('gpt-5.3-codex', deps() as never)
const unavailable = provider.classifyError(
diff --git a/scripts/e2e/e2e-codex-subscription-runtime.sh b/scripts/e2e/e2e-codex-subscription-runtime.sh
index 59977084b..feee8a2e5 100755
--- a/scripts/e2e/e2e-codex-subscription-runtime.sh
+++ b/scripts/e2e/e2e-codex-subscription-runtime.sh
@@ -221,9 +221,22 @@ token = (
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
data = json.loads(base64.urlsafe_b64decode(payload))
-scopes = data.get("scp") or data.get("scope") or []
-if isinstance(scopes, str):
- scopes = scopes.split()
+# Control JWTs emit `scopes` (array). Access tokens put Codex scopes in
+# `workflowControlScopes` and a space-delimited `scope`. Legacy `scp` is
+# kept as a fallback so a rotated claim shape cannot silently miss the grant.
+raw_scopes = (
+ data.get("scopes")
+ or data.get("workflowControlScopes")
+ or data.get("scp")
+ or data.get("scope")
+ or []
+)
+if isinstance(raw_scopes, str):
+ scopes = raw_scopes.split()
+elif isinstance(raw_scopes, list):
+ scopes = [item for item in raw_scopes if isinstance(item, str)]
+else:
+ scopes = []
print(json.dumps({
"has_codex_execute": "llm:codex:execute" in scopes,
"scope_count": len(scopes),