Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(grok): read language-model catalogs and aliases

Seth Wilson70af9abcb182
diff --git a/src/utils/provider-models.test.ts b/src/utils/provider-models.test.ts
index 30b03f17..39adc46f 100644
--- a/src/utils/provider-models.test.ts
+++ b/src/utils/provider-models.test.ts
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { buildModelCatalog, fetchProviderModelCatalog } from './provider-models.js';
+import { buildModelCatalog, fetchProviderModelCatalog, ProviderModelFetchError } from './provider-models.js';
afterEach(() => {
vi.unstubAllGlobals();
@@ -172,6 +172,63 @@ describe('buildModelCatalog', () => {
});
describe('fetchProviderModelCatalog', () => {
+ const grokConfig = {
+ name: 'grok' as const,
+ apiKey: 'test-grok-key',
+ baseUrl: 'https://api.x.ai/v1/',
+ model: 'grok-4',
+ enabled: true,
+ };
+
+ it.each(['models', 'data', 'nested data'] as const)('reads Grok language models from %s and includes chat aliases', async (shape) => {
+ const models = [
+ { id: ' grok-4-0709 ', aliases: ['grok-4', 'grok-4-latest', 'grok-4', 'other-model'], output_modalities: ['text'] },
+ { id: 'grok-vision', input_modalities: ['text', 'image'], output_modalities: ['text'] },
+ { id: 'grok-legacy' },
+ { id: 'grok-picture', aliases: ['grok-picture-latest'], output_modalities: ['image'] },
+ ];
+ const payload = shape === 'nested data' ? { data: { data: models } } : { [shape]: models };
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(payload)));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const catalog = await fetchProviderModelCatalog('grok', grokConfig);
+
+ expect(catalog).toEqual({
+ recommendedModel: 'grok-4',
+ models: ['grok-4-latest', 'grok-4-0709', 'grok-legacy', 'grok-vision'],
+ });
+ expect(fetchMock).toHaveBeenCalledWith('https://api.x.ai/v1/language-models', expect.objectContaining({
+ headers: { Authorization: 'Bearer test-grok-key' },
+ signal: expect.any(AbortSignal),
+ }));
+ });
+
+ it('prefers the documented Grok models field and ignores malformed entries', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ models: [
+ null, 'grok-invalid', { id: 42 },
+ { id: 'grok-4', aliases: [null, 1, ' grok-4-latest ', ''] },
+ { id: 'grok-malformed-aliases', aliases: 'grok-not-an-alias' },
+ { id: 'grok-malformed-modality', output_modalities: 'text' },
+ { id: 'grok-no-output', output_modalities: [] },
+ ],
+ data: [{ id: 'grok-stale' }],
+ }))));
+
+ expect(await fetchProviderModelCatalog('grok', grokConfig)).toEqual({
+ recommendedModel: 'grok-4',
+ models: ['grok-4-latest', 'grok-malformed-aliases'],
+ });
+ });
+
+ it.each([null, {}, { models: {} }, { data: { data: 'invalid' } }, { models: [] }, { models: [{ id: 'other-model' }] }])(
+ 'reports an unsupported Grok catalog without a parsing crash: %j', async (payload) => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify(payload))));
+
+ await expect(fetchProviderModelCatalog('grok', grokConfig)).rejects.toThrow(ProviderModelFetchError);
+ },
+ );
+
it('excludes non-text Atlas Cloud models using output modality metadata', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({
data: [
diff --git a/src/utils/provider-models.ts b/src/utils/provider-models.ts
index 2e058b92..68faf3cf 100644
--- a/src/utils/provider-models.ts
+++ b/src/utils/provider-models.ts
@@ -182,11 +182,8 @@ interface AnthropicModelResponse {
}
interface XAIModelResponse {
- data?: Array<{
- id?: string;
- input_modalities?: string[];
- output_modalities?: string[];
- }>;
+ models?: unknown;
+ data?: unknown;
}
interface OllamaTagsResponse {
@@ -436,7 +433,7 @@ async function fetchAnthropicModels(config: ProviderConfig): Promise<ProviderMod
}
async function fetchGrokModels(config: ProviderConfig): Promise<ProviderModelCatalog> {
- const data = await fetchJson<XAIModelResponse>(
+ const data = await fetchJson<XAIModelResponse | null>(
`${trimTrailingSlash(config.baseUrl)}/language-models`,
{
headers: {
@@ -446,10 +443,21 @@ async function fetchGrokModels(config: ProviderConfig): Promise<ProviderModelCat
'Mercury could not fetch models for this Grok key. Please re-enter it.',
);
- const ids = (data.data ?? [])
- .filter((model) => model.output_modalities?.includes('text') || model.output_modalities == null)
- .map((model) => model.id?.trim() ?? '')
- .filter((id) => id.startsWith('grok-'));
+ // /language-models uses `models`; retain the older OpenAI-shaped envelopes.
+ const legacyData = data?.data;
+ const models: unknown[] = Array.isArray(data?.models) ? data.models
+ : Array.isArray(legacyData) ? legacyData
+ : legacyData && typeof legacyData === 'object' && 'data' in legacyData && Array.isArray(legacyData.data)
+ ? legacyData.data : [];
+ const ids = models.flatMap((model) => {
+ if (!model || typeof model !== 'object') return [];
+ const { id, aliases, output_modalities: outputModalities } = model as Record<string, unknown>;
+ if (outputModalities != null && (!Array.isArray(outputModalities) || !outputModalities.includes('text'))) return [];
+ return [id, ...(Array.isArray(aliases) ? aliases : [])]
+ .filter((value): value is string => typeof value === 'string')
+ .map((value) => value.trim())
+ .filter((value) => value.startsWith('grok-'));
+ });
return buildModelCatalog('grok', ids, config.model);
}