Skip to content

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

TypeScript

fix(codex): close jozer review gaps on configure, spend, and billing

Alfredo Lopez3c62bcd1112f
diff --git a/charts/clerum-crds/crds/workflowrecipe.yaml b/charts/clerum-crds/crds/workflowrecipe.yaml
index 15bbdac77..ec9e1e366 100644
--- a/charts/clerum-crds/crds/workflowrecipe.yaml
+++ b/charts/clerum-crds/crds/workflowrecipe.yaml
@@ -273,8 +273,8 @@ spec:
provider/model bootstrap binding for a stepless
spec.pluginWorkloadSdk.promptBridge runtime.
x-kubernetes-validations:
- - rule: "!has(self.provider) || self.provider == 'codex-subscription' || has(self.secretRef)"
- message: spec.agent.secretRef is required for static-credentials providers
+ - rule: "!has(self.provider) || self.provider != 'codex-subscription' || !has(self.secretRef)"
+ message: spec.agent.secretRef is not allowed for oauth-broker providers
properties:
model:
type: string
diff --git a/codex-llm-proxy/src/chatgptUpstreamHeaders.ts b/codex-llm-proxy/src/chatgptUpstreamHeaders.ts
index 21d796e17..0a256b9c9 100644
--- a/codex-llm-proxy/src/chatgptUpstreamHeaders.ts
+++ b/codex-llm-proxy/src/chatgptUpstreamHeaders.ts
@@ -46,6 +46,6 @@ export function chatgptUpstreamHeaders(
...extra,
}
const accountId = chatgptAccountIdFromAccessToken(accessToken)
- if (accountId) headers['chatgpt-account-id'] = accountId
+ if (accountId) headers['chatgpt-account-id'] ??= accountId
return headers
}
diff --git a/codex-llm-proxy/src/codexTransport.ts b/codex-llm-proxy/src/codexTransport.ts
index 24c31b3f0..b16c480ad 100644
--- a/codex-llm-proxy/src/codexTransport.ts
+++ b/codex-llm-proxy/src/codexTransport.ts
@@ -89,8 +89,6 @@ export async function streamCodexCompletion(
if (request.model !== input.ticket.model) {
throw new CodexTransportError('model_not_allowed', 'request model does not match the ticket')
}
- const deadlineMs = assertBoundedDeadline(input.deadlineMs ?? request.deadlineMs, input.maxDeadlineMs ?? 300_000)
-
const redeemed = await input.redeem({
executionTicket: input.executionTicket,
requestHash: input.requestHash,
@@ -102,6 +100,10 @@ export async function streamCodexCompletion(
await finalizeQuietly(input, redeemed, 'error')
throw new CodexTransportError('model_not_allowed', 'served model does not match the request')
}
+ const deadlineMs = Math.min(
+ assertBoundedDeadline(input.deadlineMs ?? request.deadlineMs, input.maxDeadlineMs ?? 300_000),
+ redeemed.transport.maxStreamDurationMs
+ )
const accessToken = redeemed.accessToken
let outcome: StreamCodexCompletionResult['outcome'] = 'unknown'
@@ -317,27 +319,14 @@ async function consumeSse(
while (!signal.aborted) {
const { done, value } = await reader.read()
if (done) break
- buffer += decoder.decode(value, { stream: true })
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n').replace(/\r/g, '\n')
if (buffer.length > maxSseBufferBytes) {
throw new CodexTransportError('sse_buffer_exceeded', 'upstream SSE buffer exceeded')
}
const parts = buffer.split('\n\n')
buffer = parts.pop() ?? ''
for (const part of parts) {
- const dataLine = part
- .split('\n')
- .map(line => line.trim())
- .find(line => line.startsWith('data:'))
- if (!dataLine) continue
- const payload = dataLine.slice(5).trim()
- if (!payload || payload === '[DONE]') continue
- let parsed: unknown
- try {
- parsed = JSON.parse(payload)
- } catch {
- continue
- }
- const mapped = mapUpstreamEvent(parsed, pending)
+ const mapped = ingestSseBlock(part, pending)
if (mapped.frame) onFrame?.(mapped.frame)
if (mapped.usage) usage = mapped.usage
if (mapped.completed) completed = true
@@ -345,6 +334,14 @@ async function consumeSse(
}
if (signal.aborted) break
}
+ buffer += decoder.decode().replace(/\r\n/g, '\n').replace(/\r/g, '\n')
+ if (buffer.trim()) {
+ const mapped = ingestSseBlock(buffer, pending)
+ if (mapped.frame) onFrame?.(mapped.frame)
+ if (mapped.usage) usage = mapped.usage
+ if (mapped.completed) completed = true
+ if (mapped.failed) failed = true
+ }
} finally {
reader.releaseLock()
}
@@ -362,6 +359,24 @@ async function consumeSse(
return { outcome: 'unknown', usage }
}
+function ingestSseBlock(
+ part: string,
+ pending: Map<string, PendingToolCall>
+): ReturnType<typeof mapUpstreamEvent> {
+ const dataLine = part
+ .split('\n')
+ .map(line => line.trim())
+ .find(line => line.startsWith('data:'))
+ if (!dataLine) return {}
+ const payload = dataLine.slice(5).trim()
+ if (!payload || payload === '[DONE]') return {}
+ try {
+ return mapUpstreamEvent(JSON.parse(payload), pending)
+ } catch {
+ return {}
+ }
+}
+
type PendingToolCall = {
id: string
name: string
diff --git a/codex-llm-proxy/src/controlApiClient.ts b/codex-llm-proxy/src/controlApiClient.ts
index 282dae779..a362c7235 100644
--- a/codex-llm-proxy/src/controlApiClient.ts
+++ b/codex-llm-proxy/src/controlApiClient.ts
@@ -103,6 +103,7 @@ export class ControlApiClient {
'x-service-token': this.config.serviceName,
},
body: JSON.stringify(payload),
+ signal: AbortSignal.timeout(15_000),
})
const raw = await response.text()
let parsed: unknown = null
diff --git a/codex-llm-proxy/test/chatgptUpstreamHeaders.test.ts b/codex-llm-proxy/test/chatgptUpstreamHeaders.test.ts
index 931ef0399..1aaa54f42 100644
--- a/codex-llm-proxy/test/chatgptUpstreamHeaders.test.ts
+++ b/codex-llm-proxy/test/chatgptUpstreamHeaders.test.ts
@@ -36,4 +36,12 @@ describe('chatgptUpstreamHeaders', () => {
const token = jwtWithPayload({ auth: { chatgpt_account_id: 'acct_nested' } })
expect(chatgptAccountIdFromAccessToken(token)).toBe('acct_nested')
})
+
+ it('keeps a redeemed chatgpt-account-id instead of overwriting it with the JWT claim', () => {
+ const token = jwtWithPayload({
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'acct_from_jwt' },
+ })
+ const headers = chatgptUpstreamHeaders(token, { 'chatgpt-account-id': 'acct_redeemed' })
+ expect(headers['chatgpt-account-id']).toBe('acct_redeemed')
+ })
})
diff --git a/codex-llm-proxy/test/codexTransport.conformance.test.ts b/codex-llm-proxy/test/codexTransport.conformance.test.ts
index 89fcbb483..43fc0afbe 100644
--- a/codex-llm-proxy/test/codexTransport.conformance.test.ts
+++ b/codex-llm-proxy/test/codexTransport.conformance.test.ts
@@ -109,6 +109,66 @@ describe('streamCodexCompletion', () => {
expect(String(fetchFn.mock.calls[0]?.[1]?.body)).toContain('"store":false')
})
+ it('flushes a completed event that arrives without a trailing blank line', async () => {
+ const fetchFn = vi.fn(async () =>
+ sseResponse([
+ 'data: {"type":"response.completed","response":{"usage":{"input_tokens":1,"output_tokens":1}}}',
+ ])
+ )
+ const result = await streamCodexCompletion({
+ executionTicket: 'ticket-1',
+ requestHash: REQUEST_HASH,
+ request: REQUEST,
+ ticket: {
+ jti: 'jti-residual',
+ hostRef: 'research-host',
+ model: 'gpt-5.1',
+ requestHash: REQUEST_HASH,
+ providerAttemptId: 'att-1',
+ },
+ redeem: async () => redeemSuccess(),
+ finalize: vi.fn(async () => ({
+ providerAttemptId: 'att-1',
+ outcome: 'success' as const,
+ duplicate: false,
+ })),
+ fetchFn,
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ })
+ expect(result.outcome).toBe('success')
+ expect(result.usage).toEqual({ inputTokens: 1, outputTokens: 1 })
+ })
+
+ it('parses CRLF-delimited SSE frames', async () => {
+ const fetchFn = vi.fn(async () =>
+ sseResponse([
+ 'data: {"type":"response.completed","response":{"usage":{"input_tokens":4,"output_tokens":5}}}\r\n\r\n',
+ ])
+ )
+ const result = await streamCodexCompletion({
+ executionTicket: 'ticket-1',
+ requestHash: REQUEST_HASH,
+ request: REQUEST,
+ ticket: {
+ jti: 'jti-crlf',
+ hostRef: 'research-host',
+ model: 'gpt-5.1',
+ requestHash: REQUEST_HASH,
+ providerAttemptId: 'att-1',
+ },
+ redeem: async () => redeemSuccess(),
+ finalize: vi.fn(async () => ({
+ providerAttemptId: 'att-1',
+ outcome: 'success' as const,
+ duplicate: false,
+ })),
+ fetchFn,
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ })
+ expect(result.outcome).toBe('success')
+ expect(result.usage).toEqual({ inputTokens: 4, outputTokens: 5 })
+ })
+
it('uses the redeemed ChatGPT account id when the access token is opaque', async () => {
const fetchFn = vi.fn(async () =>
sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])
@@ -137,6 +197,37 @@ describe('streamCodexCompletion', () => {
expect(fetchFn.mock.calls[0]?.[1]?.headers?.['chatgpt-account-id']).toBe('acct_from_id_token')
})
+ it('keeps the redeemed ChatGPT account id when the access token JWT names another account', async () => {
+ const fetchFn = vi.fn(async () =>
+ sseResponse(['data: {"type":"response.completed","response":{"usage":{}}}\n\n'])
+ )
+ await streamCodexCompletion({
+ executionTicket: 'ticket-1',
+ requestHash: REQUEST_HASH,
+ request: REQUEST,
+ ticket: {
+ jti: 'jti-1',
+ hostRef: 'research-host',
+ model: 'gpt-5.1',
+ requestHash: REQUEST_HASH,
+ providerAttemptId: 'att-1',
+ },
+ redeem: async () =>
+ redeemSuccess({
+ accessToken: accessTokenFor('other-account'),
+ chatgptAccountId: 'acct_stored',
+ }),
+ finalize: vi.fn(async () => ({
+ providerAttemptId: 'att-1',
+ outcome: 'success',
+ duplicate: false,
+ })),
+ fetchFn,
+ lookup: async () => [{ address: '1.2.3.4', family: 4 }],
+ })
+ expect(fetchFn.mock.calls[0]?.[1]?.headers?.['chatgpt-account-id']).toBe('acct_stored')
+ })
+
it('refuses to fetch completions when the access token has no ChatGPT account id', async () => {
const fetchFn = vi.fn()
await expect(
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 6cfd7a2e4..53ec2ad80 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.512",
+ "version": "0.1.513",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.512",
+ "version": "0.1.513",
"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 49f561047..eeb81d295 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.512",
+ "version": "0.1.513",
"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 c041a4323..0c8a8c34f 100644
--- a/control-api/src/db.ts
+++ b/control-api/src/db.ts
@@ -10,6 +10,7 @@ import {
applyCodexChatgptAccountIdSchema,
applyCodexGrantDefaultModelSchema,
applyCodexMultiConnectionSchema,
+ applyCodexReusableConnectionKeySchema,
applyCodexSubscriptionConnectionSchema,
} from './services/codexSubscriptionConnection.js'
import { applyCodexSubscriptionOAuthStateSchema } from './services/codexSubscriptionOAuthState.js'
@@ -5981,6 +5982,10 @@ export const CONTROL_API_MIGRATIONS: DbMigration[] = [
version: '0104_codex_grant_default_model',
apply: applyCodexGrantDefaultModelSchema,
},
+ {
+ version: '0105_codex_reusable_connection_key',
+ apply: applyCodexReusableConnectionKeySchema,
+ },
]
async function consolidateWorkflowAllowedUsersToTriggers(db: DbClient): Promise<void> {
diff --git a/control-api/src/routes/admin/pluginWorkloadSdk.ts b/control-api/src/routes/admin/pluginWorkloadSdk.ts
index 23374cd77..5ebcf54e9 100644
--- a/control-api/src/routes/admin/pluginWorkloadSdk.ts
+++ b/control-api/src/routes/admin/pluginWorkloadSdk.ts
@@ -760,10 +760,14 @@ export function createAdminPluginWorkloadSdkRouter(
// Grant PERSISTED: NOW emit any Pieza D tolerations (never before the upsert
// lands, so a failed upsert leaves no audit record — mini-spec 01).
for (const event of pendingGrantTolerations) emitIncoherenceTolerated(event)
- const brokerConnectionRef = promptTargets.find(target =>
- isBrokerBackedProvider(target.provider)
- )?.connectionRef
- if (capabilityFamily === 'promptBridge' && brokerConnectionRef && deps.gateway) {
+ const brokerConnectionRef =
+ promptTargets.find(
+ target =>
+ isBrokerBackedProvider(target.provider) &&
+ target.connectionRef &&
+ !isCodexUnassignedConnectionKey(target.connectionRef)
+ )?.connectionRef ?? ''
+ if (capabilityFamily === 'promptBridge' && deps.gateway) {
try {
await deps.gateway.patchResourceAnnotations(
'workflowrecipes',
@@ -812,6 +816,33 @@ export function createAdminPluginWorkloadSdkRouter(
res.status(404).json({ error: 'grant not found' })
return
}
+ if (deps.gateway) {
+ const remaining = await listGrants({ recipeNamespace, recipeName })
+ const remainingRef =
+ remaining
+ .flatMap(grant => grant.promptTargets)
+ .find(
+ target =>
+ isBrokerBackedProvider(target.provider) &&
+ target.connectionRef &&
+ !isCodexUnassignedConnectionKey(target.connectionRef)
+ )?.connectionRef ?? ''
+ try {
+ await deps.gateway.patchResourceAnnotations(
+ 'workflowrecipes',
+ recipeName,
+ { [CODEX_CONNECTION_REF_ANNOTATION]: remainingRef },
+ recipeNamespace
+ )
+ } catch (err) {
+ log.error(
+ { err, recipeNamespace, recipeName },
+ 'failed to clear Codex connection annotation after grant delete'
+ )
+ res.status(503).json({ error: 'recipe_annotation_stamp_failed' })
+ return
+ }
+ }
res.status(200).json({ deleted: true })
})
)
diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.ts
index c446fb731..60cfca64d 100644
--- a/control-api/src/routes/admin/recipes.ts
+++ b/control-api/src/routes/admin/recipes.ts
@@ -1251,6 +1251,11 @@ function recipeUsesCodexBroker(spec?: Record<string, unknown>): boolean {
return (agent as { provider?: unknown }).provider === 'codex-subscription'
}
+function recipeHasPluginWorkloadSdk(spec?: Record<string, unknown>): boolean {
+ const sdk = spec?.pluginWorkloadSdk
+ return Boolean(sdk && typeof sdk === 'object' && !Array.isArray(sdk))
+}
+
function readRequestedCodexRecipeGrant(body: RecipeBody): string {
const raw = body.metadata?.annotations?.[CODEX_CONNECTION_REF_ANNOTATION]
return readHostCodexConnectionRef(typeof raw === 'string' ? raw : '')
@@ -1282,21 +1287,38 @@ function validateCodexRecipeGrant(body: RecipeBody): ValidationError[] {
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]: '' }
+function sanitizeRecipeCodexAnnotation(
+ body: RecipeBody,
+ currentAnnotations?: Record<string, string>
+): Record<string, string> {
+ const incoming = readRequestedCodexRecipeGrant(body)
+ if (recipeUsesCodexBroker(body.spec)) {
+ return {
+ [CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(incoming) ? '' : incoming,
+ }
}
- const key = readRequestedCodexRecipeGrant(body)
- return {
- [CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(key) ? '' : key,
+ // SDK promptBridge stamps the same annotation regardless of spec.agent.
+ // Do not wipe a live grant when the author edits an unrelated field.
+ if (recipeHasPluginWorkloadSdk(body.spec)) {
+ if (!isCodexUnassignedConnectionKey(incoming)) {
+ return { [CODEX_CONNECTION_REF_ANNOTATION]: incoming }
+ }
+ const current = readHostCodexConnectionRef(
+ typeof currentAnnotations?.[CODEX_CONNECTION_REF_ANNOTATION] === 'string'
+ ? currentAnnotations[CODEX_CONNECTION_REF_ANNOTATION]
+ : ''
+ )
+ return {
+ [CODEX_CONNECTION_REF_ANNOTATION]: isCodexUnassignedConnectionKey(current) ? '' : current,
+ }
}
+ return { [CODEX_CONNECTION_REF_ANNOTATION]: '' }
}
function sanitizeRecipeBody(
body: RecipeBody,
- currentLabels?: Record<string, string>
+ currentLabels?: Record<string, string>,
+ currentAnnotations?: Record<string, string>
): {
metadata: { name: string; labels?: Record<string, string>; annotations: Record<string, string> }
spec: Record<string, unknown>
@@ -1318,7 +1340,10 @@ function sanitizeRecipeBody(
metadata: {
name: metadata.name as string,
...(sanitizedLabels ? { labels: sanitizedLabels } : {}),
- annotations: sanitizeRecipeCodexAnnotation(body),
+ annotations: {
+ ...(currentAnnotations ?? {}),
+ ...sanitizeRecipeCodexAnnotation(body, currentAnnotations),
+ },
},
spec: body.spec as Record<string, unknown>,
}
@@ -1947,10 +1972,13 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {
return
}
}
- const currentLabels = isPlainObject(resource)
- ? stringLabels(isPlainObject(resource.metadata) ? resource.metadata.labels : undefined)
- : undefined
- const sanitized = sanitizeRecipeBody(body, currentLabels)
+ const currentMeta =
+ isPlainObject(resource) && isPlainObject(resource.metadata)
+ ? resource.metadata
+ : undefined
+ const currentLabels = stringLabels(currentMeta?.labels)
+ const currentAnnotations = stringLabels(currentMeta?.annotations)
+ const sanitized = sanitizeRecipeBody(body, currentLabels, currentAnnotations)
const updated = await updateRecipeWithConflictRetry(gateway, req.params.name, sanitized, ns)
res
.status(200)
diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
index d8989d246..ac655008d 100644
--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
@@ -112,8 +112,8 @@ export function createMcpHostLlmProviderAttemptRoutes(gateway: K8sGateway): Rout
const router = Router()
router.post(
'/mcp-host/llm/provider-attempts/authorize',
- ...llmProviderAttemptAuthorizeRateLimits(),
requireMcpHostJwt,
+ ...llmProviderAttemptAuthorizeRateLimits(),
asyncHandler(async (req: Request, res: Response) => {
const claims = req.mcpHostJwt
if (!claims) {
diff --git a/control-api/src/routes/workflows/shared/rateLimit.ts b/control-api/src/routes/workflows/shared/rateLimit.ts
index 60a35109e..b449200d3 100644
--- a/control-api/src/routes/workflows/shared/rateLimit.ts
+++ b/control-api/src/routes/workflows/shared/rateLimit.ts
@@ -167,6 +167,15 @@ export function adminCodexWriteRateLimits() {
return [adminCodexWriteEdgeRateLimit(), adminCodexWriteRateLimit()] as const
}
+function codexOAuthCallbackBucketKey(req: Request): string {
+ const state = typeof req.query.state === 'string' ? req.query.state.trim() : ''
+ if (state) {
+ const hash = createHash('sha256').update(state).digest('hex').slice(0, 32)
+ return `codex_oauth_callback:state:${hash}`
+ }
+ return `codex_oauth_callback:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`
+}
+
export function codexOAuthCallbackRateLimits() {
return [
rateLimit({
@@ -174,15 +183,13 @@ export function codexOAuthCallbackRateLimits() {
limit: CODEX_OAUTH_CALLBACK_PER_MINUTE,
standardHeaders: 'draft-7',
legacyHeaders: false,
- keyGenerator: (req: Request) =>
- `codex_oauth_callback:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`,
+ keyGenerator: codexOAuthCallbackBucketKey,
handler: workflowGrantEdgeRateLimitHandler,
}),
rateLimitMiddleware({
bucketType: 'codex_oauth_callback',
maxPerMinute: CODEX_OAUTH_CALLBACK_PER_MINUTE,
- getBucketKey: (req: Request) =>
- `codex_oauth_callback:ip:${ipKeyGenerator(req.ip ?? 'unknown')}`,
+ getBucketKey: codexOAuthCallbackBucketKey,
}),
] as const
}
diff --git a/control-api/src/services/codexSubscriptionConnection.ts b/control-api/src/services/codexSubscriptionConnection.ts
index 2ae04b2e3..4dc59368c 100644
--- a/control-api/src/services/codexSubscriptionConnection.ts
+++ b/control-api/src/services/codexSubscriptionConnection.ts
@@ -265,6 +265,14 @@ export async function applyCodexGrantDefaultModelSchema(db: DbClient): Promise<v
`)
}
+/** Drop the table-wide UNIQUE so a revoked key can be reused. The partial active index stays. */
+export async function applyCodexReusableConnectionKeySchema(db: DbClient): Promise<void> {
+ await db.query(`
+ ALTER TABLE codex_subscription_connections
+ DROP CONSTRAINT IF EXISTS codex_subscription_connections_connection_key_unique
+ `)
+}
+
export async function getSafeCodexSubscriptionConnection(
db: DbClient,
connectionKey: string = CODEX_SUBSCRIPTION_CONNECTION_KEY
diff --git a/control-api/src/services/codexSubscriptionOAuth.ts b/control-api/src/services/codexSubscriptionOAuth.ts
index 289810d3c..aeddd285b 100644
--- a/control-api/src/services/codexSubscriptionOAuth.ts
+++ b/control-api/src/services/codexSubscriptionOAuth.ts
@@ -491,11 +491,10 @@ export async function ensureFreshCodexAccessToken(deps: CodexOAuthDeps): Promise
throw new CodexSubscriptionOAuthError('no_grant', 'encrypted refresh token missing')
}
const waitedAccountId = latest.chatgptAccountId || chatgptAccountIdFromJwt(latest.accessToken)
- const stillExpiring =
- latest.accessTokenExpiresAt != null &&
- latest.accessTokenExpiresAt.getTime() - Date.now() < ACCESS_TOKEN_REFRESH_SKEW_MS
- if (latest.accessToken && !stillExpiring && waitedAccountId) {
- if (!latest.chatgptAccountId) {
+ const tokenStillValid =
+ latest.accessTokenExpiresAt == null || latest.accessTokenExpiresAt.getTime() > Date.now()
+ if (latest.accessToken && tokenStillValid) {
+ if (waitedAccountId && !latest.chatgptAccountId) {
await persistCodexChatgptAccountId(deps.db, deps.encryptionKey, waitedAccountId, key)
}
return
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index 8753e72d4..aaf02ab94 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -314,6 +314,7 @@ export async function authorizeLlmProviderAttempt(
const presentedReservationId =
typeof body.budgetReservationId === 'string' ? body.budgetReservationId.trim() : ''
+ let budgetReservationId = presentedReservationId || 'unbudgeted'
if (presentedReservationId) {
const active = await resolvedDeps.getActiveReservation(db, {
reservationId: presentedReservationId,
@@ -325,38 +326,37 @@ export async function authorizeLlmProviderAttempt(
'budget reservation is missing or expired'
)
}
- }
-
- const budget = await resolvedDeps.evaluateBudget(
- {
- host_ref: caller.hostRef,
- context_ref: null,
- team_id: null,
- user_id: null,
- provider: PROVIDER,
- model: request.model,
- llm_secret_name: null,
- source_kind: caller.callerKind === 'recipe' ? 'workflow' : 'channel',
- recipe_name: caller.recipeName,
- cron_job_id: null,
- task_ref: invocationId,
- },
- db,
- { connect: async () => tx as never },
- { requiredUnit: 'tokens', transactionClient: tx }
- )
- if (!budget.allowed) {
- throw new LlmProviderAttemptAuthorizeError(
- 'budget_denied',
- budget.reason === 'cost_unit_rejected'
- ? 'Codex attempts reject cost-unit budgets'
- : 'token budget denied this attempt'
+ } else {
+ const budget = await resolvedDeps.evaluateBudget(
+ {
+ host_ref: caller.hostRef,
+ context_ref: null,
+ team_id: null,
+ user_id:
+ typeof body.userId === 'string' && body.userId.trim() ? body.userId.trim() : claims.sub,
+ provider: PROVIDER,
+ model: request.model,
+ llm_secret_name: null,
+ source_kind: caller.callerKind === 'recipe' ? 'workflow' : 'channel',
+ recipe_name: caller.recipeName,
+ cron_job_id: null,
+ task_ref: `${invocationId}:${attemptGeneration}:${providerAttemptIndex}`,
+ },
+ db,
+ { connect: async () => tx as never },
+ { requiredUnit: 'tokens', transactionClient: tx }
)
+ if (!budget.allowed) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'budget_denied',
+ budget.reason === 'cost_unit_rejected'
+ ? 'Codex attempts reject cost-unit budgets'
+ : 'token budget denied this attempt'
+ )
+ }
+ budgetReservationId = budget.reservationIds?.[0] ?? 'unbudgeted'
}
- const budgetReservationId =
- budget.reservationIds?.[0] ?? (presentedReservationId || 'unbudgeted')
-
try {
const attempt = await resolvedDeps.insertAttempt(db, {
callerKind: caller.callerKind,
diff --git a/control-api/src/services/llmProviderAttemptFinalization.ts b/control-api/src/services/llmProviderAttemptFinalization.ts
index 068fe31b8..617405784 100644
--- a/control-api/src/services/llmProviderAttemptFinalization.ts
+++ b/control-api/src/services/llmProviderAttemptFinalization.ts
@@ -2,6 +2,7 @@ import { parseCodexAttemptReceiptV1 } from '@clerum/llm-provider-attempt-contrac
import { config } from '../config.js'
import { withTransaction } from '../db.js'
import { rootLogger } from '../observability/logger.js'
+import { releaseReservation } from './budgets/reservations.js'
import { hashCodexAttemptReceipt } from './llmProviderAttemptReceipt.js'
import { opaqueAttemptReceipt } from './llmProviderAttemptRedemption.js'
import {
@@ -103,6 +104,12 @@ export async function finalizeLlmProviderAttempt(
'provider attempt already has a different terminal outcome'
)
}
+ if (attempt.budgetReservationId && attempt.budgetReservationId !== 'unbudgeted') {
+ await releaseReservation(
+ { reservationId: attempt.budgetReservationId, hostRef: attempt.hostRef },
+ tx
+ )
+ }
log.info(
{
event: 'codex_attempt_finalized',
diff --git a/control-api/test/db.codexSubscriptionMigration.test.ts b/control-api/test/db.codexSubscriptionMigration.test.ts
index c40572a3f..144712fe0 100644
--- a/control-api/test/db.codexSubscriptionMigration.test.ts
+++ b/control-api/test/db.codexSubscriptionMigration.test.ts
@@ -62,6 +62,13 @@ describe('00a0/00a1 Codex subscription persistence', () => {
dbSource.indexOf("version: '0104_codex_grant_default_model'")
)
expect(connectionSource).toContain('ADD COLUMN IF NOT EXISTS default_model')
+ expect(dbSource).toContain("version: '0105_codex_reusable_connection_key'")
+ expect(dbSource.indexOf("version: '0104_codex_grant_default_model'")).toBeLessThan(
+ dbSource.indexOf("version: '0105_codex_reusable_connection_key'")
+ )
+ expect(connectionSource).toContain(
+ 'DROP CONSTRAINT IF EXISTS codex_subscription_connections_connection_key_unique'
+ )
})
it('creates a single active deployment-default connection with ciphertext and revisions', () => {
diff --git a/control-api/test/routes.adminPluginWorkloadSdk.test.ts b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
index 61524d097..a4efe2810 100644
--- a/control-api/test/routes.adminPluginWorkloadSdk.test.ts
+++ b/control-api/test/routes.adminPluginWorkloadSdk.test.ts
@@ -87,6 +87,7 @@ const validGrantBody = {
beforeEach(() => {
vi.mocked(sdkDb.listGrants).mockReset()
+ vi.mocked(sdkDb.listGrants).mockResolvedValue([])
vi.mocked(sdkDb.upsertGrant).mockReset()
vi.mocked(sdkDb.deleteGrant).mockReset()
vi.mocked(sdkDb.getQuotaCounters).mockReset()
@@ -668,7 +669,12 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
.send({ ...codexGrantBody, promptTargets: [targetWithoutConnection] })
expect(res.status).toBe(200)
expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()
- expect(patchResourceAnnotations).not.toHaveBeenCalled()
+ expect(patchResourceAnnotations).toHaveBeenCalledWith(
+ 'workflowrecipes',
+ 'sdk-recipe',
+ { 'clerum.io/codex-connection-ref': '' },
+ 'sandbox-recipes'
+ )
expect(sdkDb.upsertGrant).toHaveBeenCalled()
})
@@ -682,7 +688,12 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
})
expect(res.status).toBe(200)
expect(isCodexAssignmentAllowed).not.toHaveBeenCalled()
- expect(patchResourceAnnotations).not.toHaveBeenCalled()
+ expect(patchResourceAnnotations).toHaveBeenCalledWith(
+ 'workflowrecipes',
+ 'sdk-recipe',
+ { 'clerum.io/codex-connection-ref': '' },
+ 'sandbox-recipes'
+ )
expect(sdkDb.upsertGrant).toHaveBeenCalled()
})
@@ -1009,6 +1020,12 @@ describe('routes/admin/pluginWorkloadSdk — grants', () => {
'sdk-recipe',
'11111111-1111-4111-8111-111111111111'
)
+ expect(patchResourceAnnotations).toHaveBeenCalledWith(
+ 'workflowrecipes',
+ 'sdk-recipe',
+ { 'clerum.io/codex-connection-ref': '' },
+ 'sandbox-recipes'
+ )
})
})
diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.ts
index 28aeef9b6..dc3f1f81e 100644
--- a/control-api/test/routes.adminRecipes.test.ts
+++ b/control-api/test/routes.adminRecipes.test.ts
@@ -307,6 +307,49 @@ describe.sequential('routes/admin/recipes', () => {
})
})
+ it('PUT /admin/recipes/:name — keeps an SDK Codex grant and last-applied annotations', async () => {
+ await api
+ .post('/admin/recipes')
+ .send({
+ metadata: { name: 'sdk-python' },
+ spec: {
+ pluginWorkloadSdk: { promptBridge: { allowedModels: ['gpt-5.3-codex'] } },
+ workloads: [{ id: 'svc', type: 'deployment', image: 'my-image:latest' }],
+ },
+ })
+ .expect(201)
+ await gateway.updateResource(
+ 'workflowrecipes',
+ 'sdk-python',
+ {
+ metadata: {
+ annotations: {
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'kubectl.kubernetes.io/last-applied-configuration': '{"kind":"WorkflowRecipe"}',
+ },
+ },
+ spec: {
+ pluginWorkloadSdk: { promptBridge: { allowedModels: ['gpt-5.3-codex'] } },
+ workloads: [{ id: 'svc', type: 'deployment', image: 'my-image:latest' }],
+ },
+ },
+ SANDBOX_NS
+ )
+ const res = await api
+ .put('/admin/recipes/sdk-python')
+ .send({
+ spec: {
+ pluginWorkloadSdk: { promptBridge: { allowedModels: ['gpt-5.3-codex'] } },
+ workloads: [{ id: 'svc', type: 'deployment', image: 'my-image:v2' }],
+ },
+ })
+ .expect(200)
+ expect(res.body.metadata.annotations).toMatchObject({
+ 'clerum.io/codex-connection-ref': 'team-plus',
+ 'kubectl.kubernetes.io/last-applied-configuration': '{"kind":"WorkflowRecipe"}',
+ })
+ })
+
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.codexSubscriptionOAuth.test.ts b/control-api/test/services.codexSubscriptionOAuth.test.ts
index 582b2a9a3..5e4672f84 100644
--- a/control-api/test/services.codexSubscriptionOAuth.test.ts
+++ b/control-api/test/services.codexSubscriptionOAuth.test.ts
@@ -503,7 +503,7 @@ describe('codex subscription OAuth broker', () => {
expect(repos.releaseLock).toHaveBeenCalled()
})
- it('fails loud when the refresh lock is held and the token stays stale', async () => {
+ it('serves a still-valid token when the refresh lock is held by another worker', async () => {
repos.loadSecrets.mockResolvedValue({
refreshToken: 'refresh-secret',
accessToken: 'stale-access',
@@ -512,6 +512,19 @@ describe('codex subscription OAuth broker', () => {
credentialRevision: 3,
})
repos.acquireLock.mockResolvedValue(false)
+ await expect(ensureFreshCodexAccessToken(deps(vi.fn()))).resolves.toBeUndefined()
+ expect(repos.updateInPlace).not.toHaveBeenCalled()
+ })
+
+ it('fails loud when the refresh lock is held and the stored token is already expired', async () => {
+ repos.loadSecrets.mockResolvedValue({
+ refreshToken: 'refresh-secret',
+ accessToken: 'stale-access',
+ accessTokenExpiresAt: new Date(Date.now() - 1_000),
+ chatgptAccountId: null,
+ credentialRevision: 3,
+ })
+ repos.acquireLock.mockResolvedValue(false)
await expect(ensureFreshCodexAccessToken(deps(vi.fn()))).rejects.toMatchObject({
code: 'refresh_in_flight',
})
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
index 176bae6dc..7baf4da25 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.test.ts
@@ -216,6 +216,23 @@ describe('authorizeLlmProviderAttempt', () => {
})
})
+ it('reuses an active presented reservation instead of reserving again', async () => {
+ await authorizeLlmProviderAttempt(
+ claims(),
+ body({ budgetReservationId: 'res-already-held' }),
+ current
+ )
+ expect(current.evaluateBudget).not.toHaveBeenCalled()
+ expect(current.getActiveReservation).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ reservationId: 'res-already-held', hostRef: 'research-host' })
+ )
+ expect(current.insertAttempt).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ budgetReservationId: 'res-already-held' })
+ )
+ })
+
it('rejects an expired presented reservation as budget_denied', async () => {
vi.mocked(current.getActiveReservation).mockResolvedValueOnce(null)
await expect(
diff --git a/control-api/test/services.llmProviderAttemptRedemption.test.ts b/control-api/test/services.llmProviderAttemptRedemption.test.ts
index 4005544d6..a303adcdb 100644
--- a/control-api/test/services.llmProviderAttemptRedemption.test.ts
+++ b/control-api/test/services.llmProviderAttemptRedemption.test.ts
@@ -118,6 +118,32 @@ describe('redeemLlmProviderAttempt', () => {
expect(JSON.stringify(result)).not.toMatch(/encrypted|Authorization/i)
})
+ it('prefers the stored ChatGPT account id over a conflicting access-token claim', async () => {
+ const accessJwt = `hdr.${Buffer.from(
+ JSON.stringify({
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'acct_from_jwt' },
+ })
+ ).toString('base64url')}.sig`
+ const result = await redeemLlmProviderAttempt(
+ { executionTicket: 'ticket', requestHash: CLAIMS.requestHash },
+ {
+ enabled: true,
+ db: { query: vi.fn() },
+ getConnectionById: vi.fn(),
+ withTransaction: async work => work({ query: vi.fn() } as never),
+ loadSecrets: async () => ({
+ refreshToken: 'refresh-secret',
+ accessToken: accessJwt,
+ accessTokenExpiresAt: new Date(Date.now() + 120_000),
+ chatgptAccountId: 'acct_stored',
+ credentialRevision: 3,
+ }),
+ encryptionKey: Buffer.alloc(32),
+ }
+ )
+ expect(result.chatgptAccountId).toBe('acct_stored')
+ })
+
it('rejects a replayed ticket before returning any token', async () => {
vi.mocked(store.lockLlmProviderAttemptTicket).mockResolvedValueOnce({
jti: CLAIMS.jti,
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsx
index 1680d5e8c..dd27c2f9f 100644
--- a/control-ui/app/hosts/[name]/page.tsx
+++ b/control-ui/app/hosts/[name]/page.tsx
@@ -35,6 +35,7 @@ import {
listCodexConnectionModels,
listCodexSubscriptionConnections,
} from '../../../lib/codexSubscription'
+import { isDisabledCapabilityError } from '../../../lib/codexSubscriptionFeature'
import { buildContextUpdatePayload, contextMutationError } from '../../../lib/contextMutation'
import { useLlmAllowedModels } from '../../../lib/hooks/useLlmAllowedModels'
import { FIRST_PARTY_CHANNEL_WORKFLOW_CONTROL_SCOPES } from '../../../lib/hostWorkflowControl'
@@ -55,6 +56,7 @@ import {
normalizeLlmPolicy,
normalizeProvider,
offeredCodexModelNames,
+ providerRequiresLlmSecret,
resolveCodexGrantModel,
resolveDefaultModel,
validateLlmPolicy,
@@ -355,7 +357,9 @@ export default function HostDetailsPage() {
.catch(err => {
if (!cancelled) {
setCodexConnections([])
- setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')
+ if (!isDisabledCapabilityError(err)) {
+ setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')
+ }
}
})
return () => {
@@ -708,8 +712,16 @@ export default function HostDetailsPage() {
}
return options
}, [availableLlmSecrets, codexConnections, connectionRefDraft, currentSecretKeys, secretRefDraft])
+ const apiKeySecretOptions = useMemo(
+ () => llmSecretOptions.filter(option => option.group !== 'ChatGPT subscriptions'),
+ [llmSecretOptions]
+ )
const chainRequiresSecret = llmChainRequiresSecret(providerDraft, llmPolicyDraft?.fallbacks)
+ const showFallbackSecretField = providerDraft === 'codex-subscription' && chainRequiresSecret
+ const fallbackSecretLabels = (llmPolicyDraft?.fallbacks ?? [])
+ .filter(entry => providerRequiresLlmSecret(entry.provider))
+ .map(entry => getProviderLabel(entry.provider))
const isCodexAssignment = providerDraft === 'codex-subscription'
const isCodexUnassigned =
isCodexAssignment &&
@@ -723,7 +735,14 @@ export default function HostDetailsPage() {
chainRequiresSecret &&
secretRefDraft.trim().length > 0 &&
currentSecretKeys.length > 0 &&
- !isProviderUsable(providerDraft, key => currentSecretKeys.includes(key))
+ (showFallbackSecretField
+ ? !(llmPolicyDraft?.fallbacks ?? []).some(entry =>
+ isProviderUsable(entry.provider as LlmProvider, key => currentSecretKeys.includes(key))
+ )
+ : !isProviderUsable(providerDraft, key => currentSecretKeys.includes(key)))
+ const secretMismatchLabel = showFallbackSecretField
+ ? fallbackSecretLabels[0] || 'fallback'
+ : getProviderLabel(providerDraft)
const connectorOptions = useMemo(
() =>
@@ -815,7 +834,9 @@ export default function HostDetailsPage() {
return
}
if (parsed.kind === 'subscription') {
- setSecretRefDraft('')
+ if (!llmChainRequiresSecret('codex-subscription', llmPolicyDraft?.fallbacks)) {
+ setSecretRefDraft('')
+ }
setConnectionRefDraft(parsed.connectionKey)
setProviderDraft('codex-subscription')
setModelNameDraft('')
@@ -878,14 +899,20 @@ export default function HostDetailsPage() {
setError('Select an LLM secret for the static-credentials provider in this chain.')
return false
}
+ const secretUsableFor =
+ providerDraft === 'codex-subscription'
+ ? (llmPolicyDraft?.fallbacks ?? []).find(entry =>
+ isProviderUsable(entry.provider as LlmProvider, key => currentSecretKeys.includes(key))
+ )
+ : isProviderUsable(providerDraft, key => currentSecretKeys.includes(key))
if (
chainRequiresSecret &&
secretRefDraft.trim() &&
currentSecretKeys.length > 0 &&
- !isProviderUsable(providerDraft, key => currentSecretKeys.includes(key))
+ !secretUsableFor
) {
setError(
- `The linked LLM Secret does not contain a usable ${getProviderLabel(providerDraft)} credential. Update the linked credentials or choose another secret.`
+ `The linked LLM Secret does not contain a usable ${secretMismatchLabel} credential. Update the linked credentials or choose another secret.`
)
return false
}
@@ -1149,7 +1176,11 @@ export default function HostDetailsPage() {
<div className="cu-llm-secret-control">
<LlmSecretSelect
id="model-secret"
- value={credentialSelectValue(secretRefDraft, connectionRefDraft)}
+ value={
+ showFallbackSecretField
+ ? credentialSelectValue('', connectionRefDraft)
+ : credentialSelectValue(secretRefDraft, connectionRefDraft)
+ }
ariaLabel={credentialFieldLabel}
onChange={handleCredentialChange}
options={llmSecretOptions}
@@ -1158,37 +1189,80 @@ export default function HostDetailsPage() {
? isCodexUnassigned
? 'No credential assigned'
: assignedCodexLabel
- : llmSecretOptions.filter(
- option => !option.group || option.group === 'API keys'
- ).length === 0
+ : apiKeySecretOptions.length === 0
? 'No LLM Secret available'
: 'Select an LLM Secret...'
}
disabled={busy || !editingModel}
/>
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--toolbar"
- onClick={() => setLlmSecretModalOpen(true)}
- disabled={busy || !secretRefDraft.trim()}
- aria-label="Edit LLM Secret credentials"
- title="Edit LLM Secret credentials"
- >
- <IconPencil width={16} height={16} />
- </button>
+ {showFallbackSecretField ? null : (
+ <button
+ type="button"
+ className="cu-btn cu-btn--icon cu-btn--toolbar"
+ onClick={() => setLlmSecretModalOpen(true)}
+ disabled={busy || !secretRefDraft.trim()}
+ aria-label="Edit LLM Secret credentials"
+ title="Edit LLM Secret credentials"
+ >
+ <IconPencil width={16} height={16} />
+ </button>
+ )}
</div>
<span className="cu-field__hint">
- Choose an API-key secret or a ChatGPT subscription. Agents only choose; Secrets
- creates grants.
+ {showFallbackSecretField
+ ? 'Choose the ChatGPT subscription this agent spends. Agents only choose; Secrets creates grants.'
+ : 'Choose an API-key secret or a ChatGPT subscription. Agents only choose; Secrets creates grants.'}
</span>
- {linkedSecretProviderMismatch ? (
- <div className="cu-banner cu-banner--warning">
- The linked secret does not contain a usable {getProviderLabel(providerDraft)}{' '}
- credential. Choose another secret or edit its credentials before saving model
- configuration.
- </div>
- ) : null}
</div>
+ {showFallbackSecretField ? (
+ <div className="cu-field">
+ <label htmlFor="model-fallback-secret">LLM Secret</label>
+ <div className="cu-llm-secret-control">
+ <LlmSecretSelect
+ id="model-fallback-secret"
+ value={secretRefDraft}
+ ariaLabel="LLM Secret"
+ onChange={value => {
+ const parsed = parseCredentialSelect(value)
+ setSecretRefDraft(parsed.kind === 'secret' ? parsed.name : '')
+ }}
+ options={apiKeySecretOptions}
+ placeholder={
+ apiKeySecretOptions.length === 0
+ ? 'No LLM Secret available'
+ : 'Select an LLM Secret...'
+ }
+ disabled={busy || !editingModel}
+ />
+ <button
+ type="button"
+ className="cu-btn cu-btn--icon cu-btn--toolbar"
+ onClick={() => setLlmSecretModalOpen(true)}
+ disabled={busy || !secretRefDraft.trim()}
+ aria-label="Edit LLM Secret credentials"
+ title="Edit LLM Secret credentials"
+ >
+ <IconPencil width={16} height={16} />
+ </button>
+ </div>
+ <span className="cu-field__hint">
+ Needed for the {fallbackSecretLabels.join(', ') || 'static'} fallback
+ {fallbackSecretLabels.length === 1 ? '' : 's'} in this chain.
+ </span>
+ {linkedSecretProviderMismatch ? (
+ <div className="cu-banner cu-banner--warning">
+ The linked secret does not contain a usable {secretMismatchLabel} credential.
+ Choose another secret or edit its credentials before saving model
+ configuration.
+ </div>
+ ) : null}
+ </div>
+ ) : linkedSecretProviderMismatch ? (
+ <div className="cu-banner cu-banner--warning">
+ The linked secret does not contain a usable {secretMismatchLabel} credential.
+ Choose another secret or edit its credentials before saving model configuration.
+ </div>
+ ) : null}
{editingModel ? (
<>
<LlmProviderConfig
diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsx
index c068e014c..44c24adad 100644
--- a/control-ui/components/HostWizard/index.tsx
+++ b/control-ui/components/HostWizard/index.tsx
@@ -25,6 +25,7 @@ import {
listCodexConnectionModels,
listCodexSubscriptionConnections,
} from '@/lib/codexSubscription'
+import { isDisabledCapabilityError } from '@/lib/codexSubscriptionFeature'
import { useLlmAllowedModels } from '@/lib/hooks/useLlmAllowedModels'
import { getAgentNameError } from '@/lib/k8sValidation'
import {
@@ -400,7 +401,9 @@ export function HostWizard({
.catch(err => {
if (!cancelled) {
setCodexConnections([])
- setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')
+ if (!isDisabledCapabilityError(err)) {
+ setError(err instanceof Error ? err.message : 'Could not load ChatGPT subscriptions')
+ }
}
})
return () => {
diff --git a/control-ui/components/LlmModelTable.tsx b/control-ui/components/LlmModelTable.tsx
index 8c1976581..9e5b21f52 100644
--- a/control-ui/components/LlmModelTable.tsx
+++ b/control-ui/components/LlmModelTable.tsx
@@ -51,7 +51,11 @@ function compareModel(a: LlmAllowedModel, b: LlmAllowedModel): number {
const ALL_PROVIDERS = '__all__'
-type DisplayModel = LlmAllowedModel & { credentialLabel: string }
+type DisplayModel = LlmAllowedModel & {
+ credentialLabel: string
+ apiKeyRow?: LlmAllowedModel
+ subscriptionRow?: LlmAllowedModel
+}
function collapseFamilyRows(family: string, models: LlmAllowedModel[]): DisplayModel[] {
if (family !== 'openai') {
@@ -70,7 +74,12 @@ function collapseFamilyRows(family: string, models: LlmAllowedModel[]): DisplayM
const parts: string[] = []
if (apiKey) parts.push('API key')
if (subscription) parts.push('Subscription')
- return { ...primary, credentialLabel: parts.join(' · ') }
+ return {
+ ...primary,
+ credentialLabel: parts.join(' · '),
+ apiKeyRow: apiKey,
+ subscriptionRow: subscription,
+ }
})
}
@@ -453,20 +462,55 @@ export function LlmModelTable({
<RowActionsMenu
ariaLabel={`Actions for model ${model.provider}/${model.model}`}
horizontalTrigger
- actions={[
- {
- key: 'edit',
- label: 'Edit',
- onClick: () => onEdit(model.id),
- },
- {
- key: 'delete',
- label: deletingId === model.id ? 'Deleting…' : 'Delete',
- danger: true,
- disabled: deletingId === model.id,
- onClick: () => void onDelete(model),
- },
- ]}
+ actions={
+ model.apiKeyRow && model.subscriptionRow
+ ? [
+ {
+ key: 'edit-api-key',
+ label: 'Edit API key',
+ onClick: () => onEdit(model.apiKeyRow!.id),
+ },
+ {
+ key: 'edit-subscription',
+ label: 'Edit subscription',
+ onClick: () => onEdit(model.subscriptionRow!.id),
+ },
+ {
+ key: 'delete-api-key',
+ label:
+ deletingId === model.apiKeyRow.id
+ ? 'Deleting…'
+ : 'Delete API key',
+ danger: true,
+ disabled: deletingId === model.apiKeyRow.id,
+ onClick: () => void onDelete(model.apiKeyRow!),
+ },
+ {
+ key: 'delete-subscription',
+ label:
+ deletingId === model.subscriptionRow.id
+ ? 'Deleting…'
+ : 'Delete subscription',
+ danger: true,
+ disabled: deletingId === model.subscriptionRow.id,
+ onClick: () => void onDelete(model.subscriptionRow!),
+ },
+ ]
+ : [
+ {
+ key: 'edit',
+ label: 'Edit',
+ onClick: () => onEdit(model.id),
+ },
+ {
+ key: 'delete',
+ label: deletingId === model.id ? 'Deleting…' : 'Delete',
+ danger: true,
+ disabled: deletingId === model.id,
+ onClick: () => void onDelete(model),
+ },
+ ]
+ }
/>
</td>
</tr>
diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
index b78050fa9..c723b8faf 100644
--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx
@@ -422,4 +422,68 @@ describe('HostDetailsPage identity integration', () => {
)
expect(screen.queryByText('OpenAI Codex Subscription')).not.toBeInTheDocument()
})
+
+ it('does not surface a page error when ChatGPT subscriptions are disabled', async () => {
+ mockParams = { name: 'foo', tab: 'model' }
+ const err = Object.assign(new Error('disabled'), { status: 404, code: 'disabled' })
+ vi.mocked(listCodexSubscriptionConnections).mockRejectedValue(err)
+ render(<HostDetailsPage />)
+
+ await screen.findByRole('region', { name: 'LLM configuration summary' })
+ expect(screen.queryByText('Could not load ChatGPT subscriptions')).not.toBeInTheDocument()
+ expect(screen.queryByText('disabled')).not.toBeInTheDocument()
+ })
+
+ it('keeps a second LLM Secret field in existing control-ui styles when Codex has a static fallback', async () => {
+ mockParams = { name: 'foo', tab: 'model' }
+ vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
+ {
+ connectionKey: 'codex-aaa',
+ displayName: 'Team A',
+ status: 'connected',
+ credentialRevision: 1,
+ catalogRevision: 1,
+ accountFingerprint: 'fp',
+ catalogStatus: 'ready',
+ catalogSyncedAt: '2026-08-20T00:00:00.000Z',
+ lastRefreshAt: '2026-08-20T00:00:00.000Z',
+ lastAuthAt: '2026-08-20T00:00:00.000Z',
+ refreshLockHeld: false,
+ defaultModel: 'gpt-5.1',
+ },
+ ])
+ vi.mocked(listCodexConnectionModels).mockResolvedValue([
+ { model: 'gpt-5.1', enabled: true, stale: false },
+ ])
+ const fallbackHost = {
+ ...host,
+ spec: {
+ ...host.spec,
+ secretRef: 'openai-secret',
+ model: {
+ provider: 'codex-subscription',
+ name: 'gpt-5.1',
+ connectionRef: 'codex-aaa',
+ },
+ llmPolicy: { fallbacks: [{ provider: 'openai', model: 'gpt-4o' }] },
+ },
+ }
+ ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
+ host: fallbackHost,
+ contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
+ secrets: [{ name: 'openai-secret', keys: ['openai-api-key'] }],
+ users: [],
+ teams: [],
+ agentUsers: [],
+ agentTeams: [],
+ })
+ const { container } = render(<HostDetailsPage />)
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
+ expect(screen.getByLabelText('Credential')).toBeInTheDocument()
+ expect(screen.getByLabelText('LLM Secret')).toBeInTheDocument()
+ expect(container.querySelectorAll('.cu-llm-secret-control')).toHaveLength(2)
+ expect(container.querySelectorAll('.cu-field__hint').length).toBeGreaterThanOrEqual(2)
+ expect(screen.getByRole('button', { name: 'Edit LLM Secret credentials' })).toBeInTheDocument()
+ })
})
diff --git a/control-ui/components/__tests__/LlmModelTable.test.tsx b/control-ui/components/__tests__/LlmModelTable.test.tsx
index 6b8a5c2be..7f3778fc3 100644
--- a/control-ui/components/__tests__/LlmModelTable.test.tsx
+++ b/control-ui/components/__tests__/LlmModelTable.test.tsx
@@ -109,6 +109,44 @@ describe('LlmModelTable catalog-lifecycle columns', () => {
expect(screen.getByText('API key · Subscription')).toBeInTheDocument()
expect(screen.getByText('gpt-5.3-codex').closest('tr')).toHaveTextContent('Subscription')
})
+
+ it('edits the subscription row of a collapsed OpenAI family through the existing actions menu', () => {
+ const onEdit = vi.fn()
+ render(
+ <LlmModelTable
+ items={[
+ {
+ ...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',
+ },
+ ]}
+ unpricedKeys={new Set()}
+ onCreate={vi.fn()}
+ onEdit={onEdit}
+ onDelete={vi.fn().mockResolvedValue(undefined)}
+ onRefresh={vi.fn()}
+ deletingId={null}
+ refreshing={false}
+ loading={false}
+ />
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'Expand OpenAI models' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Actions for model openai/gpt-5.1' }))
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Edit subscription' }))
+ expect(onEdit).toHaveBeenCalledWith('oa-sub')
+ })
})
describe('LlmModelTable filters', () => {
diff --git a/control-ui/lib/codexSubscriptionFeature.ts b/control-ui/lib/codexSubscriptionFeature.ts
index 19177cc60..bc8510260 100644
--- a/control-ui/lib/codexSubscriptionFeature.ts
+++ b/control-ui/lib/codexSubscriptionFeature.ts
@@ -7,7 +7,7 @@ export type CodexSubscriptionCapability = {
const DISABLED_CAPABILITY: CodexSubscriptionCapability = { enabled: false }
-function isDisabledCapabilityError(error: unknown): boolean {
+export function isDisabledCapabilityError(error: unknown): boolean {
if (!error || typeof error !== 'object') return false
const status = (error as { status?: unknown }).status
const code = (error as { code?: unknown }).code
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index a570e2b37..364ead2b7 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.472",
+ "version": "0.1.473",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.472",
+ "version": "0.1.473",
"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 3e1f94978..9e778dced 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.472",
+ "version": "0.1.473",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index 0b28c1870..64b419081 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.259",
+ "version": "0.1.260",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.259",
+ "version": "0.1.260",
"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 e07c3453f..95556c9a5 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.259",
+ "version": "0.1.260",
"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.test.ts b/host-context-controller/src/codexExecutionProjection.test.ts
index d6caa7c91..7ea5cb2da 100644
--- a/host-context-controller/src/codexExecutionProjection.test.ts
+++ b/host-context-controller/src/codexExecutionProjection.test.ts
@@ -103,6 +103,29 @@ describe('projectCodexExecution', () => {
expect(first.catalogContentHash).not.toBe(second.catalogContentHash)
})
+ it('keeps the runtime drift hash stable when only connectionRevision changes', () => {
+ const spec = { model: { provider: 'codex-subscription', name: 'gpt-5.3-codex' } }
+ const first = projectCodexExecution(spec, {
+ flagEnabled: true,
+ connectionStatus: 'connected',
+ catalogContentHash: 'aaa',
+ catalogRevision: 1,
+ connectionRevision: 4,
+ enabledModels: ['codex-subscription:gpt-5.3-codex'],
+ staleModels: [],
+ })
+ const second = projectCodexExecution(spec, {
+ flagEnabled: true,
+ connectionStatus: 'connected',
+ catalogContentHash: 'aaa',
+ catalogRevision: 1,
+ connectionRevision: 12,
+ enabledModels: ['codex-subscription:gpt-5.3-codex'],
+ staleModels: [],
+ })
+ expect(first.driftHashInput).toBe(second.driftHashInput)
+ })
+
it('treats a missing Host connectionRef as unassigned, not the reserved grant', () => {
expect(assignedHostCodexConnectionRef(undefined)).toBe(CODEX_UNASSIGNED_CONNECTION_KEY)
expect(assignedHostCodexConnectionRef('')).toBe(CODEX_UNASSIGNED_CONNECTION_KEY)
diff --git a/host-context-controller/src/codexExecutionProjection.ts b/host-context-controller/src/codexExecutionProjection.ts
index f8486ae06..8b65bec9e 100644
--- a/host-context-controller/src/codexExecutionProjection.ts
+++ b/host-context-controller/src/codexExecutionProjection.ts
@@ -169,7 +169,6 @@ function freezeProjection(
const driftHashInput = JSON.stringify({
eligibleTargets: input.eligibleTargets,
derivedScopes: input.derivedScopes,
- connectionRevision: input.connectionRevision,
eligibility: input.eligibility,
})
return Object.freeze({ ...input, driftHashInput })
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 553e0fd74..4ded691e4 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.292",
+ "version": "0.1.293",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.292",
+ "version": "0.1.293",
"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 1377b2d93..d79f3f060 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.292",
+ "version": "0.1.293",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts b/mcp-host/src/__tests__/workflow/workflowRouter.test.ts
index 2e4c0ab7b..7344e1fa1 100644
--- a/mcp-host/src/__tests__/workflow/workflowRouter.test.ts
+++ b/mcp-host/src/__tests__/workflow/workflowRouter.test.ts
@@ -348,7 +348,26 @@ describe('workflowRouter — JWT auth middleware', () => {
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({}),
})
- expect([200, 400]).toContain(res.status)
+ expect(res.status).toBe(200)
+ } finally {
+ server.close()
+ }
+ })
+
+ it('POST /configure maps configured:false to HTTP 400', async () => {
+ const token = await signWorkflowToken({ sub: 'wrc', scopes: ['configure'] })
+ const { baseUrl, server } = await createTestApp(publicKeyPem, true, {
+ configure: vi.fn().mockReturnValue({ configured: false, message: 'apiKey is required' }),
+ })
+ try {
+ const res = await fetch(`${baseUrl}/api/v1/workflow/configure`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
+ body: JSON.stringify({ provider: 'openai' }),
+ })
+ expect(res.status).toBe(400)
+ const body = (await res.json()) as { configured: boolean }
+ expect(body.configured).toBe(false)
} finally {
server.close()
}
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
index e63ecf73d..b9a1326ec 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/controlApiClient.ts
@@ -377,6 +377,7 @@ export class PluginWorkloadSdkControlApiClient {
Authorization: `Bearer ${this.opts.getAccessToken()}`,
},
body: JSON.stringify(body),
+ signal: AbortSignal.timeout(15_000),
})
} catch (err) {
// Network failure — retryable.
diff --git a/mcp-host/src/workflow/__tests__/configureHandler.test.ts b/mcp-host/src/workflow/__tests__/configureHandler.test.ts
index bf7fa08f0..8a89cf97e 100644
--- a/mcp-host/src/workflow/__tests__/configureHandler.test.ts
+++ b/mcp-host/src/workflow/__tests__/configureHandler.test.ts
@@ -115,6 +115,22 @@ describe('POST /configure — provider hot-swap', () => {
const result = svc.configure({ provider: 'openai', model: 'gpt-4' } as ConfigureRequest)
expect(result.configured).toBe(false)
})
+
+ it('swaps onto codex-subscription without an apiKey so the next step cannot inherit the prior key', () => {
+ const factory = vi.fn(mockLlmFactory())
+ const svc = new WorkflowService('test', { llmFactory: factory })
+ svc.configure({ provider: 'openai', model: 'gpt-4', apiKey: 'sk-123' })
+ const result = svc.configure({
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ } as ConfigureRequest)
+ expect(result).toEqual({
+ configured: true,
+ provider: 'codex-subscription',
+ model: 'gpt-5.3-codex',
+ })
+ expect(factory).toHaveBeenLastCalledWith('codex-subscription', 'gpt-5.3-codex', '')
+ })
})
describe('POST /configure — SOUL override', () => {
diff --git a/mcp-host/src/workflow/workflowRouter.ts b/mcp-host/src/workflow/workflowRouter.ts
index 8d942d269..1372a70b2 100644
--- a/mcp-host/src/workflow/workflowRouter.ts
+++ b/mcp-host/src/workflow/workflowRouter.ts
@@ -151,7 +151,7 @@ export function createWorkflowRouter(service: WorkflowService): Router {
if (!validateWorkflowBinding(req, res, { expectedSub: 'wrc' })) return
const body = req.body as ConfigureRequest
const result = service.configure(body)
- res.json(result)
+ res.status(result.configured ? 200 : 400).json(result)
})
// POST /plugin-workload-sdk/bootstrap — publish only the public
diff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.ts
index f99f14e3b..8076479b6 100644
--- a/mcp-host/src/workflow/workflowService.ts
+++ b/mcp-host/src/workflow/workflowService.ts
@@ -602,14 +602,22 @@ export class WorkflowService {
if (!req.provider) {
return { configured: false, message: 'provider is required' }
}
- if (!req.apiKey) {
- return { configured: false, message: 'apiKey is required' }
- }
if (!isLlmProvider(req.provider)) {
return { configured: false, message: `Unknown provider: ${req.provider}` }
}
+ // oauth-broker (Codex) binds provider/model only. Control API remains the
+ // OAuth custodian; a keyless configure must still swap the in-memory
+ // provider so the next step does not inherit the previous credential.
+ const brokerBacked = descriptorFor(req.provider).authMode === 'oauth-broker'
+ if (!brokerBacked && !req.apiKey) {
+ return { configured: false, message: 'apiKey is required' }
+ }
+ if (brokerBacked && !req.model?.trim()) {
+ return { configured: false, message: 'model is required' }
+ }
+
// SOUL override
if (req.soulContent !== undefined) {
if (Buffer.byteLength(req.soulContent, 'utf-8') > MAX_SOUL_BYTES) {
@@ -620,6 +628,7 @@ export class WorkflowService {
}
const model = req.model ?? 'default'
+ const apiKey = brokerBacked ? '' : (req.apiKey ?? '')
const llmSecretName = WorkflowService.normalizeLlmSecretName(req.llmSecretName)
if (req.llmSecretName !== undefined && llmSecretName === null) {
return { configured: false, message: 'llmSecretName must be a valid Kubernetes Secret name' }
@@ -631,14 +640,14 @@ export class WorkflowService {
if (
this.currentProviderName === req.provider &&
this.currentModel === model &&
- this.currentApiKey === req.apiKey &&
+ this.currentApiKey === apiKey &&
this.configured
) {
this.currentLlmSecretName = llmSecretName
return { configured: true, provider: req.provider, model }
}
- const provider = this.llmFactory(req.provider, model, req.apiKey)
+ const provider = this.llmFactory(req.provider, model, apiKey)
if (!provider) {
return { configured: false, message: `Failed to create provider: ${req.provider}` }
}
@@ -652,10 +661,10 @@ export class WorkflowService {
this.currentProvider = effectiveProvider
this.currentProviderName = req.provider
this.currentModel = model
- this.currentApiKey = req.apiKey
+ this.currentApiKey = apiKey
this.currentLlmSecretName = llmSecretName
this.configured = true
- this.notifyLlmConfigured(req.provider, model, req.apiKey)
+ this.notifyLlmConfigured(req.provider, model, apiKey)
return { configured: true, provider: req.provider, model }
}
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 0edfc0f0c..55ecd6f83 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.311",
+ "version": "0.1.312",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.311",
+ "version": "0.1.312",
"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 42d320a88..d76e25cc4 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.311",
+ "version": "0.1.312",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/workflow/codexExecutionProjection.test.ts b/workflow-recipes/src/workflow/codexExecutionProjection.test.ts
index cd005d03e..2ddcf9998 100644
--- a/workflow-recipes/src/workflow/codexExecutionProjection.test.ts
+++ b/workflow-recipes/src/workflow/codexExecutionProjection.test.ts
@@ -75,7 +75,7 @@ describe('projectCodexExecution (WRC)', () => {
}
})
- it('does not roll the drift hash on catalog refresh; credential revision still drifts', () => {
+ it('does not roll the drift hash on catalog or credential-revision refresh', () => {
const eligible = fixture.cases.find(testCase => testCase.id === 'flag-on-connected-ready')
expect(eligible).toBeDefined()
const baseline = projectCodexExecution(eligible!.spec, eligible!.snapshot)
@@ -90,7 +90,7 @@ describe('projectCodexExecution (WRC)', () => {
})
expect(catalogOnly.derivedScopes).toEqual(baseline.derivedScopes)
expect(catalogOnly.driftHashInput).toBe(baseline.driftHashInput)
- expect(credentialChanged.driftHashInput).not.toBe(baseline.driftHashInput)
+ expect(credentialChanged.driftHashInput).toBe(baseline.driftHashInput)
})
it('treats a malformed empty broker model as ineligible', () => {
diff --git a/workflow-recipes/src/workflow/codexExecutionProjection.ts b/workflow-recipes/src/workflow/codexExecutionProjection.ts
index b069dae99..b420f2c2c 100644
--- a/workflow-recipes/src/workflow/codexExecutionProjection.ts
+++ b/workflow-recipes/src/workflow/codexExecutionProjection.ts
@@ -15,7 +15,13 @@ export type CodexProvenance = 'authoritative' | 'uncertain'
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
@@ -205,7 +211,6 @@ function freezeProjection(
const driftHashInput = JSON.stringify({
eligibleTargets: input.eligibleTargets,
derivedScopes: input.derivedScopes,
- connectionRevision: input.connectionRevision,
eligibility: input.eligibility,
})
return Object.freeze({ ...input, driftHashInput })
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
index 18ab162e3..e2b469ad8 100644
--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.test.ts
@@ -3,6 +3,7 @@ import {
CODEX_CONNECTION_REF_ANNOTATION,
parseAllowedModelsSnapshot,
readRecipeCodexConnectionRef,
+ snapshotForAssignedCodexGrant,
} from './llmAllowedModelsSnapshot'
function multiGrantConfigMap() {
@@ -91,3 +92,24 @@ describe('readRecipeCodexConnectionRef', () => {
expect(readRecipeCodexConnectionRef({})).not.toBe('deployment-default')
})
})
+
+describe('snapshotForAssignedCodexGrant', () => {
+ it('does not project a legacy flat catalog onto an unassigned recipe', () => {
+ const legacy = {
+ metadata: {
+ annotations: {
+ 'clerum.io/codex-enabled': 'true',
+ 'clerum.io/codex-connection-status': 'connected',
+ },
+ },
+ data: {
+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex', stale: false }]),
+ },
+ }
+ const fallback = parseAllowedModelsSnapshot(legacy, 'deployment-default')
+ expect(Array.from(fallback.enabledModels ?? [])).toContain('codex-subscription:gpt-5.3-codex')
+ const snapshot = snapshotForAssignedCodexGrant('unassigned', legacy, fallback)
+ expect(snapshot.connectionStatus).toBe('disconnected')
+ expect(Array.from(snapshot.enabledModels ?? [])).toEqual([])
+ })
+})
diff --git a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
index 7fc773ade..24201cffd 100644
--- a/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
+++ b/workflow-recipes/src/workflow/llmAllowedModelsSnapshot.ts
@@ -155,3 +155,24 @@ export function parseAllowedModelsSnapshot(
staleModels,
}
}
+
+/**
+ * Per-recipe snapshot. `unassigned` never inherits a legacy flat catalog —
+ * that would let a recipe without a grant spend the cluster default.
+ */
+export function snapshotForAssignedCodexGrant(
+ connectionKey: string,
+ lastConfigMap: V1ConfigMap | undefined | null,
+ fallback: CodexCatalogSnapshot
+): CodexCatalogSnapshot {
+ if (connectionKey === CODEX_UNASSIGNED_CONNECTION_KEY) {
+ return {
+ flagEnabled: fallback.flagEnabled,
+ connectionStatus: 'disconnected',
+ enabledModels: [],
+ staleModels: [],
+ }
+ }
+ if (!lastConfigMap) return fallback
+ return parseAllowedModelsSnapshot(lastConfigMap, connectionKey)
+}
diff --git a/workflow-recipes/src/workflow/modelConfigHandler.ts b/workflow-recipes/src/workflow/modelConfigHandler.ts
index 9717cf1f5..441d200bd 100644
--- a/workflow-recipes/src/workflow/modelConfigHandler.ts
+++ b/workflow-recipes/src/workflow/modelConfigHandler.ts
@@ -455,7 +455,7 @@ export class ModelConfigHandler {
wrcConfigureToken,
configureBody
)
- if (result.status >= 400) {
+ if (mcpHostConfigureRejected(result)) {
return {
status: 502,
body: { error: 'mcp_host configure failed', mcpHostStatus: result.status },
@@ -530,7 +530,7 @@ export class ModelConfigHandler {
try {
const result = await this.mcpHost.configure(mcpHostEndpoint, wrcConfigureToken, configureBody)
- if (result.status >= 400) {
+ if (mcpHostConfigureRejected(result)) {
return {
status: 502,
body: { error: 'mcp_host configure failed', mcpHostStatus: result.status },
@@ -676,6 +676,14 @@ export class ModelConfigHandler {
}
}
+/** mcp-host /configure answers HTTP 200 even when configured:false. */
+function mcpHostConfigureRejected(result: {
+ status: number
+ body?: Record<string, unknown>
+}): boolean {
+ return result.status >= 400 || result.body?.configured === false
+}
+
function isBootstrapIdentityProof(body: Record<string, unknown>): boolean {
return (
body.configured === true &&
diff --git a/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts b/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
index caa045c6b..c7fe49600 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.codexScopeProvenance.test.ts
@@ -1,7 +1,11 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { WorkflowRecipeSpec } from '../types'
import { issueMcpHostRuntimeTokens } from './mcpHostRuntimeTokenIssuerClient'
-import { WorkflowReconciler, type WorkflowReconcilerDeps } from './workflowReconciler'
+import {
+ type CodexReconcileContext,
+ WorkflowReconciler,
+ type WorkflowReconcilerDeps,
+} from './workflowReconciler'
const crashRecoveryMocks = vi.hoisted(() => ({
deletePodIfExists: vi.fn().mockResolvedValue(undefined),
@@ -73,6 +77,21 @@ function makeCodexSpec(overrides?: Partial<WorkflowRecipeSpec>): WorkflowRecipeS
}
}
+function bindNamedGrant(
+ reconciler: WorkflowReconciler,
+ recipeName = 'codex-recipe',
+ extras: Partial<CodexReconcileContext> = {}
+) {
+ reconciler.setCodexReconcileContext({
+ recipeName,
+ runtimeScopeRecipeName: extras.runtimeScopeRecipeName ?? recipeName,
+ claimedParent: extras.claimedParent ?? false,
+ parentSpec: extras.parentSpec ?? null,
+ connectionKey: extras.connectionKey ?? 'team-plus',
+ ...extras,
+ })
+}
+
function issuedScopes(): string[] {
const last = runtimeTokenIssuerMocks.issueMcpHostRuntimeTokens.mock.calls.at(-1)
return (last?.[2] ?? []) as string[]
@@ -207,6 +226,7 @@ describe('WorkflowReconciler Codex scope provenance', () => {
it('issues derived Codex scope and proxy egress from the same reconcile projection', async () => {
const { reconciler, networkingApi } = createHarness()
+ bindNamedGrant(reconciler)
await reconcileRecipe(reconciler, makeCodexSpec())
@@ -224,6 +244,16 @@ describe('WorkflowReconciler Codex scope provenance', () => {
expect(policy?.spec?.egress?.[0]?.ports).toEqual([{ port: 8080, protocol: 'TCP' }])
})
+ it('does not mint Codex scope from a live catalog when the recipe grant is unassigned', async () => {
+ const { reconciler, networkingApi } = createHarness()
+
+ await reconcileRecipe(reconciler, makeCodexSpec())
+
+ expect(issueMcpHostRuntimeTokens).toHaveBeenCalled()
+ expect(issuedScopes()).not.toContain('llm:codex:execute')
+ expect(proxyPolicyBodies(networkingApi)).toEqual([])
+ })
+
it('does not mint Codex from deriveWorkflowControlScopes when the target is static', async () => {
const { reconciler, networkingApi } = createHarness()
@@ -239,6 +269,7 @@ describe('WorkflowReconciler Codex scope provenance', () => {
it('reissues the token and withdraws egress when the target becomes static', async () => {
const { reconciler, coreApi, networkingApi } = createHarness()
+ bindNamedGrant(reconciler)
await reconcileRecipe(reconciler, makeCodexSpec())
expect(issuedScopes()).toContain('llm:codex:execute')
@@ -288,6 +319,7 @@ describe('WorkflowReconciler Codex scope provenance', () => {
it('withdraws scope and egress when the catalog marks the Codex model stale', async () => {
const { reconciler, coreApi, networkingApi } = createHarness()
+ bindNamedGrant(reconciler)
await reconcileRecipe(reconciler, makeCodexSpec())
expect(issuedScopes()).toContain('llm:codex:execute')
@@ -305,8 +337,7 @@ describe('WorkflowReconciler Codex scope provenance', () => {
it('inherits the parent target and ignores a static child body', async () => {
const { reconciler, networkingApi } = createHarness()
- reconciler.setCodexReconcileContext({
- recipeName: 'child-run',
+ bindNamedGrant(reconciler, 'child-run', {
runtimeScopeRecipeName: 'parent-recipe',
claimedParent: true,
parentSpec: makeCodexSpec(),
@@ -328,8 +359,7 @@ describe('WorkflowReconciler Codex scope provenance', () => {
it('does not mint Codex when a claimed parent fails provenance', async () => {
const { reconciler, networkingApi } = createHarness()
- reconciler.setCodexReconcileContext({
- recipeName: 'child-run',
+ bindNamedGrant(reconciler, 'child-run', {
runtimeScopeRecipeName: 'child-run',
claimedParent: true,
parentSpec: makeCodexSpec(),
@@ -347,6 +377,7 @@ describe('WorkflowReconciler Codex scope provenance', () => {
it('does not mint Codex scope or egress when the allowlist ConfigMap is forbidden', async () => {
const { reconciler, coreApi, networkingApi } = createHarness()
+ bindNamedGrant(reconciler)
coreApi.readNamespacedConfigMap.mockRejectedValue(
Object.assign(new Error('forbidden'), { code: 403 })
)
@@ -364,6 +395,7 @@ describe('WorkflowReconciler Codex scope provenance', () => {
it('does not mint Codex scope or egress when the allowlist ConfigMap times out', async () => {
const { reconciler, coreApi, networkingApi } = createHarness()
+ bindNamedGrant(reconciler)
coreApi.readNamespacedConfigMap.mockRejectedValue(
Object.assign(new Error('Kubernetes request timed out'), { code: 'ETIMEDOUT' })
)
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index fc8bb9394..48edd7a1e 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -61,6 +61,7 @@ import {
ALLOWLIST_CONFIGMAP_NAMESPACE,
CODEX_UNASSIGNED_CONNECTION_KEY,
parseAllowedModelsSnapshot,
+ snapshotForAssignedCodexGrant,
snapshotFromConfigMapError,
} from './llmAllowedModelsSnapshot'
import {
@@ -893,7 +894,7 @@ export class WorkflowReconciler {
* `codexSnapshot` then carries the fail-closed snapshot error.
*/
private lastCodexConfigMap: k8s.V1ConfigMap | undefined
- private codexContext: CodexReconcileContext | null = null
+ private readonly codexContexts = new Map<string, CodexReconcileContext>()
constructor(private readonly deps: WorkflowReconcilerDeps) {
this.pluginWorkloadSdkProvisioner = new PluginWorkloadSdkProvisioner({
@@ -927,16 +928,16 @@ export class WorkflowReconciler {
}
setCodexReconcileContext(context: CodexReconcileContext | null): void {
- this.codexContext = context
+ if (!context) return
+ this.codexContexts.set(context.recipeName, context)
}
private resolveCodexContext(
recipeName: string,
runtimeScopeRecipeName: string
): CodexReconcileContext {
- if (this.codexContext?.recipeName === recipeName) {
- return { ...this.codexContext, runtimeScopeRecipeName }
- }
+ const stored = this.codexContexts.get(recipeName)
+ if (stored) return stored
return {
recipeName,
runtimeScopeRecipeName,
@@ -972,8 +973,7 @@ export class WorkflowReconciler {
* the flat catalog. Read failures keep the fail-closed error snapshot.
*/
private codexSnapshotFor(connectionKey: string): CodexCatalogSnapshot {
- if (!this.lastCodexConfigMap) return this.codexSnapshot
- return parseAllowedModelsSnapshot(this.lastCodexConfigMap, connectionKey)
+ return snapshotForAssignedCodexGrant(connectionKey, this.lastCodexConfigMap, this.codexSnapshot)
}
private resolveEffectiveControlScopes(
@@ -2825,7 +2825,7 @@ export class WorkflowReconciler {
const codexProjection = this.projectCodex(
spec,
recipeName,
- this.codexContext?.runtimeScopeRecipeName ?? recipeName
+ this.resolveCodexContext(recipeName, recipeName).runtimeScopeRecipeName
)
const npConfig: NetworkPolicyConfig = {
recipeName,
@@ -2947,7 +2947,7 @@ export class WorkflowReconciler {
const codexProjection = this.projectCodex(
spec,
recipeName,
- this.codexContext?.runtimeScopeRecipeName ?? recipeName
+ this.resolveCodexContext(recipeName, recipeName).runtimeScopeRecipeName
)
if (!policyNames.has(codexProxyPolicyName) && codexProjection.eligibility !== 'uncertain') {
await this.safeDelete(() =>
diff --git a/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts b/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
index 828d663f7..9eb14d153 100644
--- a/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
+++ b/workflow-recipes/tests/unit/workflow/modelConfigHandler.test.ts
@@ -465,6 +465,22 @@ describe('POST /configure-model — R3 allowlist gate', () => {
expect(result.body).not.toHaveProperty('apiKey')
})
+ it('treats HTTP 200 with configured:false as a configure failure', async () => {
+ const allowlist = { 'codex-subscription': JSON.stringify([{ model: 'gpt-5.3-codex' }]) }
+ const k8s = mockK8s(DEFAULT_CONFIGMAP, DEFAULT_SECRET, allowlist)
+ const mcpHost = mockMcpHost(200, { configured: false, message: 'apiKey is required' })
+ const handler = new ModelConfigHandler(k8s, mcpHost)
+
+ const result = await handler.handle(
+ { stepId: 's1', provider: 'codex-subscription', model: 'gpt-5.3-codex' },
+ 'http://mcp:8080',
+ 'tok'
+ )
+
+ expect(result.status).toBe(502)
+ expect(result.body).toEqual({ error: 'mcp_host configure failed', mcpHostStatus: 200 })
+ })
+
it('rejects a model absent from the allowlist → 403 model_not_allowed', async () => {
const allowlist = { openai: JSON.stringify([{ model: 'gpt-4' }]) }
const k8s = mockK8s(DEFAULT_CONFIGMAP, DEFAULT_SECRET, allowlist)