Open History to see the last commit
1/**
2 * xAI Grok — first-party OpenAPI 3.1 spec at docs.x.ai/openapi.json
3 * (public). Provider id `grok` matches the @tanstack/ai-grok adapter even
4 * though xAI titles the spec "xAI's REST API".
5 */
6import { compileTokenCard, compileUnitCard } from '@modelschemas/rate-card'
7import type { RateCard, UnitCardSpec } from '@modelschemas/rate-card'
8
9import type { Activity } from '#/db/schema.ts'
10import { bearerConnect } from './connect.ts'
11import {
12 displayNameFromRawId,
13 grokGenerationEndpointId,
14 grokModelActivity,
15} from './model-meta.ts'
16import {
17 NO_FACTS,
18 assertParsed,
19 cachedDocs,
20 docsReport,
21 docsRun,
22 mapConcurrent,
23 markdownSection,
24 markdownTableRows,
25 tokenCount,
26 tryDocs,
27 unavailable,
28} from './model-facts.ts'
29import type { DocsRun, ModelFacts } from './model-facts.ts'
30import { fetchJson, fetchText, sha256Text, skippedResult } from './types.ts'
31import type {
32 ListModelsResult,
33 ModelInfo,
34 ModelReasoning,
35 OpenApiDocument,
36 ProviderConfig,
37 ProviderSecrets,
38 SpecFetchResult,
39} from './types.ts'
40
41const GROK_OPENAPI_URL = 'https://docs.x.ai/openapi.json'
42const GROK_MODELS_URL = 'https://api.x.ai/v1/models'
43/**
44 * First-party extras: per-family model endpoints carry modalities (and
45 * prices — a separate PR). Context windows are only in the docs, served
46 * as markdown with a `| Model | Context | … |` table.
47 */
48const GROK_LANGUAGE_MODELS_URL = 'https://api.x.ai/v1/language-models'
49const GROK_IMAGE_MODELS_URL = 'https://api.x.ai/v1/image-generation-models'
50const GROK_VIDEO_MODELS_URL = 'https://api.x.ai/v1/video-generation-models'
51export const GROK_DOCS_MODELS_URL = 'https://docs.x.ai/docs/models.md'
52const GROK_MODEL_PAGE = (id: string) =>
53 `https://docs.x.ai/developers/models/${id}.md`
54
55/**
56 * A model page's Capabilities bullets: `**Reasoning:** Yes` and
57 * `**Reasoning efforts (supported):** `low`, …`. Reasoning is optional only
58 * when `none` is listed; a reasoning model whose page names no efforts has
59 * no documented knob and stays null. xAI documents no per-model tool list.
60 */
61export function parseGrokReasoning(markdown: string): ModelReasoning | null {
62 const caps = markdownSection(markdown, 'Capabilities')
63 if (!/\*\*Reasoning:\*\*\s*Yes/.test(caps)) return null
64 const line = caps.match(/\*\*Reasoning efforts \(supported\):\*\*(.+)/)?.[1]
65 const efforts = [...(line ?? '').matchAll(/`([a-z]+)`/g)].flatMap((m) =>
66 m[1] ? [m[1]] : [],
67 )
68 if (efforts.length === 0) return null
69 return { mode: 'effort', mandatory: !efforts.includes('none'), efforts }
70}
71
72/**
73 * Reasoning is on, but the page names no effort list. The object stays
74 * null; callers record `path: 'silent'` instead of guessing a mode.
75 */
76export function grokReasoningGap(markdown: string): 'silent' | null {
77 if (parseGrokReasoning(markdown)) return null
78 return grokReasons(markdown) ? 'silent' : null
79}
80
81/** `**Reasoning:** Yes` in the Capabilities bullets, efforts or not. */
82export function grokReasons(markdown: string): boolean {
83 return /\*\*Reasoning:\*\*\s*Yes/.test(
84 markdownSection(markdown, 'Capabilities'),
85 )
86}
87
88/**
89 * A numeric generation cap from the model page. "No text output limit"
90 * and price rows ("Output | $6.00") are not caps.
91 */
92export function parseGrokMaxOutput(markdown: string): number | null {
93 const labeled = markdown.match(
94 /\*\*(?:Max(?:imum)? output(?: tokens)?|Output limit):\*\*\s*([^\n]+)/i,
95 )?.[1]
96 if (labeled) return grokOutputLimit(labeled)
97 for (const row of markdownTableRows(markdown)) {
98 const label = row[0]?.trim() ?? ''
99 const value = row[1]?.trim() ?? ''
100 if (/^(?:max(?:imum)? output(?: tokens)?|output limit)$/i.test(label)) {
101 return grokOutputLimit(value)
102 }
103 }
104 return null
105}
106
107function grokOutputLimit(text: string): number | null {
108 if (!/\d/.test(text) || /\bno\b/i.test(text) || text.includes('$')) {
109 return null
110 }
111 return tokenCount(text)
112}
113
114/** Listing fields that state an output cap. Absent on the live table. */
115function listingMaxOutput(m: GrokExtrasModel): number | null {
116 for (const key of [
117 'max_output_tokens',
118 'max_completion_tokens',
119 'max_output',
120 ]) {
121 const value = m[key]
122 if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
123 return value
124 }
125 }
126 return null
127}
128
129/**
130 * The files page: attached files run the `attachment_search` server-side
131 * tool, and its "Agentic models only" bullet names the models that can.
132 * xAI's other server-side tools (web_search, x_search, code_execution, …)
133 * are documented per provider, with no per-model list, so they are not
134 * assigned (#409). The bullet is "e.g.", so a model it does not name
135 * stays null with no source (#707).
136 */
137export const GROK_FILES_DOC_URL = 'https://docs.x.ai/developers/files.md'
138
139/**
140 * The files page's statement: the tool id it says attachments activate,
141 * and the models its "**Agentic models only**" bullet names. Either one
142 * missing, or the page naming two different tool ids, throws.
143 */
144export function parseGrokFileTool(markdown: string): {
145 tool: string
146 models: Array<string>
147} {
148 const tools = new Set(
149 [
150 ...markdown.matchAll(
151 /activates the `([a-z][a-z0-9_]*)` (?:\[?server-side tool|tool)/g,
152 ),
153 ].map((match) => match[1] ?? ''),
154 )
155 const line = /^\* \*\*Agentic models only\*\*:(.*)$/m.exec(markdown)?.[1]
156 const models = [...(line ?? '').matchAll(/`([a-z0-9][a-z0-9.-]*)`/g)].map(
157 (match) => match[1] ?? '',
158 )
159 const [tool] = tools
160 if (!tool || tools.size !== 1) {
161 throw new Error('xai files page: no single attachment tool id')
162 }
163 if (models.length === 0) {
164 throw new Error('xai files page: no Agentic models only list')
165 }
166 return { tool, models }
167}
168
169/**
170 * xAI tags every operation `v1`, so classify by path. The text-generation
171 * surface spans the OpenAI-compatible endpoints (chat/completions,
172 * completions, responses) and the Anthropic-compatible ones (messages,
173 * complete). Files and document search are platform endpoints.
174 */
175function classify(path: string): Activity | null {
176 if (
177 path === '/v1/chat/completions' ||
178 path === '/v1/completions' ||
179 path === '/v1/complete' ||
180 path === '/v1/messages' ||
181 path === '/v1/responses' ||
182 path === '/v1/tokenize-text'
183 ) {
184 return 'chat'
185 }
186 if (path.startsWith('/v1/images/')) return 'image'
187 if (path.startsWith('/v1/videos/')) return 'video'
188 if (path === '/v1/embeddings') return 'embeddings'
189 return null
190}
191
192async function fetchSpec(_env: ProviderSecrets): Promise<SpecFetchResult> {
193 const text = await fetchText(GROK_OPENAPI_URL)
194 const spec = JSON.parse(text) as OpenApiDocument
195 return {
196 specs: [withGrokImageQuality(spec)],
197 sources: [{ url: GROK_OPENAPI_URL, hash: await sha256Text(text) }],
198 outputStrategy: 'post-200',
199 }
200}
201
202interface GrokModelList {
203 data?: Array<{ id: string; created?: number }>
204}
205
206interface GrokExtrasModel {
207 id: string
208 aliases?: Array<string>
209 input_modalities?: Array<string>
210 output_modalities?: Array<string>
211 long_context_threshold?: number
212 [price: string]: unknown
213}
214
215/**
216 * xAI quotes every price as an integer in units of 1e-10 USD per token
217 * (`prompt_text_token_price: 12500` is $1.25 / 1M tokens, the rate its
218 * docs table publishes). `*_long_context` fields re-quote the whole
219 * request once the prompt reaches `long_context_threshold`.
220 */
221const XAI_PRICE_UNIT = 1e-10
222
223const GROK_PRICE_LEVERS: Record<string, string> = {
224 prompt_text_token_price: 'input_tokens',
225 cached_prompt_text_token_price: 'cache_read_tokens',
226 prompt_image_token_price: 'image_tokens',
227 completion_text_token_price: 'output_tokens',
228 search_price: 'web_searches',
229}
230
231function grokRates(m: GrokExtrasModel, suffix = ''): Record<string, number> {
232 const rates: Record<string, number> = {}
233 for (const [field, lever] of Object.entries(GROK_PRICE_LEVERS)) {
234 const value = m[`${field}${suffix}`]
235 if (typeof value === 'number') rates[lever] = value * XAI_PRICE_UNIT
236 }
237 return rates
238}
239
240/**
241 * `quality` is a documented `/v1/images/generations` field that
242 * docs.x.ai/openapi.json omits: the image generation guide names `low`,
243 * `medium`, and `auto`, and xai-sdk-ts adds it to `ImageGenerateParams`
244 * by hand (src/types.ts `ImageRequestFields`). Add it so the bound schema
245 * admits what the API accepts and the image card's lever is a request
246 * field.
247 */
248const GROK_IMAGE_QUALITY = {
249 type: ['string', 'null'],
250 enum: ['low', 'medium', 'auto'],
251 description:
252 'Generation quality. Defaults to `auto`, which serves `low` for generation and `medium` for editing; images are billed at the quality served. Only supported by grok-imagine-image-2.0. Documented in the image generation guide and the official TypeScript SDK, absent from docs.x.ai/openapi.json.',
253}
254
255export function withGrokImageQuality(spec: OpenApiDocument): OpenApiDocument {
256 for (const name of ['GenerateImageRequest', 'EditImageRequest']) {
257 const schema = spec.components?.schemas?.[name] as
258 | { properties?: Record<string, unknown> }
259 | undefined
260 const properties = schema?.properties
261 if (properties && !('quality' in properties)) {
262 properties.quality = GROK_IMAGE_QUALITY
263 }
264 }
265 return spec
266}
267
268/**
269 * Image-card levers, outermost first, with the request default. `auto` is
270 * the `quality` default; the guide says it serves `low` for generation,
271 * and the pricing page's $0.04 for grok-imagine-image-2.0 is the low/1k
272 * cell. Images are billed at the quality served.
273 */
274const GROK_IMAGE_KEYS = [
275 { param: 'quality', default: 'auto' },
276 { param: 'resolution', default: '1k' },
277]
278
279type GrokImageTier = { price_per_image: number } & Record<string, unknown>
280
281/**
282 * The listing's (quality, resolution) matrix. `undefined` when there is
283 * none; `null` when a tier names a dimension the request cannot state, in
284 * which case the flat `image_price` is one cell, not a rate.
285 */
286function grokImageTiers(
287 m: GrokExtrasModel,
288): Array<GrokImageTier> | null | undefined {
289 const matrix: unknown = m.pricing
290 if (!Array.isArray(matrix)) return undefined
291 const tiers: Array<GrokImageTier> = []
292 for (const tier of matrix) {
293 if (typeof tier !== 'object' || tier === null || Array.isArray(tier)) {
294 return null
295 }
296 const { price_per_image, ...dims } = tier as Record<string, unknown>
297 if (typeof price_per_image !== 'number') return null
298 for (const dim of Object.keys(dims)) {
299 if (!GROK_IMAGE_KEYS.some((key) => key.param === dim)) return null
300 }
301 tiers.push({ price_per_image, ...dims })
302 }
303 return tiers
304}
305
306/**
307 * Per-image card from the model metadata: the (quality, resolution) matrix
308 * when the listing publishes one, else the flat `image_price`.
309 */
310export async function grokImageCard(
311 m: GrokExtrasModel,
312): Promise<RateCard | null> {
313 // `n` defaults to 1 on the request, as it does here.
314 const quantity = { param: 'n', bound: 'request' as const, default: 1 }
315 const source = async (payload: unknown) => ({
316 url: GROK_IMAGE_MODELS_URL,
317 hash: await sha256Text(JSON.stringify(payload)),
318 extractedAt: new Date().toISOString(),
319 })
320 const tiers = grokImageTiers(m)
321 if (tiers === null) return null
322 if (tiers === undefined) {
323 const flat = m.image_price
324 if (typeof flat !== 'number') return null
325 return compileUnitCard(
326 { quantity, rates: flat * XAI_PRICE_UNIT },
327 await source({ image_price: flat }),
328 )
329 }
330 const dims = GROK_IMAGE_KEYS.filter((key) =>
331 tiers.some((tier) => key.param in tier),
332 )
333 const rates: Record<string, unknown> = {}
334 for (const tier of tiers) {
335 let node = rates
336 for (const [i, dim] of dims.entries()) {
337 const value = tier[dim.param]
338 if (typeof value !== 'string') return null
339 if (i === dims.length - 1) {
340 node[value] = tier.price_per_image * XAI_PRICE_UNIT
341 } else {
342 node = (node[value] ??= {}) as Record<string, unknown>
343 }
344 }
345 }
346 if (dims[0]?.param === 'quality' && rates.low !== undefined) {
347 rates.auto ??= rates.low
348 }
349 const keys = dims.map((dim) => {
350 const values = [
351 ...new Set(tiers.map((tier) => String(tier[dim.param]))),
352 ...(dim.param === 'quality' && rates.auto !== undefined ? ['auto'] : []),
353 ]
354 return {
355 param: dim.param,
356 bound: 'request' as const,
357 values,
358 ...(values.includes(dim.default) && { default: dim.default }),
359 }
360 })
361 return compileUnitCard(
362 { quantity, keys, rates: rates as UnitCardSpec['rates'] },
363 await source({ pricing: tiers }),
364 )
365}
366
367/**
368 * Per-second video rates from the docs "Imagine Pricing" table
369 * (`| grok-imagine-video | $0.050 / sec |`). The model metadata carries no
370 * price for video models.
371 */
372export function parseGrokVideoPrices(markdown: string): Map<string, number> {
373 const out = new Map<string, number>()
374 for (const [model = '', cost = ''] of markdownTableRows(markdown)) {
375 const rate = cost.match(/^\$([\d.]+)\s*\/\s*sec(ond)?$/)?.[1]
376 if (!model.startsWith('grok-') || rate === undefined) continue
377 if (!out.has(model)) out.set(model, Number(rate))
378 }
379 return out
380}
381
382/** Per-second card for a video model the docs table prices. */
383export async function grokVideoCard(
384 perSecond: number | undefined,
385): Promise<RateCard | null> {
386 if (perSecond === undefined) return null
387 return compileUnitCard(
388 { quantity: { param: 'duration', bound: 'request' }, rates: perSecond },
389 {
390 url: GROK_DOCS_MODELS_URL,
391 hash: await sha256Text(JSON.stringify({ perSecond })),
392 extractedAt: new Date().toISOString(),
393 },
394 )
395}
396
397/** Per-model token card from the first-party model metadata. */
398export async function grokRateCard(
399 m: GrokExtrasModel,
400): Promise<RateCard | null> {
401 const base = grokRates(m)
402 if (Object.keys(base).length === 0) return null
403 const long = grokRates(m, '_long_context')
404 const threshold = m.long_context_threshold
405 const tiers =
406 typeof threshold === 'number' && Object.keys(long).length > 0
407 ? // xAI bills the long-context rate at or above the threshold; the
408 // card's tiers are strictly-greater, and token counts are integers.
409 [{ minPromptTokens: threshold - 1, rates: { ...base, ...long } }]
410 : []
411 return compileTokenCard(base, tiers, {
412 url: GROK_LANGUAGE_MODELS_URL,
413 // Hashing only the priced fields keeps the stored card (and its
414 // `extractedAt`) stable across unrelated metadata edits.
415 hash: await sha256Text(
416 JSON.stringify({ base, long, threshold: threshold ?? null }),
417 ),
418 extractedAt: new Date().toISOString(),
419 })
420}
421
422/** Context windows keyed by model id from the docs pricing table. */
423export function parseGrokContextWindows(markdown: string): Map<string, number> {
424 const out = new Map<string, number>()
425 for (const [model = '', context = ''] of markdownTableRows(markdown)) {
426 const id = model.replace(/\s*\(.*$/, '').trim()
427 if (!id.startsWith('grok-') || !/^[\d,.]+\s*[kKmM]?$/.test(context))
428 continue
429 const tokens = tokenCount(context)
430 if (tokens !== null && !out.has(id)) out.set(id, tokens)
431 }
432 return out
433}
434
435interface GrokHostedTools {
436 tools: Array<string>
437 models: Array<string>
438 hash: string
439}
440
441/** The files page, or null (a failure is in `docsFailures`). */
442function grokHostedTools(
443 kv: KVNamespace | undefined,
444 run: DocsRun,
445): Promise<GrokHostedTools | null> {
446 return tryDocs(run, GROK_FILES_DOC_URL, (cached) =>
447 cached(kv, GROK_FILES_DOC_URL, async () => {
448 const markdown = await fetchText(GROK_FILES_DOC_URL)
449 const { tool, models } = parseGrokFileTool(markdown)
450 return { tools: [tool], models, hash: await sha256Text(markdown) }
451 }),
452 )
453}
454
455async function grokModelFacts(
456 headers: HeadersInit,
457 kv: KVNamespace | undefined,
458 run: DocsRun,
459): Promise<(rawId: string) => ModelFacts & Pick<ModelInfo, 'absent'>> {
460 const extras = (url: string) =>
461 fetchJson(url, { headers }) as Promise<{ models?: Array<GrokExtrasModel> }>
462 const [language, image, video, docs, hosted] = await Promise.all([
463 extras(GROK_LANGUAGE_MODELS_URL),
464 extras(GROK_IMAGE_MODELS_URL),
465 extras(GROK_VIDEO_MODELS_URL),
466 cachedDocs(kv, GROK_DOCS_MODELS_URL, async () => {
467 const markdown = await fetchText(GROK_DOCS_MODELS_URL)
468 const parsed = parseGrokContextWindows(markdown)
469 assertParsed(parsed, 'xai models docs')
470 return {
471 contexts: Object.fromEntries(parsed),
472 videoPerSecond: Object.fromEntries(parseGrokVideoPrices(markdown)),
473 }
474 }),
475 grokHostedTools(kv, run),
476 ])
477 const byId = new Map<string, GrokExtrasModel>()
478 const listedAt = new Map<string, string>()
479 for (const [url, list] of [
480 [GROK_LANGUAGE_MODELS_URL, language],
481 [GROK_IMAGE_MODELS_URL, image],
482 [GROK_VIDEO_MODELS_URL, video],
483 ] as const) {
484 for (const m of list.models ?? []) {
485 for (const id of [m.id, ...(m.aliases ?? [])]) {
486 byId.set(id, m)
487 listedAt.set(id, url)
488 }
489 }
490 }
491 const pages = new Map<
492 string,
493 {
494 value: ModelReasoning | null
495 reasons?: boolean
496 maxOutput: number | null
497 hash: string
498 }
499 >()
500 await mapConcurrent(language.models ?? [], 8, async (m) => {
501 try {
502 const page = await cachedDocs(kv, GROK_MODEL_PAGE(m.id), async () => {
503 const markdown = await fetchText(GROK_MODEL_PAGE(m.id))
504 return {
505 value: parseGrokReasoning(markdown),
506 reasons: grokReasons(markdown),
507 maxOutput: parseGrokMaxOutput(markdown),
508 hash: await sha256Text(markdown),
509 }
510 })
511 if (!page.value && !page.reasons && page.maxOutput == null) return
512 for (const id of [m.id, ...(m.aliases ?? [])]) pages.set(id, page)
513 } catch {
514 // A missing page leaves reasoning and maxOutput unknown, never a guess.
515 }
516 })
517 const cards = new Map<string, RateCard | null>()
518 for (const m of language.models ?? []) {
519 const card = await grokRateCard(m)
520 for (const id of [m.id, ...(m.aliases ?? [])]) cards.set(id, card)
521 }
522 for (const m of image.models ?? []) {
523 const card = await grokImageCard(m)
524 for (const id of [m.id, ...(m.aliases ?? [])]) cards.set(id, card)
525 }
526 for (const m of video.models ?? []) {
527 const card = await grokVideoCard(docs.videoPerSecond[m.id])
528 for (const id of [m.id, ...(m.aliases ?? [])]) cards.set(id, card)
529 }
530 return (rawId) => {
531 const m = byId.get(rawId)
532 if (!m) return NO_FACTS
533 const contextWindow = docs.contexts[rawId] ?? null
534 const modalities = m.input_modalities
535 ? { input: m.input_modalities, output: m.output_modalities ?? [] }
536 : null
537 const page = pages.get(rawId)
538 const reasons = page?.reasons === true
539 const listedMax = listingMaxOutput(m)
540 const facts: ModelFacts = {
541 contextWindow,
542 // The spec's 128k figure is a default, not a cap. Only a number the
543 // listing or the model page states is an output limit.
544 maxOutput: listedMax ?? page?.maxOutput ?? null,
545 modalities,
546 // Request-feature flags come from the bound schema; the per-model
547 // docs page adds `reasoning`, which no request property names.
548 capabilities: reasons ? ['reasoning'] : null,
549 pricing: cards.get(rawId) ?? null,
550 reasoning: page?.value ?? null,
551 }
552 // Only a language model the files page names (by id or alias) runs
553 // the server-side tools; any other row is left unknown.
554 const agentic =
555 hosted !== null &&
556 language.models?.includes(m) === true &&
557 [m.id, ...(m.aliases ?? [])].some((id) => hosted.models.includes(id))
558 if (agentic) facts.serverTools = hosted.tools
559 const sources: ModelFacts['factSources'] = {}
560 if (modalities) {
561 // No `file`: xAI reads attached files through the `attachment_search`
562 // server-side tool, not as model input, and the listing names none.
563 sources.modalities = {
564 derivation: 'listing',
565 sourceUrl: listedAt.get(rawId),
566 path: 'input_modalities',
567 }
568 }
569 if (contextWindow != null) {
570 sources.contextWindow = {
571 derivation: 'docs-derived',
572 sourceUrl: GROK_DOCS_MODELS_URL,
573 path: 'contextWindow',
574 }
575 }
576 if (listedMax != null) {
577 sources.maxOutput = { derivation: 'listing', path: 'maxOutput' }
578 } else if (page?.maxOutput != null) {
579 sources.maxOutput = {
580 derivation: 'docs-derived',
581 sourceUrl: GROK_MODEL_PAGE(m.id),
582 sourceHash: page.hash,
583 path: 'maxOutput',
584 }
585 }
586 if (page?.value) {
587 sources.reasoning = {
588 derivation: 'docs-derived',
589 sourceUrl: GROK_MODEL_PAGE(m.id),
590 sourceHash: page.hash,
591 path: 'Capabilities',
592 }
593 } else if (page?.reasons) {
594 sources.reasoning = {
595 derivation: 'docs-derived',
596 sourceUrl: GROK_MODEL_PAGE(m.id),
597 sourceHash: page.hash,
598 path: 'silent',
599 }
600 }
601 if (reasons) {
602 sources.capabilities = {
603 reasoning: {
604 derivation: 'docs-derived',
605 sourceUrl: GROK_MODEL_PAGE(m.id),
606 sourceHash: page.hash,
607 path: 'Capabilities.Reasoning',
608 },
609 }
610 }
611 if (agentic) {
612 sources.serverTools = Object.fromEntries(
613 hosted.tools.map((tool) => [
614 tool,
615 {
616 derivation: 'docs-derived' as const,
617 sourceUrl: GROK_FILES_DOC_URL,
618 sourceHash: hosted.hash,
619 path: 'Limitations: Agentic models only',
620 },
621 ]),
622 )
623 }
624 if (Object.keys(sources).length > 0) facts.factSources = sources
625 if (hosted === null) return { ...facts, ...unavailable('serverTools') }
626 return facts
627 }
628}
629
630async function listModels(
631 env: ProviderSecrets,
632 kv?: KVNamespace,
633): Promise<ListModelsResult> {
634 const key = env.XAI_API_KEY
635 if (!key) {
636 return { models: [], ...skippedResult('grok', 'XAI_API_KEY') }
637 }
638 const headers = { Authorization: `Bearer ${key}` }
639 const run = docsRun()
640 const [body, facts] = await Promise.all([
641 fetchJson(GROK_MODELS_URL, { headers }) as Promise<GrokModelList>,
642 grokModelFacts(headers, kv, run),
643 ])
644 return {
645 models: (body.data ?? []).map((m) => ({
646 rawId: m.id,
647 displayName: displayNameFromRawId(m.id),
648 activity: grokModelActivity(m.id),
649 releasedAt: m.created ?? null,
650 ...facts(m.id),
651 })),
652 docsFailures: docsReport(run),
653 }
654}
655
656export const grokProvider: ProviderConfig = {
657 id: 'grok',
658 modelNamespaces: ['xai', 'x-ai'],
659 displayName: 'xAI Grok',
660 authEnvVar: 'XAI_API_KEY',
661 defaultDerivation: 'upstream-spec',
662 specGrain: 'provider',
663 connect: bearerConnect('https://api.x.ai'),
664 fetchSpec,
665 listModels,
666 classify,
667 generationEndpointId: ({ activity }) => grokGenerationEndpointId(activity),
668}