Skip to content

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

TypeScript

feat(grok): add grok-subscription provider and attempt contract

Jose Gabriel Ramirez Encinas4391e52c9992
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.yml
index c81f91d0b..317697c8a 100644
--- a/.github/workflows/ci-public.yml
+++ b/.github/workflows/ci-public.yml
@@ -70,6 +70,7 @@ jobs:
- packages/network-policy-core
- packages/llm-provider-attempt-contract
- packages/llm-providers
+ - packages/grok-provider-attempt-contract
- packages/codex-catalog-projection
- codex-llm-proxy
diff --git a/Makefile b/Makefile
index 9343c6691..ab71b9772 100644
--- a/Makefile
+++ b/Makefile
@@ -51,7 +51,8 @@ SERVICES := \
packages/workflow-runtime-core \
packages/workflow-sdk \
packages/llm-provider-attempt-contract \
- packages/llm-providers
+ packages/llm-providers \
+ packages/grok-provider-attempt-contract
# Services that have unit tests
TEST_SERVICES := \
@@ -76,7 +77,8 @@ TEST_SERVICES := \
packages/workflow-sdk \
packages/network-policy-core \
packages/llm-provider-attempt-contract \
- packages/llm-providers
+ packages/llm-providers \
+ packages/grok-provider-attempt-contract
# ── Optional private infra (gcp-*, promotion) ──────────────────────────────
-include Makefile.infra
diff --git a/charts/clerum-crds/crds/host.yaml b/charts/clerum-crds/crds/host.yaml
index c8f2e298f..4af629905 100644
--- a/charts/clerum-crds/crds/host.yaml
+++ b/charts/clerum-crds/crds/host.yaml
@@ -28,10 +28,12 @@ spec:
- host
- contextRef
x-kubernetes-validations:
- - rule: "(has(self.model) && self.model.provider == 'codex-subscription' && (!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, f.provider != 'codex-subscription'))) || (has(self.secretRef) && size(self.secretRef) > 0)"
- message: spec.secretRef is required unless every LLM target is the Codex subscription broker
- - rule: "!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, f.provider == 'codex-subscription' && has(f.credentialSlot))"
+ - rule: "(has(self.model) && self.model.provider == 'codex-subscription' && (!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, f.provider != 'codex-subscription'))) || (has(self.model) && self.model.provider == 'grok-subscription' && (!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, f.provider != 'grok-subscription'))) || (has(self.secretRef) && size(self.secretRef) > 0)"
+ message: spec.secretRef is required unless every LLM target is the same oauth-broker provider
+ - rule: "!has(self.llmPolicy) || !has(self.llmPolicy.fallbacks) || !self.llmPolicy.fallbacks.exists(f, (f.provider == 'codex-subscription' || f.provider == 'grok-subscription') && has(f.credentialSlot))"
message: credentialSlot is not supported for oauth-broker providers
+ - rule: "!(((has(self.model) && self.model.provider == 'codex-subscription') || (has(self.llmPolicy) && has(self.llmPolicy.fallbacks) && self.llmPolicy.fallbacks.exists(f, f.provider == 'codex-subscription')) || (has(self.allowedModels) && self.allowedModels.exists(m, m.provider == 'codex-subscription'))) && ((has(self.model) && self.model.provider == 'grok-subscription') || (has(self.llmPolicy) && has(self.llmPolicy.fallbacks) && self.llmPolicy.fallbacks.exists(f, f.provider == 'grok-subscription')) || (has(self.allowedModels) && self.allowedModels.exists(m, m.provider == 'grok-subscription'))))"
+ message: a Host may declare at most one oauth-broker provider
properties:
host:
type: string
@@ -84,6 +86,7 @@ spec:
- minimax
- azure
- codex-subscription
+ - grok-subscription
description: LLM provider to use.
name:
type: string
@@ -100,6 +103,7 @@ spec:
fields, so this property must be applied before control-api
or Control UI persist spec.model.connectionRef.
allowedModels:
+ maxItems: 32
# Per-host model allowlist subset (spec v2 Topic 3a). OPTIONAL,
# ADDITIVE: when absent or empty, the host offers the FULL global
# operator allowlist for its provider(s) — existing hosts are
@@ -177,6 +181,7 @@ spec:
fallbacks:
type: array
minItems: 1
+ maxItems: 8
description: >-
Ordered fallback list, tried in order. The engine advances
to the next entry when the current one also fails.
@@ -212,6 +217,7 @@ spec:
- minimax
- azure
- codex-subscription
+ - grok-subscription
description: >-
Fallback LLM provider. Same enum as spec.model.provider.
model:
diff --git a/charts/clerum-crds/crds/workflowrecipe.yaml b/charts/clerum-crds/crds/workflowrecipe.yaml
index 082826e5f..af80735a9 100644
--- a/charts/clerum-crds/crds/workflowrecipe.yaml
+++ b/charts/clerum-crds/crds/workflowrecipe.yaml
@@ -273,7 +273,7 @@ spec:
provider/model bootstrap binding for a stepless
spec.pluginWorkloadSdk.promptBridge runtime.
x-kubernetes-validations:
- - rule: "!has(self.provider) || self.provider != 'codex-subscription' || !has(self.secretRef)"
+ - rule: "!has(self.provider) || (self.provider != 'codex-subscription' && self.provider != 'grok-subscription') || !has(self.secretRef)"
message: spec.agent.secretRef is not allowed for oauth-broker providers
properties:
model:
@@ -287,7 +287,7 @@ spec:
# transport is mono-credential and cannot deliver Bedrock's key
# pair nor azure's required non-secret AZURE_OPENAI_ENDPOINT —
# fail at admission, not mid-workflow (see workflowService).
- enum: [openai, claude, zai, bailian, vertex, openrouter, gemini, deepseek, groq, together, fireworks, mistral, xai, cerebras, deepinfra, perplexity, moonshot, nebius, novita, minimax, codex-subscription]
+ enum: [openai, claude, zai, bailian, vertex, openrouter, gemini, deepseek, groq, together, fireworks, mistral, xai, cerebras, deepinfra, perplexity, moonshot, nebius, novita, minimax, codex-subscription, grok-subscription]
description: LLM provider.
secretRef:
type: object
@@ -571,7 +571,7 @@ spec:
# bedrock AND azure intentionally absent (mono-credential
# WRC transport; see the comment on the first llm provider
# enum above).
- enum: [openai, claude, zai, bailian, vertex, openrouter, gemini, deepseek, groq, together, fireworks, mistral, xai, cerebras, deepinfra, perplexity, moonshot, nebius, novita, minimax, codex-subscription]
+ enum: [openai, claude, zai, bailian, vertex, openrouter, gemini, deepseek, groq, together, fireworks, mistral, xai, cerebras, deepinfra, perplexity, moonshot, nebius, novita, minimax, codex-subscription, grok-subscription]
soul:
type: string
description: Per-step SOUL content override.
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 997496ac6..4d871b0c3 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.554",
+ "version": "0.1.555",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.554",
+ "version": "0.1.555",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 4a60ece3d..2dcf0f57a 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.554",
+ "version": "0.1.555",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/utils/auth/mcpHostJwtToken.ts b/control-api/src/utils/auth/mcpHostJwtToken.ts
index c461b401c..801613dc7 100644
--- a/control-api/src/utils/auth/mcpHostJwtToken.ts
+++ b/control-api/src/utils/auth/mcpHostJwtToken.ts
@@ -181,6 +181,7 @@ export const ALL_MCP_HOST_CONTROL_SCOPES = [
// Derive-only Codex execution. HCC/WRC may request this after projecting an
// eligible broker target. Never add it to user-declarable Host/Recipe CRD fields.
'llm:codex:execute',
+ 'llm:grok:execute',
] as const
export type McpHostControlScope = (typeof ALL_MCP_HOST_CONTROL_SCOPES)[number]
diff --git a/control-api/test/crd.llmProviderEnums.test.ts b/control-api/test/crd.llmProviderEnums.test.ts
index 23b883ef9..e3031026f 100644
--- a/control-api/test/crd.llmProviderEnums.test.ts
+++ b/control-api/test/crd.llmProviderEnums.test.ts
@@ -62,7 +62,7 @@ describe('LLM provider CRD enums', () => {
// spec.model.provider + spec.llmPolicy.fallbacks[].provider
expect(enums).toHaveLength(2)
for (const e of enums) {
- for (const id of [...NEW_SINGLE_KEY, 'azure', 'codex-subscription']) {
+ for (const id of [...NEW_SINGLE_KEY, 'azure', 'codex-subscription', 'grok-subscription']) {
expect(e).toContain(id)
}
// additive: original providers preserved
@@ -76,7 +76,7 @@ describe('LLM provider CRD enums', () => {
// the two WRC provider enums (model.provider + a second one ~line 543)
expect(enums).toHaveLength(2)
for (const e of enums) {
- for (const id of [...NEW_SINGLE_KEY, 'codex-subscription']) {
+ for (const id of [...NEW_SINGLE_KEY, 'codex-subscription', 'grok-subscription']) {
expect(e).toContain(id)
}
// azure and bedrock must fail at admission (mono-credential WRC transport).
diff --git a/docs/architecture/grok-subscription-transport-contract.md b/docs/architecture/grok-subscription-transport-contract.md
new file mode 100644
index 000000000..7e0587b17
--- /dev/null
+++ b/docs/architecture/grok-subscription-transport-contract.md
@@ -0,0 +1,42 @@
+# Grok subscription transport contract
+
+Starting freeze: `grok-subscription-transport.v1`.
+
+This is the Phase 0 architecture freeze for provider `grok-subscription`.
+Catalog origin and CLI identity headers remain probe-gated (see
+`docs/superpowers/specs/2026-09-15-llm-coding-plan-subscriptions-design.md`
+§9 and R2-M3). Live SuperGrok confirm may tighten, never widen, this allowlist.
+
+## Ownership
+
+- Control API is the only OAuth custodian.
+- `mcp-host` authorizes each physical attempt and streams to `grok-llm-proxy`.
+- `grok-llm-proxy` redeems a single-use ticket, holds the access token in
+ operation memory only, and talks to the frozen HTTPS origins below.
+- The LLM stream never transits Control API or its gateways.
+- Traffic never enters `codex-llm-proxy` or `https://api.x.ai`.
+
+## Origins
+
+Exact HTTPS origins (no caller-supplied URL):
+
+- Device authorization: `https://auth.x.ai/oauth2/device/code`
+- Token: `https://auth.x.ai/oauth2/token`
+- Completions: `https://cli-chat-proxy.grok.com/v1/responses`
+- Catalog (starting candidate): `https://cli-chat-proxy.grok.com/v1/models`
+
+Forbidden: `https://api.x.ai`, HTTP, loopback, link-local, metadata.
+
+Redirects: at most one, HTTPS, same origin and same path and same query.
+OAuth `device/code` and `token` use `redirect: 'manual'`; any 3xx is an error.
+
+## Ticket
+
+- `typ`: `grok-execution-ticket`
+- `aud`: `grok-llm-proxy`
+- Admin permit `typ`/`aud`: `grok-admin-permit` / `grok-llm-proxy-admin`
+
+## Limits
+
+Owned by `@clerum/grok-provider-attempt-contract`. Independent of Codex
+`LIMITS` (`maxToolCalls` is 64, not 32).
diff --git a/packages/grok-provider-attempt-contract/index.cjs b/packages/grok-provider-attempt-contract/index.cjs
new file mode 100644
index 000000000..1a794d6ea
--- /dev/null
+++ b/packages/grok-provider-attempt-contract/index.cjs
@@ -0,0 +1,542 @@
+'use strict'
+
+/**
+ * @clerum/grok-provider-attempt-contract — see index.d.ts.
+ * Pure module: no network, credentials, or Kubernetes.
+ * Does not import the Codex attempt-contract LIMITS.
+ */
+
+const { createHash } = require('node:crypto')
+
+const SCHEMA_VERSION = 'grok-completion-request.v1'
+const RECEIPT_SCHEMA_VERSION = 'grok-attempt-receipt.v1'
+const PROVIDER_ID = 'grok-subscription'
+const TICKET_TYP = 'grok-execution-ticket'
+const TRANSPORT_PROTOCOL_VERSION = 'grok-subscription-transport.v1'
+const COMPLETIONS_ORIGIN = 'https://cli-chat-proxy.grok.com/v1/responses'
+const CATALOG_ORIGIN = 'https://cli-chat-proxy.grok.com/v1/models'
+
+const LIMITS = Object.freeze({
+ maxRequestBodyBytes: 1048576,
+ maxMessages: 128,
+ maxToolCalls: 64,
+ maxOutputTokens: 16384,
+ maxDeadlineMs: 300000,
+ maxIdLength: 128,
+})
+
+const ID_PATTERN = /^[A-Za-z0-9._:/-]{1,128}$/
+const SHA256_HEX = /^[a-f0-9]{64}$/
+const MESSAGE_ROLES = new Set(['system', 'user', 'assistant', 'tool'])
+const TOOL_CHOICES = new Set(['auto', 'none', 'required'])
+const RECEIPT_OUTCOMES = new Set(['success', 'canceled', 'error', 'unknown'])
+
+const ROOT_KEYS = new Set([
+ 'schemaVersion',
+ 'requestId',
+ 'idempotencyKey',
+ 'provider',
+ 'model',
+ 'messages',
+ 'tools',
+ 'generation',
+ 'deadlineMs',
+ 'transportHints',
+])
+const MESSAGE_KEYS = new Set(['role', 'content', 'name', 'toolCallId', 'toolCalls'])
+const TOOL_CALL_KEYS = new Set(['id', 'name', 'arguments'])
+const TOOL_KEYS = new Set(['name', 'description', 'parameters'])
+const GENERATION_KEYS = new Set(['temperature', 'maxOutputTokens', 'toolChoice'])
+const HINT_KEYS = new Set(['promptCacheKey'])
+const CLAIMS_KEYS = new Set([
+ 'jti',
+ 'typ',
+ 'sub',
+ 'hostRef',
+ 'recipeNamespace',
+ 'recipeName',
+ 'invocationId',
+ 'attemptGeneration',
+ 'providerAttemptId',
+ 'providerAttemptIndex',
+ 'provider',
+ 'model',
+ 'requestHash',
+ 'policyRevision',
+ 'policyHash',
+ 'budgetReservationId',
+ 'connectionRevision',
+ 'connectionId',
+])
+const AUTHORIZE_KEYS = new Set([
+ 'providerAttemptId',
+ 'requestHash',
+ 'executionTicket',
+ 'expiresAt',
+])
+const RECEIPT_KEYS = new Set(['schemaVersion', 'providerAttemptId', 'requestHash', 'outcome', 'usage'])
+const USAGE_KEYS = new Set(['inputTokens', 'outputTokens'])
+
+function fail(code, message) {
+ return { ok: false, code, message }
+}
+
+function ok(value) {
+ return { ok: true, value }
+}
+
+/**
+ * Canonical JSON serialization for deterministic hashing.
+ * Copied to stay compatible with control-api/src/utils/stableStringify.ts.
+ * Validation rejects non-finite numbers before this runs.
+ */
+function stableStringify(value) {
+ if (value === null) return 'null'
+ if (value === undefined) return 'null'
+ const t = typeof value
+ if (t === 'number') {
+ return Number.isFinite(value) ? String(value) : 'null'
+ }
+ if (t === 'string' || t === 'boolean') {
+ return JSON.stringify(value)
+ }
+ if (Array.isArray(value)) {
+ const items = value.map(item => (item === undefined ? 'null' : stableStringify(item)))
+ return `[${items.join(',')}]`
+ }
+ if (t === 'object') {
+ const obj = value
+ const keys = Object.keys(obj)
+ .filter(k => obj[k] !== undefined)
+ .sort()
+ const body = keys.map(k => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(',')
+ return `{${body}}`
+ }
+ return 'null'
+}
+
+function isPlainObject(value) {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+
+function unknownKeys(obj, allowed) {
+ return Object.keys(obj).filter(k => !allowed.has(k))
+}
+
+function isBoundedId(value) {
+ return typeof value === 'string' && ID_PATTERN.test(value)
+}
+
+// Tool names are opaque registry keys, not authorization/request identifiers.
+// Their size is bounded by maxRequestBodyBytes; transport aliases apply later.
+function isToolName(value) {
+ return typeof value === 'string' && value.length > 0 && !/[\p{Cc}\p{Cs}]/u.test(value)
+}
+
+function rejectUnknown(obj, allowed, label) {
+ const extra = unknownKeys(obj, allowed)
+ if (extra.length === 0) return null
+ return fail('unknown-field', `${label} rejects field '${extra[0]}'`)
+}
+
+function assertFiniteTree(value, label) {
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value)) {
+ return fail('non-finite', `${label} must be finite`)
+ }
+ return null
+ }
+ if (value === null || value === undefined) return null
+ if (typeof value === 'string' || typeof value === 'boolean') return null
+ if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol') {
+ return fail('invalid', `${label} has an unsupported type`)
+ }
+ if (Array.isArray(value)) {
+ for (let i = 0; i < value.length; i++) {
+ const inner = assertFiniteTree(value[i], `${label}[${i}]`)
+ if (inner) return inner
+ }
+ return null
+ }
+ if (typeof value === 'object') {
+ for (const [k, v] of Object.entries(value)) {
+ if (v === undefined) continue
+ const inner = assertFiniteTree(v, `${label}.${k}`)
+ if (inner) return inner
+ }
+ }
+ return null
+}
+
+function parseMessages(raw) {
+ if (!Array.isArray(raw) || raw.length === 0) {
+ return fail('invalid', 'messages must be a non-empty array')
+ }
+ if (raw.length > LIMITS.maxMessages) {
+ return fail('limit', `messages exceed ${LIMITS.maxMessages}`)
+ }
+ const messages = []
+ for (let i = 0; i < raw.length; i++) {
+ const item = raw[i]
+ if (!isPlainObject(item)) return fail('invalid', `messages[${i}] must be an object`)
+ const extra = rejectUnknown(item, MESSAGE_KEYS, `messages[${i}]`)
+ if (extra) return extra
+ if (!MESSAGE_ROLES.has(item.role)) return fail('invalid', `messages[${i}].role is not allowed`)
+ if (typeof item.content !== 'string') return fail('invalid', `messages[${i}].content must be a string`)
+ const message = { role: item.role, content: item.content }
+ if (item.name !== undefined) {
+ if (!isToolName(item.name)) return fail('invalid', `messages[${i}].name is invalid`)
+ message.name = item.name
+ }
+ if (item.toolCallId !== undefined) {
+ if (!isBoundedId(item.toolCallId)) return fail('invalid', `messages[${i}].toolCallId is invalid`)
+ message.toolCallId = item.toolCallId
+ }
+ if (item.toolCalls !== undefined) {
+ if (item.role !== 'assistant') {
+ return fail('invalid', `messages[${i}].toolCalls is only allowed on assistant`)
+ }
+ if (!Array.isArray(item.toolCalls) || item.toolCalls.length === 0) {
+ return fail('invalid', `messages[${i}].toolCalls must be a non-empty array`)
+ }
+ if (item.toolCalls.length > LIMITS.maxToolCalls) {
+ return fail('limit', `messages[${i}].toolCalls exceed ${LIMITS.maxToolCalls}`)
+ }
+ const toolCalls = []
+ for (let j = 0; j < item.toolCalls.length; j++) {
+ const call = item.toolCalls[j]
+ if (!isPlainObject(call)) {
+ return fail('invalid', `messages[${i}].toolCalls[${j}] must be an object`)
+ }
+ const callExtra = rejectUnknown(call, TOOL_CALL_KEYS, `messages[${i}].toolCalls[${j}]`)
+ if (callExtra) return callExtra
+ if (!isBoundedId(call.id)) {
+ return fail('invalid', `messages[${i}].toolCalls[${j}].id is invalid`)
+ }
+ if (!isToolName(call.name)) {
+ return fail('invalid', `messages[${i}].toolCalls[${j}].name is invalid`)
+ }
+ if (!isPlainObject(call.arguments)) {
+ return fail('invalid', `messages[${i}].toolCalls[${j}].arguments must be an object`)
+ }
+ const finiteArgs = assertFiniteTree(
+ call.arguments,
+ `messages[${i}].toolCalls[${j}].arguments`
+ )
+ if (finiteArgs) return finiteArgs
+ toolCalls.push({ id: call.id, name: call.name, arguments: call.arguments })
+ }
+ message.toolCalls = toolCalls
+ }
+ messages.push(message)
+ }
+ return ok(messages)
+}
+
+function parseTools(raw) {
+ if (raw === undefined) return ok(undefined)
+ if (!Array.isArray(raw)) return fail('invalid', 'tools must be an array')
+ if (raw.length === 0) return ok(undefined)
+ // The complete request is byte-bounded before parsing; definition count is
+ // not an access limit for an approved connector catalog.
+ const tools = []
+ for (let i = 0; i < raw.length; i++) {
+ const item = raw[i]
+ if (!isPlainObject(item)) return fail('invalid', `tools[${i}] must be an object`)
+ const extra = rejectUnknown(item, TOOL_KEYS, `tools[${i}]`)
+ if (extra) return extra
+ if (!isToolName(item.name)) return fail('invalid', `tools[${i}].name is invalid`)
+ if (typeof item.description !== 'string') {
+ return fail('invalid', `tools[${i}].description must be a string`)
+ }
+ if (!isPlainObject(item.parameters)) {
+ return fail('invalid', `tools[${i}].parameters must be an object`)
+ }
+ const finite = assertFiniteTree(item.parameters, `tools[${i}].parameters`)
+ if (finite) return finite
+ tools.push({
+ name: item.name,
+ description: item.description,
+ parameters: item.parameters,
+ })
+ }
+ return ok(tools)
+}
+
+function parseGeneration(raw) {
+ if (raw === undefined) return ok(undefined)
+ if (!isPlainObject(raw)) return fail('invalid', 'generation must be an object')
+ const extra = rejectUnknown(raw, GENERATION_KEYS, 'generation')
+ if (extra) return extra
+ const generation = {}
+ if (raw.temperature !== undefined) {
+ if (typeof raw.temperature !== 'number' || !Number.isFinite(raw.temperature)) {
+ return fail('non-finite', 'generation.temperature must be finite')
+ }
+ if (raw.temperature < 0 || raw.temperature > 2) {
+ return fail('invalid', 'generation.temperature is out of range')
+ }
+ generation.temperature = raw.temperature
+ }
+ if (raw.maxOutputTokens !== undefined) {
+ if (
+ typeof raw.maxOutputTokens !== 'number' ||
+ !Number.isFinite(raw.maxOutputTokens) ||
+ !Number.isInteger(raw.maxOutputTokens)
+ ) {
+ return fail('non-finite', 'generation.maxOutputTokens must be a finite integer')
+ }
+ if (raw.maxOutputTokens < 1 || raw.maxOutputTokens > LIMITS.maxOutputTokens) {
+ return fail('limit', 'generation.maxOutputTokens is out of range')
+ }
+ generation.maxOutputTokens = raw.maxOutputTokens
+ }
+ if (raw.toolChoice !== undefined) {
+ if (!TOOL_CHOICES.has(raw.toolChoice)) {
+ return fail('invalid', 'generation.toolChoice is not allowed')
+ }
+ generation.toolChoice = raw.toolChoice
+ }
+ return ok(Object.keys(generation).length > 0 ? generation : undefined)
+}
+
+function parseTransportHints(raw) {
+ if (raw === undefined) return ok(undefined)
+ if (!isPlainObject(raw)) return fail('invalid', 'transportHints must be an object')
+ const extra = rejectUnknown(raw, HINT_KEYS, 'transportHints')
+ if (extra) return extra
+ if (raw.promptCacheKey === undefined) return ok(undefined)
+ if (!isBoundedId(raw.promptCacheKey)) {
+ return fail('invalid', 'transportHints.promptCacheKey is invalid')
+ }
+ return ok({ promptCacheKey: raw.promptCacheKey })
+}
+
+function parseGrokCompletionRequestV1(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'request must be an object')
+ const encoded = Buffer.byteLength(JSON.stringify(input), 'utf8')
+ if (encoded > LIMITS.maxRequestBodyBytes) {
+ return fail('limit', 'request exceeds maxRequestBodyBytes')
+ }
+ const extra = rejectUnknown(input, ROOT_KEYS, 'request')
+ if (extra) return extra
+ if (input.schemaVersion !== SCHEMA_VERSION) {
+ return fail('invalid', 'schemaVersion is not grok-completion-request.v1')
+ }
+ if (!isBoundedId(input.requestId)) return fail('invalid', 'requestId is invalid')
+ if (!isBoundedId(input.idempotencyKey)) return fail('invalid', 'idempotencyKey is invalid')
+ if (input.provider !== PROVIDER_ID) return fail('invalid', 'provider must be grok-subscription')
+ if (!isBoundedId(input.model)) return fail('invalid', 'model is invalid')
+
+ const messages = parseMessages(input.messages)
+ if (!messages.ok) return messages
+ const tools = parseTools(input.tools)
+ if (!tools.ok) return tools
+ const generation = parseGeneration(input.generation)
+ if (!generation.ok) return generation
+ const transportHints = parseTransportHints(input.transportHints)
+ if (!transportHints.ok) return transportHints
+
+ let deadlineMs
+ if (input.deadlineMs !== undefined) {
+ if (
+ typeof input.deadlineMs !== 'number' ||
+ !Number.isFinite(input.deadlineMs) ||
+ !Number.isInteger(input.deadlineMs)
+ ) {
+ return fail('non-finite', 'deadlineMs must be a finite integer')
+ }
+ if (input.deadlineMs < 1 || input.deadlineMs > LIMITS.maxDeadlineMs) {
+ return fail('limit', 'deadlineMs is out of range')
+ }
+ deadlineMs = input.deadlineMs
+ }
+
+ const projected = {
+ schemaVersion: SCHEMA_VERSION,
+ requestId: input.requestId,
+ idempotencyKey: input.idempotencyKey,
+ provider: PROVIDER_ID,
+ model: input.model,
+ messages: messages.value,
+ }
+ if (tools.value) projected.tools = tools.value
+ if (generation.value) projected.generation = generation.value
+ if (deadlineMs !== undefined) projected.deadlineMs = deadlineMs
+ if (transportHints.value) projected.transportHints = transportHints.value
+ return ok(Object.freeze(projected))
+}
+
+function hashGrokCompletionRequestV1(request) {
+ return createHash('sha256').update(stableStringify(request)).digest('hex')
+}
+
+/**
+ * Grant-binding digest for a Grok authorize attempt. connectionKey is
+ * required; never aliases deployment-default.
+ */
+function computeGrokPolicyHash(input) {
+ if (typeof input.connectionKey !== 'string' || input.connectionKey.length === 0) {
+ throw new Error('computeGrokPolicyHash requires connectionKey')
+ }
+ if (input.connectionKey === 'deployment-default' || input.connectionKey === 'unassigned') {
+ throw new Error('computeGrokPolicyHash rejects reserved connection keys')
+ }
+ return createHash('sha256')
+ .update(
+ stableStringify({
+ catalogRevision: input.catalogRevision,
+ connectionKey: input.connectionKey,
+ credentialRevision: input.credentialRevision,
+ model: input.model,
+ provider: PROVIDER_ID,
+ })
+ )
+ .digest('hex')
+}
+
+function requireId(obj, key) {
+ if (!isBoundedId(obj[key])) return fail('invalid', `${key} is invalid`)
+ return null
+}
+
+function requireHex64(obj, key) {
+ if (typeof obj[key] !== 'string' || !SHA256_HEX.test(obj[key])) {
+ return fail('invalid', `${key} must be a SHA-256 hex digest`)
+ }
+ return null
+}
+
+function requireInt(obj, key, min) {
+ const value = obj[key]
+ if (typeof value !== 'number' || !Number.isFinite(value) || !Number.isInteger(value) || value < min) {
+ return fail('non-finite', `${key} must be a finite integer`)
+ }
+ return null
+}
+
+function parseGrokExecutionTicketClaims(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'ticket claims must be an object')
+ const extra = rejectUnknown(input, CLAIMS_KEYS, 'ticket claims')
+ if (extra) return extra
+ for (const key of ['jti', 'sub', 'hostRef', 'invocationId', 'providerAttemptId', 'budgetReservationId', 'model']) {
+ const bad = requireId(input, key)
+ if (bad) return bad
+ }
+ if (input.typ !== TICKET_TYP) return fail('invalid', 'typ must be grok-execution-ticket')
+ if (input.provider !== PROVIDER_ID) return fail('invalid', 'provider must be grok-subscription')
+ const hashErr = requireHex64(input, 'requestHash') || requireHex64(input, 'policyHash')
+ if (hashErr) return hashErr
+ const ints =
+ requireInt(input, 'attemptGeneration', 0) ||
+ requireInt(input, 'providerAttemptIndex', 0) ||
+ requireInt(input, 'policyRevision', 0) ||
+ requireInt(input, 'connectionRevision', 0)
+ if (ints) return ints
+ const claims = {
+ jti: input.jti,
+ typ: TICKET_TYP,
+ sub: input.sub,
+ hostRef: input.hostRef,
+ invocationId: input.invocationId,
+ attemptGeneration: input.attemptGeneration,
+ providerAttemptId: input.providerAttemptId,
+ providerAttemptIndex: input.providerAttemptIndex,
+ provider: PROVIDER_ID,
+ model: input.model,
+ requestHash: input.requestHash,
+ policyRevision: input.policyRevision,
+ policyHash: input.policyHash,
+ budgetReservationId: input.budgetReservationId,
+ connectionRevision: input.connectionRevision,
+ }
+ if (input.connectionId !== undefined) {
+ if (!isBoundedId(input.connectionId)) return fail('invalid', 'connectionId is invalid')
+ claims.connectionId = input.connectionId
+ }
+ if (input.recipeNamespace !== undefined) {
+ if (!isBoundedId(input.recipeNamespace)) return fail('invalid', 'recipeNamespace is invalid')
+ claims.recipeNamespace = input.recipeNamespace
+ }
+ if (input.recipeName !== undefined) {
+ if (!isBoundedId(input.recipeName)) return fail('invalid', 'recipeName is invalid')
+ claims.recipeName = input.recipeName
+ }
+ return ok(Object.freeze(claims))
+}
+
+function parseAuthorizeAttemptResponse(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'authorize response must be an object')
+ const extra = rejectUnknown(input, AUTHORIZE_KEYS, 'authorize response')
+ if (extra) return extra
+ const idErr = requireId(input, 'providerAttemptId')
+ if (idErr) return idErr
+ const hashErr = requireHex64(input, 'requestHash')
+ if (hashErr) return hashErr
+ if (typeof input.executionTicket !== 'string' || input.executionTicket.length < 8) {
+ return fail('invalid', 'executionTicket is invalid')
+ }
+ if (typeof input.expiresAt !== 'string' || Number.isNaN(Date.parse(input.expiresAt))) {
+ return fail('invalid', 'expiresAt is invalid')
+ }
+ return ok(
+ Object.freeze({
+ providerAttemptId: input.providerAttemptId,
+ requestHash: input.requestHash,
+ executionTicket: input.executionTicket,
+ expiresAt: input.expiresAt,
+ })
+ )
+}
+
+function parseGrokAttemptReceiptV1(input) {
+ if (!isPlainObject(input)) return fail('invalid', 'receipt must be an object')
+ const extra = rejectUnknown(input, RECEIPT_KEYS, 'receipt')
+ if (extra) return extra
+ if (input.schemaVersion !== RECEIPT_SCHEMA_VERSION) {
+ return fail('invalid', 'schemaVersion is not grok-attempt-receipt.v1')
+ }
+ const idErr = requireId(input, 'providerAttemptId')
+ if (idErr) return idErr
+ const hashErr = requireHex64(input, 'requestHash')
+ if (hashErr) return hashErr
+ if (!RECEIPT_OUTCOMES.has(input.outcome)) return fail('invalid', 'outcome is not allowed')
+ const receipt = {
+ schemaVersion: RECEIPT_SCHEMA_VERSION,
+ providerAttemptId: input.providerAttemptId,
+ requestHash: input.requestHash,
+ outcome: input.outcome,
+ }
+ if (input.usage !== undefined) {
+ if (!isPlainObject(input.usage)) return fail('invalid', 'usage must be an object')
+ const usageExtra = rejectUnknown(input.usage, USAGE_KEYS, 'usage')
+ if (usageExtra) return usageExtra
+ const usage = {}
+ for (const key of USAGE_KEYS) {
+ if (input.usage[key] === undefined) continue
+ const bad = requireInt(input.usage, key, 0)
+ if (bad) return bad
+ usage[key] = input.usage[key]
+ }
+ if (Object.keys(usage).length > 0) receipt.usage = usage
+ }
+ return ok(Object.freeze(receipt))
+}
+
+module.exports = {
+ SCHEMA_VERSION,
+ RECEIPT_SCHEMA_VERSION,
+ PROVIDER_ID,
+ TICKET_TYP,
+ LIMITS,
+ TRANSPORT_PROTOCOL_VERSION,
+ COMPLETIONS_ORIGIN,
+ CATALOG_ORIGIN,
+ stableStringify,
+ parseGrokCompletionRequestV1,
+ hashGrokCompletionRequestV1,
+ computeGrokPolicyHash,
+ parseGrokExecutionTicketClaims,
+ parseAuthorizeAttemptResponse,
+ parseGrokAttemptReceiptV1,
+}
diff --git a/packages/grok-provider-attempt-contract/index.d.ts b/packages/grok-provider-attempt-contract/index.d.ts
new file mode 100644
index 000000000..3b37d9e10
--- /dev/null
+++ b/packages/grok-provider-attempt-contract/index.d.ts
@@ -0,0 +1,150 @@
+/**
+ * @clerum/grok-provider-attempt-contract — bounded Grok completion request,
+ * canonical SHA-256 hashing, and safe ticket/receipt types.
+ *
+ * Sibling of @clerum/llm-provider-attempt-contract. Own LIMITS and origins.
+ * Does not import Codex LIMITS. Pure module: no network, credentials, or Kubernetes.
+ */
+
+export declare const SCHEMA_VERSION: 'grok-completion-request.v1'
+export declare const RECEIPT_SCHEMA_VERSION: 'grok-attempt-receipt.v1'
+export declare const PROVIDER_ID: 'grok-subscription'
+export declare const TICKET_TYP: 'grok-execution-ticket'
+export declare const TRANSPORT_PROTOCOL_VERSION: 'grok-subscription-transport.v1'
+export declare const COMPLETIONS_ORIGIN: 'https://cli-chat-proxy.grok.com/v1/responses'
+export declare const CATALOG_ORIGIN: 'https://cli-chat-proxy.grok.com/v1/models'
+
+export declare const LIMITS: {
+ readonly maxRequestBodyBytes: 1048576
+ readonly maxMessages: 128
+ readonly maxToolCalls: 64
+ readonly maxOutputTokens: 16384
+ readonly maxDeadlineMs: 300000
+ readonly maxIdLength: 128
+}
+
+export type ContractResult<T> =
+ | { ok: true; value: T }
+ | { ok: false; code: string; message: string }
+
+export type GrokMessageRole = 'system' | 'user' | 'assistant' | 'tool'
+
+export interface GrokAssistantToolCallV1 {
+ id: string
+ name: string
+ arguments: Record<string, unknown>
+}
+
+export interface GrokMessageV1 {
+ role: GrokMessageRole
+ content: string
+ name?: string
+ toolCallId?: string
+ toolCalls?: GrokAssistantToolCallV1[]
+}
+
+export interface GrokToolDefinitionV1 {
+ name: string
+ description: string
+ parameters: Record<string, unknown>
+}
+
+export type GrokToolChoiceV1 = 'auto' | 'none' | 'required'
+
+export interface GrokGenerationOptionsV1 {
+ temperature?: number
+ maxOutputTokens?: number
+ toolChoice?: GrokToolChoiceV1
+}
+
+export interface GrokTransportHintsV1 {
+ promptCacheKey?: string
+}
+
+export interface GrokCompletionRequestV1 {
+ schemaVersion: 'grok-completion-request.v1'
+ requestId: string
+ idempotencyKey: string
+ provider: 'grok-subscription'
+ model: string
+ messages: GrokMessageV1[]
+ tools?: GrokToolDefinitionV1[]
+ generation?: GrokGenerationOptionsV1
+ deadlineMs?: number
+ transportHints?: GrokTransportHintsV1
+}
+
+export type GrokExecutionTicketClaims = {
+ jti: string
+ typ: 'grok-execution-ticket'
+ sub: string
+ hostRef: string
+ recipeNamespace?: string
+ recipeName?: string
+ invocationId: string
+ attemptGeneration: number
+ providerAttemptId: string
+ providerAttemptIndex: number
+ provider: 'grok-subscription'
+ model: string
+ requestHash: string
+ policyRevision: number
+ policyHash: string
+ budgetReservationId: string
+ connectionRevision: number
+ connectionId?: string
+}
+
+export type AuthorizeAttemptResponse = {
+ providerAttemptId: string
+ requestHash: string
+ executionTicket: string
+ expiresAt: string
+}
+
+export type RedeemAttemptResponse = {
+ accessToken: string
+ transport: GrokTransportMetadataV1
+ expiryClass: 'short_lived' | 'upstream_managed'
+ attemptReceipt: string
+}
+
+export type GrokTransportMetadataV1 = {
+ protocolVersion: 'grok-subscription-transport.v1'
+ completionsOrigin: 'https://cli-chat-proxy.grok.com/v1/responses'
+ catalogOrigin: 'https://cli-chat-proxy.grok.com/v1/models'
+ operation: 'completion_stream' | 'completion_cancel' | 'connection_test'
+ servedModel: string
+ maxStreamDurationMs: number
+}
+
+export type GrokAttemptOutcome = 'success' | 'canceled' | 'error' | 'unknown'
+
+export type GrokAttemptReceiptV1 = {
+ schemaVersion: 'grok-attempt-receipt.v1'
+ providerAttemptId: string
+ requestHash: string
+ outcome: GrokAttemptOutcome
+ usage?: { inputTokens?: number; outputTokens?: number }
+}
+
+export declare function stableStringify(value: unknown): string
+export declare function parseGrokCompletionRequestV1(
+ input: unknown
+): ContractResult<GrokCompletionRequestV1>
+export declare function hashGrokCompletionRequestV1(request: GrokCompletionRequestV1): string
+export declare function computeGrokPolicyHash(input: {
+ model: string
+ catalogRevision: number
+ credentialRevision: number
+ connectionKey: string
+}): string
+export declare function parseGrokExecutionTicketClaims(
+ input: unknown
+): ContractResult<GrokExecutionTicketClaims>
+export declare function parseAuthorizeAttemptResponse(
+ input: unknown
+): ContractResult<AuthorizeAttemptResponse>
+export declare function parseGrokAttemptReceiptV1(
+ input: unknown
+): ContractResult<GrokAttemptReceiptV1>
diff --git a/packages/grok-provider-attempt-contract/index.test.cjs b/packages/grok-provider-attempt-contract/index.test.cjs
new file mode 100644
index 000000000..f5531047e
--- /dev/null
+++ b/packages/grok-provider-attempt-contract/index.test.cjs
@@ -0,0 +1,111 @@
+'use strict'
+
+const assert = require('node:assert/strict')
+const fs = require('node:fs')
+const path = require('node:path')
+const test = require('node:test')
+const contract = require('./index.cjs')
+
+const BASE = {
+ schemaVersion: 'grok-completion-request.v1',
+ requestId: 'req-001',
+ idempotencyKey: 'idem-001',
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ messages: [{ role: 'user', content: 'hello' }],
+}
+
+test('runtime exports stay aligned with the declaration file', () => {
+ const declarations = fs.readFileSync(path.join(__dirname, 'index.d.ts'), 'utf8')
+ const declared = Array.from(
+ declarations.matchAll(/export declare (?:const|function)\s+([A-Za-z0-9_]+)/g),
+ m => m[1]
+ ).sort()
+ assert.deepEqual(Object.keys(contract).sort(), declared)
+})
+
+test('does not import Codex LIMITS or Codex provider id', () => {
+ const src = fs.readFileSync(path.join(__dirname, 'index.cjs'), 'utf8')
+ assert.equal(src.includes("require('../llm-provider-attempt-contract"), false)
+ assert.equal(contract.PROVIDER_ID, 'grok-subscription')
+ assert.equal(contract.TICKET_TYP, 'grok-execution-ticket')
+ assert.equal(contract.LIMITS.maxToolCalls, 64)
+ assert.equal(contract.COMPLETIONS_ORIGIN, 'https://cli-chat-proxy.grok.com/v1/responses')
+ assert.equal(src.includes('chatgpt.com'), false)
+})
+
+test('parses the bounded V1 request and hashes with SHA-256', () => {
+ const parsed = contract.parseGrokCompletionRequestV1(BASE)
+ assert.equal(parsed.ok, true)
+ const digest = contract.hashGrokCompletionRequestV1(parsed.value)
+ assert.match(digest, /^[a-f0-9]{64}$/)
+})
+
+test('rejects a Codex provider id on the Grok contract', () => {
+ const parsed = contract.parseGrokCompletionRequestV1({
+ ...BASE,
+ provider: 'codex-subscription',
+ })
+ assert.equal(parsed.ok, false)
+})
+
+test('rejects NaN and Infinity before hashing', () => {
+ const nanParsed = contract.parseGrokCompletionRequestV1({
+ ...BASE,
+ generation: { temperature: Number.NaN },
+ })
+ assert.equal(nanParsed.ok, false)
+})
+
+test('policy hash requires a non-reserved connectionKey', () => {
+ assert.throws(() =>
+ contract.computeGrokPolicyHash({
+ model: 'grok-4.6',
+ catalogRevision: 1,
+ credentialRevision: 1,
+ })
+ )
+ assert.throws(() =>
+ contract.computeGrokPolicyHash({
+ model: 'grok-4.6',
+ catalogRevision: 1,
+ credentialRevision: 1,
+ connectionKey: 'deployment-default',
+ })
+ )
+ const digest = contract.computeGrokPolicyHash({
+ model: 'grok-4.6',
+ catalogRevision: 1,
+ credentialRevision: 1,
+ connectionKey: 'grok-aaaaaaaaaaaaaaaa',
+ })
+ assert.match(digest, /^[a-f0-9]{64}$/)
+})
+
+test('parses Grok ticket claims and rejects Codex typ', () => {
+ const claims = {
+ jti: 'jti-1',
+ typ: 'grok-execution-ticket',
+ sub: 'default/host-a',
+ hostRef: 'host-a',
+ invocationId: 'inv-1',
+ attemptGeneration: 1,
+ providerAttemptId: 'att-1',
+ providerAttemptIndex: 1,
+ provider: 'grok-subscription',
+ model: 'grok-4.6',
+ requestHash: 'a'.repeat(64),
+ policyRevision: 1,
+ policyHash: 'b'.repeat(64),
+ budgetReservationId: 'res-1',
+ connectionRevision: 1,
+ connectionId: 'conn-1',
+ }
+ const parsed = contract.parseGrokExecutionTicketClaims(claims)
+ assert.equal(parsed.ok, true)
+ const wrongTyp = contract.parseGrokExecutionTicketClaims({
+ ...claims,
+ typ: 'codex-execution-ticket',
+ })
+ assert.equal(wrongTyp.ok, false)
+})
diff --git a/packages/grok-provider-attempt-contract/package-lock.json b/packages/grok-provider-attempt-contract/package-lock.json
new file mode 100644
index 000000000..f4a8eecac
--- /dev/null
+++ b/packages/grok-provider-attempt-contract/package-lock.json
@@ -0,0 +1,13 @@
+{
+ "name": "@clerum/grok-provider-attempt-contract",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "@clerum/grok-provider-attempt-contract",
+ "version": "0.1.0",
+ "license": "MIT"
+ }
+ }
+}
diff --git a/packages/grok-provider-attempt-contract/package.json b/packages/grok-provider-attempt-contract/package.json
new file mode 100644
index 000000000..cc7271161
--- /dev/null
+++ b/packages/grok-provider-attempt-contract/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@clerum/grok-provider-attempt-contract",
+ "version": "0.1.0",
+ "private": true,
+ "description": "Shared bounded Grok subscription provider-attempt wire contract. Sibling of the Codex contract; own LIMITS and origins. No network clients or credentials.",
+ "main": "index.cjs",
+ "types": "index.d.ts",
+ "exports": {
+ ".": {
+ "types": "./index.d.ts",
+ "require": "./index.cjs",
+ "default": "./index.cjs"
+ }
+ },
+ "scripts": {
+ "build": "node --check index.cjs",
+ "test": "node --test index.test.cjs"
+ },
+ "license": "MIT"
+}
diff --git a/packages/llm-providers/index.cjs b/packages/llm-providers/index.cjs
index 396bba366..841ce32c0 100644
--- a/packages/llm-providers/index.cjs
+++ b/packages/llm-providers/index.cjs
@@ -53,6 +53,7 @@ const PROVIDER_IDS = Object.freeze([
'azure',
// OAuth-broker subscription provider. Not part of env-key autodetection.
'codex-subscription',
+ 'grok-subscription',
])
// Model identifiers are transport selectors, not arbitrary user text. Keep
@@ -119,8 +120,9 @@ const PROVIDER_CREDENTIAL_SLOTS = Object.freeze({
minimax: apiKeySlot('minimax-api-key', 'MINIMAX_API_KEY'),
// Azure: one API key, sent via the `api-key` header (driver concern, not here).
azure: apiKeySlot('azure-openai-api-key', 'AZURE_OPENAI_API_KEY'),
- // Subscription broker: zero Secret slots. Env autodetection must never pick it.
+ // Subscription brokers: zero Secret slots. Env autodetection must never pick them.
'codex-subscription': Object.freeze([]),
+ 'grok-subscription': Object.freeze([]),
})
/**
@@ -151,6 +153,7 @@ const PROVIDER_DISPLAY_LABELS = Object.freeze({
minimax: 'MiniMax',
azure: 'Azure OpenAI',
'codex-subscription': 'OpenAI Codex Subscription',
+ 'grok-subscription': 'xAI Grok Subscription',
})
/**
@@ -193,6 +196,7 @@ const PROVIDER_NON_SECRET_ENV = Object.freeze({
Object.freeze({ envName: 'AZURE_OPENAI_API_VERSION', required: false }),
]),
'codex-subscription': Object.freeze([]),
+ 'grok-subscription': Object.freeze([]),
})
// SECURITY: use an own-property check, NOT `in`. `in` walks the prototype chain
@@ -221,7 +225,7 @@ function isCredentialSlotOwnedByProvider(provider, credentialSlot) {
return canonical.includes(credentialSlot)
}
-const OAUTH_BROKER_IDS = Object.freeze(['codex-subscription'])
+const OAUTH_BROKER_IDS = Object.freeze(['codex-subscription', 'grok-subscription'])
/**
* Pure map builder so tests can inject a second broker id without editing
@@ -251,16 +255,19 @@ const { PROVIDER_AUTH_MODE, PROVIDER_MODEL_CATALOG_MODE } = buildProviderMaps(
/** @type {Record<string, string | undefined>} */
const PROVIDER_EXECUTE_SCOPE = Object.freeze({
'codex-subscription': 'llm:codex:execute',
+ 'grok-subscription': 'llm:grok:execute',
})
/** @type {Record<string, string | undefined>} */
const PROVIDER_PROXY_APP = Object.freeze({
'codex-subscription': 'codex-llm-proxy',
+ 'grok-subscription': 'grok-llm-proxy',
})
/** @type {Record<string, string | undefined>} */
const PROVIDER_PROXY_SERVICE = Object.freeze({
'codex-subscription': 'codex-llm-proxy',
+ 'grok-subscription': 'grok-llm-proxy',
})
function providerDescriptor(id) {
diff --git a/packages/llm-providers/index.d.ts b/packages/llm-providers/index.d.ts
index 2838bedb3..ac42965b9 100644
--- a/packages/llm-providers/index.d.ts
+++ b/packages/llm-providers/index.d.ts
@@ -29,6 +29,7 @@ export declare const PROVIDER_IDS: readonly [
'minimax',
'azure',
'codex-subscription',
+ 'grok-subscription',
]
/** Union of the canonical provider ids. */
@@ -109,7 +110,7 @@ export interface ProviderDescriptor {
export declare const PROVIDER_AUTH_MODE: Record<LlmProviderId, ProviderAuthMode>
export declare const PROVIDER_MODEL_CATALOG_MODE: Record<LlmProviderId, ProviderModelCatalogMode>
-export declare const OAUTH_BROKER_IDS: readonly ['codex-subscription']
+export declare const OAUTH_BROKER_IDS: readonly ['codex-subscription', 'grok-subscription']
export declare function buildProviderMaps(
ids: readonly string[],
brokerIds: readonly string[],
diff --git a/packages/llm-providers/index.test.cjs b/packages/llm-providers/index.test.cjs
index 7b95db7db..211c3fbe6 100644
--- a/packages/llm-providers/index.test.cjs
+++ b/packages/llm-providers/index.test.cjs
@@ -18,17 +18,20 @@ describe('buildProviderMaps', () => {
assert.equal(maps.PROVIDER_MODEL_CATALOG_MODE.openai, 'static')
})
- it('keeps production maps Codex-only and rejects unknown ids', () => {
- assert.deepEqual(providers.OAUTH_BROKER_IDS, ['codex-subscription'])
+ it('keeps production maps to known oauth-broker ids and rejects unknown ids', () => {
+ assert.deepEqual(providers.OAUTH_BROKER_IDS, ['codex-subscription', 'grok-subscription'])
assert.equal(providers.PROVIDER_AUTH_MODE['codex-subscription'], 'oauth-broker')
+ assert.equal(providers.PROVIDER_AUTH_MODE['grok-subscription'], 'oauth-broker')
+ assert.equal(providers.PROVIDER_AUTH_MODE.xai, 'static-credentials')
assert.equal(providers.PROVIDER_AUTH_MODE.openai, 'static-credentials')
- assert.equal(providers.PROVIDER_MODEL_CATALOG_MODE['codex-subscription'], 'dynamic')
+ assert.equal(providers.PROVIDER_MODEL_CATALOG_MODE['grok-subscription'], 'dynamic')
assert.throws(() => providers.providerDescriptor('not-a-provider'))
assert.throws(() => providers.providerDescriptor('fixture-broker'))
- const desc = providers.providerDescriptor('codex-subscription')
+ const desc = providers.providerDescriptor('grok-subscription')
assert.equal(desc.authMode, 'oauth-broker')
- assert.equal(desc.executeScope, 'llm:codex:execute')
- assert.equal(desc.proxyApp, 'codex-llm-proxy')
- assert.equal(desc.proxyService, 'codex-llm-proxy')
+ assert.equal(desc.executeScope, 'llm:grok:execute')
+ assert.equal(desc.proxyApp, 'grok-llm-proxy')
+ assert.equal(desc.proxyService, 'grok-llm-proxy')
+ assert.deepEqual(desc.credentialSlots, [])
})
})