Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): authorize Grok spend and dual-write recipe grants
Jose Gabriel Ramirez Encinas42525fc60c5f
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex c376d2a63..358a89549 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.558",+ "version": "0.1.559","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.558",+ "version": "0.1.559","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex ec70db9a6..b89bc1bbf 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.558",+ "version": "0.1.559","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/codexSubscription.ts b/control-api/src/routes/admin/codexSubscription.tsindex e9a8c4404..b3ce63163 100644--- a/control-api/src/routes/admin/codexSubscription.ts+++ b/control-api/src/routes/admin/codexSubscription.ts@@ -45,6 +45,35 @@ import {isPublicCodexCliClient,resolveCodexControlUiBaseUrl,} from '../../services/codexSubscriptionRedirectUri.js'+import {+ type GrokCatalogTransport,+ createGrokCatalogTransportFromEnv,+ listGrokCatalogModels,+ listOfferedGrokModelsForAssignment,+ pickGrokGrantModel,+ setGrokCatalogModelEnabled,+} from '../../services/grokSubscriptionCatalog.js'+import {+ GROK_UNASSIGNED_CONNECTION_KEY,+ GrokSubscriptionInvalidConnectionKeyError,+ assertGrokConnectionKey,+ createNamedGrokSubscriptionConnection,+ generateGrokConnectionKey,+ getSafeGrokSubscriptionConnection,+ listSafeGrokSubscriptionConnections,+ updateGrokSubscriptionConnectionMetadata,+} from '../../services/grokSubscriptionConnection.js'+import {+ type GrokOAuthDeps,+ GrokSubscriptionOAuthError,+ getGrokSubscriptionConnection,+ isGrokOAuthErrorCode,+ pollGrokDevice,+ refreshGrokSubscriptionConnection,+ revokeGrokSubscription,+ runGrokCatalogSync,+ startGrokDeviceConnect,+} from '../../services/grokSubscriptionOAuth.js'import { publishAllowedModelsConfigMapAfterGrantChange } from '../../services/llmAllowedModelsConfigMap.js'import { K8sConflictError } from '../../services/resourceService.js'import {@@ -129,6 +158,27 @@ function sendOAuthError(res.status(400).json({ error: 'invalid_connection_key' })return}+ if (err instanceof GrokSubscriptionInvalidConnectionKeyError) {+ res.status(400).json({ error: 'invalid_connection_key' })+ return+ }+ if (err instanceof GrokSubscriptionOAuthError) {+ const status =+ err.code === 'disabled'+ ? 404+ : err.code === 'replacement_required' ||+ err.code === 'fingerprint_in_use' ||+ err.code === 'connection_mismatch'+ ? 409+ : err.code === 'refresh_in_flight' || err.code === 'stale_revision'+ ? 409+ : err.code === 'not_connected' || err.code === 'no_grant'+ ? 404+ : 400+ log.warn({ event: 'grok_oauth_admin_denied', code: err.code }, 'Grok subscription OAuth denied')+ res.status(status).json({ error: err.code })+ return+ }if (err instanceof CodexSubscriptionOAuthError) {const status =err.code === 'disabled'@@ -180,10 +230,11 @@ function hostModelName(spec: unknown): string {return typeof name === 'string' ? name.trim() : ''}-function hostConnectionRef(spec: unknown): string | null {+function hostConnectionRef(spec: unknown, provider = 'codex-subscription'): string | null {const model = hostModel(spec)- if (!model || model.provider !== 'codex-subscription') return null+ if (!model || model.provider !== provider) return nullconst raw = typeof model.connectionRef === 'string' ? model.connectionRef.trim() : ''+ if (provider === 'grok-subscription') return raw || GROK_UNASSIGNED_CONNECTION_KEYreturn raw || CODEX_UNASSIGNED_CONNECTION_KEY}@@ -194,8 +245,11 @@ function assignableHostFromRecord(host: HostRecord): CodexAssignableHostRow | nuconst provider = typeof model?.provider === 'string' ? model.provider.trim() : ''const modelName = hostModelName(host.spec)const connectionRef =- provider === 'codex-subscription'- ? hostConnectionRef(host.spec) || CODEX_UNASSIGNED_CONNECTION_KEY+ provider === 'codex-subscription' || provider === 'grok-subscription'+ ? hostConnectionRef(host.spec, provider) ||+ (provider === 'grok-subscription'+ ? GROK_UNASSIGNED_CONNECTION_KEY+ : CODEX_UNASSIGNED_CONNECTION_KEY): CODEX_UNASSIGNED_CONNECTION_KEYreturn {name,@@ -212,17 +266,61 @@ function storedCodexConnectionRef(spec: unknown): string | null {return typeof model.connectionRef === 'string' ? model.connectionRef.trim() : ''}+function storedGrokConnectionRef(spec: unknown): string | null {+ const model = hostModel(spec)+ if (!model || model.provider !== 'grok-subscription') return null+ return typeof model.connectionRef === 'string' ? model.connectionRef.trim() : ''+}+export function createAdminCodexSubscriptionRouter(catalogTransport: CodexCatalogTransport = createCodexCatalogTransportFromEnv(),gateway?: K8sGateway): Router {const router = Router()mountSubscriptionAdminRoutes(router, {- providerIds: ['codex-subscription'],+ providerIds: ['codex-subscription', 'grok-subscription'],enabled: providerId =>- providerId === 'codex-subscription' ? config.codexSubscriptionEnabled : false,+ providerId === 'codex-subscription'+ ? config.codexSubscriptionEnabled+ : providerId === 'grok-subscription'+ ? config.grokSubscriptionEnabled+ : false,})+ const grokCatalogTransport: GrokCatalogTransport = createGrokCatalogTransportFromEnv()++ function reqProviderId(req: { params?: { providerId?: string } }): string {+ return typeof req.params?.providerId === 'string' ? req.params.providerId : ''+ }++ function isGrokReq(req: { params?: { providerId?: string } }): boolean {+ return reqProviderId(req) === 'grok-subscription'+ }++ function rejectGrokUnkeyed(req: Request, res: Response, next: NextFunction): void {+ if (isGrokReq(req)) {+ res.status(404).json({ error: 'not_found' })+ return+ }+ next()+ }++ function grokOauthDeps(connectionKey: string): GrokOAuthDeps {+ return {+ db: dbClient(),+ encryptionKey: deriveOAuthEncryptionKey(config.oauthEncryptionKey),+ fetchFn: fetch,+ clientId: config.grokOAuthClientId,+ enabled: config.grokSubscriptionEnabled,+ connectionKey,+ }+ }++ function grokKeyFromReq(req: { params?: { key?: string } }): string {+ const raw = typeof req.params?.key === 'string' ? req.params.key.trim() : ''+ return assertGrokConnectionKey(raw)+ }+async function listHostsOrUnavailable(): Promise<HostRecord[] | null> {if (!gateway) return nulltry {@@ -233,9 +331,13 @@ export function createAdminCodexSubscriptionRouter(}}- function hostsForConnection(hosts: HostRecord[], connectionKey: string): Array<{ name: string }> {+ function hostsForConnection(+ hosts: HostRecord[],+ connectionKey: string,+ provider = 'codex-subscription'+ ): Array<{ name: string }> {return hosts- .filter(host => hostConnectionRef(host.spec) === connectionKey)+ .filter(host => hostConnectionRef(host.spec, provider) === connectionKey).map(host => ({ name: String(host.metadata?.name ?? '') })).filter(host => host.name)}@@ -274,7 +376,8 @@ export function createAdminCodexSubscriptionRouter(async function writeHostConnectionRef(hostRef: string,host: HostRecord,- nextConnectionRef: string+ nextConnectionRef: string,+ provider: 'codex-subscription' | 'grok-subscription' = 'codex-subscription'): Promise<| { ok: true; warnings: StaleModelWarning[]; model: string }| { ok: false; status: number; error: string; message?: string; reason?: string }@@ -288,11 +391,15 @@ export function createAdminCodexSubscriptionRouter(spec.model && typeof spec.model === 'object'? { ...(spec.model as Record<string, unknown>) }: {}- model.provider = 'codex-subscription'+ const grok = provider === 'grok-subscription'+ model.provider = grok ? 'grok-subscription' : 'codex-subscription'model.connectionRef = nextConnectionReflet resolvedModel = typeof model.name === 'string' ? model.name.trim() : ''- if (nextConnectionRef !== CODEX_UNASSIGNED_CONNECTION_KEY) {- const offered = await listOfferedCodexModelsForAssignment(dbClient(), nextConnectionRef)+ const unassigned = grok ? GROK_UNASSIGNED_CONNECTION_KEY : CODEX_UNASSIGNED_CONNECTION_KEY+ if (nextConnectionRef !== unassigned) {+ const offered = grok+ ? await listOfferedGrokModelsForAssignment(dbClient(), nextConnectionRef)+ : await listOfferedCodexModelsForAssignment(dbClient(), nextConnectionRef)if (offered.length === 0) {return {ok: false,@@ -302,8 +409,13 @@ export function createAdminCodexSubscriptionRouter('This subscription has no offered models yet. Sign in and sync the catalog before assigning agents.',}}- const grant = await getSafeCodexSubscriptionConnection(dbClient(), nextConnectionRef)- resolvedModel = pickCodexGrantModel(resolvedModel, offered, grant?.defaultModel)+ if (grok) {+ const grant = await getSafeGrokSubscriptionConnection(dbClient(), nextConnectionRef)+ resolvedModel = pickGrokGrantModel(resolvedModel, offered, grant?.defaultModel)+ } else {+ const grant = await getSafeCodexSubscriptionConnection(dbClient(), nextConnectionRef)+ resolvedModel = pickCodexGrantModel(resolvedModel, offered, grant?.defaultModel)+ }model.name = resolvedModel}spec.model = model@@ -380,7 +492,8 @@ export function createAdminCodexSubscriptionRouter(async function withAssignedHosts<T extends { connectionKey: string }>(connection: T,- hosts?: HostRecord[] | null+ hosts?: HostRecord[] | null,+ provider = 'codex-subscription') {const resolved = hosts === undefined ? await listHostsOrUnavailable() : hostsif (resolved === null) {@@ -388,12 +501,17 @@ export function createAdminCodexSubscriptionRouter(}return {...connection,- assignedHosts: hostsForConnection(resolved, connection.connectionKey),+ assignedHosts: hostsForConnection(resolved, connection.connectionKey, provider),}}const getConnectionHandler = asyncHandler(async (req, res) => {try {+ if (isGrokReq(req)) {+ const connection = await getGrokSubscriptionConnection(grokOauthDeps(grokKeyFromReq(req)))+ res.status(200).json(await withAssignedHosts(connection, undefined, 'grok-subscription'))+ return+ }const connection = await getCodexSubscriptionConnection(oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req)))@@ -424,6 +542,14 @@ export function createAdminCodexSubscriptionRouter(const deviceStartHandler = asyncHandler(async (req, res) => {try {+ if (isGrokReq(req)) {+ const started = await startGrokDeviceConnect(+ grokOauthDeps(grokKeyFromReq(req)),+ parseIntent(req.body?.intent)+ )+ res.status(200).json(started)+ return+ }const started = await startCodexDeviceConnect(oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req)),parseIntent(req.body?.intent)@@ -437,6 +563,30 @@ export function createAdminCodexSubscriptionRouter(const devicePollHandler = asyncHandler(async (req, res) => {try {const state = typeof req.query.state === 'string' ? req.query.state : ''+ if (isGrokReq(req)) {+ const connectionKey = grokKeyFromReq(req)+ const deps = grokOauthDeps(connectionKey)+ let result = await pollGrokDevice(deps, state)+ if (result.status === 'connected') {+ const sync = await runGrokCatalogSync(+ deps,+ result.connection.connectionKey,+ grokCatalogTransport+ )+ if (sync.ok) {+ const latest = await getGrokSubscriptionConnection(deps)+ if ('id' in latest) result = { ...result, connection: latest }+ } else if ('connection' in result) {+ result = {+ ...result,+ connection: { ...result.connection, catalogStatus: sync.catalogStatus },+ }+ }+ if (await publishRuntimeAllowlistOrFail(res)) return+ }+ res.status(200).json(result)+ return+ }const connectionKey = keyFromReq(req)const deps = oauthDeps(req, resolveBrowserRedirectUri(req), connectionKey)let result = await pollCodexDevice(deps, state)@@ -464,6 +614,14 @@ export function createAdminCodexSubscriptionRouter(const refreshHandler = asyncHandler(async (req, res) => {try {+ if (isGrokReq(req)) {+ const connection = await refreshGrokSubscriptionConnection(+ grokOauthDeps(grokKeyFromReq(req))+ )+ if (await publishRuntimeAllowlistOrFail(res)) return+ res.status(200).json(connection)+ return+ }const connection = await refreshCodexSubscriptionConnection(oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req)))@@ -476,6 +634,43 @@ export function createAdminCodexSubscriptionRouter(const catalogSyncHandler = asyncHandler(async (req, res) => {try {+ if (isGrokReq(req)) {+ if (!config.grokSubscriptionEnabled) {+ res.status(404).json({ error: 'disabled' })+ return+ }+ const connectionKey = grokKeyFromReq(req)+ const synced = await runGrokCatalogSync(+ grokOauthDeps(connectionKey),+ connectionKey,+ grokCatalogTransport+ )+ if (synced.ok) {+ if (await publishRuntimeAllowlistOrFail(res)) return+ res.status(200).json({+ outcome: synced.catalogStatus,+ connection: synced.connection,+ })+ return+ }+ if (synced.reason === 'no_grant' || synced.reason === 'disabled') {+ res.status(404).json({ error: synced.reason })+ return+ }+ if (synced.reason === 'stale_revision') {+ res.status(409).json({ error: 'stale_revision' })+ return+ }+ if (isGrokOAuthErrorCode(synced.reason ?? '')) {+ sendOAuthError(+ res,+ new GrokSubscriptionOAuthError(synced.reason as never, synced.reason ?? '')+ )+ return+ }+ res.status(503).json({ error: 'catalog_sync_failed', outcome: synced.catalogStatus })+ return+ }if (!config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })return@@ -525,6 +720,12 @@ export function createAdminCodexSubscriptionRouter(const revokeHandler = asyncHandler(async (req, res) => {try {+ if (isGrokReq(req)) {+ const connection = await revokeGrokSubscription(grokOauthDeps(grokKeyFromReq(req)))+ if (await publishRuntimeAllowlistOrFail(res)) return+ res.status(200).json(await withAssignedHosts(connection, undefined, 'grok-subscription'))+ return+ }const connection = await revokeCodexSubscription(oauthDeps(req, resolveBrowserRedirectUri(req), keyFromReq(req)))@@ -535,16 +736,42 @@ export function createAdminCodexSubscriptionRouter(}})- router.get(`${BASE}/connection`, ...adminCodexReadRateLimits(), getConnectionHandler)- router.post(`${BASE}/browser/start`, ...adminCodexWriteRateLimits(), browserStartHandler)- router.post(`${BASE}/device/start`, ...adminCodexWriteRateLimits(), deviceStartHandler)- router.get(`${BASE}/device/poll`, ...adminCodexReadRateLimits(), devicePollHandler)- router.post(`${BASE}/refresh`, ...adminCodexWriteRateLimits(), refreshHandler)- router.post(`${BASE}/catalog/sync`, ...adminCodexWriteRateLimits(), catalogSyncHandler)- router.post(`${BASE}/revoke`, ...adminCodexWriteRateLimits(), revokeHandler)+ router.get(+ `${BASE}/connection`,+ rejectGrokUnkeyed,+ ...adminCodexReadRateLimits(),+ getConnectionHandler+ )+ router.post(+ `${BASE}/browser/start`,+ rejectGrokUnkeyed,+ ...adminCodexWriteRateLimits(),+ browserStartHandler+ )+ router.post(+ `${BASE}/device/start`,+ rejectGrokUnkeyed,+ ...adminCodexWriteRateLimits(),+ deviceStartHandler+ )+ router.get(+ `${BASE}/device/poll`,+ rejectGrokUnkeyed,+ ...adminCodexReadRateLimits(),+ devicePollHandler+ )+ router.post(`${BASE}/refresh`, rejectGrokUnkeyed, ...adminCodexWriteRateLimits(), refreshHandler)+ router.post(+ `${BASE}/catalog/sync`,+ rejectGrokUnkeyed,+ ...adminCodexWriteRateLimits(),+ catalogSyncHandler+ )+ router.post(`${BASE}/revoke`, rejectGrokUnkeyed, ...adminCodexWriteRateLimits(), revokeHandler)router.get(`${BASE}/connections/:key`, ...adminCodexReadRateLimits(), getConnectionHandler)router.post(`${BASE}/connections/:key/browser/start`,+ rejectGrokUnkeyed,...adminCodexWriteRateLimits(),browserStartHandler)@@ -569,7 +796,28 @@ export function createAdminCodexSubscriptionRouter(router.get(`${BASE}/connections`,...adminCodexReadRateLimits(),- asyncHandler(async (_req, res) => {+ asyncHandler(async (req, res) => {+ if (isGrokReq(req)) {+ if (!config.grokSubscriptionEnabled) {+ res.status(404).json({ error: 'disabled' })+ return+ }+ const rows = await listSafeGrokSubscriptionConnections(dbClient())+ const hosts = await listHostsOrUnavailable()+ const connections = []+ for (const row of rows) {+ connections.push(await withAssignedHosts(row, hosts, 'grok-subscription'))+ }+ if (hosts === null) {+ res.status(200).json({ connections, assignableHostsUnavailable: true })+ return+ }+ res.status(200).json({+ connections,+ assignableHosts: collectAssignableHosts(hosts),+ })+ return+ }if (!config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })return@@ -595,6 +843,43 @@ export function createAdminCodexSubscriptionRouter(`${BASE}/connections`,...adminCodexWriteRateLimits(),asyncHandler(async (req, res) => {+ if (isGrokReq(req)) {+ if (!config.grokSubscriptionEnabled) {+ res.status(404).json({ error: 'disabled' })+ return+ }+ try {+ const displayName =+ typeof req.body?.displayName === 'string' && req.body.displayName.trim()+ ? req.body.displayName.trim()+ : 'Grok subscription'+ if (displayName.length > 64) {+ res.status(400).json({ error: 'display_name_too_long' })+ return+ }+ const requestedKey =+ typeof req.body?.connectionKey === 'string' && req.body.connectionKey.trim()+ ? assertGrokConnectionKey(req.body.connectionKey.trim())+ : generateGrokConnectionKey()+ const created = await createNamedGrokSubscriptionConnection(dbClient(), {+ connectionKey: requestedKey,+ displayName,+ })+ res.status(201).json(await withAssignedHosts(created, undefined, 'grok-subscription'))+ } catch (err) {+ if (err instanceof GrokSubscriptionInvalidConnectionKeyError) {+ res.status(400).json({ error: 'invalid_connection_key' })+ return+ }+ const code = (err as { code?: string } | null)?.code+ if (code === '23505') {+ res.status(409).json({ error: 'connection_key_taken' })+ return+ }+ throw err+ }+ return+ }if (!config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })return@@ -636,6 +921,20 @@ export function createAdminCodexSubscriptionRouter(`${BASE}/connections/:key/models`,...adminCodexReadRateLimits(),asyncHandler(async (req, res) => {+ if (isGrokReq(req)) {+ if (!config.grokSubscriptionEnabled) {+ res.status(404).json({ error: 'disabled' })+ return+ }+ const connection = await getGrokSubscriptionConnection(grokOauthDeps(grokKeyFromReq(req)))+ if (!('id' in connection)) {+ res.status(409).json({ error: 'not_connected' })+ return+ }+ const models = await listGrokCatalogModels(dbClient(), connection.id)+ res.status(200).json({ models })+ return+ }if (!config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })return@@ -656,13 +955,14 @@ export function createAdminCodexSubscriptionRouter(`${BASE}/connections/:key`,...adminCodexWriteRateLimits(),asyncHandler(async (req, res) => {- if (!config.codexSubscriptionEnabled) {+ const grok = isGrokReq(req)+ if (grok ? !config.grokSubscriptionEnabled : !config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })return}let connectionKey: stringtry {- connectionKey = keyFromReq(req)+ connectionKey = grok ? grokKeyFromReq(req) : keyFromReq(req)} catch (err) {sendOAuthError(res, err)return@@ -683,16 +983,23 @@ export function createAdminCodexSubscriptionRouter(: '': undefinedif (defaultModel) {- const offered = await listOfferedCodexModelsForAssignment(dbClient(), connectionKey)+ const offered = grok+ ? await listOfferedGrokModelsForAssignment(dbClient(), connectionKey)+ : await listOfferedCodexModelsForAssignment(dbClient(), connectionKey)if (!offered.includes(defaultModel)) {res.status(422).json({ error: 'default_model_not_offered' })return}}- const updated = await updateCodexSubscriptionConnectionMetadata(dbClient(), connectionKey, {- ...(hasDisplayName ? { displayName: req.body.displayName } : {}),- ...(hasDefaultModel ? { defaultModel: defaultModel || null } : {}),- })+ const updated = grok+ ? await updateGrokSubscriptionConnectionMetadata(dbClient(), connectionKey, {+ ...(hasDisplayName ? { displayName: req.body.displayName } : {}),+ ...(hasDefaultModel ? { defaultModel: defaultModel || null } : {}),+ })+ : await updateCodexSubscriptionConnectionMetadata(dbClient(), connectionKey, {+ ...(hasDisplayName ? { displayName: req.body.displayName } : {}),+ ...(hasDefaultModel ? { defaultModel: defaultModel || null } : {}),+ })if (!updated) {res.status(404).json({ error: 'no_grant' })return@@ -705,13 +1012,14 @@ export function createAdminCodexSubscriptionRouter(`${BASE}/connections/:key/models/:model`,...adminCodexWriteRateLimits(),asyncHandler(async (req, res) => {- if (!config.codexSubscriptionEnabled) {+ const grok = isGrokReq(req)+ if (grok ? !config.grokSubscriptionEnabled : !config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })return}let connectionKey: stringtry {- connectionKey = keyFromReq(req)+ connectionKey = grok ? grokKeyFromReq(req) : keyFromReq(req)} catch (err) {sendOAuthError(res, err)return@@ -720,7 +1028,9 @@ export function createAdminCodexSubscriptionRouter(res.status(400).json({ error: 'invalid_enabled' })return}- const connection = await getSafeCodexSubscriptionConnection(dbClient(), connectionKey)+ const connection = grok+ ? await getSafeGrokSubscriptionConnection(dbClient(), connectionKey)+ : await getSafeCodexSubscriptionConnection(dbClient(), connectionKey)if (!connection) {res.status(404).json({ error: 'no_grant' })return@@ -730,12 +1040,9 @@ export function createAdminCodexSubscriptionRouter(res.status(404).json({ error: 'model_not_found' })return}- const models = await setCodexCatalogModelEnabled(- dbClient(),- connection.id,- model,- req.body.enabled- )+ const models = grok+ ? await setGrokCatalogModelEnabled(dbClient(), connection.id, model, req.body.enabled)+ : await setCodexCatalogModelEnabled(dbClient(), connection.id, model, req.body.enabled)if (!models) {res.status(404).json({ error: 'model_not_found' })return@@ -748,8 +1055,8 @@ export function createAdminCodexSubscriptionRouter(router.get(`${BASE}/assignable-hosts`,...adminCodexReadRateLimits(),- asyncHandler(async (_req, res) => {- if (!config.codexSubscriptionEnabled) {+ asyncHandler(async (req, res) => {+ if (isGrokReq(req) ? !config.grokSubscriptionEnabled : !config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })return}@@ -764,15 +1071,16 @@ export function createAdminCodexSubscriptionRouter(const bindUnbindHandler = (action: 'bind' | 'unbind') =>asyncHandler(async (req, res) => {- if (!config.codexSubscriptionEnabled) {+ const grok = isGrokReq(req)+ if (grok ? !config.grokSubscriptionEnabled : !config.codexSubscriptionEnabled) {res.status(404).json({ error: 'disabled' })return}let connectionKey: stringtry {- connectionKey = assertCodexConnectionKey(- typeof req.params.key === 'string' ? req.params.key : ''- )+ connectionKey = grok+ ? assertGrokConnectionKey(typeof req.params.key === 'string' ? req.params.key : '')+ : assertCodexConnectionKey(typeof req.params.key === 'string' ? req.params.key : '')} catch (err) {sendOAuthError(res, err)return@@ -788,22 +1096,26 @@ export function createAdminCodexSubscriptionRouter(res.status(loaded.status).json({ error: loaded.error })return}- const storedRef = storedCodexConnectionRef(loaded.host.spec)+ const storedRef = grok+ ? storedGrokConnectionRef(loaded.host.spec)+ : storedCodexConnectionRef(loaded.host.spec)if (storedRef === null && action === 'unbind') {- res.status(409).json({ error: 'not_codex_host' })+ res.status(409).json({ error: grok ? 'not_grok_host' : 'not_codex_host' })return}+ const unassigned = grok ? GROK_UNASSIGNED_CONNECTION_KEY : CODEX_UNASSIGNED_CONNECTION_KEY+ const provider = grok ? ('grok-subscription' as const) : ('codex-subscription' as const)// Empty/missing connectionRef is unassigned, never the reserved default grant.- // Non-Codex hosts bind as a conversion: the hub is the ops center that+ // Non-broker hosts bind as a conversion: the hub is the ops center that// sets provider, grant, and a seeded default model in one write.- const currentRef = storedRef || CODEX_UNASSIGNED_CONNECTION_KEY+ const currentRef = storedRef || unassignedconst currentModel = hostModelName(loaded.host.spec)if (action === 'unbind') {- if (currentRef === CODEX_UNASSIGNED_CONNECTION_KEY) {+ if (currentRef === unassigned) {res.status(200).json({host: hostRef,- connectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,+ connectionRef: unassigned,...(currentModel ? { model: currentModel } : {}),})return@@ -812,11 +1124,7 @@ export function createAdminCodexSubscriptionRouter(res.status(409).json({ error: 'connection_mismatch' })return}- const written = await writeHostConnectionRef(- hostRef,- loaded.host,- CODEX_UNASSIGNED_CONNECTION_KEY- )+ const written = await writeHostConnectionRef(hostRef, loaded.host, unassigned, provider)if (!written.ok) {res.status(written.status).json({error: written.error,@@ -827,7 +1135,7 @@ export function createAdminCodexSubscriptionRouter(}res.status(200).json({host: hostRef,- connectionRef: CODEX_UNASSIGNED_CONNECTION_KEY,+ connectionRef: unassigned,...(written.model ? { model: written.model } : {}),...(written.warnings.length > 0 ? { warnings: written.warnings } : {}),})@@ -842,7 +1150,7 @@ export function createAdminCodexSubscriptionRouter(})return}- const written = await writeHostConnectionRef(hostRef, loaded.host, connectionKey)+ const written = await writeHostConnectionRef(hostRef, loaded.host, connectionKey, provider)if (!written.ok) {res.status(written.status).json({error: written.error,diff --git a/control-api/src/routes/admin/recipes.ts b/control-api/src/routes/admin/recipes.tsindex 812bfd184..e3d92157e 100644--- a/control-api/src/routes/admin/recipes.ts+++ b/control-api/src/routes/admin/recipes.ts@@ -21,6 +21,11 @@ import {assertCodexConnectionKey,isCodexUnassignedConnectionKey,} from '../../services/codexSubscriptionConnection.js'+import {+ GROK_UNASSIGNED_CONNECTION_KEY,+ assertGrokConnectionKey,+ isGrokUnassignedConnectionKey,+} from '../../services/grokSubscriptionConnection.js'import {ensureRegistryPullSecrets,platformWorkloadNamespaces,@@ -1255,6 +1260,12 @@ function recipeUsesCodexBroker(spec?: Record<string, unknown>): boolean {return (agent as { provider?: unknown }).provider === 'codex-subscription'}+function recipeUsesGrokBroker(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 === 'grok-subscription'+}+function recipeHasPluginWorkloadSdk(spec?: Record<string, unknown>): boolean {const sdk = spec?.pluginWorkloadSdkreturn Boolean(sdk && typeof sdk === 'object' && !Array.isArray(sdk))@@ -1331,11 +1342,75 @@ function bodyHasCodexGrantAnnotation(body: RecipeBody): boolean {)}+function readRequestedGrokRecipeGrant(body: RecipeBody): string {+ const result = readSubscriptionConnectionRef({+ provider: 'grok-subscription',+ annotations: body.metadata?.annotations,+ })+ if (!result.ok) {+ throw new RecipeGrantAnnotationDisagreeError(result.message)+ }+ return result.connectionKey+}++function validateGrokRecipeGrant(+ body: RecipeBody,+ opts?: { allowOmittedGrant?: boolean }+): ValidationError[] {+ if (!recipeUsesGrokBroker(body.spec)) return []+ if (opts?.allowOmittedGrant && !bodyHasCodexGrantAnnotation(body)) return []+ let key: string+ try {+ key = readRequestedGrokRecipeGrant(body)+ } catch (err) {+ if (err instanceof RecipeGrantAnnotationDisagreeError) {+ return [+ {+ field: `metadata.annotations.${SUBSCRIPTION_CONNECTION_REF_ANNOTATION}`,+ rule: 'subscriptionAnnotationsDisagree',+ message: err.message,+ },+ ]+ }+ throw err+ }+ if (isGrokUnassignedConnectionKey(key) || key === GROK_UNASSIGNED_CONNECTION_KEY) {+ return [+ {+ field: `metadata.annotations.${SUBSCRIPTION_CONNECTION_REF_ANNOTATION}`,+ rule: 'grokRecipeGrantRequired',+ message: 'Grok subscription recipes must choose an existing Grok grant',+ },+ ]+ }+ try {+ assertGrokConnectionKey(key)+ } catch {+ return [+ {+ field: `metadata.annotations.${SUBSCRIPTION_CONNECTION_REF_ANNOTATION}`,+ rule: 'grokRecipeGrantInvalid',+ message: 'clerum.io/subscription-connection-ref is not a valid connection key',+ },+ ]+ }+ return []+}+function sanitizeRecipeCodexAnnotation(body: RecipeBody,currentAnnotations?: Record<string, string>,currentSpec?: Record<string, unknown>): Record<string, string> {+ const grokMirrored = (key: string) => ({+ [CODEX_CONNECTION_REF_ANNOTATION]: '',+ [SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,+ })+ if (recipeUsesGrokBroker(body.spec)) {+ if (!bodyHasCodexGrantAnnotation(body)) return {}+ const incoming = readRequestedGrokRecipeGrant(body)+ return grokMirrored(isGrokUnassignedConnectionKey(incoming) ? '' : incoming)+ }const incoming = readRequestedCodexRecipeGrant(body)const mirrored = (key: string) => ({[CODEX_CONNECTION_REF_ANNOTATION]: key,@@ -1346,7 +1421,8 @@ function sanitizeRecipeCodexAnnotation(return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)}const leavingCodex = recipeUsesCodexBroker(currentSpec) && !recipeHasPluginWorkloadSdk(body.spec)- if (leavingCodex) {+ const leavingGrok = recipeUsesGrokBroker(currentSpec) && !recipeHasPluginWorkloadSdk(body.spec)+ if (leavingCodex || leavingGrok) {return mirrored('')}if (bodyHasCodexGrantAnnotation(body)) {@@ -1671,7 +1747,7 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {res.status(422).json({ valid: false, errors })return}- const grantErrors = validateCodexRecipeGrant(body)+ const grantErrors = [...validateCodexRecipeGrant(body), ...validateGrokRecipeGrant(body)]if (grantErrors.length > 0) {res.status(422).json({ valid: false, errors: grantErrors })return@@ -1857,7 +1933,7 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {res.status(422).json({ errors })return}- const grantErrors = validateCodexRecipeGrant(body)+ const grantErrors = [...validateCodexRecipeGrant(body), ...validateGrokRecipeGrant(body)]if (grantErrors.length > 0) {res.status(422).json({ errors: grantErrors })return@@ -1967,7 +2043,10 @@ export function createAdminRecipesRouter(gateway: K8sGateway): Router {res.status(422).json({ errors })return}- const grantErrors = validateCodexRecipeGrant(body, { allowOmittedGrant: true })+ const grantErrors = [+ ...validateCodexRecipeGrant(body, { allowOmittedGrant: true }),+ ...validateGrokRecipeGrant(body, { allowOmittedGrant: true }),+ ]if (grantErrors.length > 0) {res.status(422).json({ errors: grantErrors })returndiff --git a/control-api/src/services/grokSubscriptionCatalog.ts b/control-api/src/services/grokSubscriptionCatalog.tsindex 14dbda8d0..a90847313 100644--- a/control-api/src/services/grokSubscriptionCatalog.ts+++ b/control-api/src/services/grokSubscriptionCatalog.ts@@ -171,6 +171,27 @@ export async function listOfferedGrokModelsForAssignment(return (result.rows as Array<{ model: string }>).map(row => String(row.model))}+export async function listEnabledGrokModelsGroupedByConnection(+ db: DbClient+): Promise<Record<string, string[]>> {+ const result = await db.query(+ `SELECT c.connection_key AS connection_key, m.model+ FROM grok_catalog_models m+ JOIN grok_subscription_connections c ON c.id = m.connection_id+ WHERE c.revoked_at IS NULL+ AND m.enabled+ AND m.stale = false+ ORDER BY c.connection_key ASC, m.model ASC`+ )+ const grouped: Record<string, string[]> = {}+ for (const row of result.rows as Array<{ connection_key: string; model: string }>) {+ const key = String(row.connection_key)+ grouped[key] ??= []+ grouped[key].push(String(row.model))+ }+ return grouped+}+export async function listGrokCatalogModels(db: DbClient,connectionId: stringdiff --git a/control-api/src/services/llmAllowedModelsConfigMap.ts b/control-api/src/services/llmAllowedModelsConfigMap.tsindex 77f27196a..514a95f03 100644--- a/control-api/src/services/llmAllowedModelsConfigMap.ts+++ b/control-api/src/services/llmAllowedModelsConfigMap.ts@@ -27,6 +27,11 @@ import {type CodexSubscriptionSafeConnection,listLiveCodexSubscriptionConnections,} from './codexSubscriptionConnection.js'+import { listEnabledGrokModelsGroupedByConnection } from './grokSubscriptionCatalog.js'+import {+ type GrokSubscriptionSafeConnection,+ listLiveGrokSubscriptionConnections,+} from './grokSubscriptionConnection.js'import { type AllowedModelEntry, listEnabledGroupedByProvider } from './llmAllowedModels.js'// CROSS-SERVICE CONTRACT: producer side of the allowlist ConfigMap. Consumers@@ -40,6 +45,9 @@ export const CONNECTION_REVISION_ANNOTATION = 'clerum.io/connection-revision'export const CODEX_CONNECTION_STATUS_ANNOTATION = 'clerum.io/codex-connection-status'export const CODEX_ENABLED_ANNOTATION = 'clerum.io/codex-enabled'export const CODEX_CONNECTIONS_ANNOTATION = 'clerum.io/codex-connections'+export const GROK_CONNECTION_STATUS_ANNOTATION = 'clerum.io/grok-connection-status'+export const GROK_ENABLED_ANNOTATION = 'clerum.io/grok-enabled'+export const GROK_CONNECTIONS_ANNOTATION = 'clerum.io/grok-connections'const KNOWN_CONNECTION_STATUSES = new Set(['disconnected',@@ -103,6 +111,48 @@ export function buildCodexReadinessAnnotations(return annotations}+export function mapGrokConnectionStatusForSnapshot(+ connection: GrokSubscriptionSafeConnection | null+): 'connected' | 'disconnected' | 'reauth-required' | 'unavailable' | 'revoked' {+ return mapCodexConnectionStatusForSnapshot(+ connection as unknown as CodexSubscriptionSafeConnection | null+ )+}++export function buildGrokReadinessAnnotations(+ connections: GrokSubscriptionSafeConnection[] = [],+ modelsByKey: Record<string, string[]> = {}+): Record<string, string> {+ const annotations: Record<string, string> = {+ [GROK_ENABLED_ANNOTATION]: config.grokSubscriptionEnabled ? 'true' : 'false',+ }+ const map: Record<+ string,+ {+ status: ReturnType<typeof mapGrokConnectionStatusForSnapshot>+ catalogRevision: number+ connectionRevision: number+ models: string[]+ }+ > = {}+ for (const row of connections) {+ map[row.connectionKey] = {+ status: mapGrokConnectionStatusForSnapshot(row),+ catalogRevision: row.catalogRevision,+ connectionRevision: row.credentialRevision,+ models: modelsByKey[row.connectionKey] ?? [],+ }+ }+ if (Object.keys(map).length > 0) {+ annotations[GROK_CONNECTIONS_ANNOTATION] = JSON.stringify(map)+ const first = connections[0]+ if (first) {+ annotations[GROK_CONNECTION_STATUS_ANNOTATION] = mapGrokConnectionStatusForSnapshot(first)+ }+ }+ return annotations+}+const MANAGED_BY_LABEL = 'clerum.io/managed-by'/** The materializer surface the routes / boot module depend on (test seam). */@@ -172,7 +222,12 @@ export class LlmAllowedModelsConfigMapWriter implements AllowedModelsConfigMapMaconst modelsByKey = await listEnabledCodexModelsGroupedByConnection(db)const defaultConnection =connections.find(row => row.connectionKey === 'deployment-default') ?? null- const readiness = buildCodexReadinessAnnotations(defaultConnection, connections, modelsByKey)+ const grokConnections = await listLiveGrokSubscriptionConnections(db)+ const grokModelsByKey = await listEnabledGrokModelsGroupedByConnection(db)+ const readiness = {+ ...buildCodexReadinessAnnotations(defaultConnection, connections, modelsByKey),+ ...buildGrokReadinessAnnotations(grokConnections, grokModelsByKey),+ }let lastError: unknownfor (let attempt = 1; attempt <= this.maxAttempts; attempt++) {try {diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.tsindex 7745c6187..58c7c058f 100644--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts@@ -1,3 +1,9 @@+import {+ LIMITS as GROK_LIMITS,+ computeGrokPolicyHash,+ hashGrokCompletionRequestV1,+ parseGrokCompletionRequestV1,+} from '@clerum/grok-provider-attempt-contract'import {LIMITS,computeCodexPolicyHash,@@ -17,6 +23,13 @@ import {getSafeCodexSubscriptionConnection,isCodexUnassignedConnectionKey,} from './codexSubscriptionConnection.js'+import { issueRegisteredGrokExecutionTicket } from './grokProviderAttemptTicket.js'+import { getGrokCatalogModelState } from './grokSubscriptionCatalog.js'+import {+ GROK_UNASSIGNED_CONNECTION_KEY,+ getSafeGrokSubscriptionConnection,+ isGrokUnassignedConnectionKey,+} from './grokSubscriptionConnection.js'import {getMaxLlmProviderAttemptGeneration,insertLlmProviderAttempt,@@ -36,7 +49,9 @@ import {const log = rootLogger.child({ module: 'llm-provider-attempt-authorizer' })const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'+const GROK_EXECUTE_SCOPE = 'llm:grok:execute'const PROVIDER = 'codex-subscription' as const+const GROK_PROVIDER = 'grok-subscription' as constconst AUTHORIZE_BODY_KEYS = new Set(['request',@@ -191,12 +206,280 @@ function assertClaimBinding(body: Record<string, unknown>, claims: McpHostAccess}}+function peekRequestedProvider(body: Record<string, unknown>): string {+ if (!isPlainObject(body.request)) return ''+ return typeof body.request.provider === 'string' ? body.request.provider : ''+}++async function authorizeGrokProviderAttempt(+ claims: McpHostAccessClaims,+ body: Record<string, unknown>,+ resolvedDeps: LlmProviderAttemptAuthorizerDeps+): Promise<AuthorizeAttemptSuccess> {+ if (!config.grokSubscriptionEnabled) {+ throw new LlmProviderAttemptAuthorizeError('disabled', 'Grok subscription is disabled')+ }+ if (!claims.workflowControlScopes.includes(GROK_EXECUTE_SCOPE)) {+ throw new LlmProviderAttemptAuthorizeError(+ 'insufficient_scope',+ 'mcp-host JWT lacks the llm:grok:execute scope'+ )+ }+ const serialized = JSON.stringify(body)+ if (Buffer.byteLength(serialized, 'utf8') > GROK_LIMITS.maxRequestBodyBytes) {+ throw new LlmProviderAttemptAuthorizeError('invalid_request', 'request body exceeds the limit')+ }+ const unknown = firstUnknownKey(body)+ if (unknown) {+ throw new LlmProviderAttemptAuthorizeError('unknown_field', `unknown field '${unknown}'`)+ }+ const caller = resolveCaller(claims)+ assertClaimBinding(body, claims)+ const parsed = parseGrokCompletionRequestV1(body.request)+ if (!parsed.ok) {+ throw new LlmProviderAttemptAuthorizeError('invalid_request', parsed.message)+ }+ const request = parsed.value+ const invocationId = typeof body.invocationId === 'string' ? body.invocationId.trim() : ''+ const attemptGeneration =+ typeof body.attemptGeneration === 'number' ? body.attemptGeneration : NaN+ const providerAttemptIndex =+ typeof body.providerAttemptIndex === 'number' ? body.providerAttemptIndex : 1+ const policyRevision = typeof body.policyRevision === 'number' ? body.policyRevision : NaN+ const policyHash = typeof body.policyHash === 'string' ? body.policyHash : ''+ if (!invocationId || !Number.isInteger(attemptGeneration) || attemptGeneration < 1) {+ throw new LlmProviderAttemptAuthorizeError(+ 'invalid_request',+ 'invocationId and attemptGeneration are required'+ )+ }+ if (!Number.isInteger(providerAttemptIndex) || providerAttemptIndex < 1) {+ throw new LlmProviderAttemptAuthorizeError(+ 'invalid_request',+ 'providerAttemptIndex must be a positive integer'+ )+ }+ if (+ !Number.isInteger(policyRevision) ||+ policyRevision < 1 ||+ !/^[a-f0-9]{64}$/.test(policyHash)+ ) {+ throw new LlmProviderAttemptAuthorizeError(+ 'invalid_request',+ 'policyRevision and policyHash are required'+ )+ }+ const requestHash = hashGrokCompletionRequestV1(request)+ if (typeof body.requestHash === 'string' && body.requestHash !== requestHash) {+ throw new LlmProviderAttemptAuthorizeError(+ 'invalid_request',+ 'requestHash does not match the canonical request'+ )+ }+ const assignment = await resolvedDeps.resolveAssignment(caller.hostRef)+ const liveTarget = attestLiveBrokerTarget({+ requestedProvider: GROK_PROVIDER,+ liveBrokerProviders: assignment.liveBrokerProviders,+ })+ if (!liveTarget.ok) {+ throw new LlmProviderAttemptAuthorizeError(liveTarget.code, liveTarget.message)+ }+ let resolvedConnectionRef = assignment.liveConnectionRef+ if (assignment.annotations) {+ const read = readSubscriptionConnectionRef({+ provider: GROK_PROVIDER,+ annotations: assignment.annotations,+ })+ if (!read.ok) {+ throw new LlmProviderAttemptAuthorizeError(read.code, read.message)+ }+ resolvedConnectionRef = read.connectionKey+ }+ const attested = attestRequestedBrokerProvider({+ requestedProvider: GROK_PROVIDER,+ liveBrokerProviders: assignment.liveBrokerProviders,+ liveConnectionRef: resolvedConnectionRef,+ })+ if (!attested.ok) {+ throw new LlmProviderAttemptAuthorizeError(attested.code, attested.message)+ }+ const connectionKey = attested.connectionKey+ if (+ isGrokUnassignedConnectionKey(connectionKey) ||+ connectionKey === GROK_UNASSIGNED_CONNECTION_KEY+ ) {+ throw new LlmProviderAttemptAuthorizeError(+ 'unassigned_connection',+ 'Host has no Grok subscription assigned'+ )+ }+ return resolvedDeps.withTransaction(async tx => {+ const db: DbClient = tx+ const connection = await getSafeGrokSubscriptionConnection(db, connectionKey)+ if (+ !connection ||+ connection.revokedAt ||+ connection.status === 'revoked' ||+ connection.status === 'reauth_required' ||+ connection.catalogStatus === 'auth-rejected'+ ) {+ throw new LlmProviderAttemptAuthorizeError(+ 'no_grant',+ 'Grok subscription grant is missing, revoked, or requires re-authentication'+ )+ }+ if (+ connection.status !== 'connected' ||+ connection.catalogStatus === 'unavailable' ||+ connection.catalogStatus === 'never_synced'+ ) {+ throw new LlmProviderAttemptAuthorizeError(+ 'connection_unavailable',+ 'Grok subscription catalog is not ready'+ )+ }+ const modelState = await getGrokCatalogModelState(db, connection.id, request.model)+ if (!modelState || !modelState.enabled || modelState.stale) {+ throw new LlmProviderAttemptAuthorizeError(+ 'model_not_allowed',+ 'model is disabled, stale, or absent from the Grok catalog'+ )+ }+ const expectedPolicyHash = computeGrokPolicyHash({+ model: request.model,+ catalogRevision: connection.catalogRevision,+ credentialRevision: connection.credentialRevision,+ connectionKey: connection.connectionKey,+ })+ if (policyRevision !== connection.catalogRevision || policyHash !== expectedPolicyHash) {+ throw new LlmProviderAttemptAuthorizeError(+ 'no_grant',+ 'policy revision or hash does not match the current Grok catalog'+ )+ }+ const maxGeneration = await resolvedDeps.getMaxGeneration(db, invocationId)+ if (attemptGeneration < maxGeneration) {+ throw new LlmProviderAttemptAuthorizeError(+ 'stale_generation',+ 'attemptGeneration is older than the recorded invocation'+ )+ }+ const presentedReservationId =+ typeof body.budgetReservationId === 'string' ? body.budgetReservationId.trim() : ''+ let budgetReservationId = presentedReservationId || 'unbudgeted'+ if (presentedReservationId) {+ const active = await resolvedDeps.getActiveReservation(db, {+ reservationId: presentedReservationId,+ hostRef: caller.hostRef,+ })+ if (!active) {+ throw new LlmProviderAttemptAuthorizeError(+ 'budget_denied',+ 'budget reservation is missing or expired'+ )+ }+ } else {+ const budget = await resolvedDeps.evaluateBudget(+ {+ host_ref: caller.hostRef,+ context_ref: null,+ team_id: null,+ user_id: null,+ provider: GROK_PROVIDER,+ model: request.model,+ llm_secret_name: null,+ source_kind: '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',+ 'token budget denied this attempt'+ )+ }+ budgetReservationId = budget.reservationIds?.[0] ?? 'unbudgeted'+ }+ try {+ const attempt = await resolvedDeps.insertAttempt(db, {+ callerKind: caller.callerKind,+ hostRef: caller.hostRef,+ recipeNamespace: caller.recipeNamespace,+ recipeName: caller.recipeName,+ invocationId,+ attemptGeneration,+ providerAttemptIndex,+ provider: GROK_PROVIDER,+ model: request.model,+ requestHash,+ policyRevision,+ policyHash,+ budgetReservationId,+ connectionRevision: connection.credentialRevision,+ connectionId: connection.id,+ })+ const issued = await issueRegisteredGrokExecutionTicket(db, {+ sub: claims.sub,+ hostRef: caller.hostRef,+ recipeNamespace: caller.recipeNamespace ?? undefined,+ recipeName: caller.recipeName ?? undefined,+ invocationId,+ attemptGeneration,+ providerAttemptId: attempt.id,+ providerAttemptIndex,+ model: request.model,+ requestHash,+ policyRevision,+ policyHash,+ budgetReservationId,+ connectionRevision: connection.credentialRevision,+ connectionId: connection.id,+ })+ log.info(+ {+ event: 'grok_attempt_authorized',+ providerAttemptId: attempt.id,+ hostRef: caller.hostRef,+ model: request.model,+ },+ 'authorized Grok provider attempt'+ )+ return {+ providerAttemptId: attempt.id,+ requestHash,+ executionTicket: issued.executionTicket,+ expiresAt: issued.expiresAt.toISOString(),+ }+ } catch (err) {+ const code = (err as { code?: string }).code+ if (code === '23505') {+ throw new LlmProviderAttemptAuthorizeError(+ 'idempotency_conflict',+ 'an attempt with this invocation binding already exists'+ )+ }+ throw err+ }+ })+}+export async function authorizeLlmProviderAttempt(claims: McpHostAccessClaims,body: unknown,deps: LlmProviderAttemptAuthorizerDeps | Partial<LlmProviderAttemptAuthorizerDeps> = defaultDeps()): Promise<AuthorizeAttemptSuccess> {const resolvedDeps: LlmProviderAttemptAuthorizerDeps = { ...defaultDeps(), ...deps }+ if (!isPlainObject(body)) {+ throw new LlmProviderAttemptAuthorizeError('invalid_request', 'body must be an object')+ }+ if (peekRequestedProvider(body) === GROK_PROVIDER) {+ return authorizeGrokProviderAttempt(claims, body, resolvedDeps)+ }if (!resolvedDeps.enabled) {throw new LlmProviderAttemptAuthorizeError('disabled', 'Codex subscription is disabled')}@@ -206,9 +489,6 @@ export async function authorizeLlmProviderAttempt('mcp-host JWT lacks the llm:codex:execute scope')}- if (!isPlainObject(body)) {- throw new LlmProviderAttemptAuthorizeError('invalid_request', 'body must be an object')- }const serialized = JSON.stringify(body)if (Buffer.byteLength(serialized, 'utf8') > LIMITS.maxRequestBodyBytes) {throw new LlmProviderAttemptAuthorizeError('invalid_request', 'request body exceeds the limit')diff --git a/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts b/control-api/test/db.oauthGrantsOwnerGeneralization.test.tsindex a61f1911c..f475ccab2 100644--- a/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts+++ b/control-api/test/db.oauthGrantsOwnerGeneralization.test.ts@@ -21,7 +21,7 @@ describe('0101 oauth_grants owner generalization migration', () => {const { CONTROL_API_MIGRATIONS } = await import('../src/db.js')const versions = CONTROL_API_MIGRATIONS.map(m => m.version)expect(versions).toContain('0106_oauth_grants_owner_generalization')- expect(versions.at(-1)).toBe('0108_llm_provider_attempts_sdk_link_on_delete_set_null')+ expect(versions.at(-1)).toBe('0112_llm_provider_attempts_grok_broker')expect(versions.indexOf('0100_seed_minimax_allowed_model')).toBeLessThan(versions.indexOf('0106_oauth_grants_owner_generalization'))diff --git a/control-api/test/llmProviders.test.ts b/control-api/test/llmProviders.test.tsindex 5382bf447..0fd321de7 100644--- a/control-api/test/llmProviders.test.ts+++ b/control-api/test/llmProviders.test.ts@@ -17,7 +17,7 @@ import {// (same convention as @clerum/image-policy → control-api/test/imagePolicy.test.ts).describe('PROVIDER_IDS', () => {- it('is the canonical 22 static providers plus the Codex broker', () => {+ it('is the canonical 22 static providers plus the Codex and Grok brokers', () => {expect([...PROVIDER_IDS]).toEqual(['openai','claude',@@ -42,6 +42,7 @@ describe('PROVIDER_IDS', () => {'minimax','azure','codex-subscription',+ 'grok-subscription',])})@@ -49,7 +50,7 @@ describe('PROVIDER_IDS', () => {for (const id of PROVIDER_IDS) {expect(PROVIDER_DISPLAY_LABELS[id]).toBeTruthy()expect(PROVIDER_NON_SECRET_ENV[id]).toBeInstanceOf(Array)- if (id === 'codex-subscription') {+ if (id === 'codex-subscription' || id === 'grok-subscription') {expect(PROVIDER_CREDENTIAL_SLOTS[id]).toEqual([])} else {expect(PROVIDER_CREDENTIAL_SLOTS[id].length).toBeGreaterThan(0)diff --git a/control-api/test/routes.admin.codexSubscription.test.ts b/control-api/test/routes.admin.codexSubscription.test.tsindex d3933b441..7d3d57686 100644--- a/control-api/test/routes.admin.codexSubscription.test.ts+++ b/control-api/test/routes.admin.codexSubscription.test.ts@@ -140,6 +140,7 @@ describe('admin Codex subscription routes', () => {beforeEach(() => {app = makeAuthedApp()config.codexSubscriptionEnabled = true+ config.grokSubscriptionEnabled = falseconfig.codexOAuthClientId = originalClientIdconfig.controlUiBaseUrl = originalControlUiBaseUrlfor (const fn of Object.values(oauth)) fn.mockReset()@@ -172,10 +173,29 @@ describe('admin Codex subscription routes', () => {expect(res.body).toEqual({ error: 'not_found' })})- it('returns 404 not_found for grok-subscription until that adapter is mounted', async () => {+ it('returns 404 disabled for grok-subscription when that flag is off', async () => {+ config.grokSubscriptionEnabled = falseconst res = await request(app).get('/admin/llm/providers/grok-subscription/connections')expect(res.status).toBe(404)+ expect(res.body).toEqual({ error: 'disabled' })+ })++ it('does not expose Codex un-keyed aliases for grok-subscription', async () => {+ config.grokSubscriptionEnabled = true+ const res = await request(app).get('/admin/llm/providers/grok-subscription/connection')+ expect(res.status).toBe(404)expect(res.body).toEqual({ error: 'not_found' })+ const browser = await request(app).post('/admin/llm/providers/grok-subscription/browser/start')+ expect(browser.status).toBe(404)+ expect(browser.body).toEqual({ error: 'not_found' })+ })++ it('lists Grok connections when the Grok flag is on', async () => {+ config.grokSubscriptionEnabled = true+ vi.mocked(pool.query).mockResolvedValue({ rows: [], rowCount: 0 })+ const res = await request(app).get('/admin/llm/providers/grok-subscription/connections')+ expect(res.status).toBe(200)+ expect(res.body.connections).toEqual([])})it('returns 404 disabled for the connections list when the Codex flag is off', async () => {diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.tsindex 079fe8ac1..ffe9d38fc 100644--- a/control-api/test/routes.adminRecipes.test.ts+++ b/control-api/test/routes.adminRecipes.test.ts@@ -271,6 +271,7 @@ describe.sequential('routes/admin/recipes', () => {.expect(201)expect(res.body.metadata.annotations).toEqual({'clerum.io/codex-connection-ref': 'team-plus',+ 'clerum.io/subscription-connection-ref': 'team-plus',})})@@ -304,6 +305,7 @@ describe.sequential('routes/admin/recipes', () => {.expect(200)expect(res.body.metadata.annotations).toEqual({'clerum.io/codex-connection-ref': '',+ 'clerum.io/subscription-connection-ref': '',})})@@ -324,6 +326,7 @@ describe.sequential('routes/admin/recipes', () => {.expect(200)expect(res.body.metadata.annotations).toEqual({'clerum.io/codex-connection-ref': 'team-plus',+ 'clerum.io/subscription-connection-ref': 'team-plus',})expect(res.body.spec.steps[0].instruction).toBe('Write v2')})diff --git a/packages/codex-catalog-projection/index.cjs b/packages/codex-catalog-projection/index.cjsindex 9f62eb343..e224c243a 100644--- a/packages/codex-catalog-projection/index.cjs+++ b/packages/codex-catalog-projection/index.cjs@@ -13,6 +13,12 @@ const CODEX_UNASSIGNED_CONNECTION_KEY = 'unassigned'const CODEX_PROVIDER = 'codex-subscription'const CODEX_EXECUTE_SCOPE = 'llm:codex:execute'const CODEX_PROVIDER_PREFIX = `${CODEX_PROVIDER}:`+const GROK_PROVIDER = 'grok-subscription'+const GROK_EXECUTE_SCOPE = 'llm:grok:execute'+const GROK_PROVIDER_PREFIX = `${GROK_PROVIDER}:`+const GROK_ENABLED_ANNOTATION = 'clerum.io/grok-enabled'+const GROK_CONNECTIONS_ANNOTATION = 'clerum.io/grok-connections'+const GROK_CONNECTION_STATUS_ANNOTATION = 'clerum.io/grok-connection-status'function assignedCodexConnectionKey(value) {const trimmed = typeof value === 'string' ? value.trim() : ''@@ -385,6 +391,160 @@ function toEligiblePolicyBinding(cm, connectionKey, model) {}}+function toGrokPolicyBinding(cm, connectionKey) {+ const key = assignedCodexConnectionKey(connectionKey)+ if (!cm || key === CODEX_UNASSIGNED_CONNECTION_KEY) return null+ const annotations = (cm.metadata && cm.metadata.annotations) || {}+ const rawMap = annotations[GROK_CONNECTIONS_ANNOTATION]+ if (!rawMap) return null+ let parsed+ try {+ parsed = JSON.parse(rawMap)+ } catch {+ return null+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null+ const assigned = parsed[key]+ if (+ !assigned ||+ !Array.isArray(assigned.models) ||+ !Number.isInteger(assigned.catalogRevision) ||+ !Number.isInteger(assigned.connectionRevision)+ ) {+ return null+ }+ return {+ catalogRevision: assigned.catalogRevision,+ credentialRevision: assigned.connectionRevision,+ connectionKey: key,+ models: assigned.models.filter(model => typeof model === 'string' && model),+ }+}++function parseGrokAllowedModelsSnapshot(cm, connectionKey) {+ if (!cm) return snapshotFromConfigMapError('missing')+ const annotations = (cm.metadata && cm.metadata.annotations) || {}+ const flagEnabled = annotations[GROK_ENABLED_ANNOTATION] === 'true'+ const assignedKey = assignedCodexConnectionKey(connectionKey)+ const rawMap = annotations[GROK_CONNECTIONS_ANNOTATION]+ if (!rawMap) {+ return {+ flagEnabled,+ connectionStatus: 'disconnected',+ enabledModels: [],+ staleModels: [],+ catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] || null,+ }+ }+ let parsed+ try {+ parsed = JSON.parse(rawMap)+ } catch {+ return snapshotFromConfigMapError('malformed')+ }+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return snapshotFromConfigMapError('malformed')+ }+ const assigned = parsed[assignedKey]+ if (!assigned || !Array.isArray(assigned.models)) {+ return {+ flagEnabled,+ connectionStatus: 'disconnected',+ enabledModels: [],+ staleModels: [],+ catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] || null,+ }+ }+ const enabledModels = assigned.models+ .filter(model => typeof model === 'string' && model.trim())+ .map(model => `${GROK_PROVIDER}:${model}`)+ return {+ flagEnabled,+ connectionStatus: assigned.status || annotations[GROK_CONNECTION_STATUS_ANNOTATION] || null,+ catalogRevision: Number.isInteger(assigned.catalogRevision) ? assigned.catalogRevision : null,+ connectionRevision: Number.isInteger(assigned.connectionRevision)+ ? assigned.connectionRevision+ : null,+ enabledModels,+ staleModels: [],+ catalogContentHash: annotations[CONTENT_HASH_ANNOTATION] || null,+ }+}++function projectGrokExecution(spec, snapshot) {+ const targets = collectCodexTargets(spec || {})+ const brokerTargets = targets.filter(target => target.provider === GROK_PROVIDER)+ const enabled = new Set(snapshot.enabledModels ?? [])+ if (snapshot.snapshotError) {+ return freezeProjection({+ targets,+ eligibleTargets: [],+ derivedScopes: [],+ requiresGrokProxyEgress: false,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: 'uncertain',+ reason: `snapshot_${snapshot.snapshotError}`,+ })+ }+ if (!snapshot.flagEnabled) {+ return freezeProjection({+ targets,+ eligibleTargets: [],+ derivedScopes: [],+ requiresGrokProxyEgress: false,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: 'ineligible',+ reason: 'flag_off',+ })+ }+ if (brokerTargets.length === 0) {+ return freezeProjection({+ targets,+ eligibleTargets: [],+ derivedScopes: [],+ requiresGrokProxyEgress: false,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: 'ineligible',+ reason: 'static_only',+ })+ }+ if (snapshot.connectionStatus !== 'connected') {+ return freezeProjection({+ targets,+ eligibleTargets: [],+ derivedScopes: [],+ requiresGrokProxyEgress: false,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: 'ineligible',+ reason: `connection_${snapshot.connectionStatus ?? 'unknown'}`,+ })+ }+ const eligibleTargets = brokerTargets.filter(target => {+ if (!target.model.trim()) return false+ return enabled.has(`${target.provider}:${target.model}`)+ })+ const eligible = eligibleTargets.length > 0+ return freezeProjection({+ targets,+ eligibleTargets,+ derivedScopes: eligible ? [GROK_EXECUTE_SCOPE] : [],+ requiresGrokProxyEgress: eligible,+ catalogContentHash: snapshot.catalogContentHash ?? null,+ catalogRevision: snapshot.catalogRevision ?? null,+ connectionRevision: snapshot.connectionRevision ?? null,+ eligibility: eligible ? 'eligible' : 'ineligible',+ reason: eligible ? 'eligible' : 'no_eligible_broker_target',+ })+}+module.exports = {ALLOWED_MODELS_CONFIGMAP_NAME,CONTENT_HASH_ANNOTATION,@@ -398,6 +558,11 @@ module.exports = {CODEX_UNASSIGNED_CONNECTION_KEY,CODEX_PROVIDER,CODEX_EXECUTE_SCOPE,+ GROK_PROVIDER,+ GROK_EXECUTE_SCOPE,+ GROK_ENABLED_ANNOTATION,+ GROK_CONNECTIONS_ANNOTATION,+ GROK_CONNECTION_STATUS_ANNOTATION,assignedCodexConnectionKey,isCodexUnassignedConnectionKey,readSubscriptionConnectionRef,@@ -406,6 +571,9 @@ module.exports = {snapshotForAssignedCodexGrant,collectCodexTargets,projectCodexExecution,+ parseGrokAllowedModelsSnapshot,+ projectGrokExecution,toPolicyBinding,+ toGrokPolicyBinding,toEligiblePolicyBinding,}diff --git a/packages/codex-catalog-projection/index.d.ts b/packages/codex-catalog-projection/index.d.tsindex 886193317..e93220930 100644--- a/packages/codex-catalog-projection/index.d.ts+++ b/packages/codex-catalog-projection/index.d.ts@@ -19,6 +19,11 @@ export declare const SUBSCRIPTION_CONNECTION_REF_ANNOTATION: 'clerum.io/subscripexport declare const CODEX_UNASSIGNED_CONNECTION_KEY: 'unassigned'export declare const CODEX_PROVIDER: 'codex-subscription'export declare const CODEX_EXECUTE_SCOPE: 'llm:codex:execute'+export declare const GROK_PROVIDER: 'grok-subscription'+export declare const GROK_EXECUTE_SCOPE: 'llm:grok:execute'+export declare const GROK_ENABLED_ANNOTATION: 'clerum.io/grok-enabled'+export declare const GROK_CONNECTIONS_ANNOTATION: 'clerum.io/grok-connections'+export declare const GROK_CONNECTION_STATUS_ANNOTATION: 'clerum.io/grok-connection-status'export type CodexConfigMapView = {metadata?: { annotations?: Record<string, string> | null } | null@@ -127,6 +132,22 @@ export declare function projectCodexExecution(spec: CodexHostSpec,snapshot: CodexCatalogSnapshot): CodexExecutionProjection+export declare function parseGrokAllowedModelsSnapshot(+ cm: CodexConfigMapView | undefined | null,+ connectionKey?: string+): CodexCatalogSnapshot+export declare function projectGrokExecution(+ spec: CodexHostSpec,+ snapshot: CodexCatalogSnapshot+): CodexExecutionProjection & { requiresGrokProxyEgress: boolean }+/**+ * Grok Host-chat revision view. Reads only `clerum.io/grok-connections`.+ * Never falls back to Codex annotations or the flat catalog.+ */+export declare function toGrokPolicyBinding(+ cm: CodexConfigMapView | undefined | null,+ connectionKey?: string+): CodexPolicyBinding | null/*** Structural revision view for the Host chat reader (`configStore`). It does* NOT decide eligibility: a transiently `unavailable`/`reauth-required`diff --git a/packages/codex-catalog-projection/index.test.cjs b/packages/codex-catalog-projection/index.test.cjsindex f3aa8e529..d2656f80f 100644--- a/packages/codex-catalog-projection/index.test.cjs+++ b/packages/codex-catalog-projection/index.test.cjs@@ -439,3 +439,109 @@ test('toPolicyBinding still serves Host chat through a degraded connection', ()assert.equal(projection.toEligiblePolicyBinding(cm, 'personal-pro', 'gpt-5.1').binding, null)}})++function grokView(key, models, status = 'connected') {+ return {+ metadata: {+ annotations: {+ 'clerum.io/grok-enabled': 'true',+ 'clerum.io/grok-connection-status': status,+ 'clerum.io/grok-connections': JSON.stringify({+ [key]: {+ status,+ catalogRevision: 5,+ connectionRevision: 2,+ models,+ },+ }),+ 'clerum.io/codex-enabled': 'true',+ 'clerum.io/codex-connection-status': 'connected',+ 'clerum.io/catalog-revision': '99',+ 'clerum.io/connection-revision': '88',+ 'clerum.io/codex-connections': JSON.stringify({+ 'personal-pro': {+ status: 'connected',+ catalogRevision: 4,+ connectionRevision: 2,+ models: ['gpt-5.1'],+ },+ }),+ },+ },+ data: {+ 'grok-subscription': JSON.stringify(models.map(model => ({ model }))),+ 'codex-subscription': JSON.stringify([{ model: 'gpt-5.1' }]),+ },+ }+}++test('parseGrokAllowedModelsSnapshot ignores Codex annotations and the flat catalog', () => {+ const snapshot = projection.parseGrokAllowedModelsSnapshot(grokView('team-grok', ['grok-4.6']))+ assert.equal(snapshot.flagEnabled, true)+ assert.equal(snapshot.connectionStatus, 'disconnected')+ assert.deepEqual([...(snapshot.enabledModels ?? [])], [])+})++test('parseGrokAllowedModelsSnapshot reads only grok-connections for the assigned key', () => {+ const snapshot = projection.parseGrokAllowedModelsSnapshot(+ grokView('team-grok', ['grok-4.6', 'grok-build-0.1']),+ 'team-grok'+ )+ assert.equal(snapshot.flagEnabled, true)+ assert.equal(snapshot.connectionStatus, 'connected')+ assert.equal(snapshot.catalogRevision, 5)+ assert.equal(snapshot.connectionRevision, 2)+ assert.deepEqual([...(snapshot.enabledModels ?? [])], [+ 'grok-subscription:grok-4.6',+ 'grok-subscription:grok-build-0.1',+ ])+})++test('toGrokPolicyBinding never falls back to Codex revisions', () => {+ assert.equal(projection.toGrokPolicyBinding(grokView('team-grok', ['grok-4.6']), 'unassigned'), null)+ assert.equal(projection.toGrokPolicyBinding(grokView('team-grok', ['grok-4.6']), 'personal-pro'), null)+ assert.deepEqual(projection.toGrokPolicyBinding(grokView('team-grok', ['grok-4.6']), 'team-grok'), {+ catalogRevision: 5,+ credentialRevision: 2,+ connectionKey: 'team-grok',+ models: ['grok-4.6'],+ })+ const codexOnly = {+ metadata: {+ annotations: {+ 'clerum.io/catalog-revision': '7',+ 'clerum.io/connection-revision': '3',+ 'clerum.io/codex-connections': JSON.stringify({+ 'team-grok': {+ status: 'connected',+ catalogRevision: 7,+ connectionRevision: 3,+ models: ['gpt-5.1'],+ },+ }),+ },+ },+ }+ assert.equal(projection.toGrokPolicyBinding(codexOnly, 'team-grok'), null)+})++test('projectGrokExecution mints llm:grok:execute only for an eligible Grok target', () => {+ const snapshot = projection.parseGrokAllowedModelsSnapshot(+ grokView('team-grok', ['grok-4.6']),+ 'team-grok'+ )+ const eligible = projection.projectGrokExecution(+ { model: { provider: 'grok-subscription', name: 'grok-4.6' } },+ snapshot+ )+ assert.equal(eligible.eligibility, 'eligible')+ assert.deepEqual(eligible.derivedScopes, [projection.GROK_EXECUTE_SCOPE])+ assert.equal(eligible.requiresGrokProxyEgress, true)+ const staticOnly = projection.projectGrokExecution(+ { model: { provider: 'codex-subscription', name: 'gpt-5.1' } },+ snapshot+ )+ assert.equal(staticOnly.eligibility, 'ineligible')+ assert.deepEqual(staticOnly.derivedScopes, [])+ assert.equal(staticOnly.requiresGrokProxyEgress, false)+})