Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: close leftover Grok grant, Host roll, and step-broker UI holes
Jose Gabriel Ramirez Encinas627f49281db7
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 25e25e66b..6d49b16ad 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.570",+ "version": "0.1.571","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.570",+ "version": "0.1.571","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 2bdae541b..bd0138c83 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.570",+ "version": "0.1.571","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/services/grokProviderAttemptRedemption.ts b/control-api/src/services/grokProviderAttemptRedemption.tsindex a1a5a3a67..4fc6d90d0 100644--- a/control-api/src/services/grokProviderAttemptRedemption.ts+++ b/control-api/src/services/grokProviderAttemptRedemption.ts@@ -154,7 +154,7 @@ export async function redeemGrokProviderAttempt(} catch (err) {if (err instanceof GrokSubscriptionOAuthError) {throw new GrokProviderAttemptRedeemError(- err.code === 'no_grant' || err.code === 'not_connected'+ err.code === 'no_grant' || err.code === 'not_connected' || err.code === 'reauth_required'? 'no_grant': err.code === 'provider_unavailable'? 'provider_unavailable'diff --git a/control-api/src/services/grokSubscriptionOAuth.ts b/control-api/src/services/grokSubscriptionOAuth.tsindex 03c31e1cb..5a670a82a 100644--- a/control-api/src/services/grokSubscriptionOAuth.ts+++ b/control-api/src/services/grokSubscriptionOAuth.ts@@ -449,7 +449,19 @@ async function rotateLockedRefresh(throw err}const accountFingerprint = fingerprintAccount(subject)- const updated = await updateGrokAccessTokenInPlace(+ if (+ current?.accountFingerprint &&+ accountFingerprint &&+ current.accountFingerprint !== accountFingerprint+ ) {+ const marked = await markGrokRefreshSubjectMismatch(+ deps.db,+ key,+ persisted.credentialRevision+ )+ return marked ?? { ...persisted, status: 'reauth_required' }+ }+ return updateGrokAccessTokenInPlace(deps.db,deps.encryptionKey,persisted.credentialRevision,@@ -460,15 +472,6 @@ async function rotateLockedRefresh(key,lockToken)- if (- current?.accountFingerprint &&- accountFingerprint &&- current.accountFingerprint !== accountFingerprint- ) {- const marked = await markGrokRefreshSubjectMismatch(deps.db, key, updated.credentialRevision)- return marked ?? { ...updated, status: 'reauth_required' }- }- return updated} catch (err) {if (err instanceof GrokSubscriptionStaleRevisionError) {throw new GrokSubscriptionOAuthError('stale_revision', 'refresh lost the credential race')diff --git a/control-api/src/services/llmProviderAttemptFinalization.ts b/control-api/src/services/llmProviderAttemptFinalization.tsindex 470c9057d..d036ccfe4 100644--- a/control-api/src/services/llmProviderAttemptFinalization.ts+++ b/control-api/src/services/llmProviderAttemptFinalization.ts@@ -66,6 +66,12 @@ export async function finalizeLlmProviderAttempt(if (!attempt) {throw new LlmProviderAttemptFinalizeError('ticket_invalid', 'provider attempt was not found')}+ if (attempt.provider !== 'codex-subscription') {+ throw new LlmProviderAttemptFinalizeError(+ 'ticket_invalid',+ 'attempt provider is not codex-subscription'+ )+ }if (attempt.requestHash !== receipt.requestHash) {throw new LlmProviderAttemptFinalizeError('request_hash_mismatch',diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.tsindex 83bf8392e..05cd1108d 100644--- a/control-api/test/routes.adminRecipes.test.ts+++ b/control-api/test/routes.adminRecipes.test.ts@@ -330,6 +330,37 @@ describe.sequential('routes/admin/recipes', () => {})})+ it('PUT /admin/recipes/:name — clears leftover Grok when switching to Codex without annotations', async () => {+ await api+ .post('/admin/recipes')+ .send({+ metadata: {+ name: 'grok-then-codex-omit',+ annotations: { 'clerum.io/subscription-connection-ref': 'team-grok' },+ },+ spec: {+ agent: { provider: 'grok-subscription', model: 'grok-4.6' },+ triggers: { onDemand: { allowedActors: ['user'] } },+ steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],+ },+ })+ .expect(201)+ const res = await api+ .put('/admin/recipes/grok-then-codex-omit')+ .send({+ spec: {+ agent: { provider: 'codex-subscription', model: 'gpt-5.1' },+ triggers: { onDemand: { allowedActors: ['user'] } },+ steps: [{ id: 'draft', instruction: 'Write', timeoutSeconds: 600 }],+ },+ })+ .expect(200)+ expect(res.body.metadata.annotations).toEqual({+ 'clerum.io/codex-connection-ref': '',+ 'clerum.io/subscription-connection-ref': '',+ })+ })+it('POST /admin/recipes — rejects mixed oauth-broker providers on agent and steps', async () => {const res = await api.post('/admin/recipes').send({metadata: { name: 'mixed-broker' },diff --git a/control-api/test/services.grokProviderAttemptRedemption.test.ts b/control-api/test/services.grokProviderAttemptRedemption.test.tsindex 6d6ffe51c..334939068 100644--- a/control-api/test/services.grokProviderAttemptRedemption.test.ts+++ b/control-api/test/services.grokProviderAttemptRedemption.test.ts@@ -6,6 +6,7 @@ import {} from '../src/services/grokProviderAttemptRedemption.js'import * as ticket from '../src/services/grokProviderAttemptTicket.js'import * as connection from '../src/services/grokSubscriptionConnection.js'+import { GrokSubscriptionOAuthError } from '../src/services/grokSubscriptionOAuth.js'import * as store from '../src/services/llmProviderAttemptStore.js'vi.mock('../src/db.js', () => ({@@ -86,4 +87,36 @@ describe('redeemGrokProviderAttempt', () => {).rejects.toMatchObject({ code: 'ticket_invalid' })expect(loadSecrets).not.toHaveBeenCalled()})++ it('maps reauth_required refresh to a non-retryable no_grant', async () => {+ vi.spyOn(store, 'peekLlmProviderAttemptTicket').mockResolvedValue({+ jti: CLAIMS.jti,+ providerAttemptId: CLAIMS.providerAttemptId,+ status: 'issued',+ expiresAt: new Date(Date.now() + 30_000),+ receiptHash: null,+ })+ vi.spyOn(store, 'loadLlmProviderAttempt').mockResolvedValue({+ id: CLAIMS.providerAttemptId,+ provider: 'grok-subscription',+ connectionId: CONNECTION_ID,+ status: 'authorized',+ } as never)+ await expect(+ redeemGrokProviderAttempt(+ { executionTicket: 'ticket', requestHash: CLAIMS.requestHash },+ {+ enabled: true,+ db: { query: vi.fn() },+ withTransaction: async work => work({ query: vi.fn() }),+ loadSecrets: vi.fn(),+ getConnectionById: vi.fn().mockResolvedValue({ connectionKey: 'team-grok' }),+ encryptionKey: Buffer.alloc(32),+ ensureFreshAccessToken: async () => {+ throw new GrokSubscriptionOAuthError('reauth_required', 'refresh token was rejected')+ },+ }+ )+ ).rejects.toMatchObject({ code: 'no_grant' })+ })})diff --git a/control-api/test/services.grokProviderAttemptTicket.test.ts b/control-api/test/services.grokProviderAttemptTicket.test.tsindex c327631d3..8d34bb7a6 100644--- a/control-api/test/services.grokProviderAttemptTicket.test.ts+++ b/control-api/test/services.grokProviderAttemptTicket.test.ts@@ -58,22 +58,52 @@ describe('Grok execution ticket', () => {expect(claims.aud).toBe(GROK_EXECUTION_TICKET_AUDIENCE)expect(claims.aud).not.toBe(CODEX_EXECUTION_TICKET_AUDIENCE)- const codexShaped = jwt.sign(- {- ...binding,- jti: randomUUID(),- typ: 'codex-execution-ticket',- provider: 'codex-subscription',- },- config.adminJwtPrivateKey,- {+ const sign = (claims: Record<string, unknown>, audience: string) =>+ jwt.sign(claims, config.adminJwtPrivateKey, {algorithm: 'RS256',issuer: config.adminJwtIssuer,- audience: CODEX_EXECUTION_TICKET_AUDIENCE,+ audience,expiresIn: GROK_EXECUTION_TICKET_TTL_SECONDS,- }- )- expect(verifyGrokExecutionTicket(codexShaped)).toBeNull()+ })+ expect(+ verifyGrokExecutionTicket(+ sign(+ {+ ...binding,+ jti: randomUUID(),+ typ: 'codex-execution-ticket',+ provider: 'grok-subscription',+ },+ GROK_EXECUTION_TICKET_AUDIENCE+ )+ )+ ).toBeNull()+ expect(+ verifyGrokExecutionTicket(+ sign(+ {+ ...binding,+ jti: randomUUID(),+ typ: 'grok-execution-ticket',+ provider: 'codex-subscription',+ },+ GROK_EXECUTION_TICKET_AUDIENCE+ )+ )+ ).toBeNull()+ expect(+ verifyGrokExecutionTicket(+ sign(+ {+ ...binding,+ jti: randomUUID(),+ typ: 'grok-execution-ticket',+ provider: 'grok-subscription',+ },+ CODEX_EXECUTION_TICKET_AUDIENCE+ )+ )+ ).toBeNull()})it('expires after 60 seconds', async () => {diff --git a/control-api/test/services.grokSubscriptionOAuth.test.ts b/control-api/test/services.grokSubscriptionOAuth.test.tsindex 328da31ee..dd58af4cc 100644--- a/control-api/test/services.grokSubscriptionOAuth.test.ts+++ b/control-api/test/services.grokSubscriptionOAuth.test.ts@@ -523,6 +523,7 @@ describe('grok subscription OAuth device broker', () => {expect(refreshed.status).toBe('reauth_required')expect(repos.persistRefresh).toHaveBeenCalled()expect(repos.markMismatch).toHaveBeenCalled()+ expect(repos.updateInPlace).not.toHaveBeenCalled()expect(repos.rotate).not.toHaveBeenCalled()})diff --git a/control-api/test/services.llmProviderAttemptFinalization.test.ts b/control-api/test/services.llmProviderAttemptFinalization.test.tsindex 042138cfe..a3330377f 100644--- a/control-api/test/services.llmProviderAttemptFinalization.test.ts+++ b/control-api/test/services.llmProviderAttemptFinalization.test.ts@@ -63,6 +63,19 @@ describe('finalizeLlmProviderAttempt', () => {markFinalized.mockReset()})+ it('rejects a Grok attempt on the Codex finalize path', async () => {+ loadAttempt.mockResolvedValueOnce({ ...attemptRow, provider: 'grok-subscription' })+ const tx = { query: vi.fn() }+ await expect(+ finalizeLlmProviderAttempt(+ { attemptReceipt: attemptReceipt(), receipt: successReceipt },+ runTx(tx) as never+ )+ ).rejects.toMatchObject({ code: 'ticket_invalid' })+ expect(markFinalized).not.toHaveBeenCalled()+ expect(ingest).not.toHaveBeenCalled()+ })+it('rejects a malformed receipt without inventing usage', async () => {await expect(finalizeLlmProviderAttempt({diff --git a/control-ui/components/RecipeEditor.tsx b/control-ui/components/RecipeEditor.tsxindex 6154d149d..0ee60b238 100644--- a/control-ui/components/RecipeEditor.tsx+++ b/control-ui/components/RecipeEditor.tsx@@ -100,13 +100,28 @@ function checkPolicyL1(parsed: { spec?: unknown } | null): ServerValidationErrorreturn null}-function readRecipeAgentProvider(spec: unknown): string {+function readRecipeOauthBrokerProvider(spec: unknown): string {if (!spec || typeof spec !== 'object' || Array.isArray(spec)) return ''- const agent = (spec as { agent?: unknown }).agent- if (!agent || typeof agent !== 'object' || Array.isArray(agent)) return ''- return typeof (agent as { provider?: unknown }).provider === 'string'- ? (agent as { provider: string }).provider.trim()- : ''+ const ids: string[] = []+ const push = (value: unknown) => {+ if (typeof value !== 'string') return+ const provider = value.trim()+ if (+ (provider === OPENAI_SUBSCRIPTION_PROVIDER || provider === GROK_SUBSCRIPTION_PROVIDER) &&+ !ids.includes(provider)+ ) {+ ids.push(provider)+ }+ }+ const rec = spec as {+ agent?: { provider?: unknown }+ steps?: Array<{ agent?: { provider?: unknown } }>+ }+ push(rec.agent?.provider)+ for (const step of rec.steps ?? []) {+ push(step?.agent?.provider)+ }+ return ids.length === 1 ? ids[0] : ''}function readRecipeCodexGrantAnnotation(@@ -1728,7 +1743,7 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)const isCodexRecipe = useMemo(() => {try {const parsed = JSON.parse(jsonInput) as { spec?: unknown }- return readRecipeAgentProvider(parsed.spec) === OPENAI_SUBSCRIPTION_PROVIDER+ return readRecipeOauthBrokerProvider(parsed.spec) === OPENAI_SUBSCRIPTION_PROVIDER} catch {return false}@@ -1737,7 +1752,7 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)const isGrokRecipe = useMemo(() => {try {const parsed = JSON.parse(jsonInput) as { spec?: unknown }- return readRecipeAgentProvider(parsed.spec) === GROK_SUBSCRIPTION_PROVIDER+ return readRecipeOauthBrokerProvider(parsed.spec) === GROK_SUBSCRIPTION_PROVIDER} catch {return false}@@ -1872,7 +1887,7 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)namespace?: string}const grantAnnotations = recipeGrantAnnotations(- readRecipeAgentProvider(specToUse),+ readRecipeOauthBrokerProvider(specToUse),codexConnectionRef)diff --git a/control-ui/components/__tests__/RecipeEditor.test.tsx b/control-ui/components/__tests__/RecipeEditor.test.tsxindex b7ddce262..8c90d0151 100644--- a/control-ui/components/__tests__/RecipeEditor.test.tsx+++ b/control-ui/components/__tests__/RecipeEditor.test.tsx@@ -5,6 +5,7 @@ import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testiimport * as api from '../../lib/api'import type { WorkflowRecipeResource } from '../../lib/api'import { listCodexSubscriptionConnections } from '../../lib/codexSubscription'+import { listGrokSubscriptionConnections } from '../../lib/grokSubscription'import { validateRecipe } from '../../lib/recipeValidator'import { RecipeEditor } from '../RecipeEditor'import { ToastProvider } from '../Toast'@@ -1778,6 +1779,62 @@ describe('RecipeEditor — grants in editor', () => {expect(onSaved).toHaveBeenCalled()})+ it('deploys a step-only Grok recipe with the canonical grant annotation', async () => {+ vi.mocked(listGrokSubscriptionConnections).mockResolvedValueOnce([+ {+ connectionKey: 'team-grok',+ displayName: 'Team Grok',+ status: 'connected',+ catalogStatus: 'ready',+ credentialRevision: 1,+ catalogRevision: 1,+ accountFingerprint: 'fp',+ catalogSyncedAt: '2026-08-01T00:00:00.000Z',+ lastRefreshAt: null,+ lastAuthAt: '2026-08-01T00:00:00.000Z',+ refreshLockHeld: false,+ },+ ])+ render(<RecipeEditor onSaved={vi.fn()} onCancel={vi.fn()} />)+ fireEvent.change(screen.getByRole('textbox'), {+ target: {+ value: JSON.stringify(+ {+ apiVersion: 'clerum.io/v1alpha1',+ kind: 'WorkflowRecipe',+ metadata: { name: 'step-grok' },+ spec: {+ agent: { provider: 'openai', model: 'gpt-5.1' },+ triggers: { onDemand: { allowedActors: ['user'] } },+ steps: [+ {+ id: 'draft',+ instruction: 'Write',+ timeoutSeconds: 600,+ agent: { provider: 'grok-subscription', model: 'grok-4.6' },+ },+ ],+ },+ },+ null,+ 2+ ),+ },+ })+ reviewAndProceedToDeploy()+ fireEvent.click(await screen.findByRole('button', { name: 'Grok grant' }))+ fireEvent.click(await screen.findByRole('option', { name: /Team Grok/ }))+ fireEvent.click(await screen.findByText('Deploy plugin'))+ await waitFor(() => expect(api.createRecipe).toHaveBeenCalled())+ const createPayload = vi.mocked(api.createRecipe).mock.calls[0][0] as {+ metadata?: { annotations?: Record<string, string> }+ }+ expect(createPayload.metadata?.annotations).toEqual({+ 'clerum.io/codex-connection-ref': '',+ 'clerum.io/subscription-connection-ref': 'team-grok',+ })+ })+it('blocks a Codex recipe that has not chosen a ChatGPT grant', async () => {render(<RecipeEditor onSaved={vi.fn()} onCancel={vi.fn()} />)fireEvent.change(screen.getByRole('combobox'), {diff --git a/control-ui/lib/__tests__/llm.test.ts b/control-ui/lib/__tests__/llm.test.tsindex bd22a6e83..04bee4ebb 100644--- a/control-ui/lib/__tests__/llm.test.ts+++ b/control-ui/lib/__tests__/llm.test.ts@@ -350,4 +350,22 @@ describe('broker-backed authoring helpers', () => {})).toMatch(/unit tokens/)})++ it('requires a Grok grant when only a step agent uses grok-subscription', () => {+ expect(+ brokerBackedRecipeAuthoringError({+ agent: { provider: 'openai', model: 'gpt-5.1' },+ steps: [{ agent: { provider: 'grok-subscription', model: 'grok-4.6' } }],+ })+ ).toMatch(/Grok grant/)+ expect(+ brokerBackedRecipeAuthoringError(+ {+ agent: { provider: 'openai', model: 'gpt-5.1' },+ steps: [{ agent: { provider: 'grok-subscription', model: 'grok-4.6' } }],+ },+ 'team-grok'+ )+ ).toBeNull()+ })})diff --git a/control-ui/lib/llm.ts b/control-ui/lib/llm.tsindex 6905053c9..0fda436d8 100644--- a/control-ui/lib/llm.ts+++ b/control-ui/lib/llm.ts@@ -290,13 +290,31 @@ export function budgetUnitAllowedForProviders(// Recipe authoring guard: a broker-backed agent must name an explicit model// and must not carry an LLM secretRef or a cost-unit budget. The grant lives// on metadata.annotations[clerum.io/codex-connection-ref], not in spec.+function recipeOauthBrokerAgent(spec: Record<string, unknown>): Record<string, unknown> | null {+ const consider = (value: unknown): Record<string, unknown> | null => {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null+ const record = value as Record<string, unknown>+ const provider = typeof record.provider === 'string' ? record.provider : ''+ if (isLlmProviderId(provider) && PROVIDER_AUTH_MODE[provider] === 'oauth-broker') return record+ return null+ }+ const top = consider(spec.agent)+ if (top) return top+ if (!Array.isArray(spec.steps)) return null+ for (const step of spec.steps) {+ if (!step || typeof step !== 'object' || Array.isArray(step)) continue+ const found = consider((step as Record<string, unknown>).agent)+ if (found) return found+ }+ return null+}+export function brokerBackedRecipeAuthoringError(spec: Record<string, unknown>,connectionRef?: string): string | null {- const agent = spec.agent- if (!agent || typeof agent !== 'object' || Array.isArray(agent)) return null- const record = agent as Record<string, unknown>+ const record = recipeOauthBrokerAgent(spec)+ if (!record) return nullconst provider = typeof record.provider === 'string' ? record.provider : ''if (!isLlmProviderId(provider) || PROVIDER_AUTH_MODE[provider] !== 'oauth-broker') {return nulldiff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex c0df12b81..120b830d6 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.587",+ "version": "0.1.589","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.587",+ "version": "0.1.589","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/frontend-components": "file:../packages/frontend-components",diff --git a/control-ui/package.json b/control-ui/package.jsonindex c852dbe31..c36f97bca 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.588",+ "version": "0.1.589","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.jsonindex ab7cd6286..09b0df8a8 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.330",+ "version": "0.1.331","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.330",+ "version": "0.1.331","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex a20e65372..d666b0946 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.330",+ "version": "0.1.331","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/hostReconciler.ts b/host-context-controller/src/hostReconciler.tsindex 48545e8bf..0a1c4c3fb 100644--- a/host-context-controller/src/hostReconciler.ts+++ b/host-context-controller/src/hostReconciler.ts@@ -1265,12 +1265,21 @@ export class HostReconciler {frontsOAuthServer,}),].sort()- const derived = [...(projection?.derivedScopes ?? []), ...(grokProjection?.derivedScopes ?? [])]- if (derived.length === 0) {+ const codexDerived = projection?.derivedScopes ?? []+ const grokDerived = grokProjection?.derivedScopes ?? []+ if (codexDerived.length === 0 && grokDerived.length === 0) {return HostReconciler.shortHash(runtimeScopes)}+ // Codex-only Hosts must keep the pre-Grok hash input so an HCC upgrade+ // does not remint every existing Codex runtime token.+ if (grokDerived.length === 0) {+ return HostReconciler.shortHash({+ scopes: [...runtimeScopes, ...codexDerived].sort(),+ drift: projection?.driftHashInput,+ })+ }return HostReconciler.shortHash({- scopes: [...runtimeScopes, ...derived].sort(),+ scopes: [...runtimeScopes, ...codexDerived, ...grokDerived].sort(),drift: {codex: projection?.driftHashInput,grok: grokProjection?.driftHashInput,diff --git a/host-context-controller/test/hostReconciler.test.ts b/host-context-controller/test/hostReconciler.test.tsindex 6e71c845f..2f2fcd480 100644--- a/host-context-controller/test/hostReconciler.test.ts+++ b/host-context-controller/test/hostReconciler.test.ts@@ -2126,11 +2126,24 @@ describe('HostReconciler oauth:user-token runtime scope provisioning', () => {runtimeTokenScopeHash(host: HostCRD,hasChannelIngress?: boolean,- frontsOAuthServer?: boolean+ frontsOAuthServer?: boolean,+ projection?: { derivedScopes?: string[]; driftHashInput?: string },+ grokProjection?: { derivedScopes?: string[]; driftHashInput?: string }): string}).runtimeTokenScopeHash+ it('keeps the pre-Grok scope hash when Grok has no derived scopes', () => {+ const host = makeHost()+ const codex = { derivedScopes: ['llm:codex:execute'], driftHashInput: '{"k":1}' }+ expect(scopeHashOf(host, false, false, codex, { derivedScopes: [] })).toBe(+ scopeHashOf(host, false, false, codex)+ )+ expect(+ scopeHashOf(host, false, false, codex, { derivedScopes: ['llm:grok:execute'] })+ ).not.toBe(scopeHashOf(host, false, false, codex))+ })+it('requests oauth:user-token through the real issuance payload when the Host fronts an enabled oauth mcp-server', async () => {vi.mocked(issueMcpHostRuntimeTokens).mockClear()const { reconciler } = createReconciler()diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 52e6f875d..4aeebf225 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.340",+ "version": "0.1.341","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.340",+ "version": "0.1.341","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex cc9263bf9..6a3664633 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.340",+ "version": "0.1.341","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.tsindex 6f348bb87..dbe3ab4f2 100644--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts@@ -73,8 +73,10 @@ function makeBridge(}}),}- const createProvider = ((_keys: ApiKeys, model: ModelConfig) => {+ const capturedCalls: unknown[] = []+ const createProvider = ((_keys: ApiKeys, model: ModelConfig, captured?: unknown) => {providerCalls.push(`${model.provider}/${model.name}`)+ capturedCalls.push(captured)return (providers[model.name] ?? null) as unknown as SingleTurnProvider | null}) as typeof createLLMProviderreturn {@@ -84,6 +86,7 @@ function makeBridge(...(maxResponseBytes !== undefined ? { maxResponseBytes } : {}),}),providerCalls,+ capturedCalls,credentialCalls,resolver,}@@ -916,12 +919,63 @@ const codexReceipt = {fallbackUsed: false,}+const grokTarget: PromptBridgeTarget = {+ targetRef: 'grok-primary',+ provider: 'grok-subscription',+ model: 'grok-4.6',+ credentialSlot: '',+ connectionRef: 'team-grok',+}++function installGrokBinding(): void {+ replaceSdkOnlyGrokBinding({+ connectionKey: 'team-grok',+ catalogRevision: 1,+ credentialRevision: 1,+ model: grokTarget.model,+ bindingHash: computeGrokPolicyHash({+ model: grokTarget.model,+ catalogRevision: 1,+ credentialRevision: 1,+ connectionKey: 'team-grok',+ }),+ })+}+describe('LlmBridge oauth-broker terminal accounting', () => {afterEach(() => {replaceSdkOnlyCodexBinding(null)replaceSdkOnlyGrokBinding(null)})+ it('forwards capturedGrokAttemptContext into createLLMProvider', async () => {+ installGrokBinding()+ const grok = new FakeProvider(() => Promise.resolve(OK))+ const { bridge, capturedCalls } = makeBridge({ [grokTarget.model]: grok })+ const providerAttemptReporter = { report: vi.fn().mockResolvedValue(undefined) }+ await bridge.complete({+ ...request,+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'prompt-notify',+ targets: [{ target: grokTarget }],+ credentialTicketIssuer: {+ issue: vi.fn(async () => ({+ credentialTicket: '',+ providerAttemptId: 'sdk-grok-primary',+ providerAttemptIndex: 1,+ })),+ },+ providerAttemptReporter,+ })+ expect(capturedCalls[0]).toEqual({+ capturedGrokAttemptContext: expect.objectContaining({+ invocationId: 'inv-1',+ pluginWorkloadSdkProviderAttemptId: 'sdk-grok-primary',+ targetRef: 'grok-primary',+ }),+ })+ })+it('keeps a pre-dispatch Codex budget denial revivable and carries its receipt', async () => {installCodexBinding()const codex = new FakeProvider(() => Promise.reject(new Error('budget denied')), {diff --git a/packages/grok-provider-attempt-contract/index.cjs b/packages/grok-provider-attempt-contract/index.cjsindex 93182c587..647c61ff4 100644--- a/packages/grok-provider-attempt-contract/index.cjs+++ b/packages/grok-provider-attempt-contract/index.cjs@@ -19,6 +19,7 @@ const CATALOG_ORIGIN = 'https://cli-chat-proxy.grok.com/v1/models'const LIMITS = Object.freeze({maxRequestBodyBytes: 1048576,maxMessages: 128,+ // Grok's Responses tool list is larger than Codex's 32.maxToolCalls: 64,maxOutputTokens: 16384,maxDeadlineMs: 300000,diff --git a/scripts/tests/test-grok-subscription-t0.sh b/scripts/tests/test-grok-subscription-t0.shindex ac638af72..cc2f526fd 100755--- a/scripts/tests/test-grok-subscription-t0.sh+++ b/scripts/tests/test-grok-subscription-t0.sh@@ -120,6 +120,11 @@ require_file workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.grokPolirequire_file workflow-recipes/tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.tsrequire_file mcp-host/src/pluginWorkloadSdk/bootstrapIdentity.test.tsrequire_file packages/codex-catalog-projection/index.test.cjs+require_file control-api/test/services.usageEvents.test.ts+require_file control-api/test/services.llmProviderAttemptFinalization.test.ts+require_file workflow-recipes/tests/unit/workflow/podFactory.test.ts+require_file control-ui/components/__tests__/RecipeEditor.test.tsx+require_file control-ui/lib/__tests__/llm.test.tsrequire_file control-ui/components/__tests__/PluginWorkloadSdkPage.test.tsxexpected_device_url='https://auth.x.ai/oauth2/device/code'@@ -158,16 +163,16 @@ run_group "grok-llm-proxy tsc" \bash -lc "cd '${ROOT}/grok-llm-proxy' && npx tsc --noEmit && echo 'pass 1'"run_group "control-api grok grant/oauth/redeem/authorize" \- bash -lc "cd '${ROOT}/control-api' && npx vitest run test/db.grokSubscriptionMigration.test.ts test/services.grokSubscriptionConnection.test.ts test/services.grokSubscriptionOAuth.test.ts test/services.grokSubscriptionCatalog.test.ts test/services.grokProviderAttemptRedemption.test.ts test/services.grokProviderAttemptTicket.test.ts test/services.llmProviderAttemptAuthorizer.grok.test.ts test/subscriptionGrantIdentity.test.ts test/routes.adminPluginWorkloadSdk.test.ts test/services.recipeCodexGrantIdentity.test.ts test/hostSpecValidation.grokSubscription.test.ts test/crd.llmProviderEnums.test.ts test/routes.mcp-host.plugin-workload-sdk.test.ts --no-file-parallelism"+ bash -lc "cd '${ROOT}/control-api' && npx vitest run test/db.grokSubscriptionMigration.test.ts test/services.grokSubscriptionConnection.test.ts test/services.grokSubscriptionOAuth.test.ts test/services.grokSubscriptionCatalog.test.ts test/services.grokProviderAttemptRedemption.test.ts test/services.grokProviderAttemptTicket.test.ts test/services.llmProviderAttemptAuthorizer.grok.test.ts test/subscriptionGrantIdentity.test.ts test/routes.adminPluginWorkloadSdk.test.ts test/services.recipeCodexGrantIdentity.test.ts test/hostSpecValidation.grokSubscription.test.ts test/crd.llmProviderEnums.test.ts test/routes.mcp-host.plugin-workload-sdk.test.ts test/services.usageEvents.test.ts test/services.llmProviderAttemptFinalization.test.ts --no-file-parallelism"run_group "workflow-recipes grok SDK" \- bash -lc "cd '${ROOT}/workflow-recipes' && npx vitest run src/workflow/codexRecipeVerdict.test.ts src/workflow/sdkOnlyGrokBinding.test.ts src/workflow/pluginWorkloadSdkProvisioner.grokPolicy.test.ts src/reconciler/pluginWorkloadSdkValidator.test.ts tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts --no-file-parallelism"+ bash -lc "cd '${ROOT}/workflow-recipes' && npx vitest run src/workflow/codexRecipeVerdict.test.ts src/workflow/sdkOnlyGrokBinding.test.ts src/workflow/pluginWorkloadSdkProvisioner.grokPolicy.test.ts src/reconciler/pluginWorkloadSdkValidator.test.ts tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts tests/unit/workflow/podFactory.test.ts --no-file-parallelism"run_group "mcp-host grok bootstrap" \bash -lc "cd '${ROOT}/mcp-host' && npx vitest run src/pluginWorkloadSdk/bootstrapIdentity.test.ts src/pluginWorkloadSdk/promptBridge/controlApiClient.test.ts src/pluginWorkloadSdk/promptBridge/llmBridge.failover.test.ts --no-file-parallelism"run_group "control-ui grok SDK picker" \- bash -lc "cd '${ROOT}/control-ui' && npx vitest run components/__tests__/PluginWorkloadSdkPage.test.tsx components/__tests__/HostWizard.test.tsx components/__tests__/HostDetailsPage.identity.test.tsx --no-file-parallelism"+ bash -lc "cd '${ROOT}/control-ui' && npx vitest run components/__tests__/PluginWorkloadSdkPage.test.tsx components/__tests__/HostWizard.test.tsx components/__tests__/HostDetailsPage.identity.test.tsx components/__tests__/RecipeEditor.test.tsx lib/__tests__/llm.test.ts --no-file-parallelism"if ! bash "${ROOT}/scripts/tests/test-grok-llm-proxy-deploy-contract.sh"; thenfail "grok-llm-proxy deploy contract"diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.jsonindex b7b56484c..6c54afd28 100644--- a/workflow-recipes/package-lock.json+++ b/workflow-recipes/package-lock.json@@ -1,12 +1,12 @@{"name": "workload-recipes-controller",- "version": "0.1.359",+ "version": "0.1.360","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "workload-recipes-controller",- "version": "0.1.359",+ "version": "0.1.360","license": "SEE LICENSE IN LICENSE","dependencies": {"@aws-sdk/client-s3": "^3.1009.0",diff --git a/workflow-recipes/package.json b/workflow-recipes/package.jsonindex 7c87ab678..43954016d 100644--- a/workflow-recipes/package.json+++ b/workflow-recipes/package.json@@ -1,6 +1,6 @@{"name": "workload-recipes-controller",- "version": "0.1.359",+ "version": "0.1.360","description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface","main": "dist/main.js","engines": {diff --git a/workflow-recipes/tsconfig.build.json b/workflow-recipes/tsconfig.build.jsonindex bb0710f84..4b83d6591 100644--- a/workflow-recipes/tsconfig.build.json+++ b/workflow-recipes/tsconfig.build.json@@ -4,5 +4,13 @@"rootDir": "./src","noEmit": false},- "exclude": ["node_modules", "dist", "test", "tests", "**/*.test.ts", "**/__tests__/**"]+ "exclude": [+ "node_modules",+ "dist",+ "test",+ "tests",+ "**/*.test.ts",+ "**/*.testFixtures.ts",+ "**/__tests__/**"+ ]}diff --git a/workflow-recipes/tsconfig.json b/workflow-recipes/tsconfig.jsonindex 2ff462a46..815bef379 100644--- a/workflow-recipes/tsconfig.json+++ b/workflow-recipes/tsconfig.json@@ -17,5 +17,5 @@},"references": [{ "path": "../packages/workflow-runtime-core" }],"include": ["src/**/*"],- "exclude": ["node_modules", "dist", "**/*.test.ts", "**/__tests__/**"]+ "exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.testFixtures.ts", "**/__tests__/**"]}