Skip to content

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

TypeScript

fix: close Grok SDK spend, usage, persist-first, and Docker COPY holes

Jose Gabriel Ramirez Encinasa65c45affe22
diff --git a/.github/workflows/build-publish.yml b/.github/workflows/build-publish.yml
index a8a3470bb..26431902a 100644
--- a/.github/workflows/build-publish.yml
+++ b/.github/workflows/build-publish.yml
@@ -167,6 +167,7 @@ jobs:
- 'packages/network-policy-core/**'
- 'packages/llm-provider-attempt-contract/**'
- 'packages/codex-catalog-projection/**'
+ - 'packages/grok-provider-attempt-contract/**'
- 'scripts/e2e/**'
- 'tests/e2e/fixtures/**'
stdio-bridge:
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index 4952950c0..9d9c6d7c6 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -261,7 +261,8 @@ jobs:
services.llmProviderAttemptStore.realPostgres.integration \
services.llmProviderAttemptRedemption.realPostgres.integration \
services.llmProviderAttemptFinalization.realPostgres.integration \
- pluginWorkloadSdkCodexDualLedger.realPostgres.integration
+ pluginWorkloadSdkCodexDualLedger.realPostgres.integration \
+ services.grokSubscriptionConnection.realPostgres.integration
do
grep -Fq "$suite" "$normalized_log" || {
echo "real-Postgres control-api lane omitted Codex suite ${suite}" >&2
diff --git a/control-api/Dockerfile b/control-api/Dockerfile
index 7744ab58d..55a70e52d 100644
--- a/control-api/Dockerfile
+++ b/control-api/Dockerfile
@@ -12,6 +12,7 @@ COPY packages/llm-providers ./packages/llm-providers
# imports validateDisplayField from it.
COPY packages/display-field ./packages/display-field
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
# Build the shared @clerum/workflow-runtime-core package (TS → dist) BEFORE
# control-api's npm ci, so its file: dependency on it resolves with the compiled
diff --git a/control-api/Dockerfile.dockerignore b/control-api/Dockerfile.dockerignore
index fae00af40..d2a770244 100644
--- a/control-api/Dockerfile.dockerignore
+++ b/control-api/Dockerfile.dockerignore
@@ -8,6 +8,10 @@
!packages/display-field/**
!packages/llm-providers/
!packages/llm-providers/**
+!packages/llm-provider-attempt-contract/
+!packages/llm-provider-attempt-contract/**
+!packages/grok-provider-attempt-contract/
+!packages/grok-provider-attempt-contract/**
!packages/workflow-runtime-core/
!packages/workflow-runtime-core/package.json
!packages/workflow-runtime-core/package-lock.json
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 4f0bc6abc..bbf4e6598 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.566",
+ "version": "0.1.567",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.566",
+ "version": "0.1.567",
"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.json
index 9afa490e1..9b5fe517e 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.566",
+ "version": "0.1.567",
"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/recipes.ts b/control-api/src/routes/admin/recipes.ts
index 9cd7ae80b..a3ef8949d 100644
--- a/control-api/src/routes/admin/recipes.ts
+++ b/control-api/src/routes/admin/recipes.ts
@@ -1264,15 +1264,13 @@ function validateRecipeBody(body: RecipeBody): ValidationError[] {
}
function recipeUsesCodexBroker(spec?: Record<string, unknown>): boolean {
- const agent = spec?.agent
- if (!agent || typeof agent !== 'object' || Array.isArray(agent)) return false
- return (agent as { provider?: unknown }).provider === 'codex-subscription'
+ if (!spec) return false
+ return collectRecipeOauthBrokerProviders(spec).includes('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'
+ if (!spec) return false
+ return collectRecipeOauthBrokerProviders(spec).includes('grok-subscription')
}
function recipeHasPluginWorkloadSdk(spec?: Record<string, unknown>): boolean {
@@ -1431,13 +1429,21 @@ function sanitizeRecipeCodexAnnotation(
const incoming = readRequestedGrokRecipeGrant(body)
return grokMirrored(isGrokUnassignedConnectionKey(incoming) ? '' : incoming)
}
- const incoming = readRequestedCodexRecipeGrant(body)
const mirrored = (key: string) => ({
[CODEX_CONNECTION_REF_ANNOTATION]: key,
[SUBSCRIPTION_CONNECTION_REF_ANNOTATION]: key,
})
if (recipeUsesCodexBroker(body.spec)) {
if (!bodyHasCodexGrantAnnotation(body)) return {}
+ const annotations = recipeAnnotationStrings(body.metadata?.annotations) ?? {}
+ const alias = (annotations[CODEX_CONNECTION_REF_ANNOTATION] ?? '').trim()
+ const canonical = (annotations[SUBSCRIPTION_CONNECTION_REF_ANNOTATION] ?? '').trim()
+ if (canonical && alias && canonical !== alias) {
+ throw new RecipeGrantAnnotationDisagreeError('subscription connection annotations disagree')
+ }
+ // Grok writers emit canonical only. Do not promote that leftover to a Codex grant.
+ if (!alias) return mirrored('')
+ const incoming = readRequestedCodexRecipeGrant(body)
return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)
}
const leavingCodex = recipeUsesCodexBroker(currentSpec) && !recipeHasPluginWorkloadSdk(body.spec)
@@ -1446,6 +1452,10 @@ function sanitizeRecipeCodexAnnotation(
return mirrored('')
}
if (bodyHasCodexGrantAnnotation(body)) {
+ const annotations = recipeAnnotationStrings(body.metadata?.annotations) ?? {}
+ const alias = (annotations[CODEX_CONNECTION_REF_ANNOTATION] ?? '').trim()
+ if (!alias) return mirrored('')
+ const incoming = readRequestedCodexRecipeGrant(body)
return mirrored(isCodexUnassignedConnectionKey(incoming) ? '' : incoming)
}
void currentAnnotations
diff --git a/control-api/src/services/grokProviderAttemptFinalization.ts b/control-api/src/services/grokProviderAttemptFinalization.ts
index fd2e7b179..acab61ce1 100644
--- a/control-api/src/services/grokProviderAttemptFinalization.ts
+++ b/control-api/src/services/grokProviderAttemptFinalization.ts
@@ -164,7 +164,7 @@ async function ingestGrokFinalizeLedgerRow(
) {
return
}
- await ingestUsageEventsInTransaction(
+ const ingest = await ingestUsageEventsInTransaction(
[
{
request_id: attempt.id,
@@ -196,4 +196,10 @@ async function ingestGrokFinalizeLedgerRow(
undefined,
{ origin: 'finalize' }
)
+ if (ingest.result.rejected !== 0 || ingest.result.accepted + ingest.result.duplicates !== 1) {
+ throw new GrokProviderAttemptFinalizeError(
+ 'invalid_receipt',
+ 'Grok usage could not be bound to a single ledger row'
+ )
+ }
}
diff --git a/control-api/src/services/grokSubscriptionOAuth.ts b/control-api/src/services/grokSubscriptionOAuth.ts
index 099265ca7..03c31e1cb 100644
--- a/control-api/src/services/grokSubscriptionOAuth.ts
+++ b/control-api/src/services/grokSubscriptionOAuth.ts
@@ -424,7 +424,7 @@ async function rotateLockedRefresh(
}
const current = await getSafeGrokSubscriptionConnection(deps.db, key)
const observedRevision = secrets.credentialRevision
- const token = await exchangeRefreshToken(deps, secrets.refreshToken, {
+ const pair = await exchangeRefreshToken(deps, secrets.refreshToken, {
expectedRevision: observedRevision,
lockToken,
connectionKey: key,
@@ -434,23 +434,36 @@ async function rotateLockedRefresh(
connectionKey: key,
expectedRevision: observedRevision,
lockToken,
- refreshToken: token.refreshToken,
+ refreshToken: pair.refreshToken,
})
+ let subject: string
+ try {
+ subject = subjectFromTokens(pair.idToken, pair.accessToken)
+ } catch (err) {
+ const marked = await markGrokRefreshSubjectMismatch(
+ deps.db,
+ key,
+ persisted.credentialRevision
+ )
+ if (marked) return marked
+ throw err
+ }
+ const accountFingerprint = fingerprintAccount(subject)
const updated = await updateGrokAccessTokenInPlace(
deps.db,
deps.encryptionKey,
persisted.credentialRevision,
{
- accessToken: token.accessToken,
- accessTokenExpiresAt: token.expiresAt,
+ accessToken: pair.accessToken,
+ accessTokenExpiresAt: pair.expiresAt,
},
key,
lockToken
)
if (
current?.accountFingerprint &&
- token.accountFingerprint &&
- current.accountFingerprint !== token.accountFingerprint
+ accountFingerprint &&
+ current.accountFingerprint !== accountFingerprint
) {
const marked = await markGrokRefreshSubjectMismatch(deps.db, key, updated.credentialRevision)
return marked ?? { ...updated, status: 'reauth_required' }
@@ -529,10 +542,14 @@ async function persistGrantedTokens(
}
}
-type ParsedGrokToken = {
+type GrokTokenPair = {
accessToken: string
refreshToken: string
expiresAt: Date | null
+ idToken: string | null
+}
+
+type ParsedGrokToken = GrokTokenPair & {
accountFingerprint: string
}
@@ -576,7 +593,7 @@ async function exchangeRefreshToken(
deps: GrokOAuthDeps,
refreshToken: string,
fence: { expectedRevision: number; lockToken: string; connectionKey: string }
-): Promise<ParsedGrokToken> {
+): Promise<GrokTokenPair> {
const result = await postForm(deps, GROK_OAUTH_TOKEN_URL, {
grant_type: 'refresh_token',
refresh_token: refreshToken,
@@ -602,17 +619,18 @@ async function exchangeRefreshToken(
'invalid_grant observed after a lost refresh race'
)
}
+ await markGrokRefreshSubjectMismatch(deps.db, fence.connectionKey, fence.expectedRevision)
throw new GrokSubscriptionOAuthError('reauth_required', 'refresh token was rejected')
}
throw new GrokSubscriptionOAuthError('provider_unavailable', 'refresh token exchange failed')
}
- return parseTokenResponse(result.body, { requireRefresh: true })
+ return readGrokTokenPair(result.body, { requireRefresh: true })
}
-function parseTokenResponse(
+function readGrokTokenPair(
body: Record<string, unknown>,
opts: { requireRefresh: boolean }
-): ParsedGrokToken {
+): GrokTokenPair {
const accessToken = requiredString(body.access_token, 'access_token')
const refreshToken = typeof body.refresh_token === 'string' ? body.refresh_token : ''
if (opts.requireRefresh && !refreshToken) {
@@ -623,12 +641,22 @@ function parseTokenResponse(
}
const expiresIn = typeof body.expires_in === 'number' ? body.expires_in : null
const idToken = typeof body.id_token === 'string' ? body.id_token : null
- const subject = subjectFromTokens(idToken, accessToken)
return {
accessToken,
refreshToken,
expiresAt: expiresIn ? new Date(Date.now() + expiresIn * 1000) : null,
- accountFingerprint: fingerprintAccount(subject),
+ idToken,
+ }
+}
+
+function parseTokenResponse(
+ body: Record<string, unknown>,
+ opts: { requireRefresh: boolean }
+): ParsedGrokToken {
+ const pair = readGrokTokenPair(body, opts)
+ return {
+ ...pair,
+ accountFingerprint: fingerprintAccount(subjectFromTokens(pair.idToken, pair.accessToken)),
}
}
diff --git a/control-api/src/services/llmProviderAttemptAuthorizer.ts b/control-api/src/services/llmProviderAttemptAuthorizer.ts
index 873eeaa4b..cc208ddb0 100644
--- a/control-api/src/services/llmProviderAttemptAuthorizer.ts
+++ b/control-api/src/services/llmProviderAttemptAuthorizer.ts
@@ -366,6 +366,35 @@ async function authorizeGrokProviderAttempt(
'attemptGeneration is older than the recorded invocation'
)
}
+ const pluginWorkloadSdkProviderAttemptId =
+ typeof body.pluginWorkloadSdkProviderAttemptId === 'string'
+ ? body.pluginWorkloadSdkProviderAttemptId.trim()
+ : ''
+ let sdkLinkRecipe: { namespace: string; name: string } | null = null
+ if (pluginWorkloadSdkProviderAttemptId) {
+ if (!UUID_RE.test(pluginWorkloadSdkProviderAttemptId)) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'invalid_request',
+ 'pluginWorkloadSdkProviderAttemptId must be a UUID'
+ )
+ }
+ if (caller.callerKind === 'host') {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'host Grok chat cannot bind a Plugin Workload SDK provider attempt'
+ )
+ }
+ if (!caller.recipeNamespace || !caller.recipeName) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'pluginWorkloadSdkProviderAttemptId does not match the reserved SDK attempt'
+ )
+ }
+ sdkLinkRecipe = { namespace: caller.recipeNamespace, name: caller.recipeName }
+ }
+ if (sdkLinkRecipe) {
+ await lockPluginWorkloadSdkRecipe(db, sdkLinkRecipe.namespace, sdkLinkRecipe.name)
+ }
const presentedReservationId =
typeof body.budgetReservationId === 'string' ? body.budgetReservationId.trim() : ''
let budgetReservationId = presentedReservationId || 'unbudgeted'
@@ -407,6 +436,57 @@ async function authorizeGrokProviderAttempt(
}
budgetReservationId = budget.reservationIds?.[0] ?? 'unbudgeted'
}
+ const presentedTargetRef = typeof body.targetRef === 'string' ? body.targetRef.trim() : ''
+ let reservedSdkAttemptToPromote: {
+ id: string
+ invocationId: string
+ recipeNamespace: string
+ recipeName: string
+ attemptGeneration: number
+ attemptIndex: number
+ model: string
+ targetRef: string
+ } | null = null
+ if (pluginWorkloadSdkProviderAttemptId) {
+ const sdkAttempt = await getPluginWorkloadSdkProviderAttemptForUpdate(
+ pluginWorkloadSdkProviderAttemptId,
+ db
+ )
+ const spendExists = sdkAttempt
+ ? await pluginWorkloadSdkSpendOutcomeExists(sdkAttempt.id, db)
+ : false
+ if (
+ !sdkAttempt ||
+ spendExists ||
+ sdkAttempt.invocationId !== invocationId ||
+ sdkAttempt.attemptGeneration !== attemptGeneration ||
+ sdkAttempt.attemptIndex !== providerAttemptIndex ||
+ sdkAttempt.recipeNamespace !== caller.recipeNamespace ||
+ sdkAttempt.recipeName !== caller.recipeName ||
+ sdkAttempt.provider !== GROK_PROVIDER ||
+ sdkAttempt.model !== request.model ||
+ !sdkAttempt.targetRef.trim() ||
+ (presentedTargetRef !== '' && presentedTargetRef !== sdkAttempt.targetRef) ||
+ !['reserved', 'in_progress'].includes(sdkAttempt.status)
+ ) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'pluginWorkloadSdkProviderAttemptId does not match the reserved SDK attempt'
+ )
+ }
+ if (sdkAttempt.status === 'reserved') {
+ reservedSdkAttemptToPromote = {
+ id: sdkAttempt.id,
+ invocationId: sdkAttempt.invocationId,
+ recipeNamespace: sdkAttempt.recipeNamespace,
+ recipeName: sdkAttempt.recipeName,
+ attemptGeneration: sdkAttempt.attemptGeneration,
+ attemptIndex: sdkAttempt.attemptIndex,
+ model: sdkAttempt.model,
+ targetRef: sdkAttempt.targetRef,
+ }
+ }
+ }
try {
const attempt = await resolvedDeps.insertAttempt(db, {
callerKind: caller.callerKind,
@@ -424,7 +504,20 @@ async function authorizeGrokProviderAttempt(
budgetReservationId,
connectionRevision: connection.credentialRevision,
connectionId: connection.id,
+ ...(pluginWorkloadSdkProviderAttemptId ? { pluginWorkloadSdkProviderAttemptId } : {}),
})
+ if (reservedSdkAttemptToPromote) {
+ const promoted = await promoteReservedOauthBrokerProviderAttempt(
+ { ...reservedSdkAttemptToPromote, provider: GROK_PROVIDER },
+ db
+ )
+ if (!promoted) {
+ throw new LlmProviderAttemptAuthorizeError(
+ 'no_grant',
+ 'pluginWorkloadSdkProviderAttemptId is no longer reserved for Grok authorize'
+ )
+ }
+ }
const issued = await issueRegisteredGrokExecutionTicket(db, {
sub: claims.sub,
hostRef: caller.hostRef,
@@ -800,7 +893,7 @@ export async function authorizeLlmProviderAttempt(
})
if (reservedSdkAttemptToPromote) {
const promoted = await promoteReservedOauthBrokerProviderAttempt(
- reservedSdkAttemptToPromote,
+ { ...reservedSdkAttemptToPromote, provider: PROVIDER },
db
)
if (!promoted) {
diff --git a/control-api/src/services/pluginWorkloadSdkDb.ts b/control-api/src/services/pluginWorkloadSdkDb.ts
index 879fb2969..de4d91ea8 100644
--- a/control-api/src/services/pluginWorkloadSdkDb.ts
+++ b/control-api/src/services/pluginWorkloadSdkDb.ts
@@ -1549,9 +1549,10 @@ export async function pluginWorkloadSdkSpendOutcomeExists(
}
/**
- * JTI-free reserved → in_progress for Codex authorize-link. Does not write
- * credential_jti. The secret-ticket path still promotes through
- * registerPluginWorkloadSdkCredentialTicketJti.
+ * JTI-free reserved → in_progress for oauth-broker authorize-link. Does not
+ * write credential_jti. The secret-ticket path still promotes through
+ * registerPluginWorkloadSdkCredentialTicketJti. Provider is a bind parameter
+ * so Codex and Grok cannot promote each other's reserved rows.
*/
export async function promoteReservedOauthBrokerProviderAttempt(
input: {
@@ -1563,6 +1564,7 @@ export async function promoteReservedOauthBrokerProviderAttempt(
attemptIndex: number
model: string
targetRef: string
+ provider: 'codex-subscription' | 'grok-subscription'
},
db: DbClient
): Promise<boolean> {
@@ -1575,7 +1577,7 @@ export async function promoteReservedOauthBrokerProviderAttempt(
AND recipe_name = $4
AND attempt_generation = $5
AND attempt_index = $6
- AND provider = 'codex-subscription'
+ AND provider = $9
AND model = $7
AND target_ref = $8
AND status = 'reserved'
@@ -1589,6 +1591,7 @@ export async function promoteReservedOauthBrokerProviderAttempt(
input.attemptIndex,
input.model,
input.targetRef,
+ input.provider,
]
)
return (result.rowCount ?? 0) === 1
diff --git a/control-api/src/services/usageEvents.ts b/control-api/src/services/usageEvents.ts
index 9734c6e52..101ac376f 100644
--- a/control-api/src/services/usageEvents.ts
+++ b/control-api/src/services/usageEvents.ts
@@ -202,10 +202,11 @@ export function validateUsageEvent(
const origin = options?.origin === 'finalize' ? 'finalize' : 'reporter'
const provider = typeof r.provider === 'string' ? r.provider.trim() : ''
if (!provider) return null
- // Codex spend belongs to proxy finalize. Reporter shapes (workflow, desktop,
- // plugin_workload_sdk) must not open a second ledger row.
- if (provider === 'codex-subscription' && origin !== 'finalize') return null
- if (origin === 'finalize' && provider !== 'codex-subscription') return null
+ // oauth-broker spend belongs to proxy finalize. Reporter shapes (workflow,
+ // desktop, plugin_workload_sdk) must not open a second ledger row.
+ const oauthBroker = provider === 'codex-subscription' || provider === 'grok-subscription'
+ if (oauthBroker && origin !== 'finalize') return null
+ if (origin === 'finalize' && !oauthBroker) return null
const model = typeof r.model === 'string' ? r.model.trim() : ''
if (!model) return null
diff --git a/control-api/src/utils/log/redact.ts b/control-api/src/utils/log/redact.ts
index 40befb711..e8d7e9d57 100644
--- a/control-api/src/utils/log/redact.ts
+++ b/control-api/src/utils/log/redact.ts
@@ -8,6 +8,7 @@ export const TOKEN_LEAK_REDACT_PATHS: readonly string[] = [
'headers.cookie',
'token',
'accessToken',
+ 'access_token',
'refreshToken',
'chatgptAccountId',
'accountId',
@@ -44,6 +45,7 @@ export const REQUIRED_REDACT_PATHS: readonly string[] = [
"req.headers['x-service-token']",
'headers.authorization',
'accessToken',
+ 'access_token',
'refreshToken',
'chatgptAccountId',
'accountId',
diff --git a/control-api/test/crd.llmProviderEnums.test.ts b/control-api/test/crd.llmProviderEnums.test.ts
index fc712e75d..063819f0c 100644
--- a/control-api/test/crd.llmProviderEnums.test.ts
+++ b/control-api/test/crd.llmProviderEnums.test.ts
@@ -99,11 +99,8 @@ describe('LLM provider CRD enums', () => {
it('WorkflowRecipe CEL rejects mixed oauth-broker agent and step providers', () => {
const recipe = readFileSync(resolve(crdsDir, 'workflowrecipe.yaml'), 'utf8')
expect(recipe).toContain('a WorkflowRecipe may declare at most one oauth-broker provider')
- expect(recipe).toMatch(
- /self\.steps\.exists\(s, has\(s\.agent\) && has\(s\.agent\.provider\) && s\.agent\.provider == 'codex-subscription'\)/
- )
- expect(recipe).toMatch(
- /self\.steps\.exists\(s, has\(s\.agent\) && has\(s\.agent\.provider\) && s\.agent\.provider == 'grok-subscription'\)/
+ expect(recipe).toContain(
+ "!(((has(self.agent) && has(self.agent.provider) && self.agent.provider == 'codex-subscription') || (has(self.steps) && self.steps.exists(s, has(s.agent) && has(s.agent.provider) && s.agent.provider == 'codex-subscription'))) && ((has(self.agent) && has(self.agent.provider) && self.agent.provider == 'grok-subscription') || (has(self.steps) && self.steps.exists(s, has(s.agent) && has(s.agent.provider) && s.agent.provider == 'grok-subscription'))))"
)
})
})
diff --git a/control-api/test/routes.adminRecipes.test.ts b/control-api/test/routes.adminRecipes.test.ts
index baf06c8a6..b56f669b5 100644
--- a/control-api/test/routes.adminRecipes.test.ts
+++ b/control-api/test/routes.adminRecipes.test.ts
@@ -295,6 +295,26 @@ describe.sequential('routes/admin/recipes', () => {
expect(res.body.errors[0].message).toMatch(/at most one oauth-broker/)
})
+ it('POST /admin/recipes — requires a Grok grant when only a step uses grok-subscription', async () => {
+ const res = await api.post('/admin/recipes').send({
+ 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' },
+ },
+ ],
+ },
+ })
+ expect(res.status).toBe(422)
+ expect(res.body.errors[0].rule).toBe('grokRecipeGrantRequired')
+ })
+
it('POST /admin/recipes — rejects a Codex recipe without a named grant', async () => {
const res = await api
.post('/admin/recipes')
diff --git a/control-api/test/services.grokProviderAttemptTicket.test.ts b/control-api/test/services.grokProviderAttemptTicket.test.ts
new file mode 100644
index 000000000..c327631d3
--- /dev/null
+++ b/control-api/test/services.grokProviderAttemptTicket.test.ts
@@ -0,0 +1,87 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import jwt from 'jsonwebtoken'
+import { createPublicKey, randomUUID } from 'node:crypto'
+import { config } from '../src/config.js'
+import {
+ GROK_EXECUTION_TICKET_AUDIENCE,
+ GROK_EXECUTION_TICKET_TTL_SECONDS,
+ issueRegisteredGrokExecutionTicket,
+ verifyGrokExecutionTicket,
+} from '../src/services/grokProviderAttemptTicket.js'
+import { CODEX_EXECUTION_TICKET_AUDIENCE } from '../src/services/llmProviderAttemptTicket.js'
+
+const binding = {
+ sub: 'host/research-host',
+ hostRef: 'research-host',
+ invocationId: 'invocation-1',
+ attemptGeneration: 1,
+ providerAttemptId: '33333333-3333-4333-8333-333333333333',
+ providerAttemptIndex: 1,
+ model: 'grok-4.6',
+ requestHash: 'a'.repeat(64),
+ policyRevision: 7,
+ policyHash: 'b'.repeat(64),
+ budgetReservationId: 'unbudgeted',
+ connectionRevision: 3,
+ connectionId: '11111111-1111-4111-8111-111111111111',
+}
+
+function memoryDb() {
+ return {
+ query: async () => ({ rows: [] }),
+ }
+}
+
+describe('Grok execution ticket', () => {
+ afterEach(() => {
+ vi.useRealTimers()
+ })
+
+ it('verifies an issued ticket and rejects Codex audience or typ', async () => {
+ const issued = await issueRegisteredGrokExecutionTicket(memoryDb(), binding)
+ expect(verifyGrokExecutionTicket(issued.executionTicket)).toMatchObject({
+ typ: 'grok-execution-ticket',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ connectionId: binding.connectionId,
+ })
+
+ const publicKey = createPublicKey(config.adminJwtPrivateKey).export({
+ type: 'spki',
+ format: 'pem',
+ })
+ const claims = jwt.verify(issued.executionTicket, publicKey, {
+ algorithms: ['RS256'],
+ issuer: config.adminJwtIssuer,
+ audience: GROK_EXECUTION_TICKET_AUDIENCE,
+ }) as jwt.JwtPayload
+ 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,
+ {
+ algorithm: 'RS256',
+ issuer: config.adminJwtIssuer,
+ audience: CODEX_EXECUTION_TICKET_AUDIENCE,
+ expiresIn: GROK_EXECUTION_TICKET_TTL_SECONDS,
+ }
+ )
+ expect(verifyGrokExecutionTicket(codexShaped)).toBeNull()
+ })
+
+ it('expires after 60 seconds', async () => {
+ vi.useFakeTimers()
+ vi.setSystemTime(new Date('2026-08-20T12:00:00.000Z'))
+ const issued = await issueRegisteredGrokExecutionTicket(memoryDb(), binding)
+ expect(verifyGrokExecutionTicket(issued.executionTicket)).not.toBeNull()
+ vi.advanceTimersByTime(60_001)
+ expect(verifyGrokExecutionTicket(issued.executionTicket)).toBeNull()
+ })
+})
diff --git a/control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts b/control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts
new file mode 100644
index 000000000..aae1778c9
--- /dev/null
+++ b/control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts
@@ -0,0 +1,151 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomBytes } from 'node:crypto'
+import { Pool } from 'pg'
+import { initDb } from '../src/db.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import {
+ acquireGrokSubscriptionRefreshLock,
+ insertInitialGrokSubscriptionConnection,
+ releaseGrokSubscriptionRefreshLock,
+} from '../src/services/grokSubscriptionConnection.js'
+import { insertLlmProviderAttempt } from '../src/services/llmProviderAttemptStore.js'
+
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+const KEY = deriveOAuthEncryptionKey('ab'.repeat(32))
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+function quoteIdent(value: string): string {
+ return `"${value.replace(/"/g, '""')}"`
+}
+
+describeRealPostgres('Grok subscription connection on real PostgreSQL', () => {
+ const database = `grok_subscription_${randomBytes(6).toString('hex')}`
+ const connectionString = databaseUrl(
+ adminUrl ?? `postgresql://postgres@${['127', '0', '0', '1'].join('.')}/postgres`,
+ database
+ )
+ let adminPool: Pool
+ let pool: Pool
+
+ beforeAll(async () => {
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE ${quoteIdent(database)}`)
+ pool = new Pool({ connectionString })
+ await initDb({ connect: () => pool.connect() })
+ }, 60_000)
+
+ afterAll(async () => {
+ await pool?.end()
+ if (adminPool) {
+ await adminPool
+ .query(`DROP DATABASE IF EXISTS ${quoteIdent(database)}`)
+ .catch(() => undefined)
+ await adminPool.end()
+ }
+ })
+
+ it('creates Grok grant tables', async () => {
+ const tables = await pool.query<{ table_name: string }>(
+ `SELECT table_name
+ FROM information_schema.tables
+ WHERE table_schema = 'public'
+ AND table_name = ANY($1::text[])
+ ORDER BY table_name`,
+ [['grok_catalog_models', 'grok_subscription_connections', 'grok_subscription_oauth_states']]
+ )
+ expect(tables.rows.map(row => row.table_name)).toEqual([
+ 'grok_catalog_models',
+ 'grok_subscription_connections',
+ 'grok_subscription_oauth_states',
+ ])
+ })
+
+ it('rejects reserved Grok connection keys', async () => {
+ await expect(
+ insertInitialGrokSubscriptionConnection(
+ pool,
+ KEY,
+ { refreshToken: 'refresh', accountFingerprint: 'fp' },
+ 'unassigned'
+ )
+ ).rejects.toThrow()
+ await expect(
+ insertInitialGrokSubscriptionConnection(
+ pool,
+ KEY,
+ { refreshToken: 'refresh', accountFingerprint: 'fp' },
+ 'deployment-default'
+ )
+ ).rejects.toThrow()
+ })
+
+ it('lets only one concurrent refresh lock win and reclaims after expiry', async () => {
+ const created = await insertInitialGrokSubscriptionConnection(
+ pool,
+ KEY,
+ { refreshToken: 'refresh-lock', accountFingerprint: 'fp-lock' },
+ 'team-grok-lock'
+ )
+ expect(created.connectionKey).toBe('team-grok-lock')
+ const [first, second] = await Promise.all([
+ acquireGrokSubscriptionRefreshLock(pool, 'lock-a', 5_000, 'team-grok-lock'),
+ acquireGrokSubscriptionRefreshLock(pool, 'lock-b', 5_000, 'team-grok-lock'),
+ ])
+ expect([first, second].filter(Boolean)).toHaveLength(1)
+ const winner = first ? 'lock-a' : 'lock-b'
+ expect(await releaseGrokSubscriptionRefreshLock(pool, winner, 'team-grok-lock')).toBe(true)
+ expect(await acquireGrokSubscriptionRefreshLock(pool, 'lock-c', 1, 'team-grok-lock')).toBe(true)
+ await new Promise(resolve => setTimeout(resolve, 20))
+ expect(await acquireGrokSubscriptionRefreshLock(pool, 'lock-d', 5_000, 'team-grok-lock')).toBe(
+ true
+ )
+ })
+
+ it('requires connection_id on grok-subscription provider attempts', async () => {
+ const created = await insertInitialGrokSubscriptionConnection(
+ pool,
+ KEY,
+ { refreshToken: 'refresh-check', accountFingerprint: 'fp-check' },
+ 'team-grok-check'
+ )
+ await expect(
+ insertLlmProviderAttempt(pool, {
+ callerKind: 'host',
+ hostRef: 'research-host',
+ invocationId: `invocation-${randomBytes(8).toString('hex')}`,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ requestHash: 'd'.repeat(64),
+ policyRevision: 1,
+ policyHash: 'e'.repeat(64),
+ budgetReservationId: 'unbudgeted',
+ connectionRevision: 1,
+ })
+ ).rejects.toThrow()
+ const row = await insertLlmProviderAttempt(pool, {
+ callerKind: 'host',
+ hostRef: 'research-host',
+ invocationId: `invocation-${randomBytes(8).toString('hex')}`,
+ attemptGeneration: 1,
+ providerAttemptIndex: 1,
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ requestHash: 'd'.repeat(64),
+ policyRevision: 1,
+ policyHash: 'e'.repeat(64),
+ budgetReservationId: 'unbudgeted',
+ connectionRevision: 1,
+ connectionId: created.id,
+ })
+ expect(row.provider).toBe('grok-subscription')
+ expect(row.connectionId).toBe(created.id)
+ })
+})
diff --git a/control-api/test/services.grokSubscriptionOAuth.test.ts b/control-api/test/services.grokSubscriptionOAuth.test.ts
index 828c4cfac..328da31ee 100644
--- a/control-api/test/services.grokSubscriptionOAuth.test.ts
+++ b/control-api/test/services.grokSubscriptionOAuth.test.ts
@@ -348,6 +348,8 @@ describe('grok subscription OAuth device broker', () => {
await expect(refreshGrokSubscriptionConnection(deps(fetchFn))).rejects.toMatchObject({
code: 'reauth_required',
})
+ expect(repos.markMismatch).toHaveBeenCalled()
+ expect(repos.persistRefresh).not.toHaveBeenCalled()
})
it('maps invalid_grant after a lock/revision change to a lost race', async () => {
@@ -431,6 +433,50 @@ describe('grok subscription OAuth device broker', () => {
expect(repos.releaseLock).toHaveBeenCalled()
})
+ it('persists a rotated refresh before failing closed on an opaque token with no subject', async () => {
+ repos.getSafe.mockResolvedValue({
+ connectionKey: CONNECTION_KEY,
+ status: 'connected',
+ credentialRevision: 7,
+ accountFingerprint: fingerprint('acct_raw_123'),
+ refreshLockHeld: true,
+ })
+ repos.acquireLock.mockResolvedValue(true)
+ repos.loadSecrets.mockResolvedValue({
+ refreshToken: 'old-refresh',
+ accessToken: null,
+ accessTokenExpiresAt: null,
+ credentialRevision: 7,
+ })
+ repos.persistRefresh.mockResolvedValue({
+ connectionKey: CONNECTION_KEY,
+ status: 'connected',
+ credentialRevision: 7,
+ })
+ repos.markMismatch.mockResolvedValue({
+ connectionKey: CONNECTION_KEY,
+ status: 'reauth_required',
+ credentialRevision: 7,
+ })
+ const fetchFn = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: async () => ({
+ access_token: 'opaque-access-token',
+ refresh_token: 'rotated-refresh',
+ }),
+ })
+ const refreshed = await refreshGrokSubscriptionConnection(deps(fetchFn))
+ expect(refreshed.status).toBe('reauth_required')
+ expect(repos.persistRefresh).toHaveBeenCalledWith(
+ expect.anything(),
+ KEY,
+ expect.objectContaining({ refreshToken: 'rotated-refresh' })
+ )
+ expect(repos.markMismatch).toHaveBeenCalled()
+ expect(repos.updateInPlace).not.toHaveBeenCalled()
+ })
+
it('keeps the stored fingerprint and marks reauth_required when the subject differs', async () => {
repos.getSafe.mockResolvedValue({
connectionKey: CONNECTION_KEY,
diff --git a/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts b/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts
index 069f6d8e7..d80c027c0 100644
--- a/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts
+++ b/control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts
@@ -221,4 +221,18 @@ describe('authorizeLlmProviderAttempt grok-subscription', () => {
})
)
})
+
+ it('denies Grok spend when the live Host has no oauth-broker target', async () => {
+ const current = deps({
+ resolveAssignment: async () => ({
+ liveBrokerProviders: [],
+ liveConnectionRef: 'team-grok',
+ }),
+ })
+ await expect(authorizeLlmProviderAttempt(claims(), body(), current)).rejects.toMatchObject({
+ code: 'host_binding_mismatch',
+ })
+ expect(grokRepos.getConnection).not.toHaveBeenCalled()
+ expect(current.insertAttempt).not.toHaveBeenCalled()
+ })
})
diff --git a/control-api/test/services.pluginWorkloadSdkDb.test.ts b/control-api/test/services.pluginWorkloadSdkDb.test.ts
index 21885dc08..a82c84454 100644
--- a/control-api/test/services.pluginWorkloadSdkDb.test.ts
+++ b/control-api/test/services.pluginWorkloadSdkDb.test.ts
@@ -697,13 +697,15 @@ describe('SQL contracts that a silent edit would otherwise break', () => {
attemptIndex: 1,
model: 'gpt-5.1',
targetRef: 'primary-codex',
+ provider: 'codex-subscription',
},
pool
)
- const [sql] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
+ const [sql, params] = vi.mocked(pool.query).mock.calls[0] as unknown as [string, unknown[]]
expect(sql).toContain('AND credential_jti IS NULL')
expect(sql).toContain("AND status = 'reserved'")
- expect(sql).toContain("AND provider = 'codex-subscription'")
+ expect(sql).toContain('AND provider = $9')
+ expect(params[8]).toBe('codex-subscription')
})
it('only revives an invocation that is persisted as failed', async () => {
diff --git a/control-api/test/services.usageEvents.test.ts b/control-api/test/services.usageEvents.test.ts
index 33677d999..bd8a30a17 100644
--- a/control-api/test/services.usageEvents.test.ts
+++ b/control-api/test/services.usageEvents.test.ts
@@ -203,6 +203,7 @@ describe('validateUsageEvent', () => {
it('rejects reporter Codex events in every reporter shape', () => {
expect(validateUsageEvent({ ...VALID_EVENT, provider: 'codex-subscription' })).toBeNull()
+ expect(validateUsageEvent({ ...VALID_EVENT, provider: 'grok-subscription' })).toBeNull()
expect(
validateUsageEvent({
...VALID_EVENT,
@@ -256,6 +257,38 @@ describe('validateUsageEvent', () => {
})
})
+ it('accepts finalize-origin Grok channel events with a null secret', () => {
+ const ev = validateUsageEvent(
+ {
+ request_id: '33333333-3333-4333-8333-333333333333',
+ ts: '2026-04-29T10:00:00.000Z',
+ run_id: null,
+ host_ref: 'research-host',
+ context_ref: null,
+ team_id: null,
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ llm_secret_name: null,
+ source_kind: 'channel',
+ user_id: null,
+ sender: null,
+ channel_type: null,
+ recipe_name: null,
+ cron_job_id: null,
+ task_id: null,
+ iteration: null,
+ input_tokens: 12,
+ output_tokens: 4,
+ },
+ { origin: 'finalize' }
+ )
+ expect(ev).toMatchObject({
+ provider: 'grok-subscription',
+ source_kind: 'channel',
+ request_id: '33333333-3333-4333-8333-333333333333',
+ })
+ })
+
it('rejects finalize-origin Codex events that still carry a secret or a non-channel source', () => {
const base = {
request_id: '33333333-3333-4333-8333-333333333333',
diff --git a/control-api/test/utils.log.redact.test.ts b/control-api/test/utils.log.redact.test.ts
index 3260ea0d9..9ec748f57 100644
--- a/control-api/test/utils.log.redact.test.ts
+++ b/control-api/test/utils.log.redact.test.ts
@@ -55,6 +55,7 @@ describe('token-leak redaction', () => {
'user_code',
'accountSubject',
'account_subject',
+ 'access_token',
'*.access_token',
'*.refresh_token',
'*.id_token',
diff --git a/control-ui/package.json b/control-ui/package.json
index 9990e37e6..c852dbe31 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.587",
+ "version": "0.1.588",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --git a/deploy/images.json b/deploy/images.json
index fefd7aca7..390247fd0 100644
--- a/deploy/images.json
+++ b/deploy/images.json
@@ -3,18 +3,14 @@
{
"name": "channel-reader",
"path": "channel-reader",
- "source_paths": [
- "channel-reader/**"
- ],
+ "source_paths": ["channel-reader/**"],
"published": true,
"deployed_to_minikube": true
},
{
"name": "workflow-approval-request-reader",
"path": "workflow-approval-request-reader",
- "source_paths": [
- "workflow-approval-request-reader/**"
- ],
+ "source_paths": ["workflow-approval-request-reader/**"],
"published": true,
"deployed_to_minikube": true
},
@@ -51,9 +47,7 @@
{
"name": "external-rest-api",
"path": "external-rest-api",
- "source_paths": [
- "external-rest-api/**"
- ],
+ "source_paths": ["external-rest-api/**"],
"published": true,
"deployed_to_minikube": true
},
@@ -129,27 +123,21 @@
{
"name": "mcp-proxy",
"path": "mcp-proxy",
- "source_paths": [
- "mcp-proxy/**"
- ],
+ "source_paths": ["mcp-proxy/**"],
"published": true,
"deployed_to_minikube": true
},
{
"name": "gfs-controller",
"path": "gfs-controller",
- "source_paths": [
- "gfs-controller/**"
- ],
+ "source_paths": ["gfs-controller/**"],
"published": true,
"deployed_to_minikube": true
},
{
"name": "nginx-egress-proxy",
"path": "nginx-egress-proxy",
- "source_paths": [
- "nginx-egress-proxy/**"
- ],
+ "source_paths": ["nginx-egress-proxy/**"],
"published": true,
"deployed_to_minikube": true
},
@@ -168,9 +156,7 @@
{
"name": "rpc-proxy",
"path": "rpc-proxy",
- "source_paths": [
- "rpc-proxy/**"
- ],
+ "source_paths": ["rpc-proxy/**"],
"published": true,
"deployed_to_minikube": true
},
@@ -187,6 +173,7 @@
"packages/network-policy-core/**",
"packages/llm-provider-attempt-contract/**",
"packages/codex-catalog-projection/**",
+ "packages/grok-provider-attempt-contract/**",
"scripts/e2e/**",
"tests/e2e/fixtures/**"
],
@@ -207,6 +194,7 @@
"packages/network-policy-core/**",
"packages/llm-provider-attempt-contract/**",
"packages/codex-catalog-projection/**",
+ "packages/grok-provider-attempt-contract/**",
"scripts/e2e/**",
"tests/e2e/fixtures/**"
],
@@ -226,6 +214,7 @@
"packages/network-policy-core/**",
"packages/llm-provider-attempt-contract/**",
"packages/codex-catalog-projection/**",
+ "packages/grok-provider-attempt-contract/**",
"scripts/e2e/**",
"tests/e2e/fixtures/**"
],
@@ -246,6 +235,7 @@
"packages/network-policy-core/**",
"packages/llm-provider-attempt-contract/**",
"packages/codex-catalog-projection/**",
+ "packages/grok-provider-attempt-contract/**",
"scripts/e2e/**",
"tests/e2e/fixtures/**"
],
@@ -255,27 +245,21 @@
{
"name": "stdio-bridge",
"path": "stdio-bridge",
- "source_paths": [
- "stdio-bridge/**"
- ],
+ "source_paths": ["stdio-bridge/**"],
"published": true,
"deployed_to_minikube": true
},
{
"name": "workspace-files-controller",
"path": "workspace-files-controller",
- "source_paths": [
- "workspace-files-controller/**"
- ],
+ "source_paths": ["workspace-files-controller/**"],
"published": true,
"deployed_to_minikube": true
},
{
"name": "airtable-mcp-server",
"path": "mcp-servers/airtable",
- "source_paths": [
- "mcp-servers/airtable/**"
- ],
+ "source_paths": ["mcp-servers/airtable/**"],
"published": true,
"deployed_to_minikube": false
},
@@ -283,9 +267,7 @@
"name": "playwright-server",
"path": "mcp-servers/playwright",
"local_name": "playwright-mcp-server",
- "source_paths": [
- "mcp-servers/playwright/**"
- ],
+ "source_paths": ["mcp-servers/playwright/**"],
"published": true,
"deployed_to_minikube": false
},
@@ -293,45 +275,35 @@
"name": "web-search-mcp",
"path": "mcp-servers/web-search",
"local_tag": "v1",
- "source_paths": [
- "mcp-servers/web-search/**"
- ],
+ "source_paths": ["mcp-servers/web-search/**"],
"published": true,
"deployed_to_minikube": false
},
{
"name": "mock-mcp-server",
"path": "tests/e2e/fixtures/mock-mcp-server",
- "source_paths": [
- "tests/e2e/fixtures/mock-mcp-server/**"
- ],
+ "source_paths": ["tests/e2e/fixtures/mock-mcp-server/**"],
"published": true,
"deployed_to_minikube": true
},
{
"name": "mock-stdio-mcp-server",
"path": "tests/e2e/fixtures/mock-stdio-mcp-server",
- "source_paths": [
- "tests/e2e/fixtures/mock-stdio-mcp-server/**"
- ],
+ "source_paths": ["tests/e2e/fixtures/mock-stdio-mcp-server/**"],
"published": true,
"deployed_to_minikube": true
},
{
"name": "webhook-gateway",
"path": "webhook-gateway",
- "source_paths": [
- "webhook-gateway/**"
- ],
+ "source_paths": ["webhook-gateway/**"],
"published": true,
"deployed_to_minikube": true
},
{
"name": "webhook-proxy",
"path": "webhook-proxy",
- "source_paths": [
- "webhook-proxy/**"
- ],
+ "source_paths": ["webhook-proxy/**"],
"published": true,
"deployed_to_minikube": true
},
@@ -339,10 +311,7 @@
"name": "codex-llm-proxy",
"path": "codex-llm-proxy",
"rooted": true,
- "source_paths": [
- "codex-llm-proxy/**",
- "packages/llm-provider-attempt-contract/**"
- ],
+ "source_paths": ["codex-llm-proxy/**", "packages/llm-provider-attempt-contract/**"],
"published": true,
"deployed_to_minikube": true
},
@@ -350,10 +319,7 @@
"name": "grok-llm-proxy",
"path": "grok-llm-proxy",
"rooted": true,
- "source_paths": [
- "grok-llm-proxy/**",
- "packages/grok-provider-attempt-contract/**"
- ],
+ "source_paths": ["grok-llm-proxy/**", "packages/grok-provider-attempt-contract/**"],
"published": true,
"deployed_to_minikube": true
},
diff --git a/deploy/scripts/apply-inter-service-tokens.sh b/deploy/scripts/apply-inter-service-tokens.sh
index 0df10f923..64e965215 100755
--- a/deploy/scripts/apply-inter-service-tokens.sh
+++ b/deploy/scripts/apply-inter-service-tokens.sh
@@ -343,6 +343,7 @@ kctl -n channels patch secret workflow-approval-request-reader-credentials --typ
# FORCE_CONSUMER_RESTART=true.
for pair in "control-plane:control-api" \
"control-plane:codex-llm-proxy" \
+ "control-plane:grok-llm-proxy" \
"control-plane:workflow-recipes" \
"control-plane:host-context-controller" \
"profiles:external-rest-api" \
diff --git a/mcp-host/Dockerfile b/mcp-host/Dockerfile
index 5331cdff2..562221e79 100644
--- a/mcp-host/Dockerfile
+++ b/mcp-host/Dockerfile
@@ -15,6 +15,7 @@ WORKDIR /app
# Shared prebuilt data-only package (no build step — ships index.cjs + .d.ts).
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
# Install dependencies (file: deps resolve to ../packages/llm-providers and
@@ -38,6 +39,7 @@ WORKDIR /app
# Copy the shared package + package files, install production dependencies only
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
diff --git a/mcp-host/Dockerfile.desktop b/mcp-host/Dockerfile.desktop
index c0efaeb13..77abb297d 100644
--- a/mcp-host/Dockerfile.desktop
+++ b/mcp-host/Dockerfile.desktop
@@ -6,6 +6,7 @@ FROM node:24.16.0-alpine@sha256:21f403ab171f2dc89bad4dd69d7721bfd15f084ccb46cdd2
WORKDIR /app
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
@@ -49,6 +50,7 @@ ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
WORKDIR /app
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY --from=builder /app/mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
diff --git a/mcp-host/Dockerfile.full b/mcp-host/Dockerfile.full
index c90a6630b..e7f10d824 100644
--- a/mcp-host/Dockerfile.full
+++ b/mcp-host/Dockerfile.full
@@ -13,6 +13,7 @@ WORKDIR /app
# Shared prebuilt data-only package (no build step — ships index.cjs + .d.ts).
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
# Install dependencies (file: deps resolve to ../packages/llm-providers and
@@ -46,6 +47,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
# Copy the shared package + package files, install production dependencies only
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
diff --git a/mcp-host/Dockerfile.slim b/mcp-host/Dockerfile.slim
index 79feed2b6..2b5ee21a8 100644
--- a/mcp-host/Dockerfile.slim
+++ b/mcp-host/Dockerfile.slim
@@ -13,6 +13,7 @@ WORKDIR /app
# Shared prebuilt data-only package (no build step — ships index.cjs + .d.ts).
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
# Install dependencies (file: deps resolve to ../packages/llm-providers and
@@ -49,6 +50,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
# Copy the shared package + package files, install production dependencies only
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY mcp-host/package*.json ./mcp-host/
WORKDIR /app/mcp-host
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 105b5d6a4..52e6f875d 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.339",
+ "version": "0.1.340",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.339",
+ "version": "0.1.340",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index b217eb623..cc9263bf9 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.339",
+ "version": "0.1.340",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/llm/index.ts b/mcp-host/src/llm/index.ts
index 44cdba89c..d6c54c35b 100644
--- a/mcp-host/src/llm/index.ts
+++ b/mcp-host/src/llm/index.ts
@@ -91,6 +91,7 @@ function createCodexRuntimeDeps(captured?: CodexAttemptContext) {
export type CreateLlmProviderOptions = {
capturedCodexAttemptContext?: CodexAttemptContext
+ capturedGrokAttemptContext?: GrokAttemptContext
}
/**
@@ -135,7 +136,7 @@ export function createLLMProvider(
provider === 'codex-subscription'
? { codex: createCodexRuntimeDeps(options?.capturedCodexAttemptContext) }
: provider === 'grok-subscription'
- ? { grok: createGrokRuntimeDeps() }
+ ? { grok: createGrokRuntimeDeps(options?.capturedGrokAttemptContext) }
: undefined
)
} catch (err) {
diff --git a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
index f89ebcd92..9ab941622 100644
--- a/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
+++ b/mcp-host/src/pluginWorkloadSdk/promptBridge/llmBridge.ts
@@ -3,6 +3,7 @@ import { type ChatMessage, FinishReason } from '../../core/types'
import { type SingleTurnProvider, createLLMProvider } from '../../llm'
import type { CodexAttemptContext } from '../../llm/codexSubscription'
import { type ClassifiedLike, type FailoverClass, classifyFailoverClass } from '../../llm/failover'
+import type { GrokAttemptContext } from '../../llm/grokSubscription'
import { descriptorFor, isLlmProvider } from '../../llm/registryCore'
import { CircuitBreaker } from '../domain/circuitBreaker'
import { PluginWorkloadError, type PluginWorkloadProviderAttemptContext } from '../domain/errors'
@@ -142,11 +143,14 @@ function remainingTimeoutMs(deadlineAt: number): number {
return deadlineAt - Date.now()
}
-function captureSdkOnlyCodexAttemptContext(
+function captureSdkOnlyBrokerAttemptContext(
request: LlmBridgeRequest,
target: PromptBridgeTarget,
ticket: { providerAttemptId?: string; providerAttemptIndex?: number }
-): CodexAttemptContext | null {
+):
+ | { capturedCodexAttemptContext: CodexAttemptContext }
+ | { capturedGrokAttemptContext: GrokAttemptContext }
+ | null {
const grok = target.provider === 'grok-subscription'
const binding = grok ? readSdkOnlyGrokBinding() : readSdkOnlyCodexBinding()
const hashOk = grok
@@ -161,7 +165,7 @@ function captureSdkOnlyCodexAttemptContext(
) {
return null
}
- return {
+ const captured = {
invocationId: request.invocationId,
attemptGeneration: request.attemptGeneration,
providerAttemptIndex: ticket.providerAttemptIndex,
@@ -173,6 +177,7 @@ function captureSdkOnlyCodexAttemptContext(
...(request.recipeNamespace ? { recipeNamespace: request.recipeNamespace } : {}),
...(request.recipeName ? { recipeName: request.recipeName } : {}),
}
+ return grok ? { capturedGrokAttemptContext: captured } : { capturedCodexAttemptContext: captured }
}
function providerOutcomeUnknownError(
@@ -639,7 +644,7 @@ export class LlmBridge {
return { kind: 'error', error, terminal: !eligible || index === request.targets.length - 1 }
}
- const captured = captureSdkOnlyCodexAttemptContext(request, authorized.target, ticket)
+ const captured = captureSdkOnlyBrokerAttemptContext(request, authorized.target, ticket)
if (!captured) {
if (ticket.providerAttemptId && ticket.providerAttemptIndex !== undefined) {
await reportProviderAttemptBestEffort(request.providerAttemptReporter, {
@@ -774,7 +779,9 @@ export class LlmBridge {
credential: BrokeredCredential,
request: LlmBridgeRequest,
breaker: CircuitBreaker,
- capturedCodexAttemptContext?: CodexAttemptContext
+ captured?:
+ | { capturedCodexAttemptContext: CodexAttemptContext }
+ | { capturedGrokAttemptContext: GrokAttemptContext }
): Promise<
Pick<
LlmBridgeResult,
@@ -805,7 +812,7 @@ export class LlmBridge {
provider: providerId,
name: credential.target.model,
},
- capturedCodexAttemptContext ? { capturedCodexAttemptContext } : undefined
+ captured
)
if (!provider) {
throw new PluginWorkloadError(
diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts b/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
index 957874967..2bd62f9e2 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/index.test.ts
@@ -129,7 +129,7 @@ describe('PluginWorkloadSdk server usage attribution', () => {
expect(JSON.stringify(event)).not.toContain('secret-')
})
- it('does not emit reporter usage for Codex subscription', () => {
+ it('does not emit reporter usage for oauth-broker subscriptions', () => {
expect(
buildPromptBridgeUsageEvent({
binding: {
@@ -171,5 +171,21 @@ describe('PluginWorkloadSdk server usage attribution', () => {
},
})
).toBeNull()
+ expect(
+ buildPromptBridgeUsageEvent({
+ binding: {
+ hostRef: 'plugin-workload-sdk/sandbox-app',
+ recipeNamespace: 'sandbox-apps',
+ recipeName: 'prompt-notify',
+ },
+ runtimeMode: 'sdk-only',
+ invocationId: '00000000-0000-4000-8000-000000000100',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ inputTokens: 10,
+ outputTokens: 5,
+ callerRef: 'backend-worker',
+ })
+ ).toBeNull()
})
})
diff --git a/mcp-host/src/pluginWorkloadSdk/server/index.ts b/mcp-host/src/pluginWorkloadSdk/server/index.ts
index e18cfd3a8..16a6b71ae 100644
--- a/mcp-host/src/pluginWorkloadSdk/server/index.ts
+++ b/mcp-host/src/pluginWorkloadSdk/server/index.ts
@@ -64,7 +64,9 @@ export function buildPromptBridgeUsageEvent(input: {
}
metadata?: Record<string, unknown>
}): LlmUsageEvent | null {
- if (input.provider === 'codex-subscription') return null
+ if (input.provider === 'codex-subscription' || input.provider === 'grok-subscription') {
+ return null
+ }
// Explicit runtime mode is authoritative for recipe-bound hosts. The
// namespace fallback remains only for older non-recipe callers that do not
// yet inject the mode into their pod.
diff --git a/mcp-host/src/workflow/workflowService.ts b/mcp-host/src/workflow/workflowService.ts
index 5b48bf890..f232f016d 100644
--- a/mcp-host/src/workflow/workflowService.ts
+++ b/mcp-host/src/workflow/workflowService.ts
@@ -626,7 +626,9 @@ export class WorkflowService {
input_tokens: usage?.input_tokens ?? 0,
output_tokens: usage?.output_tokens ?? 0,
}
- if (served.provider === 'codex-subscription') return
+ if (served.provider === 'codex-subscription' || served.provider === 'grok-subscription') {
+ return
+ }
this.usageReporter.enqueue(event)
}
diff --git a/scripts/tests/test-dockerfile-local-packages.sh b/scripts/tests/test-dockerfile-local-packages.sh
index 4cb097107..393366895 100755
--- a/scripts/tests/test-dockerfile-local-packages.sh
+++ b/scripts/tests/test-dockerfile-local-packages.sh
@@ -183,22 +183,31 @@ assert_dockerignore_mutations_rejected() {
# Direct consumers. The first four are Node services; profile-ui and
# control-ui are Next.js consumers and therefore also require materialization.
assert_copy_before_every_ci control-api/Dockerfile \
- display-field image-policy llm-providers workflow-recipe-capability-policy workflow-runtime-core
+ display-field grok-provider-attempt-contract image-policy llm-provider-attempt-contract \
+ llm-providers workflow-recipe-capability-policy workflow-runtime-core
assert_copy_before_every_ci control-ui/Dockerfile \
display-field frontend-components gfs-interaction-policy llm-providers workflow-recipe-capability-policy
assert_copy_before_every_ci profile-ui/Dockerfile desktop-app-links frontend-components
assert_copy_before_every_ci host-context-controller/Dockerfile \
image-policy llm-providers network-policy-core workflow-recipe-capability-policy
-assert_copy_before_every_ci mcp-host/Dockerfile llm-providers
-assert_copy_before_every_ci mcp-host/Dockerfile.desktop llm-providers
-assert_copy_before_every_ci mcp-host/Dockerfile.full llm-providers
-assert_copy_before_every_ci mcp-host/Dockerfile.slim llm-providers
+assert_copy_before_every_ci mcp-host/Dockerfile \
+ grok-provider-attempt-contract llm-provider-attempt-contract llm-providers
+assert_copy_before_every_ci mcp-host/Dockerfile.desktop \
+ grok-provider-attempt-contract llm-provider-attempt-contract llm-providers
+assert_copy_before_every_ci mcp-host/Dockerfile.full \
+ grok-provider-attempt-contract llm-provider-attempt-contract llm-providers
+assert_copy_before_every_ci mcp-host/Dockerfile.slim \
+ grok-provider-attempt-contract llm-provider-attempt-contract llm-providers
# workflow-runtime-core is built in a separate stage before workflow-recipes;
# these are the packages needed by that stage, while the application install
# also needs the recipe and image policy packages in its final stage.
-assert_copy_before_every_ci workflow-recipes/Dockerfile llm-providers network-policy-core workflow-runtime-core
-assert_copy_before_every_ci workflow-recipes/Dockerfile.coordinator llm-providers network-policy-core workflow-runtime-core
+assert_copy_before_every_ci workflow-recipes/Dockerfile \
+ grok-provider-attempt-contract llm-provider-attempt-contract llm-providers \
+ network-policy-core workflow-runtime-core
+assert_copy_before_every_ci workflow-recipes/Dockerfile.coordinator \
+ grok-provider-attempt-contract llm-provider-attempt-contract llm-providers \
+ network-policy-core workflow-runtime-core
assert_copy_before_last_ci workflow-recipes/Dockerfile workflow-recipe-capability-policy
assert_copy_before_last_ci workflow-recipes/Dockerfile image-policy
assert_copy_before_last_ci workflow-recipes/Dockerfile.coordinator workflow-recipe-capability-policy
@@ -213,7 +222,11 @@ assert_materialized profile-ui/Dockerfile desktop-app-links
assert_materialized profile-ui/Dockerfile frontend-components
assert_dockerignore_allows control-api/Dockerfile.dockerignore display-field
+assert_dockerignore_allows control-api/Dockerfile.dockerignore grok-provider-attempt-contract
+assert_dockerignore_allows control-api/Dockerfile.dockerignore llm-provider-attempt-contract
assert_dockerignore_allows control-api/Dockerfile.dockerignore llm-providers
+assert_dockerignore_allows workflow-recipes/Dockerfile.dockerignore grok-provider-attempt-contract
+assert_dockerignore_allows workflow-recipes/Dockerfile.coordinator.dockerignore grok-provider-attempt-contract
assert_dockerignore_allows control-ui/Dockerfile.dockerignore display-field
assert_dockerignore_allows control-ui/Dockerfile.dockerignore gfs-interaction-policy
assert_dockerignore_allows control-ui/Dockerfile.dockerignore llm-providers
diff --git a/scripts/tests/test-grok-subscription-t0.sh b/scripts/tests/test-grok-subscription-t0.sh
index 6f5c0fe65..4fa0d3721 100755
--- a/scripts/tests/test-grok-subscription-t0.sh
+++ b/scripts/tests/test-grok-subscription-t0.sh
@@ -53,6 +53,16 @@ assert_executed_counts() {
rm -f "$normalized"
return 1
fi
+ if grep -Eq '(Test Files|Tests).*[1-9][0-9]* todo' "$normalized"; then
+ fail "${name}: Vitest reported todo tests"
+ rm -f "$normalized"
+ return 1
+ fi
+ if grep -Eq '^(#|ℹ) todo[[:space:]]+[1-9]' "$normalized"; then
+ fail "${name}: node:test reported todo tests"
+ rm -f "$normalized"
+ return 1
+ fi
if grep -Eiq 'no test files|no tests found' "$normalized"; then
fail "${name}: reporter found no tests"
rm -f "$normalized"
@@ -85,6 +95,8 @@ require_file packages/grok-provider-attempt-contract/index.test.cjs
require_file grok-llm-proxy/test/contractFreeze.test.ts
require_file grok-llm-proxy/test/originPolicy.test.ts
require_file control-api/test/services.grokSubscriptionOAuth.test.ts
+require_file control-api/test/services.grokProviderAttemptTicket.test.ts
+require_file control-api/test/services.grokSubscriptionConnection.realPostgres.integration.test.ts
require_file control-api/test/services.grokProviderAttemptRedemption.test.ts
require_file control-api/test/db.grokSubscriptionMigration.test.ts
require_file control-api/test/services.llmProviderAttemptAuthorizer.grok.test.ts
@@ -140,8 +152,11 @@ run_group "grok-catalog-projection" \
run_group "grok-llm-proxy freeze+origin" \
bash -lc "cd '${ROOT}/grok-llm-proxy' && npx vitest run test/contractFreeze.test.ts test/originPolicy.test.ts test/grokTransport.conformance.test.ts --no-file-parallelism"
+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.llmProviderAttemptAuthorizer.grok.test.ts test/subscriptionGrantIdentity.test.ts test/routes.adminPluginWorkloadSdk.test.ts test/services.recipeCodexGrantIdentity.test.ts test/hostSpecValidation.codexSubscription.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.codexSubscription.test.ts test/crd.llmProviderEnums.test.ts test/routes.mcp-host.plugin-workload-sdk.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.codexPolicy.test.ts src/reconciler/pluginWorkloadSdkValidator.test.ts tests/unit/workflow/modelConfigHandler.pluginSdkBroker.test.ts --no-file-parallelism"
@@ -159,7 +174,7 @@ else
pass "grok-llm-proxy deploy contract"
fi
-if [[ "$GROUPS_RUN" -lt 8 ]]; then
+if [[ "$GROUPS_RUN" -lt 9 ]]; then
fail "T0 ran too few groups (${GROUPS_RUN})"
fi
diff --git a/workflow-recipes/Dockerfile b/workflow-recipes/Dockerfile
index f8cb20a72..94da471ad 100644
--- a/workflow-recipes/Dockerfile
+++ b/workflow-recipes/Dockerfile
@@ -8,6 +8,7 @@ WORKDIR /app
# workflow-recipes consumes it directly.
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY packages/network-policy-core ./packages/network-policy-core
COPY packages/workflow-runtime-core/package.json packages/workflow-runtime-core/package-lock.json ./packages/workflow-runtime-core/
@@ -33,6 +34,7 @@ WORKDIR /app
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY packages/network-policy-core ./packages/network-policy-core
COPY packages/workflow-runtime-core/package.json packages/workflow-runtime-core/package-lock.json ./packages/workflow-runtime-core/
diff --git a/workflow-recipes/Dockerfile.coordinator b/workflow-recipes/Dockerfile.coordinator
index b8b42813b..db1ef0cdd 100644
--- a/workflow-recipes/Dockerfile.coordinator
+++ b/workflow-recipes/Dockerfile.coordinator
@@ -7,6 +7,7 @@ WORKDIR /app
# depends on it (file:../llm-providers) and workflow-recipes consumes it directly.
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
# Issue #299: workflow-recipes also imports the shared egress accumulator
# package through a local file dependency, so it must be present before npm ci.
@@ -34,6 +35,7 @@ WORKDIR /app
COPY packages/llm-providers ./packages/llm-providers
COPY packages/llm-provider-attempt-contract ./packages/llm-provider-attempt-contract
+COPY packages/grok-provider-attempt-contract ./packages/grok-provider-attempt-contract
COPY packages/codex-catalog-projection ./packages/codex-catalog-projection
COPY packages/network-policy-core ./packages/network-policy-core
COPY packages/workflow-runtime-core/package.json packages/workflow-runtime-core/package-lock.json ./packages/workflow-runtime-core/
diff --git a/workflow-recipes/Dockerfile.coordinator.dockerignore b/workflow-recipes/Dockerfile.coordinator.dockerignore
index bca04b97f..3a979cb89 100644
--- a/workflow-recipes/Dockerfile.coordinator.dockerignore
+++ b/workflow-recipes/Dockerfile.coordinator.dockerignore
@@ -2,6 +2,8 @@
!packages/
!packages/llm-provider-attempt-contract/
!packages/llm-provider-attempt-contract/**
+!packages/grok-provider-attempt-contract/
+!packages/grok-provider-attempt-contract/**
!packages/codex-catalog-projection/
!packages/codex-catalog-projection/**
!packages/network-policy-core/
diff --git a/workflow-recipes/Dockerfile.dockerignore b/workflow-recipes/Dockerfile.dockerignore
index bca04b97f..3a979cb89 100644
--- a/workflow-recipes/Dockerfile.dockerignore
+++ b/workflow-recipes/Dockerfile.dockerignore
@@ -2,6 +2,8 @@
!packages/
!packages/llm-provider-attempt-contract/
!packages/llm-provider-attempt-contract/**
+!packages/grok-provider-attempt-contract/
+!packages/grok-provider-attempt-contract/**
!packages/codex-catalog-projection/
!packages/codex-catalog-projection/**
!packages/network-policy-core/
diff --git a/workflow-recipes/package-lock.json b/workflow-recipes/package-lock.json
index 689805fa3..131e1b300 100644
--- a/workflow-recipes/package-lock.json
+++ b/workflow-recipes/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.356",
+ "version": "0.1.357",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "workload-recipes-controller",
- "version": "0.1.356",
+ "version": "0.1.357",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@aws-sdk/client-s3": "^3.1009.0",
diff --git a/workflow-recipes/package.json b/workflow-recipes/package.json
index 92d9dce1d..a8106ffd3 100644
--- a/workflow-recipes/package.json
+++ b/workflow-recipes/package.json
@@ -1,6 +1,6 @@
{
"name": "workload-recipes-controller",
- "version": "0.1.356",
+ "version": "0.1.357",
"description": "Workload Recipes Controller (WRC) - WorkloadRecipe lifecycle management and MCP server interface",
"main": "dist/main.js",
"engines": {
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts
index 096d446fe..d569e2c91 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.codexPolicy.test.ts
@@ -7,7 +7,11 @@ import {
PluginWorkloadSdkProvisioner,
type PluginWorkloadSdkProvisionerDeps,
} from './pluginWorkloadSdkProvisioner'
-import { buildMcpHostPod, pluginWorkloadSdkRuntimeContractHash } from './podFactory'
+import {
+ buildMcpHostPod,
+ pluginWorkloadSdkRuntimeContractHash,
+ recipeDeclaresGrokSubscription,
+} from './podFactory'
import type { WorkflowRuntimePlan } from './runtimePlan'
import type { PluginWorkloadSdkCodexBindingProof } from './sdkOnlyCodexBinding'
import type { WorkflowConfig } from './types'
@@ -160,6 +164,9 @@ function desiredRuntimeContractHash(): string {
mountWorkflowOutput: false,
pluginWorkloadSdkCapabilities: ['promptBridge'],
pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ grokSubscriptionEnabled: TEST_CONFIG.grokSubscriptionEnabled === true,
+ recipeAgentProvider: CODEX_SPEC.agent.provider,
+ recipeDeclaresGrok: recipeDeclaresGrokSubscription(CODEX_SPEC),
}
)
)
@@ -180,6 +187,9 @@ function grokRuntimeContractHash(): string {
mountWorkflowOutput: false,
pluginWorkloadSdkCapabilities: ['promptBridge'],
pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ grokSubscriptionEnabled: TEST_CONFIG.grokSubscriptionEnabled === true,
+ recipeAgentProvider: GROK_SPEC.agent.provider,
+ recipeDeclaresGrok: recipeDeclaresGrokSubscription(GROK_SPEC),
}
)
)
@@ -461,6 +471,59 @@ describe('eager Codex policy gate', () => {
})
describe('eager Grok policy gate', () => {
+ it('injects Grok proxy env when the WRC flag is on and the recipe declares grok-subscription', () => {
+ const pod = buildMcpHostPod(
+ GROK_RECIPE,
+ GROK_SPEC.agent,
+ TEST_CONFIG,
+ GROK_RECIPE,
+ SANDBOX_NS,
+ undefined,
+ undefined,
+ undefined,
+ {
+ mountWorkflowOutput: false,
+ pluginWorkloadSdkCapabilities: ['promptBridge'],
+ pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ grokSubscriptionEnabled: true,
+ recipeAgentProvider: GROK_SPEC.agent.provider,
+ recipeDeclaresGrok: recipeDeclaresGrokSubscription(GROK_SPEC),
+ }
+ )
+ const env = pod.spec?.containers?.[0].env ?? []
+ expect(env).toContainEqual({ name: 'MCP_HOST_GROK_SUBSCRIPTION_ENABLED', value: 'true' })
+ expect(env).toContainEqual({
+ name: 'GROK_LLM_PROXY_RUNTIME_URL',
+ value: 'http://grok-llm-proxy.control-plane.svc.cluster.local:8080',
+ })
+ })
+
+ it('omits Grok proxy env when the WRC flag is off', () => {
+ const pod = buildMcpHostPod(
+ GROK_RECIPE,
+ GROK_SPEC.agent,
+ TEST_CONFIG,
+ GROK_RECIPE,
+ SANDBOX_NS,
+ undefined,
+ undefined,
+ undefined,
+ {
+ mountWorkflowOutput: false,
+ pluginWorkloadSdkCapabilities: ['promptBridge'],
+ pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ grokSubscriptionEnabled: false,
+ recipeAgentProvider: GROK_SPEC.agent.provider,
+ recipeDeclaresGrok: recipeDeclaresGrokSubscription(GROK_SPEC),
+ }
+ )
+ const env = pod.spec?.containers?.[0].env ?? []
+ expect(env).not.toContainEqual({
+ name: 'MCP_HOST_GROK_SUBSCRIPTION_ENABLED',
+ value: 'true',
+ })
+ })
+
it('accepts a Grok hash on subscriptionBinding and reports ready', async () => {
const harness = makeHarness(readyGrokBootstrapBody(GROK_MINTED), GROK_SPEC)
expect(await harness.reconcile({ grokBinding: GROK_MINTED })).toBe('ready')
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
index 2f123606f..2848c280d 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.imageDrift.test.ts
@@ -3,7 +3,11 @@ import type { WorkflowRecipeSpec } from '../types'
import type { CodexRecipeVerdict } from './codexRecipeVerdict'
import { PluginWorkloadSdkProvisioner } from './pluginWorkloadSdkProvisioner'
import type { PluginWorkloadSdkProvisionerDeps } from './pluginWorkloadSdkProvisioner'
-import { buildMcpHostPod, pluginWorkloadSdkRuntimeContractHash } from './podFactory'
+import {
+ buildMcpHostPod,
+ pluginWorkloadSdkRuntimeContractHash,
+ recipeDeclaresGrokSubscription,
+} from './podFactory'
import type { WorkflowRuntimePlan } from './runtimePlan'
import type { WorkflowConfig } from './types'
@@ -131,6 +135,9 @@ function desiredRuntimeContractHash(): string {
mountWorkflowOutput: false,
pluginWorkloadSdkCapabilities: ['promptBridge'],
pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ grokSubscriptionEnabled: TEST_CONFIG.grokSubscriptionEnabled === true,
+ recipeAgentProvider: SPEC.agent.provider,
+ recipeDeclaresGrok: recipeDeclaresGrokSubscription(SPEC),
}
)
return pluginWorkloadSdkRuntimeContractHash(desiredPod)
diff --git a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
index 5bdd0b07c..a6e41a93d 100644
--- a/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
+++ b/workflow-recipes/src/workflow/pluginWorkloadSdkProvisioner.ts
@@ -25,6 +25,7 @@ import {
buildMcpHostPod,
declaredPluginWorkloadSdkCapabilities,
pluginWorkloadSdkRuntimeContractHash,
+ recipeDeclaresGrokSubscription,
} from './podFactory'
import {
PLUGIN_WORKLOAD_SDK_LEGACY_TOKEN_DATA_KEY,
@@ -278,6 +279,9 @@ export class PluginWorkloadSdkProvisioner {
mountWorkflowOutput: false,
pluginWorkloadSdkCapabilities: capabilities,
pluginWorkloadSdkRuntimeMode: 'sdk-only',
+ grokSubscriptionEnabled: this.deps.config.grokSubscriptionEnabled === true,
+ recipeAgentProvider: mcpHostAgent?.provider,
+ recipeDeclaresGrok: recipeDeclaresGrokSubscription(spec),
...(tokenRefresh?.tokenGeneration
? { runtimeTokenGeneration: tokenRefresh.tokenGeneration }
: {}),
diff --git a/workflow-recipes/src/workflow/podFactory.ts b/workflow-recipes/src/workflow/podFactory.ts
index 1a0bcab86..706b9bbe5 100644
--- a/workflow-recipes/src/workflow/podFactory.ts
+++ b/workflow-recipes/src/workflow/podFactory.ts
@@ -605,6 +605,15 @@ export interface McpHostPodOptions {
runtimeTokenGeneration?: string
grokSubscriptionEnabled?: boolean
recipeAgentProvider?: string
+ recipeDeclaresGrok?: boolean
+}
+
+export function recipeDeclaresGrokSubscription(spec: {
+ agent?: { provider?: string }
+ steps?: Array<{ agent?: { provider?: string } }>
+}): boolean {
+ if (spec.agent?.provider === 'grok-subscription') return true
+ return (spec.steps ?? []).some(step => step?.agent?.provider === 'grok-subscription')
}
export function buildMcpHostPod(
@@ -759,7 +768,8 @@ export function buildMcpHostPod(
value: 'http://codex-llm-proxy.control-plane.svc.cluster.local:8080',
},
...(options.grokSubscriptionEnabled &&
- options.recipeAgentProvider === 'grok-subscription'
+ (options.recipeDeclaresGrok === true ||
+ options.recipeAgentProvider === 'grok-subscription')
? [
{ name: 'MCP_HOST_GROK_SUBSCRIPTION_ENABLED', value: 'true' },
{
diff --git a/workflow-recipes/src/workflow/workflowReconciler.ts b/workflow-recipes/src/workflow/workflowReconciler.ts
index dabca33c8..c48eab8a9 100644
--- a/workflow-recipes/src/workflow/workflowReconciler.ts
+++ b/workflow-recipes/src/workflow/workflowReconciler.ts
@@ -107,6 +107,7 @@ import {
buildWorkflowOutputPreparePod,
buildWorkflowOutputPreparePodName,
declaredPluginWorkloadSdkCapabilities,
+ recipeDeclaresGrokSubscription,
workflowOutputLabelValue,
} from './podFactory'
import {
@@ -2223,6 +2224,7 @@ export class WorkflowReconciler {
: [],
grokSubscriptionEnabled: this.deps.config.grokSubscriptionEnabled === true,
recipeAgentProvider: spec.agent?.provider,
+ recipeDeclaresGrok: recipeDeclaresGrokSubscription(spec),
}
)
await this.createIfNotExists(
diff --git a/workflow-recipes/tests/unit/workflow/podFactory.test.ts b/workflow-recipes/tests/unit/workflow/podFactory.test.ts
index c94b8ffbc..309857704 100644
--- a/workflow-recipes/tests/unit/workflow/podFactory.test.ts
+++ b/workflow-recipes/tests/unit/workflow/podFactory.test.ts
@@ -432,6 +432,32 @@ describe('Pod Factory', () => {
value: 'http://wrc:8082',
})
})
+
+ it('injects Grok proxy env when the flag is on and the recipe declares grok-subscription', () => {
+ const pod = buildMcpHostPod(
+ 'my-wf',
+ { provider: 'grok-subscription', model: 'grok-4.6' },
+ config,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ {
+ mountWorkflowOutput: false,
+ grokSubscriptionEnabled: true,
+ recipeDeclaresGrok: true,
+ }
+ )
+ expect(pod.spec?.containers?.[0].env).toContainEqual({
+ name: 'MCP_HOST_GROK_SUBSCRIPTION_ENABLED',
+ value: 'true',
+ })
+ expect(pod.spec?.containers?.[0].env).toContainEqual({
+ name: 'GROK_LLM_PROXY_RUNTIME_URL',
+ value: 'http://grok-llm-proxy.control-plane.svc.cluster.local:8080',
+ })
+ })
})
describe('buildMcpHostPod', () => {