Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(models): 同步 xAI 真实资料并接通 Grok 4.7 Fast (#5060)

Chris Zhang2770145bab04
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
index c525386674..74e5e53690 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
@@ -120,7 +120,7 @@ describe('active-catalog discovered augment', () => {
it.each([
['xai', 'xai', 'grok-4.5', 'grok-4.6'],
] as const)(
- 'uses the same default selection for builtin and independent %s accounts',
+ 'preserves catalog visibility without reranking builtin and independent %s accounts',
(id, native, oldId, newId) => {
const catalog = bundledWithoutRegistry();
const builtin = catalog.providers.find((provider) => provider.id === id)!;
@@ -152,7 +152,7 @@ describe('active-catalog discovered augment', () => {
`${providerId}/${agent}: ${listed(providerId)
.map((model) => model.id)
.join(',')}`,
- ).toBe(false);
+ ).toBe(true);
expect(listed(providerId).find((model) => model.id === newId)?.defaultEnabled).toBe(true);
}
expect(listed(api.id).find((model) => model.id === oldId)?.defaultEnabled).toBe(true);
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 96a665681a..c01e92d616 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -3,6 +3,7 @@ import { once } from 'node:events';
import { WebSocket, WebSocketServer } from 'ws';
import { createServer, request as httpRequest } from 'node:http';
import { Transform } from 'node:stream';
+import { gzipSync, brotliCompressSync } from 'node:zlib';
import type { AddressInfo } from 'node:net';
import os from 'node:os';
import path from 'node:path';
@@ -2705,7 +2706,7 @@ describe('codex proxy host', () => {
const requestScopedTransforms = proxyOpts.transformRequest.filter(
(transform) => transform.onRequestSettled,
);
- expect(requestScopedTransforms).toHaveLength(1);
+ expect(requestScopedTransforms).toHaveLength(2);
expect(requestScopedTransforms[0]?.errorMode).toBe('reject-request');
const strip = mockState.createAnthropicCompatProxy.mock.calls[0][0].transformRequest.at(-2);
const body = { model: 'gpt-5', input: [] };
@@ -3728,7 +3729,7 @@ describe('codex proxy host', () => {
// transforms; routing must therefore resolve the same parent-aware model.
await expect(Promise.resolve(routingTransform(rawGuardianBody, ctx))).resolves.toEqual({
upstreamOverride: 'https://api.x.ai/v1',
- headerOverride: { authorization: 'Bearer xai-review-token' },
+ headerOverride: { authorization: 'Bearer xai-review-token', 'accept-encoding': 'identity' },
headerDelete: ['chatgpt-account-id', 'openai-beta', 'originator', 'session_id'],
});
@@ -4394,8 +4395,12 @@ describe('codex proxy host', () => {
});
describe('xAI 服务端搜索工具(x_search)注入', () => {
- async function runXaiTransforms(sessionSuffix: string, body: Record<string, unknown>): Promise<unknown> {
+ async function runXaiTransforms(sessionSuffix: string, body: Record<string, unknown>, fastMembers?: string[] | null, expectedPrice?: 'standard' | 'priority'): Promise<unknown> {
const host = await freshCodexProxyHost();
+ if (fastMembers !== undefined) {
+ const { setXaiDiscoveredModels } = await import('../active-catalog.js');
+ setXaiDiscoveredModels(fastMembers?.map(id => ({ id: `xai/${id}`, contextWindow: 500000, nativeApi: 'openai-responses' })) ?? null);
+ }
const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
url: 'http://127.0.0.1:43210',
@@ -4408,16 +4413,118 @@ describe('codex proxy host', () => {
setSessionProvider(sessionId, 'xai');
const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];
- const ctx = { method: 'POST', url: '/responses', headers: { 'thread-id': threadId } };
+ const { registerUsagePricing, clearUsagePricing } = await import('../model-usage-pricing.js');
+ const resolvePrice = registerUsagePricing(sessionId);
+ const ctx = { reqId: 1, method: 'POST', url: '/responses', headers: { 'thread-id': threadId } };
let current: unknown = body;
for (const transform of transforms) {
const next = transform(current, ctx);
if (next !== null && next !== undefined) current = next;
}
+ if (expectedPrice) {
+ // Discovery changes after dispatch must not change the accepted execution price.
+ const { setXaiDiscoveredModels } = await import('../active-catalog.js');
+ setXaiDiscoveredModels(null);
+ const observer = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.responseObserver;
+ const sink = observer({ ...ctx, upstreamBase: 'https://api.x.ai/v1', status: 200,
+ requestHeaders: ctx.headers, responseHeaders: { 'content-type': 'text/event-stream' },
+ requestBody: Buffer.from(JSON.stringify(current)) });
+ sink?.onData?.(Buffer.from('data: ' + JSON.stringify({ type: 'response.completed',
+ response: { usage: { input_tokens: 30, output_tokens: 5, input_tokens_details: { cached_tokens: 10 } } },
+ }) + '\n\n'));
+ sink?.onEnd?.();
+ expect(resolvePrice({ threadId, inputTokens: 30, outputTokens: 5, cacheReadTokens: 10 })).toBe(expectedPrice);
+ }
+ clearUsagePricing(sessionId);
clearSessionProvider(sessionId);
return current;
}
+ it.each([
+ ['grok-4.7', 'priority', true, 'grok-4.7-build-fast', undefined],
+ ['grok-4.7', undefined, true, 'grok-4.7', undefined],
+ ['grok-4.7', 'priority', false, 'grok-4.7', undefined],
+ ['grok-4.7', 'priority', null, 'grok-4.7', undefined],
+ ['grok-4.6', 'priority', true, 'grok-4.6', undefined],
+ ['grok-4.7', 'default', false, 'grok-4.7', 'default'],
+ ] as const)('Fast mapping %s tier=%s available=%s', async (model, tier, available, expected, expectedTier) => {
+ const out = await runXaiTransforms('fast', { model: `xai/${model}`, input: [], service_tier: tier },
+ available === null ? null : ['grok-4.7', 'grok-4.6', ...(available ? ['grok-4.7-build-fast'] : [])],
+ expected === 'grok-4.7-build-fast' ? 'priority' : 'standard') as Record<string, unknown>;
+ expect(out.model).toBe(expected);
+ expect(out.service_tier).toBe(expectedTier);
+ });
+
+ it.each([
+ ['gzip', false], ['br', false], ['gzip', true], ['br', true],
+ ] as const)('negotiates uncompressed xAI usage when the client accepts %s (Fast available=%s)', async (encoding, available) => {
+ const host = await freshCodexProxyHost();
+ const { setXaiDiscoveredModels } = await import('../active-catalog.js');
+ const { registerUsagePricing, clearUsagePricing } = await import('../model-usage-pricing.js');
+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');
+ const { setProviderOAuthTokenReader } = await import('../provider-route.js');
+ const real = await vi.importActual<typeof import('@cindy/anthropic-compat-proxy')>('@cindy/anthropic-compat-proxy');
+ setXaiDiscoveredModels(['grok-4.7', ...(available ? ['grok-4.7-build-fast'] : [])]
+ .map(id => ({ id: `xai/${id}`, contextWindow: 500000, nativeApi: 'openai-responses' })));
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({ url: 'http://127.0.0.1:43210', dispose: vi.fn() });
+ await host.ensureCodexProxyReady();
+ const options = mockState.createAnthropicCompatProxy.mock.calls[0][0];
+ host.registerComposed('compression-session', 'compression-thread', 'PRODUCT_PROMPT');
+ host.setCodexProxyAuthInjection('env-key');
+ setSessionProvider('compression-session', 'xai');
+ setProviderOAuthTokenReader(() => 'fixture-xai-token');
+ const resolvePrice = registerUsagePricing('compression-session');
+ let acceptedEncoding: string | undefined;
+ let outboundModel: string | undefined;
+ const wire = 'data: ' + JSON.stringify({ type: 'response.completed', response: {
+ usage: { input_tokens: 30, output_tokens: 5, input_tokens_details: { cached_tokens: 10 } },
+ } }) + '\n\n';
+ const server = createServer(async (req, res) => {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
+ outboundModel = JSON.parse(Buffer.concat(chunks).toString()).model;
+ acceptedEncoding = req.headers['accept-encoding'];
+ const compress = acceptedEncoding !== 'identity';
+ res.writeHead(200, { 'content-type': 'text/event-stream', ...(compress ? { 'content-encoding': encoding } : {}) });
+ res.end(compress ? (encoding === 'gzip' ? gzipSync(wire) : brotliCompressSync(wire)) : wire);
+ });
+ server.listen(0, '127.0.0.1');
+ await once(server, 'listening');
+ const upstream = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+ const proxy = await real.createAnthropicCompatProxy({ upstream: () => upstream,
+ transformRequest: options.transformRequest, responseObserver: options.responseObserver,
+ routingTransform: async (body, ctx) => ({ ...(await options.routingTransform(body, ctx)), upstreamOverride: upstream }),
+ });
+ try {
+ const response = await fetch(`${proxy.url}/responses`, { method: 'POST',
+ headers: { 'content-type': 'application/json', 'thread-id': 'compression-thread', 'accept-encoding': encoding },
+ body: JSON.stringify({ model: 'xai/grok-4.7', service_tier: 'priority', input: [] }),
+ });
+ expect(response.status).toBe(200);
+ expect(await response.text()).toBe(wire);
+ expect(acceptedEncoding).toBe('identity');
+ expect(outboundModel).toBe(available ? 'grok-4.7-build-fast' : 'grok-4.7');
+ expect(resolvePrice({ threadId: 'compression-thread', inputTokens: 30, outputTokens: 5, cacheReadTokens: 10 }))
+ .toBe(available ? 'priority' : 'standard');
+ } finally {
+ await proxy.dispose();
+ server.closeAllConnections();
+ await new Promise<void>(resolve => server.close(() => resolve()));
+ clearUsagePricing('compression-session');
+ clearSessionProvider('compression-session');
+ setProviderOAuthTokenReader(() => null);
+ setXaiDiscoveredModels(null);
+ }
+ });
+
+ it('preserves priority when an xAI session sends a request through the default OpenAI route', async () => {
+ const out = await runXaiTransforms('fast-other-route', {
+ model: 'chatgpt/gpt-5.5', input: [], service_tier: 'priority',
+ }, null) as Record<string, unknown>;
+ expect(out.service_tier).toBe('priority');
+ expect(out.model).not.toContain('grok');
+ });
+
it('独立 xAI 账号(auth.native=xai、id 非 xai)的会话同样走 xAI 兼容改写:tool-less compact 不会带着 tool_choice 裸发(#4888)', async () => {
const host = await freshCodexProxyHost();
const { buildUserProvider } = await import('@cindy/model-providers');
diff --git a/apps/desktop/src/main/maker-host/__tests__/modelUsagePricing.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelUsagePricing.test.ts
new file mode 100644
index 0000000000..01966b344e
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/modelUsagePricing.test.ts
@@ -0,0 +1,43 @@
+import { afterEach, expect, it } from 'vitest';
+import { captureUsagePricing, clearUsagePricing, createUsagePricingObserver, registerUsagePricing } from '../model-usage-pricing.js';
+
+afterEach(() => clearUsagePricing('session'));
+const usage = { inputTokens: 30, outputTokens: 5, cacheReadTokens: 10 };
+const response = { usage: { input_tokens: 30, output_tokens: 5, input_tokens_details: { cached_tokens: 10 } } };
+
+it('matches completed requests by thread and usage, consumes once, and isolates runtime restarts', () => {
+ const resolve = registerUsagePricing('session');
+ const oldRequest = captureUsagePricing('session', 'priority', 'thread-1');
+ captureUsagePricing('session', 'standard', 'thread-2')(response);
+ oldRequest(response);
+ expect(resolve({ ...usage, threadId: 'unknown' })).toBeUndefined();
+ expect(resolve({ ...usage, threadId: 'thread-1', outputTokens: 6 })).toBeUndefined();
+ expect(resolve({ ...usage, threadId: 'thread-1' })).toBe('priority');
+ expect(resolve({ ...usage, threadId: 'thread-1' })).toBeUndefined();
+ expect(resolve({ ...usage, threadId: 'thread-2' })).toBe('standard');
+ clearUsagePricing('session');
+ const resumed = registerUsagePricing('session');
+ oldRequest(response);
+ expect(resumed({ ...usage, threadId: 'thread-1' })).toBeUndefined();
+});
+
+it.each(['application/json', 'text/event-stream'])('accepts split %s native responses and chat usage', contentType => {
+ const resolve = registerUsagePricing('session');
+ const sink = createUsagePricingObserver(contentType, captureUsagePricing('session', 'standard'));
+ const value = JSON.stringify({ choices: [], usage: { prompt_tokens: 30, completion_tokens: 5, prompt_tokens_details: { cached_tokens: 10 } } });
+ const wire = contentType === 'application/json' ? value : `data: ${value}\r\n\r\ndata: [DONE]\r\n\r\n`;
+ for (const byte of Buffer.from(wire)) sink.onData?.(Buffer.from([byte]));
+ sink.onEnd?.();
+ expect(resolve(usage)).toBe('standard');
+ expect(resolve(usage)).toBeUndefined();
+});
+
+it('keeps final usage after oversized or malformed SSE content without retaining response text', () => {
+ const resolve = registerUsagePricing('session');
+ const sink = createUsagePricingObserver('text/event-stream', captureUsagePricing('session', 'priority'));
+ sink.onData?.(Buffer.from('data: ' + 'x'.repeat(1024 * 1024 + 1)));
+ sink.onData?.(Buffer.from('\n\ndata: {broken "usage"\n\n'));
+ sink.onData?.(Buffer.from('data: ' + JSON.stringify({ type: 'response.completed', response }) + '\n\n'));
+ sink.onEnd?.();
+ expect(resolve(usage)).toBe('priority');
+});
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
index a4422f2c5f..b67885544a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -2616,6 +2616,29 @@ describe('buildPiNativeProvidersFromConfigs', () => {
describe('server metadata reaches every native Pi transport', () => {
+ it('turns the API sync artifact into a native Pi model without an SDK model entry', async () => {
+ const { buildXaiSyncCandidate, inspectXaiImport } = await import('../../../../../../tools/model-catalog/xai-sync.js');
+ const candidate = buildXaiSyncCandidate(BUNDLED_CATALOG, { data: [{
+ id: 'grok-future-api-fixture', name: 'Future model', api_backend: 'responses',
+ context_window: 600_000, max_completion_tokens: 80_000,
+ reasoning_efforts: ['high', 'low'], reasoning_effort: 'high',
+ }] }, { models: [{ id: 'grok-future-api-fixture', input_modalities: ['text'], output_modalities: ['text'],
+ prompt_text_token_price: 20_000, completion_text_token_price: 60_000,
+ }] }, '2026-09-24T12:00:00.000Z');
+ inspectXaiImport(candidate);
+ try {
+ const result = buildPiSubscriptionNativeProviders(getActiveCatalog(), 'http://127.0.0.1:4567',
+ new Map([['xai', new Map()]]));
+ expect(result.providers.find(p => p.id === 'xai')!.models.find(m => m.id === 'grok-future-api-fixture'))
+ .toMatchObject({ wireId: 'grok-future-api-fixture', api: 'openai-responses',
+ contextWindow: 600_000, maxTokens: 80_000, input: ['text'], reasoning: true,
+ thinkingLevelMap: { low: 'low', high: 'high', medium: null } });
+ } finally {
+ setXaiDiscoveredModels(null);
+ setActiveCatalog(BUNDLED_CATALOG);
+ }
+ });
+
it.each(['discovery', 'user-addition'] as const)('carries a new Grok model from %s into local and SSH Pi routes', async (source) => {
setActiveCatalog(BUNDLED_CATALOG);
const addition = {
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
index 5c7bc7d689..c3dfc23440 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@ -41,6 +41,9 @@ import {
getPiNativeSubscriptionHandler,
type PiNativeSubscriptionHandlerDeps,
} from '../anthropic-responses-bridge-host.js';
+import { setXaiDiscoveredModels } from '../active-catalog.js';
+import { registerUsagePricing, clearUsagePricing } from '../model-usage-pricing.js';
+import { setSessionFastMode } from '../session-effort-store.js';
function responseRecorder() {
const response = new EventEmitter() as EventEmitter & {
@@ -91,10 +94,54 @@ function deps(overrides: Partial<PiNativeSubscriptionHandlerDeps> = {}): PiNativ
describe('PI native subscription forwarding', () => {
afterEach(() => {
+ setXaiDiscoveredModels(null);
+ setSessionFastMode('session-fast', false);
+ clearUsagePricing('session-fast');
ownerState.pending = false;
ownerState.scope = 'cloud:owner-a:1';
});
+ it.each([['grok-4.7', true, 'grok-4.7-build-fast'], ['grok-4.7', false, 'grok-4.7'],
+ ['grok-4.6', true, 'grok-4.6']] as const)('forwards %s Fast=%s to %s', async (model, fast, expected) => {
+ setXaiDiscoveredModels(['grok-4.7', 'grok-4.7-build-fast', 'grok-4.6'].map(id => ({
+ id: `xai/${id}`, contextWindow: 500000, nativeApi: 'openai-responses',
+ })));
+ setSessionFastMode('session-fast', fast);
+ const injected = deps();
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-fast', injected);
+ const parsedBody = { model, input: 'OK' };
+ await handler({ rawBody: Buffer.from(JSON.stringify(parsedBody)), parsedBody,
+ ctx: { reqId: 1, method: 'POST', url: '/v1/responses', headers: {} }, res: responseRecorder() } as never);
+ const request = JSON.parse(Buffer.from(vi.mocked(injected.fetch).mock.calls[0][1]!.body as Uint8Array).toString());
+ expect(request.model).toBe(expected);
+ expect(request.service_tier).toBeUndefined();
+ });
+
+ it.each([true, false, null])('prices the actual native execution when Fast availability is %s', async available => {
+ setXaiDiscoveredModels(available === null ? null : ['grok-4.7', ...(available ? ['grok-4.7-build-fast'] : [])]
+ .map(id => ({ id: `xai/${id}`, contextWindow: 500000, nativeApi: 'openai-responses' })));
+ setSessionFastMode('session-fast', true);
+ const resolvePrice = registerUsagePricing('session-fast');
+ const wire = 'data: ' + JSON.stringify({ type: 'response.completed', response: {
+ usage: { input_tokens: 30, output_tokens: 5, input_tokens_details: { cached_tokens: 10 } },
+ } }) + '\n\n';
+ const injected = deps({ fetch: vi.fn(async () => {
+ setXaiDiscoveredModels(null);
+ setSessionFastMode('session-fast', false);
+ return new Response(wire, { headers: { 'content-type': 'text/event-stream' } });
+ }) });
+ const parsedBody = { model: 'grok-4.7', input: 'OK' };
+ const res = responseRecorder();
+ await getPiNativeSubscriptionHandler('xai', 'session-fast', injected)({
+ rawBody: Buffer.from(JSON.stringify(parsedBody)), parsedBody,
+ ctx: { reqId: 1, method: 'POST', url: '/v1/responses', headers: {} }, res,
+ } as never);
+ const request = JSON.parse(Buffer.from(vi.mocked(injected.fetch).mock.calls[0][1]!.body as Uint8Array).toString());
+ expect(request.model).toBe(available ? 'grok-4.7-build-fast' : 'grok-4.7');
+ expect(Buffer.concat(res.chunks).toString()).toBe(wire);
+ expect(resolvePrice({ inputTokens: 30, outputTokens: 5, cacheReadTokens: 10 })).toBe(available ? 'priority' : 'standard');
+ });
+
it('forwards Codex Responses bytes unchanged with host-owned ChatGPT auth', async () => {
const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {
status: 200,
diff --git a/apps/desktop/src/main/maker-host/__tests__/xaiSyncImport.test.ts b/apps/desktop/src/main/maker-host/__tests__/xaiSyncImport.test.ts
new file mode 100644
index 0000000000..1143371949
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/xaiSyncImport.test.ts
@@ -0,0 +1,300 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import { BUNDLED_CATALOG, buildUserProvider, parseCatalog } from '@cindy/model-providers';
+import { buildXaiSyncCandidate, inspectXaiImport } from '../../../../../../tools/model-catalog/xai-sync.js';
+import { getActiveCatalog, setActiveCatalog, setCustomProviders, setLocalCatalogOverrides, setXaiDiscoveredModels } from '../active-catalog.js';
+import { fastModelId } from '../model-fast-mode.js';
+import { EMPTY_MODEL_CATALOG_OVERRIDES, sanitizeModelCatalogOverrides } from '../model-plane/localCatalogOverrides.js';
+import { parseCachedXaiModels, parseXaiAccountModels } from '../model-discovery/xai-models.js';
+
+const observedAt = '2026-09-24T12:00:00.000Z';
+// The API shape is real; this deliberately unseen ID guards against per-model branches.
+const account = { data: [{ id: 'grok-4.8', name: 'Grok 4.8', context_window: 600_000,
+ api_backend: 'responses', reasoning_efforts: ['xhigh', 'high', 'medium', 'low'], reasoning_effort: 'high' }] };
+const details = { models: [{ id: 'grok-4.8', input_modalities: ['text', 'image'], output_modalities: ['text'],
+ prompt_text_token_price: 20_000, completion_text_token_price: 60_000, cached_prompt_text_token_price: 5_000,
+ long_context_threshold: 200_000, prompt_text_token_price_long_context: 40_000,
+ completion_text_token_price_long_context: 120_000, cached_prompt_text_token_price_long_context: 10_000,
+ capabilities: { reasoning_effort: ['low', 'medium', 'high', 'xhigh'], default_reasoning_effort: 'high' } }] };
+const build = (a: unknown = account, d: unknown = details) => buildXaiSyncCandidate(BUNDLED_CATALOG, a, d, observedAt);
+afterEach(() => {
+ setXaiDiscoveredModels(null);
+ setXaiDiscoveredModels(null, 'grok-work');
+ setCustomProviders([]);
+ setLocalCatalogOverrides(EMPTY_MODEL_CATALOG_OVERRIDES);
+ setActiveCatalog(BUNDLED_CATALOG);
+});
+
+describe('xAI API sync through the actual picker import', () => {
+ it('keeps Fast targets default-off when the loaded server catalog predates the client mapping', () => {
+ const oldCatalog = structuredClone(BUNDLED_CATALOG);
+ const fastId = 'xai/grok-4.7-build-fast';
+ oldCatalog.modelRegistry!.models = oldCatalog.modelRegistry!.models.filter(m => m.id !== fastId);
+ oldCatalog.modelRegistry!.baseModels = oldCatalog.modelRegistry!.baseModels!.filter(m => m.id !== fastId);
+ const xai = oldCatalog.providers.find(p => p.id === 'xai')!;
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ xai.models[agent] = xai.models[agent]!.filter(m => !m.id.endsWith('grok-4.7-build-fast'));
+ for (const model of xai.models[agent]!) delete model.fastModelId;
+ }
+ setActiveCatalog(oldCatalog);
+ setCustomProviders([buildUserProvider({ id: 'grok-work', name: 'Work',
+ auth: { method: 'oauth', native: 'xai' }, runtimes: {} })]);
+ const members = ['xai/grok-4.7', fastId, 'xai/grok-new-fixture'].map(id => ({
+ id, contextWindow: 500_000, nativeApi: 'openai-responses' as const,
+ }));
+ setXaiDiscoveredModels(members);
+ setXaiDiscoveredModels(members, 'grok-work');
+ for (const providerId of ['xai', 'grok-work']) {
+ const provider = getActiveCatalog().providers.find(p => p.id === providerId)!;
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ const parentId = agent === 'pi' ? 'grok-4.7' : 'xai/grok-4.7';
+ expect(provider.models[agent]!.find(m => m.id.endsWith('grok-4.7-build-fast'))?.defaultEnabled).toBe(false);
+ expect(fastModelId(providerId, agent, parentId)).toBe(agent === 'pi' ? 'grok-4.7-build-fast' : fastId);
+ }
+ expect(provider.models.codex!.find(m => m.id === 'xai/grok-new-fixture')?.defaultEnabled).toBe(true);
+ }
+ const updatedCatalog = structuredClone(oldCatalog);
+ updatedCatalog.providers.find(p => p.id === 'xai')!.models.codex!.push({
+ id: fastId, name: 'Grok 4.7 Fast', contextWindow: 500_000,
+ efforts: [], defaultEffort: null, defaultEnabled: true,
+ });
+ setActiveCatalog(updatedCatalog);
+ expect(getActiveCatalog().providers.find(p => p.id === 'xai')!.models.codex!
+ .find(m => m.id === fastId)?.defaultEnabled).toBe(true);
+ });
+
+ it.each(['catalog', 'local override'] as const)('rejects stale Fast capability without an execution mapping from %s', source => {
+ const catalog = structuredClone(BUNDLED_CATALOG);
+ const xai = catalog.providers.find(p => p.id === 'xai')!;
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ // Older server catalogs also lack the valid 4.7 mapping; bundled fallback must still work.
+ for (const model of xai.models[agent]!) {
+ delete model.fastModelId;
+ if (source === 'catalog' && model.id.endsWith('grok-4.6')) model.supportsFastMode = true;
+ }
+ }
+ setActiveCatalog(catalog);
+ setCustomProviders([buildUserProvider({ id: 'grok-work', name: 'Work',
+ auth: { method: 'oauth', native: 'xai' }, runtimes: {} })]);
+ const members = ['xai/grok-4.6', 'xai/grok-4.7', 'xai/grok-4.7-build-fast'].map(id => ({
+ id, contextWindow: 500_000, nativeApi: 'openai-responses' as const,
+ }));
+ for (const providerId of ['xai', 'grok-work']) setXaiDiscoveredModels(members, providerId);
+ if (source === 'local override') {
+ const patches = Object.fromEntries(['xai', 'grok-work'].flatMap(providerId =>
+ ['xai/grok-4.6', 'grok-4.6'].map(id => [`${providerId}:${id}`, { base: { supportsFastMode: true } }])));
+ setLocalCatalogOverrides(sanitizeModelCatalogOverrides({ version: 1, patches }).overrides);
+ }
+ for (const providerId of ['xai', 'grok-work']) {
+ const provider = getActiveCatalog().providers.find(p => p.id === providerId)!;
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ const prefix = agent === 'pi' ? '' : 'xai/';
+ expect(provider.models[agent]!.find(m => m.id === `${prefix}grok-4.6`)!.supportsFastMode, `${providerId}/${agent}`).not.toBe(true);
+ expect(fastModelId(providerId, agent, `${prefix}grok-4.6`)).toBeUndefined();
+ expect(fastModelId(providerId, agent, `${prefix}grok-4.7`)).toBe(`${prefix}grok-4.7-build-fast`);
+ }
+ }
+ });
+
+ it('never borrows Fast availability from another subscription account', () => {
+ setActiveCatalog(BUNDLED_CATALOG);
+ setCustomProviders([buildUserProvider({ id: 'grok-work', name: 'Work',
+ auth: { method: 'oauth', native: 'xai' }, runtimes: {} })]);
+ const ordinary = { id: 'xai/grok-4.7', contextWindow: 500000 };
+ const fast = { id: 'xai/grok-4.7-build-fast', contextWindow: 500000 };
+ setXaiDiscoveredModels([ordinary, fast]);
+ setXaiDiscoveredModels([ordinary], 'grok-work');
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ const id = agent === 'pi' ? 'grok-4.7' : ordinary.id;
+ expect(fastModelId('xai', agent, id)).toBe(agent === 'pi' ? 'grok-4.7-build-fast' : fast.id);
+ expect(fastModelId('grok-work', agent, id)).toBeUndefined();
+ expect(fastModelId('custom-api-key', agent, id)).toBeUndefined();
+ }
+ setXaiDiscoveredModels([ordinary, fast], 'grok-work');
+ expect(fastModelId('grok-work', 'codex', ordinary.id)).toBe(fast.id);
+ });
+
+ it('imports verified 4.7 Fast execution and exact tariffs without giving 4.6 a Fast mapping', () => {
+ const members = ['grok-4.7', 'grok-4.7-build-fast', 'grok-4.6'].map(id => ({ ...account.data[0], id, name: id }));
+ const candidate = build({ data: members }, { models: ['grok-4.7', 'grok-4.6'].map(id => ({ ...details.models[0], id })) });
+ // Old readers ignore fastModelId; the serialized artifact must not make them send priority.
+ for (const models of Object.values(candidate.catalog.providers.find(p => p.id === 'xai')!.models)) {
+ expect(models!.find(m => m.id === 'grok-4.7' || m.id === 'xai/grok-4.7')!.supportsFastMode).not.toBe(true);
+ }
+ const report = inspectXaiImport(candidate);
+ const parent = report.rows.find(r => r.modelId === 'xai/grok-4.7')!;
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ expect(parent.harnesses[agent].supportsFastMode).toBe(true);
+ expect(parent.harnesses[agent].apiReferencePrice?.priority).toMatchObject({
+ inputPerMtok: 4, outputPerMtok: 12, cacheReadPerMtok: 1,
+ inputTokenPriceBands: [
+ { minInputTokens: 0, maxInputTokens: 200001, inputPerMtok: 4 },
+ { minInputTokens: 200001, inputPerMtok: 6, outputPerMtok: 18, cacheReadPerMtok: 1.5 },
+ ],
+ });
+ const direct = report.rows.find(r => r.modelId.endsWith('build-fast'))!.harnesses[agent];
+ expect(direct.defaultEnabled).toBe(false);
+ expect(direct.apiReferencePrice).toMatchObject({ inputPerMtok: 4, outputPerMtok: 12 });
+ expect(report.rows.find(r => r.modelId === 'xai/grok-4.6')!.harnesses[agent].supportsFastMode).not.toBe(true);
+ }
+ setXaiDiscoveredModels(parseXaiAccountModels({ data: members.filter(m => !m.id.endsWith('build-fast')) }));
+ for (const models of Object.values(getActiveCatalog().providers.find(p => p.id === 'xai')!.models)) {
+ expect(models!.find(m => m.id.endsWith('/grok-4.7') || m.id === 'grok-4.7')!.supportsFastMode).toBe(false);
+ }
+ });
+ it('imports an unseen API model into all harnesses with ascending efforts, native defaults and banded prices', () => {
+ const before = JSON.stringify(BUNDLED_CATALOG);
+ const candidate = build();
+ expect(() => parseCatalog(JSON.stringify(candidate.catalog))).not.toThrow();
+ const report = inspectXaiImport(candidate);
+ expect(report.harnessProjections).toBe(3);
+ const { harnesses } = report.rows[0];
+ for (const agent of ['claude-code', 'codex', 'pi'] as const) {
+ expect(harnesses[agent]).toMatchObject({
+ id: agent === 'pi' ? 'grok-4.8' : 'xai/grok-4.8',
+ contextWindow: 600_000, supportsImageInput: true,
+ efforts: ['low', 'medium', 'high', 'xhigh'], defaultEffort: 'high',
+ apiReferencePrice: { inputPerMtok: 2, outputPerMtok: 6, cacheReadPerMtok: 0.5,
+ inputTokenPriceBands: [
+ { minInputTokens: 0, maxInputTokens: 200_000, inputPerMtok: 2 },
+ { minInputTokens: 200_000, inputPerMtok: 4, outputPerMtok: 12, cacheReadPerMtok: 1 },
+ ] },
+ });
+ expect(harnesses[agent].defaultEnabled).toBe(agent !== 'claude-code');
+ }
+ expect(JSON.stringify(BUNDLED_CATALOG)).toBe(before);
+ expect(report.complete).toBe(false);
+ expect(report.gaps[0].fields).toEqual(['apiMaxOutput', 'fastExecution']);
+ });
+
+ it('preserves explicit catalog opt-outs while enabling a new native variant', () => {
+ const candidate = build();
+ const provider = candidate.catalog.providers.find(p => p.id === 'xai')!;
+ provider.models.pi!.find(m => m.id === 'grok-4.8')!.defaultEnabled = false;
+ const again = buildXaiSyncCandidate(candidate.catalog, account, details, '2026-09-25T12:00:00.000Z');
+ expect(inspectXaiImport(again).rows[0].harnesses.pi.defaultEnabled).toBe(false);
+ });
+
+ it('keeps curated effort intent and per-harness opt-outs ahead of API recommendations', () => {
+ const first = build();
+ const entry = first.catalog.modelRegistry!.models.find(m => m.id === 'xai/grok-4.8')!;
+ entry.routes[0].defaults!.defaultEffort = 'low';
+ entry.perAgent!.codex!.defaultEnabled = false;
+ const next = buildXaiSyncCandidate(first.catalog, account, details, '2026-09-25T12:00:00.000Z');
+ const row = inspectXaiImport(next).rows[0].harnesses.codex;
+ expect(row.defaultEffort).toBe('low');
+ expect(row.defaultEnabled).toBe(false);
+ });
+
+ it('does not infer capabilities or prices from a Fast suffix, description, or adjacent model', () => {
+ const candidate = build({ data: [...account.data, { ...account.data[0], id: 'grok-4.8-build-fast',
+ name: 'Grok 4.8 Fast', description: 'Fast variant. 2x the price.' }] });
+ const report = inspectXaiImport(candidate);
+ const fast = report.rows.find(row => row.modelId.endsWith('build-fast'))!;
+ for (const row of Object.values(fast.harnesses)) {
+ expect(row.supportsFastMode).toBeUndefined();
+ expect(row.supportsImageInput).toBeUndefined();
+ expect(row.apiReferencePrice).toBeNull();
+ expect(row.defaultEnabled).toBe(row.protocol?.mode === 'matching');
+ }
+ expect(report.gaps.find(g => g.modelId === fast.modelId)?.fields).toContain('apiReferencePrice');
+ });
+
+ it('does not add account-inaccessible detail models and rejects ambiguous aliases', () => {
+ const candidate = build(account, { models: [...details.models, { ...details.models[0], id: 'not-in-account' }] });
+ expect(inspectXaiImport(candidate).rows.map(r => r.modelId)).toEqual(['xai/grok-4.8']);
+ expect(() => build(account, { models: ['one', 'two'].map(id => ({ ...details.models[0], id, aliases: ['grok-4.8'] })) })).toThrow('Ambiguous');
+ });
+
+ it('honors zero long-context fallback and explicit text-only input', () => {
+ const candidate = build(account, { models: [{ ...details.models[0], input_modalities: ['text'],
+ prompt_text_token_price_long_context: 0, completion_text_token_price_long_context: 0,
+ cached_prompt_text_token_price_long_context: 0 }] });
+ const row = inspectXaiImport(candidate).rows[0].harnesses.pi;
+ expect(row.supportsImageInput).toBe(false);
+ expect(row.apiReferencePrice?.inputTokenPriceBands?.[1]).toMatchObject({ inputPerMtok: 2, outputPerMtok: 6, cacheReadPerMtok: 0.5 });
+ });
+
+ it('preserves known tariff history and all unrelated catalog data on repeat synchronization', () => {
+ const first = build();
+ const next = buildXaiSyncCandidate(first.catalog, account, details, '2026-09-25T12:00:00.000Z');
+ const prices = next.catalog.modelRegistry!.baseModels!.find(b => b.id === 'xai/grok-4.8')!.referencePriceGroups![0].prices;
+ expect(prices).toHaveLength(2);
+ expect(prices[0].effectiveFrom).toBe('2026-09-24');
+ expect(prices[0].source.verifiedAt).toBe('2026-09-25');
+ expect(next.catalog.presets).toEqual(BUNDLED_CATALOG.presets);
+ expect(next.catalog.providers.filter(p => p.id !== 'xai')).toEqual(BUNDLED_CATALOG.providers.filter(p => p.id !== 'xai'));
+ const changed = buildXaiSyncCandidate(next.catalog, account,
+ { models: [{ ...details.models[0], prompt_text_token_price: 30_000 }] }, '2026-09-26T12:00:00.000Z');
+ const history = changed.catalog.modelRegistry!.baseModels!.find(b => b.id === 'xai/grok-4.8')!.referencePriceGroups![0].prices;
+ expect(history).toHaveLength(4);
+ expect(history[0].effectiveUntil).toBe('2026-09-26');
+ expect(history[2].inputPerMtok).toBe(3);
+ });
+
+ it('preserves verified cache prices on sparse updates and reports missing API cache fields', () => {
+ const first = build();
+ const sparse = { ...details.models[0], prompt_text_token_price: 30_000,
+ cached_prompt_text_token_price: undefined, cached_prompt_text_token_price_long_context: undefined };
+ const candidate = buildXaiSyncCandidate(first.catalog, account, { models: [sparse] }, '2026-09-25T12:00:00.000Z');
+ const prices = candidate.catalog.modelRegistry!.baseModels!.find(b => b.id === 'xai/grok-4.8')!.referencePriceGroups![0].prices;
+ expect(prices).toHaveLength(4);
+ expect(prices[0].effectiveUntil).toBe('2026-09-25');
+ expect(prices[2]).toMatchObject({ inputPerMtok: 3, cacheReadPerMtok: 0.5,
+ source: { verifiedAt: '2026-09-24' } });
+ expect(prices[3].cacheReadPerMtok).toBe(1);
+ const report = inspectXaiImport(candidate);
+ expect(report.gaps[0].fields).toContain('apiCacheReadPrice');
+ expect(report.evidence[0].fieldsFromCatalog).toContain('cacheReadReferencePrice');
+ expect(report.rows[0].harnesses.codex.apiReferencePrice?.cacheReadPerMtok).toBe(0.5);
+
+ const unknown = build(account, { models: [sparse] });
+ expect(unknown.gaps[0].fields).toContain('apiCacheReadPrice');
+ expect(unknown.evidence[0].fieldsFromCatalog).not.toContain('cacheReadReferencePrice');
+ expect(inspectXaiImport(unknown).rows[0].harnesses.codex.apiReferencePrice?.cacheReadPerMtok).toBeUndefined();
+
+ const zero = buildXaiSyncCandidate(first.catalog, account, { models: [{ ...sparse,
+ cached_prompt_text_token_price: 0, cached_prompt_text_token_price_long_context: 0 }] }, '2026-09-25T12:00:00.000Z');
+ expect(zero.gaps[0].fields).not.toContain('apiCacheReadPrice');
+ expect(inspectXaiImport(zero).rows[0].harnesses.codex.apiReferencePrice?.cacheReadPerMtok).toBe(0);
+ });
+
+ it.each([
+ ['all cache prices missing', undefined],
+ ['only long-context cache price missing', 5_000],
+ ] as const)('keeps serialized repeat sync stable with %s', (_case, standardCache) => {
+ const sparseDetails = JSON.parse(JSON.stringify({ models: [{ ...details.models[0],
+ cached_prompt_text_token_price: standardCache,
+ cached_prompt_text_token_price_long_context: undefined }] }));
+ let candidate = build(account, sparseDetails);
+ for (const at of ['2026-09-24T18:00:00.000Z', '2026-09-25T12:00:00.000Z']) {
+ const savedCatalog = parseCatalog(JSON.stringify(candidate.catalog));
+ candidate = buildXaiSyncCandidate(savedCatalog, account, sparseDetails, at);
+ const prices = candidate.catalog.modelRegistry!.baseModels!.find(b => b.id === 'xai/grok-4.8')!.referencePriceGroups![0].prices;
+ expect(prices).toHaveLength(2);
+ expect(prices.every(p => p.effectiveFrom === '2026-09-24' && p.effectiveUntil === undefined)).toBe(true);
+ expect(prices[0].cacheReadPerMtok).toBe(standardCache === undefined ? undefined : 0.5);
+ expect(prices[1]).not.toHaveProperty('cacheReadPerMtok');
+ expect(candidate.gaps[0].fields).toContain('apiCacheReadPrice');
+ }
+ });
+
+ it('keeps user capability overrides after import and serializes discovery backend through the old cache envelope', () => {
+ const parsed = parseXaiAccountModels(account);
+ expect(parseCachedXaiModels(JSON.parse(JSON.stringify({ models: parsed })))).toEqual(parsed);
+ const candidate = build();
+ setLocalCatalogOverrides(sanitizeModelCatalogOverrides({ version: 1, patches: {
+ 'xai:xai/grok-4.8': { base: { contextWindow: 300_000, supportsImageInput: false } },
+ } }).overrides);
+ inspectXaiImport(candidate);
+ const rows = getActiveCatalog().providers.find(p => p.id === 'xai')!.models;
+ expect(rows.codex!.find(m => m.id === 'xai/grok-4.8')).toMatchObject({ contextWindow: 300_000, supportsImageInput: false });
+ });
+
+ it('rejects unusable input before producing any replacement', () => {
+ expect(() => build({ data: [] })).toThrow('Empty account');
+ expect(() => build({ data: [{ ...account.data[0], api_backend: 'future-protocol' }] })).toThrow('Unsupported');
+ expect(() => build(account, { error: 'unauthorized' })).toThrow('Invalid or empty');
+ expect(() => build({ data: [{ id: 'new-model' }] })).toThrow('Unknown context');
+ expect(() => build(account, { models: [details.models[0], details.models[0]] })).toThrow('Duplicate');
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index d582154fa1..1c0617ba11 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -145,16 +145,8 @@ const discoveredByProvider = new Map<string, Partial<Record<AgentKind, CatalogMo
* `[]` = 本次发现没有条目,不抹除公共声明。成员保存为 canonical `xai/grok-*`,
* 补充 Claude/Codex 公共声明;Pi 消费显式的逐 Harness 声明。遗漏不构成禁止。
*/
-export interface XaiDiscoveredModel {
- id: string;
- name?: string;
- description?: string;
- contextWindow?: number;
- contextWindowVerified?: boolean;
- maxOutput?: number;
- efforts?: CatalogModel['efforts'];
- defaultEffort?: CatalogModel['defaultEffort'];
-}
+export type { XaiDiscoveredModel } from './model-discovery/xai-models.js';
+import type { XaiDiscoveredModel } from './model-discovery/xai-models.js';
let xaiDiscoveredModels: XaiDiscoveredModel[] | null = null;
const xaiAccountModels = new Map<string, XaiDiscoveredModel[]>();
@@ -924,6 +916,12 @@ function materializeXaiAccountModels(
return discovered.map((entry, index) => {
const catalogModel = xaiCatalogModelById(provider, entry.id, agent);
const registry = modelRegistryMetaFields('xai', agent, entry.id);
+ // The server catalog may predate a client-known variant. Its bundled visibility
+ // remains a sparse fallback; explicit server and later user choices still win.
+ const bundledEntry = findModelRegistryRoute(BUNDLED_CATALOG.modelRegistry, 'xai', entry.id,
+ agent === 'pi' ? undefined : agent)?.entry;
+ const bundledDefaultEnabled = (agent === 'pi' ? undefined : bundledEntry?.perAgent?.[agent]?.defaultEnabled)
+ ?? bundledEntry?.defaultEnabled;
const { efforts, defaultEffort } = resolveXaiAccountCapabilities(
entry,
registry?.efforts ?? catalogModel?.efforts,
@@ -938,6 +936,7 @@ function materializeXaiAccountModels(
: registry?.contextWindow !== undefined || catalogModel?.contextWindowVerified === true;
return {
...catalogModel,
+ ...(entry.nativeApi !== undefined ? { nativeApi: entry.nativeApi } : {}),
discoveredMetadata: {
...catalogModelMetadata(entry),
...(entry.efforts ? { efforts: canonicalEffortOrder(entry.efforts) } : {}),
@@ -966,7 +965,7 @@ function materializeXaiAccountModels(
? { supportsFastMode: registry.supportsFastMode }
: {}),
status: registry?.status ?? catalogModel?.status ?? 'active',
- defaultEnabled: registry?.defaultEnabled ?? catalogModel?.defaultEnabled ?? true,
+ defaultEnabled: registry?.defaultEnabled ?? catalogModel?.defaultEnabled ?? bundledDefaultEnabled ?? true,
};
});
}
@@ -1613,6 +1612,9 @@ function computeMerged(): Catalog {
// chatgpt/ aliases never hide their sibling Codex route. Explicit user visibility stays external.
providers = providers.map((provider) => {
const catalogId = providerCatalogId(provider);
+ // xAI's catalog owns per-harness visibility. Re-ranking account discovery here
+ // silently hid newly synced native models (including separately callable variants).
+ if (catalogId === 'xai') return provider;
if (!isOpenAiSubscriptionProvider(provider) &&
((provider.source === 'user' && !provider.auth.native) || !['anthropic', 'xai'].includes(catalogId)))
return provider;
@@ -1814,6 +1816,26 @@ function computeMerged(): Catalog {
imageDefaults: provider.imageDefaults ? { standard: id } : undefined,
};
});
+ // Execution mappings are provider data, not a guess based on a model's name.
+ // Gate after every overlay so a preference cannot claim a target absent from this account.
+ providers = providers.map(provider => {
+ if (providerCatalogId(provider) !== 'xai' || provider.auth.method !== 'oauth') return provider;
+ const members = provider.id === 'xai' ? xaiDiscoveredModels : xaiAccountModels.get(provider.id);
+ const available = new Set(members?.map(m => m.id.replace(/^xai\//, '')) ?? []);
+ return { ...provider, models: Object.fromEntries(Object.entries(provider.models).map(([agent, models]) => [
+ agent, models?.map(model => {
+ const fallback = bundledXai?.models[agent as AgentKind]?.find(m => m.id === model.id);
+ const target = model.fastModelId === undefined ? fallback?.fastModelId : model.fastModelId;
+ if (target === undefined) {
+ return model.supportsFastMode === true ? { ...model, supportsFastMode: false } : model;
+ }
+ return { ...model, fastModelId: target,
+ supportsFastMode: model.supportsFastMode !== false && Boolean(target &&
+ available.has(target.replace(/^xai\//, '')) &&
+ models.some(m => m.id === target && m.status !== 'retired')) };
+ }),
+ ])) };
+ });
return { ...b, modelRegistry, providers };
}
diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index 5e95c7c1b0..c953f2fa5e 100644
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@ -1,3 +1,7 @@
+import { fastModelId, rewriteFastModel } from './model-fast-mode.js';
+import { captureUsagePricing, createUsagePricingObserver } from './model-usage-pricing.js';
+import type { ResponseObserverSink } from '@cindy/anthropic-compat-proxy';
+import { getSessionFastMode } from './session-effort-store.js';
import { isXaiSubscriptionProviderId } from './subscription-account-auth.js';
/**
* Desktop 端 anthropic-responses-bridge 装配 ——
@@ -336,6 +340,7 @@ function codexProviderConfig(providerId = 'openai'): BridgeProviderConfig {
/** xAI(SuperGrok 订阅)provider 配置:xai/ 前缀 → api.x.ai/v1,注入 Grok OAuth Bearer。 */
function xaiProviderConfig(providerId = 'xai'): BridgeProviderConfig {
return {
+ fastModel: model => fastModelId(providerId, 'claude-code', `xai/${model}`)?.replace(/^xai\//, ''),
prefix: XAI_MODEL_PREFIX,
wireProtocol: 'openai-responses',
upstreamBase: 'https://api.x.ai/v1',
@@ -695,7 +700,7 @@ function withNativeXaiServerSideTools(
return toolsChanged ? next : null;
}
-async function pipeNativeResponse(response: Response, res: Parameters<LocalRequestHandler>[0]['res']): Promise<void> {
+async function pipeNativeResponse(response: Response, res: Parameters<LocalRequestHandler>[0]['res'], observer?: ResponseObserverSink): Promise<void> {
res.writeHead(response.status, nativeResponseHeaders(response));
if (!response.body) {
res.end();
@@ -705,7 +710,8 @@ async function pipeNativeResponse(response: Response, res: Parameters<LocalReque
try {
while (!res.destroyed) {
const chunk = await reader.read();
- if (chunk.done) break;
+ if (chunk.done) { observer?.onEnd?.(); break; }
+ observer?.onData?.(Buffer.from(chunk.value));
if (!res.write(Buffer.from(chunk.value))) {
await new Promise<void>((resolve) => {
const done = (): void => {
@@ -746,6 +752,7 @@ export function getPiNativeSubscriptionHandler(
const abortOnClose = (): void => controller.abort();
res.once('close', abortOnClose);
const scopeAtStart = activeOwnerScopeKey();
+ const fastAtStart = getSessionFastMode(sessionId);
try {
throwIfOwnerBoundDispatchUnsafe(scopeAtStart);
let accessToken: string;
@@ -764,6 +771,7 @@ export function getPiNativeSubscriptionHandler(
}
headers['content-type'] = ctx.headers['content-type'] ?? 'application/json';
headers.accept = ctx.headers.accept ?? 'text/event-stream';
+ let recordUsage: ReturnType<typeof captureUsagePricing> | undefined;
let outboundBody = rawBody;
let contentEncoding: string | undefined = ctx.headers['content-encoding'];
if (isOpenAiSubscriptionProviderId(providerId)) {
@@ -781,11 +789,14 @@ export function getPiNativeSubscriptionHandler(
? parsedBody
: parseJsonRecord(rawBody);
const sanitized = parsed ? sanitizeXaiModelInputBody(parsed) : null;
- const current = sanitized ?? parsed;
+ const withFast = parsed ? rewriteFastModel(providerId, 'pi', sanitized ?? parsed, fastAtStart) : null;
+ const current = withFast ?? sanitized ?? parsed;
+ recordUsage = captureUsagePricing(sessionId,
+ withFast && withFast.model !== parsed?.model ? 'priority' : 'standard');
const withServerTools = current
? withNativeXaiServerSideTools(current, upstream.wireProtocol)
: null;
- if (sanitized || withServerTools) {
+ if (sanitized || withFast || withServerTools) {
outboundBody = Buffer.from(JSON.stringify(withServerTools ?? current));
// The proxy parsed a plain JSON request. After reserializing it the
// original content encoding, if any, no longer describes the bytes.
@@ -830,7 +841,8 @@ export function getPiNativeSubscriptionHandler(
res.end(errorBody);
return;
}
- await pipeNativeResponse(response, res);
+ await pipeNativeResponse(response, res, recordUsage
+ ? createUsagePricingObserver(response.headers.get('content-type') ?? '', recordUsage) : undefined);
} catch (err) {
if (controller.signal.aborted || res.destroyed) return;
// Once a 200/SSE response has started, an upstream body failure cannot
diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
index ed1c70d04a..36d42a8a29 100644
--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
@@ -1,3 +1,5 @@
+import { captureUsagePricing, createUsagePricingObserver } from './model-usage-pricing.js';
+import { rewriteFastModel } from './model-fast-mode.js';
import { createAttachmentRecovery } from './oversized-attachment-recovery.js';
import { clearCodexTextOnlyPolicies, codexTextOnlyRequestGuard, codexTextOnlyWebSocketTransforms, isCodexTextOnly } from './codex-text-only-policy.js';
import {
@@ -1752,8 +1754,10 @@ function createByteDanceSeedResponsesCompatTransform(): RequestTransform {
};
}
-function createXaiResponsesCompatTransform(): RequestTransform {
- return (body, ctx) => {
+type XaiRequestPricing = Map<number, ReturnType<typeof captureUsagePricing>>;
+
+function createXaiResponsesCompatTransform(pricing: XaiRequestPricing): RequestTransform {
+ const transform: RequestTransform = (body, ctx) => {
if (!isPlainObject(body)) return null;
const requestModel = typeof body.model === 'string' ? body.model : '';
const providerContext = providerContextForRequest(ctx.headers, requestModel);
@@ -1826,8 +1830,18 @@ function createXaiResponsesCompatTransform(): RequestTransform {
current = withNormalizedInputItems;
changed = true;
}
+ const withFast = rewriteFastModel(xaiProviderId, 'codex', current, current.service_tier === 'priority');
+ const sessionId = sessionIdFromHeaders(ctx.headers);
+ if (sessionId && ctx.url.split('?', 1)[0]?.endsWith('/responses') && !isGuardian) {
+ pricing.set(ctx.reqId, captureUsagePricing(sessionId,
+ withFast && withFast.model !== current.model ? 'priority' : 'standard',
+ selectedThreadIdFromHeaders(ctx.headers)));
+ }
+ if (withFast) { current = withFast; changed = true; }
return changed ? current : null;
};
+ transform.onRequestSettled = reqId => { pricing.delete(reqId); };
+ return transform;
}
function responsesCompatibilityRoute(
@@ -2924,6 +2938,7 @@ export function createModelRoutingTransform(
function createTransformRequestChain(
frozenAuthInjection?: CodexProxyAuthInjection,
execAdapter = createCodexResponsesCompatibilityAdapter(),
+ pricing: XaiRequestPricing = new Map(),
): RequestTransform[] {
const execFunctionAdapterTransform: RequestTransform = (body, ctx) => {
if (!isPlainObject(body)) return null;
@@ -3008,7 +3023,7 @@ function createTransformRequestChain(
// ModelInput deserialize 前洗 input[]。订阅直连那条会再洗一次(幂等)。
createXaiModelInputSanitizeTransform(),
sanitizeDeepSeekV4CustomTools,
- createXaiResponsesCompatTransform(),
+ createXaiResponsesCompatTransform(pricing),
createGatewayGrokResponsesCompatTransform(frozenAuthInjection),
createByteDanceSeedResponsesCompatTransform(),
createMiniMaxResponsesCompatTransform(),
@@ -3126,10 +3141,23 @@ function createCodexProxyHandle(
frozenCustomProviderRoutes?: readonly CodexCustomProviderRoute[],
): Promise<ProxyHandle> {
const execAdapter = createCodexResponsesCompatibilityAdapter();
+ const pricing: XaiRequestPricing = new Map();
+ const route = createModelRoutingTransform(frozenAuthInjection, frozenCustomProviderRoutes);
+ const routeWithUsageEncoding: RoutingTransform = (body, ctx) => {
+ const uncompressed = (decision: RoutingDecision | null): RoutingDecision | null => {
+ if (decision?.localHandler || !isXaiUpstream(decision?.upstreamOverride ?? '')
+ || ctx.method !== 'POST' || !ctx.url.split('?', 1)[0]?.endsWith('/responses')) return decision;
+ // The observer receives raw wire bytes. Negotiate plaintext so the execution-price
+ // receipt is recorded synchronously before Codex can emit the corresponding usage.
+ return { ...decision, headerOverride: { ...decision?.headerOverride, 'accept-encoding': 'identity' } };
+ };
+ const decision = route(body, ctx);
+ return decision instanceof Promise ? decision.then(uncompressed) : uncompressed(decision);
+ };
return createAnthropicCompatProxy({
// 默认上游 = gateway(含 /v1);普通模型 + oauth 由 routingTransform 覆盖到 ChatGPT。
upstream: () => buildCodexGatewayBaseUrl(),
- transformRequest: createTransformRequestChain(frozenAuthInjection, execAdapter).map(
+ transformRequest: createTransformRequestChain(frozenAuthInjection, execAdapter, pricing).map(
(transform): RequestTransform => {
// Namespaced Responses use a frozen Provider route. Preserve its native
// fields and model. The dedicated transform below reconciles effort
@@ -3168,10 +3196,15 @@ function createCodexProxyHandle(
// 常规 session proxy 继续读取当前全局 spawn 形态;control-plane proxy 在创建时
// 冻结自己的形态,两个 app-server 并行时不会互相改写路由。
routingTransform: withCodexUpstreamRecording(
- createModelRoutingTransform(frozenAuthInjection, frozenCustomProviderRoutes),
+ routeWithUsageEncoding,
() => buildCodexGatewayBaseUrl(),
),
responseObserver: composeResponseObservers(
+ ctx => {
+ const record = pricing.get(ctx.reqId);
+ return record && ctx.status >= 200 && ctx.status < 300
+ ? createUsagePricingObserver(ctx.responseHeaders['content-type'] ?? '', record) : null;
+ },
createCodexResponseObserver(),
createProviderUpstreamErrorObserver({
agent: 'codex',
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index 15cf22b056..de009ef972 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -139,6 +139,7 @@ import { resolveVisionBackendRoute, setVisionGatewayKeyReader } from './provider
import { resolveSessionCcDebugFile, trackSessionCcDebugFile } from '../logger.js';
import { resetProviderModelAutoRefreshCooldowns } from './provider-model-auto-refresh.js';
import { getThinkingEnabledFromMemory } from './newMakerDefaultsCache.js';
+import { registerUsagePricing, clearUsagePricing } from './model-usage-pricing.js';
import { getSessionFastMode } from './session-effort-store.js';
import { createSshDaemonTransport } from './codex-remote-transport.js';
import { getRemoteSshPool, broadcastSilentInstallStatus, ensureRemoteAgentInstalledOrInstall } from '../remote-ssh/index.js';
@@ -2593,6 +2594,9 @@ export function getMaker(): Maker {
);
if (thinkingEnabled !== undefined) opts.thinkingEnabled = thinkingEnabled;
}
+ if (opts.agentKind === 'codex' || opts.agentKind === 'pi') {
+ opts.resolveUsagePriceVariant = registerUsagePricing(sessionId);
+ }
// 主干新增:pi 的价格档跟随会话 Fast 开关。
if (opts.agentKind === 'pi') {
opts.getPriceVariant = () => (getSessionFastMode(sessionId) ? 'priority' : 'standard');
@@ -2734,6 +2738,7 @@ export function getMaker(): Maker {
await writeCodexHistoryHasProductPrompt(sessionId, historyHasProductPrompt);
},
onClose: async (sessionId, options) => {
+ clearUsagePricing(sessionId);
const lease = worktreeRuntimeLeases.get(options);
if (lease) {
await releaseWorktreeRuntimeLease(lease).catch((error) => {
diff --git a/apps/desktop/src/main/maker-host/model-discovery/xai-models.ts b/apps/desktop/src/main/maker-host/model-discovery/xai-models.ts
new file mode 100644
index 0000000000..dffe88ca96
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/model-discovery/xai-models.ts
@@ -0,0 +1,159 @@
+/** Pure xAI discovery parsing, shared by runtime refresh and the sync CLI. */
+import { effortRank, type Effort, type CatalogModel } from '@cindy/model-providers';
+
+export interface XaiDiscoveredModel {
+ id: string;
+ name?: string;
+ description?: string;
+ contextWindow?: number;
+ contextWindowVerified?: boolean;
+ maxOutput?: number;
+ efforts?: CatalogModel['efforts'];
+ nativeApi?: CatalogModel['nativeApi'];
+ defaultEffort?: CatalogModel['defaultEffort'];
+}
+
+const VALID_EFFORTS: ReadonlySet<string> = new Set(['minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']);
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function stringField(record: Record<string, unknown>, ...keys: string[]): string | undefined {
+ for (const key of keys) {
+ const value = record[key];
+ if (typeof value === 'string' && value.trim()) return value.trim();
+ }
+ return undefined;
+}
+
+function positiveIntegerField(
+ record: Record<string, unknown>,
+ ...keys: string[]
+): number | undefined {
+ for (const key of keys) {
+ const value = record[key];
+ if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return value;
+ }
+ return undefined;
+}
+
+function effort(value: unknown): Effort | undefined {
+ return typeof value === 'string' && VALID_EFFORTS.has(value) ? (value as Effort) : undefined;
+}
+
+/**
+ * 档位数组一律**规范升序**(低 → 高)。x.ai 的 `/v1/models` 下发的是**降序**
+ * (Chris 2026-08-19 实测:`['high','medium','low']`),而全仓消费端(EffortSlider 的
+ * 按下标画轴、`efforts[0]`=最低 / `efforts.at(-1)`=最高的取值点)契约都是升序 ——
+ * 原序透传出去,Grok 4.5 的滑杆整条轴反向,用户以为在拉高、实际每次都写 low。
+ * 顺序是**表示细节**,在入库这一点归一,payload / 磁盘缓存怎么排都不再泄漏到下游;
+ * `parseCachedXaiModels` 复用本函数,已落盘的降序缓存下次读取即被纠正,不必等刷新。
+ */
+function canonicalEffortOrder(list: readonly Effort[]): Effort[] {
+ return [...list].sort((a, b) => effortRank(a) - effortRank(b));
+}
+
+function parseReasoningEfforts(raw: unknown): { efforts?: Effort[]; declaredDefault?: Effort } {
+ if (!Array.isArray(raw)) return {};
+ const efforts: Effort[] = [];
+ let declaredDefault: Effort | undefined;
+ for (const item of raw) {
+ const value = effort(typeof item === 'string' ? item : isRecord(item) ? item.value : undefined);
+ if (!value || efforts.includes(value)) continue;
+ efforts.push(value);
+ if (isRecord(item) && item.default === true) declaredDefault = value;
+ }
+ return { efforts: canonicalEffortOrder(efforts), declaredDefault };
+}
+
+function canonicalModelId(raw: string): string {
+ return raw.startsWith('xai/') ? raw : `xai/${raw}`;
+}
+
+/** Parse membership without guessing missing capability fields. */
+export function parseXaiAccountModels(payload: unknown): XaiDiscoveredModel[] {
+ if (!isRecord(payload) || !Array.isArray(payload.data)) {
+ throw new Error('xAI account model discovery returned an invalid models payload');
+ }
+ const seen = new Set<string>();
+ const models: XaiDiscoveredModel[] = [];
+ for (const value of payload.data) {
+ if (!isRecord(value)) continue;
+ const meta = isRecord(value._meta) ? value._meta : {};
+ if (value.hidden === true || meta.hidden === true) continue;
+ const rawId =
+ stringField(value, 'model', 'modelId', 'id') ?? stringField(meta, 'model', 'modelId');
+ if (!rawId) continue;
+ const id = canonicalModelId(rawId);
+ if (seen.has(id)) continue;
+ seen.add(id);
+ const contextWindow =
+ positiveIntegerField(value, 'contextWindow', 'context_window') ??
+ positiveIntegerField(meta, 'contextWindow', 'totalContextTokens');
+ const maxOutput = positiveIntegerField(value, 'maxCompletionTokens', 'max_completion_tokens');
+ const parsedEfforts = parseReasoningEfforts(
+ value.reasoningEfforts ?? value.reasoning_efforts ?? meta.reasoningEfforts,
+ );
+ const declaredDefault =
+ parsedEfforts.declaredDefault ??
+ effort(value.reasoningEffort ?? value.reasoning_effort ?? meta.reasoningEffort);
+ let efforts = parsedEfforts.efforts;
+ if (value.supportsReasoningEffort === false || value.supports_reasoning_effort === false) {
+ efforts = [];
+ } else if (efforts === undefined && declaredDefault) {
+ efforts = [declaredDefault];
+ } else if (efforts && declaredDefault && !efforts.includes(declaredDefault)) {
+ // 追加后重排:declaredDefault 直接 push 到尾部会破坏 parseReasoningEfforts
+ // 已经建立的规范升序(见 canonicalEffortOrder)。
+ efforts = canonicalEffortOrder([...efforts, declaredDefault]);
+ }
+ const name = stringField(value, 'name');
+ const description = stringField(value, 'description');
+ models.push({
+ id,
+ ...(value.api_backend === 'responses' ? { nativeApi: 'openai-responses' as const } : {}),
+ ...(name ? { name } : {}),
+ ...(description ? { description } : {}),
+ ...(contextWindow !== undefined ? { contextWindow, contextWindowVerified: true } : {}),
+ ...(maxOutput !== undefined ? { maxOutput } : {}),
+ ...(efforts !== undefined ? { efforts } : {}),
+ ...(declaredDefault !== undefined ? { defaultEffort: declaredDefault } : {}),
+ });
+ }
+ return models;
+}
+
+export function parseCachedXaiModels(payload: unknown): XaiDiscoveredModel[] | null {
+ if (!isRecord(payload) || !Array.isArray(payload.models)) return null;
+ const out: XaiDiscoveredModel[] = [];
+ const seen = new Set<string>();
+ for (const value of payload.models) {
+ if (!isRecord(value) || typeof value.id !== 'string') return null;
+ const id = canonicalModelId(value.id);
+ if (seen.has(id)) continue;
+ seen.add(id);
+ const efforts =
+ value.efforts === undefined ? undefined : parseReasoningEfforts(value.efforts).efforts;
+ const defaultEffort = effort(value.defaultEffort);
+ if (value.efforts !== undefined && efforts === undefined) return null;
+ out.push({
+ id,
+ ...(value.nativeApi === 'openai-responses' ? { nativeApi: value.nativeApi } : {}),
+ ...(typeof value.name === 'string' ? { name: value.name } : {}),
+ ...(typeof value.description === 'string' ? { description: value.description } : {}),
+ ...(positiveIntegerField(value, 'contextWindow') !== undefined
+ ? {
+ contextWindow: positiveIntegerField(value, 'contextWindow'),
+ ...(value.contextWindowVerified === true ? { contextWindowVerified: true } : {}),
+ }
+ : {}),
+ ...(positiveIntegerField(value, 'maxOutput') !== undefined
+ ? { maxOutput: positiveIntegerField(value, 'maxOutput') }
+ : {}),
+ ...(efforts !== undefined ? { efforts } : {}),
+ ...(defaultEffort !== undefined ? { defaultEffort } : {}),
+ });
+ }
+ return out;
+}
diff --git a/apps/desktop/src/main/maker-host/model-discovery/xai.ts b/apps/desktop/src/main/maker-host/model-discovery/xai.ts
index d032461485..4e44860ac4 100644
--- a/apps/desktop/src/main/maker-host/model-discovery/xai.ts
+++ b/apps/desktop/src/main/maker-host/model-discovery/xai.ts
@@ -3,7 +3,8 @@
import fsp from 'node:fs/promises';
import path from 'node:path';
-import { effortRank, type Effort } from '@cindy/model-providers';
+import { parseXaiAccountModels, parseCachedXaiModels } from './xai-models.js';
+export { parseXaiAccountModels } from './xai-models.js';
import { activeOwnerScopeKey, ownerScopedUserDataPath } from '../../appSessionState.js';
import { createLogger, type Logger } from '../../logger.js';
@@ -22,17 +23,20 @@ export const XAI_ACCOUNT_USER_URL = 'https://cli-chat-proxy.grok.com/v1/user?inc
export const XAI_ACCOUNT_MODELS_URL = 'https://cli-chat-proxy.grok.com/v1/models';
export const XAI_GROK_CLIENT_VERSION = '1.0.3';
+function stringField(record: Record<string, unknown>, ...keys: string[]): string | undefined {
+ for (const key of keys) {
+ const value = record[key];
+ if (typeof value === 'string' && value.trim()) return value.trim();
+ }
+ return undefined;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
const HTTP_TIMEOUT_MS = 15_000;
const MAX_ERROR_BODY_BYTES = 8 * 1024;
-const VALID_EFFORTS: ReadonlySet<string> = new Set([
- 'minimal',
- 'low',
- 'medium',
- 'high',
- 'xhigh',
- 'max',
- 'ultra',
-]);
const log = createLogger('model-discovery:xai');
let cacheMutationQueue: Promise<void> = Promise.resolve();
let cacheTempSequence = 0;
@@ -84,147 +88,6 @@ class XaiDiscoveryHttpError extends Error {
}
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return value !== null && typeof value === 'object' && !Array.isArray(value);
-}
-
-function stringField(record: Record<string, unknown>, ...keys: string[]): string | undefined {
- for (const key of keys) {
- const value = record[key];
- if (typeof value === 'string' && value.trim()) return value.trim();
- }
- return undefined;
-}
-
-function positiveIntegerField(
- record: Record<string, unknown>,
- ...keys: string[]
-): number | undefined {
- for (const key of keys) {
- const value = record[key];
- if (typeof value === 'number' && Number.isSafeInteger(value) && value > 0) return value;
- }
- return undefined;
-}
-
-function effort(value: unknown): Effort | undefined {
- return typeof value === 'string' && VALID_EFFORTS.has(value) ? (value as Effort) : undefined;
-}
-
-/**
- * 档位数组一律**规范升序**(低 → 高)。x.ai 的 `/v1/models` 下发的是**降序**
- * (Chris 2026-08-19 实测:`['high','medium','low']`),而全仓消费端(EffortSlider 的
- * 按下标画轴、`efforts[0]`=最低 / `efforts.at(-1)`=最高的取值点)契约都是升序 ——
- * 原序透传出去,Grok 4.5 的滑杆整条轴反向,用户以为在拉高、实际每次都写 low。
- * 顺序是**表示细节**,在入库这一点归一,payload / 磁盘缓存怎么排都不再泄漏到下游;
- * `parseCachedModels` 复用本函数,已落盘的降序缓存下次读取即被纠正,不必等刷新。
- */
-function canonicalEffortOrder(list: readonly Effort[]): Effort[] {
- return [...list].sort((a, b) => effortRank(a) - effortRank(b));
-}
-
-function parseReasoningEfforts(raw: unknown): { efforts?: Effort[]; declaredDefault?: Effort } {
- if (!Array.isArray(raw)) return {};
- const efforts: Effort[] = [];
- let declaredDefault: Effort | undefined;
- for (const item of raw) {
- const value = effort(typeof item === 'string' ? item : isRecord(item) ? item.value : undefined);
- if (!value || efforts.includes(value)) continue;
- efforts.push(value);
- if (isRecord(item) && item.default === true) declaredDefault = value;
- }
- return { efforts: canonicalEffortOrder(efforts), declaredDefault };
-}
-
-function canonicalModelId(raw: string): string {
- return raw.startsWith('xai/') ? raw : `xai/${raw}`;
-}
-
-/** Parse membership without guessing missing capability fields. */
-export function parseXaiAccountModels(payload: unknown): XaiDiscoveredModel[] {
- if (!isRecord(payload) || !Array.isArray(payload.data)) {
- throw new Error('xAI account model discovery returned an invalid models payload');
- }
- const seen = new Set<string>();
- const models: XaiDiscoveredModel[] = [];
- for (const value of payload.data) {
- if (!isRecord(value)) continue;
- const meta = isRecord(value._meta) ? value._meta : {};
- if (value.hidden === true || meta.hidden === true) continue;
- const rawId =
- stringField(value, 'model', 'modelId', 'id') ?? stringField(meta, 'model', 'modelId');
- if (!rawId) continue;
- const id = canonicalModelId(rawId);
- if (seen.has(id)) continue;
- seen.add(id);
- const contextWindow =
- positiveIntegerField(value, 'contextWindow', 'context_window') ??
- positiveIntegerField(meta, 'contextWindow', 'totalContextTokens');
- const maxOutput = positiveIntegerField(value, 'maxCompletionTokens', 'max_completion_tokens');
- const parsedEfforts = parseReasoningEfforts(
- value.reasoningEfforts ?? value.reasoning_efforts ?? meta.reasoningEfforts,
- );
- const declaredDefault =
- parsedEfforts.declaredDefault ??
- effort(value.reasoningEffort ?? value.reasoning_effort ?? meta.reasoningEffort);
- let efforts = parsedEfforts.efforts;
- if (value.supportsReasoningEffort === false || value.supports_reasoning_effort === false) {
- efforts = [];
- } else if (efforts === undefined && declaredDefault) {
- efforts = [declaredDefault];
- } else if (efforts && declaredDefault && !efforts.includes(declaredDefault)) {
- // 追加后重排:declaredDefault 直接 push 到尾部会破坏 parseReasoningEfforts
- // 已经建立的规范升序(见 canonicalEffortOrder)。
- efforts = canonicalEffortOrder([...efforts, declaredDefault]);
- }
- const name = stringField(value, 'name');
- const description = stringField(value, 'description');
- models.push({
- id,
- ...(name ? { name } : {}),
- ...(description ? { description } : {}),
- ...(contextWindow !== undefined ? { contextWindow, contextWindowVerified: true } : {}),
- ...(maxOutput !== undefined ? { maxOutput } : {}),
- ...(efforts !== undefined ? { efforts } : {}),
- ...(declaredDefault !== undefined ? { defaultEffort: declaredDefault } : {}),
- });
- }
- return models;
-}
-
-function parseCachedModels(payload: unknown): XaiDiscoveredModel[] | null {
- if (!isRecord(payload) || !Array.isArray(payload.models)) return null;
- const out: XaiDiscoveredModel[] = [];
- const seen = new Set<string>();
- for (const value of payload.models) {
- if (!isRecord(value) || typeof value.id !== 'string') return null;
- const id = canonicalModelId(value.id);
- if (seen.has(id)) continue;
- seen.add(id);
- const efforts =
- value.efforts === undefined ? undefined : parseReasoningEfforts(value.efforts).efforts;
- const defaultEffort = effort(value.defaultEffort);
- if (value.efforts !== undefined && efforts === undefined) return null;
- out.push({
- id,
- ...(typeof value.name === 'string' ? { name: value.name } : {}),
- ...(typeof value.description === 'string' ? { description: value.description } : {}),
- ...(positiveIntegerField(value, 'contextWindow') !== undefined
- ? {
- contextWindow: positiveIntegerField(value, 'contextWindow'),
- ...(value.contextWindowVerified === true ? { contextWindowVerified: true } : {}),
- }
- : {}),
- ...(positiveIntegerField(value, 'maxOutput') !== undefined
- ? { maxOutput: positiveIntegerField(value, 'maxOutput') }
- : {}),
- ...(efforts !== undefined ? { efforts } : {}),
- ...(defaultEffort !== undefined ? { defaultEffort } : {}),
- });
- }
- return out;
-}
-
function enqueueCacheMutation(
task: () => Promise<void>,
deps: XaiModelDiscoveryDeps,
@@ -270,7 +133,7 @@ export async function loadXaiModelsFromDiskCache(
const token = deps.peekAccessToken();
if (!token) return false;
try {
- const parsed = parseCachedModels(JSON.parse(await fsp.readFile(deps.cacheFilePath(), 'utf-8')));
+ const parsed = parseCachedXaiModels(JSON.parse(await fsp.readFile(deps.cacheFilePath(), 'utf-8')));
if (parsed === null || !isCurrent(deps, scopeKey, token)) return false;
deps.applySnapshot(parsed);
return true;
diff --git a/apps/desktop/src/main/maker-host/model-fast-mode.ts b/apps/desktop/src/main/maker-host/model-fast-mode.ts
new file mode 100644
index 0000000000..3db43bcc87
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/model-fast-mode.ts
@@ -0,0 +1,25 @@
+import type { AgentKind } from '@cindy/model-providers';
+import { getActiveCatalog } from './active-catalog.js';
+
+/** Resolve only in the selected connection. Active catalog has already gated account availability. */
+export function fastModelId(providerId: string, agent: AgentKind, modelId: string): string | undefined {
+ const models = getActiveCatalog().providers.find(p => p.id === providerId)?.models[agent];
+ const model = models?.find(m => m.id === modelId);
+ if (!model?.supportsFastMode || !model.fastModelId) return undefined;
+ const target = models?.find(m => m.id === model.fastModelId && m.status !== 'retired');
+ return target?.id;
+}
+
+/** Called within xAI subscription routes. Fast intent must never become an upstream priority tier. */
+export function rewriteFastModel(
+ providerId: string, agent: AgentKind, body: Record<string, unknown>, fast: boolean,
+): Record<string, unknown> | null {
+ if (!fast || typeof body.model !== 'string') return null;
+ const target = fastModelId(providerId, agent, body.model);
+ // A persisted Fast setting can outlive account availability, including before discovery.
+ // Fall back to the original model while still consuming Codex's Fast intent marker.
+ if (!target && body.service_tier !== 'priority') return null;
+ const next: Record<string, unknown> = { ...body, model: target ?? body.model };
+ delete next.service_tier;
+ return next;
+}
diff --git a/apps/desktop/src/main/maker-host/model-usage-pricing.ts b/apps/desktop/src/main/maker-host/model-usage-pricing.ts
new file mode 100644
index 0000000000..ae04f151c9
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/model-usage-pricing.ts
@@ -0,0 +1,87 @@
+import { StringDecoder } from 'node:string_decoder';
+import type { ResponseObserverSink } from '@cindy/anthropic-compat-proxy';
+
+type PriceVariant = 'standard' | 'priority';
+interface UsageKey {
+ threadId?: string;
+ /** Total prompt tokens, including cached tokens. */
+ inputTokens: number;
+ outputTokens: number;
+ cacheReadTokens: number;
+}
+type Receipt = UsageKey & { priceVariant: PriceVariant };
+const sessions = new Map<string, Receipt[]>();
+const recordOf = (value: unknown): Record<string, unknown> | undefined =>
+ value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
+
+/** Each runtime gets its own receipt list, so delayed responses cannot affect a resumed runtime. */
+export function registerUsagePricing(sessionId: string): (usage: UsageKey) => PriceVariant | undefined {
+ const receipts: Receipt[] = [];
+ sessions.set(sessionId, receipts);
+ return usage => {
+ const index = receipts.findIndex(receipt => receipt.threadId === usage.threadId
+ && receipt.inputTokens === usage.inputTokens && receipt.outputTokens === usage.outputTokens
+ && receipt.cacheReadTokens === usage.cacheReadTokens);
+ return index < 0 ? undefined : receipts.splice(index, 1)[0]?.priceVariant;
+ };
+}
+
+export function clearUsagePricing(sessionId: string): void {
+ sessions.delete(sessionId);
+}
+
+/** Capture the runtime and dispatch choice, never re-read the catalog or Fast preference at completion. */
+export function captureUsagePricing(sessionId: string, priceVariant: PriceVariant, threadId?: string) {
+ const receipts = sessions.get(sessionId);
+ return (value: unknown): void => {
+ if (!receipts || !value || typeof value !== 'object') return;
+ const body = recordOf(value);
+ if (!body) return;
+ if (typeof body.type === 'string' && body.type.startsWith('response.')
+ && body.type !== 'response.completed' && body.type !== 'response.incomplete') return;
+ const response = recordOf(body.response) ?? body;
+ const usage = recordOf(response.usage);
+ if (!usage) return;
+ const inputTokens = usage.input_tokens ?? usage.prompt_tokens;
+ const outputTokens = usage.output_tokens ?? usage.completion_tokens;
+ const cacheReadTokens = recordOf(usage.input_tokens_details)?.cached_tokens ?? recordOf(usage.prompt_tokens_details)?.cached_tokens ?? 0;
+ const validCount = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0;
+ if (!validCount(inputTokens) || !validCount(outputTokens) || !validCount(cacheReadTokens)) return;
+ // Bound unmatched receipts (cancelled requests, compaction, or delayed agent notifications).
+ if (receipts.length >= 64) receipts.shift();
+ receipts.push({ threadId, inputTokens, outputTokens, cacheReadTokens, priceVariant });
+ };
+}
+
+/** Read-only tee of native JSON/SSE responses; token/content bytes reach the harness unchanged. */
+export function createUsagePricingObserver(contentType: string, record: (value: unknown) => void): ResponseObserverSink {
+ const sse = contentType.includes('text/event-stream');
+ const decoder = new StringDecoder('utf8');
+ let pending = '';
+ let overflow = false;
+ const parse = (value: string): void => {
+ if (!value.includes('"usage"')) return;
+ try { record(JSON.parse(value)); } catch { /* Malformed frames remain the harness's responsibility. */ }
+ };
+ const ingest = (text: string): void => {
+ pending += text;
+ if (sse) {
+ let boundary: RegExpExecArray | null;
+ while ((boundary = /\r?\n\r?\n/.exec(pending))) {
+ const frame = pending.slice(0, boundary.index);
+ pending = pending.slice(boundary.index + boundary[0].length);
+ if (!overflow) parse(frame.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n'));
+ overflow = false;
+ }
+ }
+ if (pending.length > 1024 * 1024) { pending = ''; overflow = true; }
+ };
+ return {
+ onData: chunk => ingest(decoder.write(chunk)),
+ onEnd: () => {
+ ingest(decoder.end());
+ if (sse) ingest('\n\n');
+ else if (!overflow) parse(pending);
+ },
+ };
+}
diff --git a/docs/dev-rules/model-catalog-maintenance.md b/docs/dev-rules/model-catalog-maintenance.md
index 855dd48f80..daf374f42f 100644
--- a/docs/dev-rules/model-catalog-maintenance.md
+++ b/docs/dev-rules/model-catalog-maintenance.md
@@ -76,7 +76,7 @@ Pi 走 `providers[].models.pi`(用户补丁 perAgent.pi 另属合法 schema)
## 默认可见性:产品合同与实现差异
[产品合同](configuration-and-overrides.md#模型可见性):用户开关优先,否则跟随目录 defaultEnabled。
-但 `active-catalog.ts` 的 `selectDefaultModels` 仍可能将订阅/Gateway 的 true 筛成 false;不删除成员或写用户偏好。
+xAI 已直接保留目录默认开关;其他订阅/Gateway 的 `selectDefaultModels` 仍可能将 true 筛成 false,不删除成员或写用户偏好。
这是待收敛的行为差异,不是合同豁免。排查须同时检查上游值、活动目录值和用户 override;本文不改变行为。
<a id="release"></a>
@@ -163,3 +163,18 @@ app-server 的完整 `model/list`,不使用控制端 OpenAI 登录或网关目
剥离新增组与引用字段;V4 保留公共资料、本地域及原覆盖语义。各版本响应有独立 ETag。
旧服务端仍可返回旧目录,新客户端保留旧格式读取;应先部署服务端再发布客户端。
本次只迁移已有、已核实的价格,不补猜测价格,不改变 XD 的缺价处理。
+
+## xAI 双接口同步与导入验收
+
+新维护入口为 [`tools/model-catalog/sync-xai.mts`](../../tools/model-catalog/sync-xai.mts),
+用账号 `/models` 与官方 `/language-models` 合并型号和资料,再通过实际活动目录、三引擎
+选择器数据与参考价解析验收。运行方式、凭证边界、缺项报告与实测限制见
+[同步说明](../../tools/model-catalog/README.md)。输出是账号范围的本地导入候选,不可直接
+作为全局 Server 清单发布;它不改用户覆盖,也不以抓取成功代替完整适配。
+
+订阅 Fast 若通过独立上游型号执行,在 `providers.models[agent].fastModelId` 声明同来源、
+同引擎的目标 ID;不能只下发 `supportsFastMode: true`。客户端结合当前账号发现结果计算
+可用性,并在 Claude / Codex / Pi 请求边界统一切模,不再叠加 `service_tier: priority`。
+`null` 可显式撤销映射;缺省保持旧行为。旧客户端忽略新映射,因此执行适配需先随客户端
+发布;后续相同执行方式的新型号可维护目录数据。4.7 的关系与 Fast 价表已由官方文档和
+实测补证,4.6 不从版本号推导 Fast 支持。
diff --git a/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts b/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
index 8063f9ef07..456a21445c 100644
--- a/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
+++ b/packages/anthropic-responses-bridge/src/__tests__/handler.test.ts
@@ -134,6 +134,25 @@ describe('createResponsesHandler', () => {
expect(standard.text).toContain('"service_tier":"default"');
});
+ it.each([true, false])('Fast model mapping changes wire model only, preserves billing identity (stream=%s)', async stream => {
+ const seen: Record<string, unknown>[] = [];
+ vi.stubGlobal('fetch', vi.fn(async (_url: string, init: RequestInit) => {
+ seen.push(JSON.parse(String(init.body)));
+ return new Response(sse(OK_SSE), { headers: { 'content-type': 'text/event-stream' } });
+ }));
+ const handler = createResponsesHandler({ providers: [providerConfig({ prefix: 'xai/',
+ fastModel: model => model === 'grok-4.7' ? 'grok-4.7-build-fast' : undefined,
+ })] });
+ const result = await invoke(handler, { model: 'xai/grok-4.7', messages: [], stream }, { prefs: { fast: true } });
+ expect(seen[0].model).toBe('grok-4.7-build-fast');
+ expect(seen[0].service_tier).toBeUndefined();
+ expect(result.text).toContain('"model":"xai/grok-4.7"');
+ expect(result.text).toContain('"service_tier":"priority"');
+ await invoke(handler, { model: 'xai/grok-4.7', messages: [], stream }, { prefs: { fast: false } });
+ expect(seen[1].model).toBe('grok-4.7');
+ expect(seen[1].service_tier).toBeUndefined();
+ });
+
it('provider.strictFunctionTools 是生产控制面:启用 provider 逐工具 strict,未启用 provider 全 false', async () => {
const seen: Array<{ body: Record<string, unknown> }> = [];
vi.stubGlobal('fetch', vi.fn(async (_url: string, init: RequestInit) => {
diff --git a/packages/anthropic-responses-bridge/src/handler.ts b/packages/anthropic-responses-bridge/src/handler.ts
index 05c9ed5a35..1236f7d243 100644
--- a/packages/anthropic-responses-bridge/src/handler.ts
+++ b/packages/anthropic-responses-bridge/src/handler.ts
@@ -348,7 +348,10 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses
const reasoningEffort = !reasoningSupported ? 'none' : prefEffort;
// Fast 模式:prefs.fast × provider.fastServiceTier(codex='priority')。
- const serviceTier = prefs?.fast === true && provider.fastServiceTier ? provider.fastServiceTier : undefined;
+ const fastModel = prefs?.fast === true ? provider.fastModel?.(realModel) : undefined;
+ const serviceTier = !fastModel && prefs?.fast === true ? provider.fastServiceTier : undefined;
+ // Cindy's existing usage variant uses priority for Fast pricing, independently of wire service_tier.
+ const priceTier = fastModel ? 'priority' : serviceTier ?? 'default';
// 上游服务端工具(如 xAI x_search):只由 provider 按 model 静态声明,不受会话态影响,
// 保证同一会话逐轮请求带同一份工具列表(前缀稳定)。
@@ -363,7 +366,7 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses
&& provider.prefix === 'xai/'
&& realModel === 'grok-4.6';
const responsesReq = translateRequest(parsed, {
- model: realModel,
+ model: fastModel ?? realModel,
promptCacheKey: sessionId,
maxOutputTokensSupported: provider.maxOutputTokensSupported,
reasoningEffort,
@@ -481,7 +484,7 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses
// 完整的 Anthropic Message JSON。上游恒回 SSE(只接受流式),所以这里缓冲整流后组装;
// 同时兼容个别上游直接给 Responses JSON 的情况。
if (!downstreamStreaming) {
- const translator = new SseTranslator(wireModel, serviceTier ?? 'default', provider.reasoningNamespace);
+ const translator = new SseTranslator(wireModel, priceTier, provider.reasoningNamespace);
const collector = new AnthropicMessageCollector();
const collect = (event: AnthropicSseEvent): void => {
diagnostics?.recordDownstreamEvent(event);
@@ -547,7 +550,7 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses
// 用 wireModel(带前缀,如 chatgpt/gpt-5.5)而非 realModel 构造 —— message_start 回显带前缀 id,
// CC 的 modelUsage 据此记账,下游 usage 可按前缀区分订阅轮,不与真网关同名裸模型混淆。
- const translator = new SseTranslator(wireModel, serviceTier ?? 'default', provider.reasoningNamespace);
+ const translator = new SseTranslator(wireModel, priceTier, provider.reasoningNamespace);
const reader = upstream.body.getReader();
const decoder = new TextDecoder();
let buf = '';
diff --git a/packages/anthropic-responses-bridge/src/types.ts b/packages/anthropic-responses-bridge/src/types.ts
index a27235d837..000cbfaebc 100644
--- a/packages/anthropic-responses-bridge/src/types.ts
+++ b/packages/anthropic-responses-bridge/src/types.ts
@@ -223,9 +223,11 @@ export interface BridgeProviderConfig {
/**
* Fast 模式(host 经 prefs.fast 闭包传入)映射到的 Responses `service_tier` 值。codex 后端为
* 'priority'(models_cache 的 service_tiers 声明,UI 名 "Fast")。省略 = 该 provider 不支持
- * Fast,handler 忽略 fast 偏好(如 api.x.ai 未声明 priority tier)。
+ * Fast service tier。独立模型方式由 fastModel 声明;两者都缺省时忽略 Fast 偏好。
*/
fastServiceTier?: string;
+ /** Fast via a distinct upstream model. Takes precedence over fastServiceTier (never charge both). */
+ fastModel?: (model: string) => string | undefined;
/**
* 上游响应头里的 `x-ratelimit-*` 限流信息(标准 OpenAI 风格,api.x.ai 返回;codex 后端不返)。
* 每个成功上游响应解析后回调一次;缺头 → 不回调。回调抛错被吞(不影响流转发)。
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index f4caa86fa8..b5a0585b12 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -1785,6 +1785,13 @@ export interface StartSessionOptions {
* prices already-started requests with the tariff they actually used.
*/
getPriceVariant?: () => 'standard' | 'priority';
+ /** Match completed proxy usage to its actual execution tariff, before preference-based pricing. */
+ resolveUsagePriceVariant?: (usage: {
+ threadId?: string;
+ inputTokens: number;
+ outputTokens: number;
+ cacheReadTokens: number;
+ }) => 'standard' | 'priority' | undefined;
/** Pi + thinking-toggle 模型:false 时启动即关思考。缺省保持模型默认(开)。 */
thinkingEnabled?: boolean;
/**
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 9772d87d57..e89653c2d6 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -6004,6 +6004,33 @@ describe('CodexAgent.startSession developerInstructions', () => {
});
describe('CodexAgent fast mode service tier', () => {
+ it.each(['standard', 'priority'] as const)('prices the actual proxy execution (%s) without clearing Fast', async priceVariant => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, method => method === Method.TurnStart ? { turn: { id: 'turn-1' } } : undefined);
+ const resolveUsagePriceVariant = vi.fn(() => priceVariant);
+ const handle = await agent.startSession({ sessionId: 'session-xai-pricing', model: 'xai/grok-4.7',
+ fastMode: true, workingDir: '/repo', resolveUsagePriceVariant });
+ const handlers = host.getThreadHandlers()!;
+ const events: AgentEvent[] = [];
+ void (async () => { for await (const event of handle.events()) events.push(event); })();
+ const sending = handle.send({ type: 'user', content: 'hello' });
+ await waitForExpectation(() => expect(host.request.mock.calls.some(([m]) => m === Method.TurnStart)).toBe(true));
+ handlers.turnStarted!({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });
+ handlers.tokenUsageUpdated!({ threadId: 'start-thread-id', turnId: 'turn-1', tokenUsage: {
+ total: { totalTokens: 35, inputTokens: 30, outputTokens: 5, cachedInputTokens: 10 },
+ last: { totalTokens: 35, inputTokens: 30, outputTokens: 5, cachedInputTokens: 10 },
+ } });
+ handlers.turnCompleted!({ threadId: 'start-thread-id', turn: { id: 'turn-1', status: 'completed' } });
+ await sending;
+ await waitForExpectation(() => expect(events.some(e => e.type === 'done')).toBe(true));
+ expect(resolveUsagePriceVariant).toHaveBeenCalledWith({ threadId: 'start-thread-id', inputTokens: 30, outputTokens: 5, cacheReadTokens: 10 });
+ expect((events.find(e => e.type === 'done')?.data as { usage: { segments: unknown[] } }).usage.segments)
+ .toEqual([expect.objectContaining({ inputTokens: 20, outputTokens: 5, cacheReadTokens: 10, priceVariant })]);
+ expect(handle.getFastMode?.()).toBe(true);
+ await handle.close();
+ });
+
+
it('normalizes app-server priority service tier from thread/start as fast mode', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent, (method) => {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 25491a1f15..4793fe7cbc 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -11835,11 +11835,16 @@ export class CodexAgent extends BaseAgent {
cacheCreateTokens: cacheWrite,
reasoningTokens: last.reasoningOutputTokens ?? 0,
model: turnOriginByTurnId.get(params.turnId)?.model ?? activeTurnModel ?? mutableModel,
- priceVariant: isFastServiceTier(
+ priceVariant: opts.resolveUsagePriceVariant?.({
+ threadId: params.threadId,
+ inputTokens: totalInput,
+ outputTokens: last.outputTokens ?? 0,
+ cacheReadTokens: cached,
+ }) ?? (isFastServiceTier(
turnServiceTier !== undefined ? turnServiceTier : mutableServiceTier,
)
? 'priority'
- : 'standard',
+ : 'standard'),
});
// Input/cache-only segments still belong in the ledger, but cannot
// pair already reported output with a later generation denominator.
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
index 0b0e25f2a0..03614642d5 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
@@ -1440,6 +1440,23 @@ describe('pi translator', () => {
expect(events.filter((event) => event.type === 'done')).toHaveLength(1);
});
+ it.each(['standard', 'priority'] as const)('uses the native execution receipt (%s) instead of the Fast preference', priceVariant => {
+ const ctx = createPiTranslateContext(noopLogger);
+ ctx.getPriceVariant = () => 'priority';
+ ctx.resolveUsagePriceVariant = vi.fn(() => priceVariant);
+ const { queue, events } = makeQueue();
+ translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
+ translatePiEvent(ev({ type: 'message_start' }), queue, ctx);
+ translatePiEvent(ev({ type: 'message_end', message: {
+ role: 'assistant', model: 'grok-4.7', content: [{ type: 'text', text: 'OK' }],
+ usage: { input: 20, output: 5, cacheRead: 10 },
+ } }), queue, ctx);
+ translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
+ expect(ctx.resolveUsagePriceVariant).toHaveBeenCalledWith({ inputTokens: 30, outputTokens: 5, cacheReadTokens: 10 });
+ expect((events.find(event => event.type === 'done')!.data as { usage: { segments: unknown[] } }).usage.segments)
+ .toEqual([expect.objectContaining({ inputTokens: 20, outputTokens: 5, cacheReadTokens: 10, priceVariant })]);
+ });
+
it('locks the Pi price variant from bridge usage metadata at each provider request boundary', () => {
const ctx = createPiTranslateContext(noopLogger);
let fast = false;
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index aa29a114f2..e9493a3031 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -3778,6 +3778,7 @@ export class PiAgent extends BaseAgent {
const queue: AsyncQueue<AgentEvent> = createAsyncQueue<AgentEvent>();
const ctx: PiTranslateContext = createPiTranslateContext(this.deps.logger);
ctx.getPriceVariant = opts.getPriceVariant;
+ ctx.resolveUsagePriceVariant = opts.resolveUsagePriceVariant;
ctx.workingContextWindow = startupWorkingContextWindow;
const contextModeRoot = findContextModePackageRoot([
...nativePackageRoots,
diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.ts
index d6fc6d1fc3..35b4d2b246 100644
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@ -17,6 +17,7 @@
import { randomUUID } from 'node:crypto';
import { parseMessageToolUse } from '@cindy/maker-shared/message-normalize';
+import type { StartSessionOptions } from '../base-agent.js';
import type { Logger } from '../../interfaces/logger.js';
import { PI_SUBAGENT_TOOL_NAME, subagentSpawnResultIndicatesRunning } from '@cindy/maker-shared/agent-task';
import {
@@ -95,6 +96,7 @@ export interface PiTranslateContext {
logger: Logger;
/** Host-owned live tariff selector fallback when the provider response has no accepted tier. */
getPriceVariant?: () => 'standard' | 'priority';
+ resolveUsagePriceVariant?: StartSessionOptions['resolveUsagePriceVariant'];
/** get_state 拿到的 contextWindow(模型切换时更新)。 */
contextWindow: number;
/** Applied compaction budget; separate from the native request capacity. */
@@ -716,8 +718,13 @@ export function translatePiEvent(
if (!message || message.role !== 'assistant') return;
const pendingPriceVariant = ctx.pendingPriceVariants.shift();
const reportedPriceVariant = priceVariantFromServiceTier(message.usage?.service_tier);
+ const executionPriceVariant = message.usage && ctx.resolveUsagePriceVariant?.({
+ inputTokens: (message.usage.input ?? 0) + (message.usage.cacheRead ?? 0) + (message.usage.cacheWrite ?? 0),
+ outputTokens: message.usage.output ?? 0,
+ cacheReadTokens: message.usage.cacheRead ?? 0,
+ });
const priceVariant =
- pendingPriceVariant ?? reportedPriceVariant ?? ctx.getPriceVariant?.() ?? 'standard';
+ executionPriceVariant ?? pendingPriceVariant ?? reportedPriceVariant ?? ctx.getPriceVariant?.() ?? 'standard';
applyUsage(ctx, message.usage, message.model, priceVariant);
const hadGenerationHeartbeat = ctx.generationHeartbeatAt > 0;
samplePiGenerationHeartbeat(ctx);
diff --git a/packages/model-providers/catalog/model-registry.json b/packages/model-providers/catalog/model-registry.json
index 5479d52765..af4fecf825 100644
--- a/packages/model-providers/catalog/model-registry.json
+++ b/packages/model-providers/catalog/model-registry.json
@@ -1,6 +1,6 @@
{
"schemaVersion": 5,
- "updatedAt": "2026-09-24T10:51:31.000Z",
+ "updatedAt": "2026-09-24T14:16:12.766Z",
"models": [
{
"id": "openai/gpt-6-sol",
@@ -847,12 +847,39 @@
{
"providerId": "xai",
"modelId": "xai/grok-4.7",
- "agents": ["claude-code", "codex"],
+ "agents": [
+ "claude-code",
+ "codex"
+ ],
+ "referencePriceGroup": "global"
+ }
+ ],
+ "nativeApi": "openai-responses",
+ "modelRef": "xai/grok-4.7",
+ "perAgent": {
+ "claude-code": {
+ "defaultEnabled": false
+ }
+ }
+ },
+ {
+ "id": "xai/grok-4.7-build-fast",
+ "name": "Grok 4.7 Fast",
+ "status": "active",
+ "defaultEnabled": false,
+ "routes": [
+ {
+ "providerId": "xai",
+ "modelId": "xai/grok-4.7-build-fast",
+ "agents": [
+ "claude-code",
+ "codex"
+ ],
"referencePriceGroup": "global"
}
],
"nativeApi": "openai-responses",
- "modelRef": "xai/grok-4.7"
+ "modelRef": "xai/grok-4.7-build-fast"
},
{
"id": "xai/grok-4.6",
@@ -4050,7 +4077,12 @@
"name": "Grok 4.7",
"group": "grok",
"contextWindow": 500000,
- "efforts": ["low", "medium", "high", "xhigh"],
+ "efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
"defaultEffort": "high",
"supportsImageInput": true
},
@@ -4085,6 +4117,87 @@
"url": "https://docs.x.ai/developers/pricing",
"verifiedAt": "2026-09-22"
}
+ },
+ {
+ "currency": "USD",
+ "variant": "fast",
+ "inputPerMtok": 4,
+ "outputPerMtok": 12,
+ "cacheReadPerMtok": 1,
+ "maxInputTokens": 200001,
+ "effectiveFrom": "2026-09-24",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-09-24"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "fast",
+ "inputPerMtok": 6,
+ "outputPerMtok": 18,
+ "cacheReadPerMtok": 1.5,
+ "minInputTokens": 200001,
+ "effectiveFrom": "2026-09-24",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-09-24"
+ }
+ }
+ ]
+ }
+ ]
+ },
+ {
+ "id": "xai/grok-4.7-build-fast",
+ "aliases": [],
+ "defaults": {
+ "name": "Grok 4.7 Fast",
+ "group": "grok",
+ "contextWindow": 500000,
+ "efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
+ "defaultEffort": "high",
+ "supportsImageInput": true,
+ "supportsFastMode": false
+ },
+ "referencePriceGroups": [
+ {
+ "id": "global",
+ "prices": [
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 4,
+ "outputPerMtok": 12,
+ "cacheReadPerMtok": 1,
+ "maxInputTokens": 200001,
+ "effectiveFrom": "2026-09-24",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-09-24"
+ }
+ },
+ {
+ "currency": "USD",
+ "variant": "standard",
+ "inputPerMtok": 6,
+ "outputPerMtok": 18,
+ "cacheReadPerMtok": 1.5,
+ "minInputTokens": 200001,
+ "effectiveFrom": "2026-09-24",
+ "source": {
+ "kind": "provider-official",
+ "url": "https://docs.x.ai/developers/pricing",
+ "verifiedAt": "2026-09-24"
+ }
}
]
}
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index 8de3cb5866..79c0520438 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -67,6 +67,7 @@
{
"id": "xai/grok-4.7",
"name": "Grok 4.7",
+ "fastModelId": "xai/grok-4.7-build-fast",
"group": "grok",
"sortOrder": 47,
"contextWindow": 500000,
@@ -190,6 +191,7 @@
{
"id": "xai/grok-4.7",
"name": "Grok 4.7",
+ "fastModelId": "xai/grok-4.7-build-fast",
"group": "grok",
"sortOrder": 47,
"contextWindow": 500000,
@@ -313,6 +315,7 @@
{
"id": "grok-4.7",
"name": "Grok 4.7",
+ "fastModelId": "grok-4.7-build-fast",
"piApi": "openai-responses",
"group": "grok",
"sortOrder": 47,
diff --git a/packages/model-providers/src/__tests__/modelDefaultEffort.test.ts b/packages/model-providers/src/__tests__/modelDefaultEffort.test.ts
index 9ae7d69984..6bd743c609 100644
--- a/packages/model-providers/src/__tests__/modelDefaultEffort.test.ts
+++ b/packages/model-providers/src/__tests__/modelDefaultEffort.test.ts
@@ -77,12 +77,12 @@ describe("medium-first defaults", () => {
rawRegistry as unknown as ModelRegistry,
)) {
if (!model.efforts?.length) continue;
- // Grok 4.7 uses official high; Kimi Code uses max, unlike our
+ // Grok 4.7 (including Build Fast) uses official high; Kimi Code uses max, unlike our
// medium-first fallback for models without this official default.
expect(model.defaultEffort, model.id).toBe(
model.id === "moonshotai/kimi-k2.8-preview"
? "max"
- : model.id === "xai/grok-4.7" ? "high"
+ : ["xai/grok-4.7", "xai/grok-4.7-build-fast"].includes(model.id) ? "high"
: defaultEffortForCapabilities(model.efforts),
);
for (const override of Object.values(model.perAgent ?? {})) {
diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.ts
index 940b129320..90f4fc6952 100644
--- a/packages/model-providers/src/catalog.ts
+++ b/packages/model-providers/src/catalog.ts
@@ -156,6 +156,10 @@ function validateModel(
if (m.api !== undefined) {
assert(isPiModelApi(m.api), `model.api invalid for '${m.id}'`);
}
+ if (m.fastModelId !== undefined && m.fastModelId !== null) {
+ assert(typeof m.fastModelId === 'string' && m.fastModelId.trim().length > 0 && m.fastModelId !== m.id,
+ `model.fastModelId invalid for '${m.id}'`);
+ }
if (m.piApi !== undefined) {
assert(isPiModelApi(m.piApi), `model.piApi invalid for '${m.id}'`);
}
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 2e1e7ab89a..52421904f3 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -397,6 +397,10 @@ export interface CatalogModel {
* 不能读跨 provider 拍平去重后的列表(那只保留首个 provider 的值,会错)。
*/
supportsFastMode?: boolean;
+ /** Same-provider, same-harness catalog model used for Fast. null explicitly disables mapping.
+ * Unlike a service tier, this changes the upstream model; availability must be checked per account.
+ */
+ fastModelId?: string | null;
/**
* 该模型在 Codex 下使用的模型级兼容 bridge 协议。
*
diff --git a/tools/model-catalog/README.md b/tools/model-catalog/README.md
new file mode 100644
index 0000000000..71a24636e9
--- /dev/null
+++ b/tools/model-catalog/README.md
@@ -0,0 +1,118 @@
+# xAI API catalog sync
+
+This entry joins **two real provider APIs**, rather than inferring capabilities from model names
+or copying a Pi SDK model list. It emits an account-scoped catalog using Cindy's existing V5
+schema and exercises the production active-catalog, picker descriptor and reference-price paths.
+The runtime refresh and this script share the same account-response parser.
+
+```sh
+node --import tsx tools/model-catalog/sync-xai.mts \
+ --grok-auth "$HOME/.grok/auth.json" --output /tmp/xai-sync-run
+```
+
+An explicit `CINDY_XAI_ACCESS_TOKEN` environment variable can replace `--grok-auth`. Credentials
+stay in memory; the script neither refreshes nor writes the login, follows redirects, nor sends
+generation requests. The two authenticated destinations are fixed official hosts. Each output
+run must use a new directory; an error never replaces a previous successful result.
+
+- `catalog.json`: load through the existing `XDT_MODELS_PATH` Desktop catalog-source setting in
+ an isolated development profile. The script validates both serialized-file import and the
+ normal account-discovery overlay. It does not start or reconfigure a running app.
+- `report.json`: resolved fields for Claude Code, Codex and Pi, price bands, API field provenance,
+ and unresolved facts. `complete: false` is not full support. `--require-complete` exits **2**
+ after writing the reviewable result if any required facts remain unresolved; transport, input
+ or import errors exit **1**. Success fetching/parsing alone is never described as complete.
+
+**Scope:** xAI subscription account discovery. Do not publish the artifact wholesale as a public
+server catalog: an account's member list is not a universal model list. Public catalog changes
+must preserve the existing server source and review scope. This script does not modify either
+server sources or client bundled snapshots, user preferences, schedules, or historical tasks.
+There is no model-version whitelist: the regression uses an unseen `grok-4.8` fixture, not a claim
+that this model exists. A new transport still needs a real client adapter.
+
+## Sources and conversion
+
+- `https://cli-chat-proxy.grok.com/v1/models` supplies account members, display names, context,
+ declared backend and effort ladder. Hidden entries are excluded. Explicit `responses` backend
+ is carried through discovery/cache; other newly declared backends stop the sync for review.
+- `https://api.x.ai/v1/language-models` supplies modalities and manufacturer reference prices.
+ Join exact IDs or a **unique explicitly returned alias**, never version/suffix similarity.
+ Extra models from this endpoint do not become account members.
+- The current public Cindy V5 catalog supplies curated defaults and existing routing. Use
+ `--catalog FILE` for a fixed baseline. Sparse metadata does not clear curated facts. Explicit
+ native-only defaults are generated per harness; existing opt-outs remain. Local user overrides
+ are still applied by the app, not written by this tool.
+
+The [official REST contract](https://docs.x.ai/developers/rest-api-reference/inference/models)
+expresses text prices in **USD cents per 100 million tokens**: divide by 10,000 for USD per million.
+Long-context prices apply at `long_context_threshold` (inclusive); zero in a long-context price
+field means the standard price, while a zero standard price is an actual zero. Cache reads are
+not cache writes. Unknown/missing prices never become zero, and reference prices are not
+subscription billing.
+
+Unchanged tariffs keep their historical start date; changed tariffs close the previous interval
+and start at the observation date. This is the first observed price, not an invented provider
+launch date. Ambiguous same-day changes are rejected because V5 prices have day precision.
+Other variants, markets, routes and historical prices are retained.
+Missing cache-read fields retain verified active cache prices only for the same input-token
+band, without advancing their verification date. The report still lists `apiCacheReadPrice`
+as missing and identifies inherited cache prices as catalog facts. An explicit zero replaces
+the previous rate; an absent field does not.
+
+## Repeatable verification
+
+```sh
+node --import tsx tools/model-catalog/sync-xai.mts --catalog /tmp/baseline.json \
+ --account-input /tmp/account-response.json --details-input /tmp/language-models-response.json \
+ --observed-at 2026-09-24T12:00:00.000Z --output /tmp/xai-replay
+pnpm exec tsc --noEmit -p tools/model-catalog/tsconfig.json
+pnpm --filter desktop exec vitest run \
+ src/main/maker-host/__tests__/xaiSyncImport.test.ts \
+ src/main/maker-host/__tests__/xaiModelDiscovery.test.ts \
+ src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts \
+ --maxWorkers=1 --no-file-parallelism
+```
+
+Never put account auth files or unfiltered API captures into repository fixtures. The sync report
+contains allowlisted model fields, not request headers, user identity or raw upstream responses.
+
+## Live check (2026-09-24)
+
+Authenticated metadata GETs returned four account models and eight language-model detail records.
+All four account members reached the three production picker projections (12 records); ordinary
+Grok 4.7 reference prices resolved to $2/$0.5/$6 input/cache/output per million, and $4/$1/$12 from
+200,000 input tokens. Claude Code's compatibility route was default-off. Pi native model-spec
+conversion is covered by an unseen-model regression without an SDK entry.
+
+Fast is now declared with a provider/harness `fastModelId` mapping: Grok 4.7 →
+`grok-4.7-build-fast`. The [official 4.7 documentation](https://docs.x.ai/developers/grok-4-7)
+identifies Fast as the same model on faster infrastructure, available via Grok Build / Cursor,
+not the public API-key product. Account discovery determines whether this connection has it.
+There is no verified Build Fast mapping for 4.6; do not manufacture one from its version number.
+
+The [explicit Fast tariff](https://docs.x.ai/developers/pricing) is $4/$1/$12 per million
+input/cache/output, rising to $6/$1.5/$18 when input **exceeds** 200,000 tokens. Do not calculate
+long-context Fast pricing by doubling the ordinary long-context tariff. These curated facts
+supplement API omissions; `fieldsFromCatalog` distinguishes them from live API evidence.
+
+Claude bridge, Codex proxy and Pi native forwarding consume the same account-gated mapping.
+Fast sends the target model without also sending `service_tier: priority`. Existing usage
+accounting names its Fast price variant `priority`; that internal label is not an upstream tier.
+Codex and Pi match completed native usage to the dispatch-time model choice. When account
+availability forces a standard fallback, usage keeps the standard tariff even if Fast remains
+enabled; later catalog refreshes or Fast toggles cannot reprice that completed request.
+Direct Fast model IDs remain callable for existing selections, default-off for new selection.
+
+This execution adapter requires a client release. The optional mapping alone does not enable
+Fast on old clients. After that adapter is installed, future verified model mappings and tariffs
+can be updated in catalog data; neither a Fast-looking name nor discovery alone proves a mapping.
+No production catalog has been published by this tool.
+
+Remaining gaps: the Fast individual detail endpoint returns 404; both APIs omit maximum output.
+The report retains those unknowns, rather than presenting existing Pi runtime output budgets as
+verified provider limits. The metadata check does not launch the GUI or certify full agent turns.
+
+A separate minimal live inference probe on 2026-09-24 verified the normal/Fast model IDs through
+Claude's real translation handler and the Codex/Pi mapping helpers (HTTP 200). Full host proxy
+chains are additionally covered by local request/response tests with a mocked upstream. These
+probes are not a GUI or complete coding-task acceptance test.
diff --git a/tools/model-catalog/sync-xai.mts b/tools/model-catalog/sync-xai.mts
new file mode 100644
index 0000000000..fd0bad9385
--- /dev/null
+++ b/tools/model-catalog/sync-xai.mts
@@ -0,0 +1,100 @@
+/** Run: node --import tsx tools/model-catalog/sync-xai.mts --help */
+import { readFile, mkdir, writeFile, rm } from 'node:fs/promises';
+import path from 'node:path';
+import { parseArgs } from 'node:util';
+import { parseCatalog } from '../../packages/model-providers/src/index.js';
+import { buildXaiSyncCandidate, inspectXaiImport, XAI_MODELS_URL, XAI_DETAILS_URL } from './xai-sync.js';
+
+const { values } = parseArgs({ options: {
+ help: { type: 'boolean' }, catalog: { type: 'string' }, output: { type: 'string' },
+ 'grok-auth': { type: 'string' }, 'account-input': { type: 'string' }, 'details-input': { type: 'string' },
+ 'observed-at': { type: 'string' }, 'require-complete': { type: 'boolean' },
+} });
+if (values.help) {
+ console.log(`Sync xAI API metadata into an account-scoped Cindy catalog and verify three harness projections.
+
+node --import tsx tools/model-catalog/sync-xai.mts --grok-auth /path/to/.grok/auth.json --output /tmp/xai-sync-run
+ Alternatively set CINDY_XAI_ACCESS_TOKEN (never pass tokens as command arguments).
+ --catalog FILE Existing V5 catalog; otherwise GET the Cindy public catalog.
+ --account-input FILE --details-input FILE Offline replay; both are required together.
+ --observed-at ISO Observation time for offline replay only.
+ --require-complete Exit 2 if the report has unknown capability/price fields.
+
+Creates a new output directory containing catalog.json and report.json only after validation.
+For isolated Desktop verification use XDT_MODELS_PATH=<output>/catalog.json.
+Does not modify credentials, preferences, the running app, server catalog, or scheduled tasks.
+Account membership is private to this connection: do not publish this artifact as a global catalog.
+Only metadata GETs; no inference requests. Verified catalog mappings supplement missing API facts.`);
+ process.exit(0);
+}
+if (!values.output) throw new Error('--output is required');
+const offline = !!values['account-input'];
+if (offline !== !!values['details-input']) throw new Error('Offline replay requires both input files');
+if (values['observed-at'] && !offline) throw new Error('--observed-at is only allowed for offline replay');
+const readJson = async (file: string): Promise<unknown> => {
+ let text: string;
+ try { text = await readFile(file, 'utf8'); }
+ catch { throw new Error('Could not read an input JSON file'); }
+ // JSON.parse errors can contain source snippets, including tokens in a malformed auth file.
+ try { return JSON.parse(text) as unknown; }
+ catch { throw new Error('An input file contains invalid JSON'); }
+};
+async function getJson(url: string, headers: Record<string, string> = {}) {
+ let response: Response;
+ try {
+ response = await fetch(url, { method: 'GET', headers: { Accept: 'application/json', ...headers },
+ redirect: 'error', signal: AbortSignal.timeout(20_000) });
+ } catch { throw new Error(`Metadata GET failed: ${url}`); }
+ if (!response.ok) throw new Error(`Metadata GET HTTP ${response.status}: ${url}`);
+ // Do not print upstream error bodies, request headers, or credentials.
+ try { return await response.json() as unknown; }
+ catch { throw new Error(`Invalid JSON: ${url}`); }
+}
+try {
+ const catalogUrl = 'https://model-access.cindy.app/api/model-catalog/catalog?registrySchemaVersion=5&registryMedia=1';
+ const baseline = parseCatalog(values.catalog ? await readJson(values.catalog) : await getJson(catalogUrl));
+ let account: unknown;
+ let details: unknown;
+ if (offline) {
+ account = await readJson(values['account-input']!);
+ details = await readJson(values['details-input']!);
+ } else {
+ let token = process.env.CINDY_XAI_ACCESS_TOKEN;
+ if (values['grok-auth']) {
+ const auth = await readJson(values['grok-auth']);
+ // The native CLI keys its store by authorization-server URL + client ID.
+ const rows = auth && typeof auth === 'object' ? Object.values(auth) : [];
+ const candidates = rows.filter(row => row && typeof row === 'object' && typeof row.key === 'string');
+ if (candidates.length !== 1) throw new Error('Expected exactly one Grok login; use CINDY_XAI_ACCESS_TOKEN to select explicitly');
+ token = candidates[0].key;
+ }
+ if (!token) throw new Error('Supply --grok-auth or CINDY_XAI_ACCESS_TOKEN');
+ const headers = { Authorization: `Bearer ${token}`, 'X-XAI-Token-Auth': 'xai-grok-cli',
+ 'x-grok-client-version': '1.0.3', 'x-grok-client-mode': 'interactive' };
+ // Fixed official hosts only; credentials never follow redirects or a user-controlled URL.
+ [account, details] = await Promise.all([getJson(XAI_MODELS_URL, headers), getJson(XAI_DETAILS_URL, headers)]);
+ }
+ const observedAt = values['observed-at'] ?? new Date().toISOString();
+ const candidate = buildXaiSyncCandidate(baseline, account, details, observedAt);
+ const report = { observedAt, scope: 'xai-subscription-account',
+ sources: { membership: XAI_MODELS_URL, details: XAI_DETAILS_URL, catalog: values.catalog ? 'local' : catalogUrl },
+ ...inspectXaiImport(candidate) };
+ const destination = path.resolve(values.output);
+ await mkdir(path.dirname(destination), { recursive: true });
+ // Exclusive directory creation leaves every prior successful run untouched.
+ await mkdir(destination, { mode: 0o700 });
+ try {
+ await writeFile(path.join(destination, 'catalog.json'), JSON.stringify(candidate.catalog, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
+ await writeFile(path.join(destination, 'report.json'), JSON.stringify(report, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
+ } catch (error) {
+ await rm(destination, { force: true, recursive: true });
+ throw error;
+ }
+ console.log(JSON.stringify({ output: destination, importedModels: report.importedModels,
+ harnessProjections: report.harnessProjections, complete: report.complete, gaps: report.gaps, generationRequests: 0 }, null, 2));
+ if (values['require-complete'] && !report.complete) process.exitCode = 2;
+} catch (error) {
+ // Parser diagnostics are controlled, never serialize the upstream response or auth store.
+ console.error(error instanceof Error ? error.message : 'Model sync failed');
+ process.exitCode = 1;
+}
diff --git a/tools/model-catalog/tsconfig.json b/tools/model-catalog/tsconfig.json
new file mode 100644
index 0000000000..8956cc8824
--- /dev/null
+++ b/tools/model-catalog/tsconfig.json
@@ -0,0 +1,5 @@
+{
+ "extends": "../../apps/desktop/tsconfig.json",
+ "compilerOptions": { "noEmit": true },
+ "include": ["./*.ts", "./*.mts", "../../apps/desktop/env.d.ts", "../../apps/desktop/src/renderer/vite-env.d.ts"]
+}
diff --git a/tools/model-catalog/xai-sync.ts b/tools/model-catalog/xai-sync.ts
new file mode 100644
index 0000000000..dd365ff057
--- /dev/null
+++ b/tools/model-catalog/xai-sync.ts
@@ -0,0 +1,285 @@
+import { isDeepStrictEqual } from 'node:util';
+/** Account-scoped import: discovery owns membership; official details own reference tariffs. */
+import {
+ applyModelMetadata, BUNDLED_CATALOG, catalogModelMetadata, parseCatalog, resolveModelMetadata,
+ type Catalog, type CatalogModel, type ModelMetadata,
+} from '../../packages/model-providers/src/index.js';
+import type { ModelReferencePrice } from '../../packages/model-providers/src/modelAccessBean.js';
+import { parseXaiAccountModels } from '../../apps/desktop/src/main/maker-host/model-discovery/xai-models.js';
+import { getActiveCatalog, setActiveCatalog, setXaiDiscoveredModels } from '../../apps/desktop/src/main/maker-host/active-catalog.js';
+import { deriveAvailableModels } from '../../apps/desktop/src/main/maker-host/catalog-to-descriptors.js';
+import { modelProtocolComparison } from '../../packages/model-providers/src/modelProtocol.js';
+import { providerReferencePriceQuote } from '../../apps/desktop/src/shared/modelPriceQuote.js';
+
+export const XAI_MODELS_URL = 'https://cli-chat-proxy.grok.com/v1/models';
+export const XAI_DETAILS_URL = 'https://api.x.ai/v1/language-models';
+const agents = ['claude-code', 'codex', 'pi'] as const;
+type RecordValue = Record<string, unknown>;
+function record(value: unknown): value is RecordValue {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+function strings(value: unknown): string[] | undefined {
+ return Array.isArray(value) && value.every(v => typeof v === 'string') ? value : undefined;
+}
+function price(value: unknown): number | undefined {
+ // Official REST contract: USD cents per 100 million tokens -> USD per million.
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
+ ? value / 10_000 : undefined;
+}
+function tariffs(row: RecordValue, observedAt: string): ModelReferencePrice[] | undefined {
+ const input = price(row.prompt_text_token_price);
+ const output = price(row.completion_text_token_price);
+ if (input === undefined || output === undefined) return undefined;
+ const cache = price(row.cached_prompt_text_token_price);
+ const threshold = row.long_context_threshold;
+ if (threshold !== undefined && (!Number.isSafeInteger(threshold) || Number(threshold) < 0)) {
+ throw new Error('Invalid xAI long-context threshold');
+ }
+ const standard: ModelReferencePrice = {
+ currency: 'USD', variant: 'standard', inputPerMtok: input, outputPerMtok: output,
+ ...(cache !== undefined ? { cacheReadPerMtok: cache } : {}),
+ // Observation date, not a claim about the provider's historical launch date.
+ effectiveFrom: observedAt.slice(0, 10),
+ source: { kind: 'provider-official', url: XAI_DETAILS_URL, verifiedAt: observedAt.slice(0, 10) },
+ };
+ if (!threshold) return [standard];
+ const long = (key: string, fallback: number | undefined) => {
+ const value = price(row[key]);
+ // xAI explicitly defines zero as “use standard” for *_long_context fields.
+ return value === 0 ? fallback : value;
+ };
+ const longInput = long('prompt_text_token_price_long_context', input);
+ const longOutput = long('completion_text_token_price_long_context', output);
+ if (longInput === undefined || longOutput === undefined) return undefined;
+ const longCache = long('cached_prompt_text_token_price_long_context', cache);
+ const { cacheReadPerMtok: _standardCache, ...longBase } = standard;
+ return [
+ { ...standard, maxInputTokens: Number(threshold) },
+ { ...longBase, minInputTokens: Number(threshold), inputPerMtok: longInput,
+ outputPerMtok: longOutput, ...(longCache !== undefined ? { cacheReadPerMtok: longCache } : {}) },
+ ];
+}
+function tariffValue(prices: ModelReferencePrice[]) {
+ return prices.map(({ source: _source, effectiveFrom: _from, effectiveUntil: _until, ...value }) => value)
+ .sort((a, b) => (a.minInputTokens ?? 0) - (b.minInputTokens ?? 0));
+}
+/** Keep history and other variants; a changed price starts at first observation, never backdated. */
+function mergeTariffs(previous: ModelReferencePrice[], next: ModelReferencePrice[], day: string) {
+ const active = previous.filter(p => p.variant === 'standard' && p.currency === 'USD' &&
+ p.effectiveFrom <= day && (!p.effectiveUntil || day < p.effectiveUntil));
+ const sameBand = (a: ModelReferencePrice, b: ModelReferencePrice) =>
+ (a.minInputTokens ?? 0) === (b.minInputTokens ?? 0) && a.maxInputTokens === b.maxInputTokens;
+ let inheritedCache = false;
+ next = next.map(p => {
+ if (p.cacheReadPerMtok !== undefined) return p;
+ const known = active.find(old => sameBand(old, p) && old.cacheReadPerMtok !== undefined);
+ if (!known) return p;
+ inheritedCache = true;
+ return { ...p, cacheReadPerMtok: known.cacheReadPerMtok,
+ // The API did not re-verify the carried cache price. Keep the older verification date.
+ source: { ...p.source, verifiedAt: known.source.verifiedAt < p.source.verifiedAt
+ ? known.source.verifiedAt : p.source.verifiedAt } };
+ });
+ if (isDeepStrictEqual(tariffValue(active), tariffValue(next))) {
+ return { inheritedCache, prices: previous.map(p => active.includes(p)
+ ? { ...p, source: next.find(n => sameBand(n, p))!.source } : p) };
+ }
+ // A date-only schema cannot represent two changes in one day. Refuse to destroy that history.
+ if (active.some(p => p.effectiveFrom === day)) throw new Error('Conflicting xAI tariffs on the same date');
+ return { inheritedCache,
+ prices: [...previous.map(p => active.includes(p) ? { ...p, effectiveUntil: day } : p), ...next] };
+}
+
+export function buildXaiSyncCandidate(baseline: Catalog, accountPayload: unknown, detailsPayload: unknown, observedAt: string) {
+ if (!Number.isFinite(Date.parse(observedAt))) throw new Error('Invalid observation timestamp');
+ const catalog = structuredClone(baseline);
+ if (catalog.modelRegistry?.schemaVersion !== 5) throw new Error('Sync requires an existing V5 catalog');
+ const registry = catalog.modelRegistry;
+ const provider = catalog.providers.find(p => p.id === 'xai');
+ if (!provider) throw new Error('Catalog lacks xAI subscription routing');
+ // API discovery supplies no Fast execution relation or tariff. Preserve explicitly verified
+ // catalog facts; never derive these from a suffix or from "2x" in a description.
+ const verified = BUNDLED_CATALOG.providers.find(p => p.id === 'xai')!;
+ const fastParents = [...new Map([
+ ...(verified.models.codex ?? []), ...(provider.models.codex ?? []),
+ ].filter(m => m.fastModelId).map(m => [m.id, m])).values()];
+ for (const parent of fastParents) {
+ for (const id of [parent.id, parent.fastModelId!]) {
+ const source = BUNDLED_CATALOG.modelRegistry?.baseModels?.find(b => b.id === id);
+ if (!source) continue;
+ registry.baseModels ??= [];
+ const existing = registry.baseModels.find(b => b.id === id);
+ if (!existing) registry.baseModels.push(structuredClone(source));
+ else for (const sourceGroup of source.referencePriceGroups ?? []) {
+ existing.referencePriceGroups ??= [];
+ const group = existing.referencePriceGroups.find(g => g.id === sourceGroup.id);
+ if (!group) existing.referencePriceGroups.push(structuredClone(sourceGroup));
+ else for (const variant of new Set(sourceGroup.prices.map(p => p.variant))) {
+ if (!group.prices.some(p => p.variant === variant)) {
+ group.prices.push(...structuredClone(sourceGroup.prices.filter(p => p.variant === variant)));
+ }
+ }
+ }
+ }
+ }
+ if (record(accountPayload) && Array.isArray(accountPayload.data)) {
+ for (const row of accountPayload.data) {
+ if (!record(row) || row.hidden === true || (record(row._meta) && row._meta.hidden === true)) continue;
+ if (row.api_backend !== undefined && row.api_backend !== 'responses') {
+ throw new Error('Unsupported xAI discovery backend; keep the previous catalog');
+ }
+ }
+ }
+ const discovered = parseXaiAccountModels(accountPayload);
+ if (!discovered.length) throw new Error('Empty account list: refusing to replace a working catalog');
+ if (!record(detailsPayload) || !Array.isArray(detailsPayload.models) || !detailsPayload.models.length) {
+ throw new Error('Invalid or empty xAI language-models response');
+ }
+ const details = detailsPayload.models;
+ if (!details.every(row => record(row) && typeof row.id === 'string')) throw new Error('Invalid xAI detail record');
+ const ids = new Set(details.map(row => row.id));
+ if (ids.size !== details.length) throw new Error('Duplicate xAI detail IDs');
+ const gaps: Array<{ modelId: string; fields: string[] }> = [];
+ const evidence: Array<{ modelId: string; detailId?: string; fieldsFromApi: string[]; fieldsFromCatalog: string[] }> = [];
+ for (const member of discovered) {
+ const wireId = member.id.replace(/^xai\//, '');
+ const exact = details.filter(row => row.id === wireId);
+ const matches = exact.length ? exact : details.filter(row => strings(row.aliases)?.includes(wireId));
+ if (matches.length > 1) throw new Error(`Ambiguous xAI alias: ${wireId}`);
+ const detail = matches[0];
+ const input = detail && strings(detail.input_modalities);
+ const output = detail && strings(detail.output_modalities);
+ const capabilities = detail && record(detail.capabilities) ? detail.capabilities : undefined;
+ // Reuse the runtime parser for effort validation and ascending order.
+ const capabilityModel = capabilities ? parseXaiAccountModels({ data: [{ id: wireId,
+ reasoning_efforts: capabilities.reasoning_effort,
+ reasoning_effort: capabilities.default_reasoning_effort,
+ }] })[0] : undefined;
+ const metadata: ModelMetadata = {
+ ...(input ? { supportsImageInput: input.includes('image') } : {}),
+ ...(input && output ? { modalities: { input, output } } : {}),
+ ...(capabilityModel?.efforts !== undefined ? { efforts: capabilityModel.efforts } : {}),
+ ...(capabilityModel?.defaultEffort !== undefined ? { defaultEffort: capabilityModel.defaultEffort } : {}),
+ };
+ let entry = registry.models.find(e => e.routes.some(r => r.providerId === 'xai' && r.modelId === member.id));
+ if (!entry) {
+ entry = { id: member.id, name: member.name ?? wireId, status: 'active', modelRef: member.id,
+ routes: [{ providerId: 'xai', modelId: member.id, agents: ['claude-code', 'codex'] }] };
+ registry.models.push(entry);
+ }
+ const baseId = entry.modelRef ?? entry.id;
+ registry.baseModels ??= [];
+ let baseModel = registry.baseModels.find(b => b.id === baseId);
+ if (!baseModel) { baseModel = { id: baseId, aliases: [], defaults: {} }; registry.baseModels.push(baseModel); }
+ // Account-only fields stay on this connection's route; never become universal public facts.
+ const route = entry.routes.find(r => r.providerId === 'xai' && r.modelId === member.id)!;
+ const configuredDefault = resolveModelMetadata(registry, 'xai', member.id).defaultEffort;
+ const accountMetadata = catalogModelMetadata(member);
+ // A recommended effort is not a new configuration decision. Existing intent wins.
+ if (configuredDefault !== undefined) delete accountMetadata.defaultEffort;
+ route.defaults = { ...route.defaults, ...accountMetadata };
+ const baseDefault = baseModel.defaults.defaultEffort;
+ baseModel.defaults = { ...baseModel.defaults, ...metadata,
+ ...(baseDefault !== undefined ? { defaultEffort: baseDefault } : {}) };
+ if (member.nativeApi === 'openai-responses' && entry.nativeApi === undefined) entry.nativeApi = member.nativeApi;
+ const prices = detail ? tariffs(detail, observedAt) : undefined;
+ const knownFast = fastParents.some(m => m.fastModelId === member.id);
+ const knownParent = fastParents.some(m => m.id === member.id);
+ if (knownFast || knownParent) route.referencePriceGroup ??= 'global';
+ let inheritedCache = false;
+ if (prices) {
+ baseModel.referencePriceGroups ??= [];
+ let group = baseModel.referencePriceGroups.find(g => g.id === 'global');
+ if (!group) { group = { id: 'global', prices: [] }; baseModel.referencePriceGroups.push(group); }
+ const merged = mergeTariffs(group.prices, prices, observedAt.slice(0, 10));
+ group.prices = merged.prices;
+ inheritedCache = merged.inheritedCache;
+ route.referencePriceGroup ??= 'global';
+ }
+ const missing: string[] = [];
+ const hasCatalogPrice = baseModel.referencePriceGroups?.some(g => g.prices.some(p =>
+ p.variant === 'standard' && p.effectiveFrom <= observedAt.slice(0, 10) &&
+ (!p.effectiveUntil || observedAt.slice(0, 10) < p.effectiveUntil)));
+ if (!detail) missing.push('officialDetails');
+ if (!prices && !hasCatalogPrice) missing.push('apiReferencePrice');
+ if (prices?.some(p => p.cacheReadPerMtok === undefined)) missing.push('apiCacheReadPrice');
+ if (!input && baseModel.defaults.supportsImageInput === undefined) missing.push('inputModalities');
+ if (member.maxOutput === undefined) missing.push('apiMaxOutput');
+ // Neither endpoint declares the Fast toggle's execution semantics. Names are not evidence.
+ if (!knownFast && !knownParent) missing.push('fastExecution');
+ gaps.push({ modelId: member.id, fields: missing });
+ evidence.push({ modelId: member.id, ...(detail ? { detailId: detail.id as string } : {}),
+ fieldsFromCatalog: [...(knownParent || knownFast ? ['fastExecution'] : []),
+ ...(inheritedCache ? ['cacheReadReferencePrice'] : []),
+ ...(!prices && hasCatalogPrice ? ['referencePrices'] : [])],
+ fieldsFromApi: [...Object.keys(catalogModelMetadata(member)), ...Object.keys(metadata), ...(prices ? ['referencePrices'] : [])] });
+ for (const agent of agents) {
+ const id = agent === 'pi' ? wireId : member.id;
+ provider.models[agent] ??= [];
+ const old = provider.models[agent]!.find(m => m.id === id);
+ const resolved = resolveModelMetadata(registry, 'xai', member.id, catalogModelMetadata(member), undefined, agent);
+ if (!resolved.contextWindow && !old?.contextWindow) throw new Error(`Unknown context window: ${member.id}`);
+ const efforts = resolved.efforts ?? old?.efforts ?? [];
+ const seed: CatalogModel = old ?? { id, name: member.name ?? wireId,
+ contextWindow: resolved.contextWindow!, efforts, defaultEffort: null, status: 'active' };
+ const model = applyModelMetadata(seed, resolved);
+ const fastMapping = verified.models[agent]?.find(m => m.id === id)?.fastModelId;
+ if (model.fastModelId === undefined && fastMapping !== undefined) model.fastModelId = fastMapping;
+ // The new runtime derives Fast capability from the mapping + account membership.
+ // Do not publish a boolean that would make an older client send service_tier instead.
+ if (member.nativeApi !== undefined) model.nativeApi = member.nativeApi;
+ if (agent === 'pi' && member.nativeApi === 'openai-responses') model.piApi = 'openai-responses';
+ const comparison = modelProtocolComparison(provider, { [agent]: model }).forAgent(agent);
+ // Unspecified user preferences follow native engines only; the real user override is applied later.
+ const declaredDefault = (agent === 'pi' ? undefined : entry.perAgent?.[agent]?.defaultEnabled)
+ ?? entry.defaultEnabled ?? old?.defaultEnabled;
+ model.defaultEnabled = declaredDefault !== false && !knownFast && comparison?.mode === 'matching';
+ if (agent !== 'pi') {
+ entry.perAgent ??= {};
+ entry.perAgent[agent] = { ...entry.perAgent[agent], defaultEnabled: model.defaultEnabled };
+ }
+ provider.models[agent] = [...provider.models[agent]!.filter(m => m.id !== id), model];
+ }
+ }
+ // Keep monotonic revision even when the clock is behind the baseline's publication time.
+ registry.updatedAt = new Date(Math.max(Date.parse(observedAt), Date.parse(registry.updatedAt) + 1)).toISOString();
+ return { catalog: parseCatalog(catalog), discovered, evidence, gaps, observedAt };
+}
+
+/** Actual app import -> active catalog -> picker descriptors and price presentation input. */
+export function inspectXaiImport(candidate: ReturnType<typeof buildXaiSyncCandidate>) {
+ // Verify the artifact alone, then again with normal live discovery layered on top.
+ setXaiDiscoveredModels(null);
+ setActiveCatalog(parseCatalog(JSON.stringify(candidate.catalog)));
+ const fromFile = getActiveCatalog();
+ for (const member of candidate.discovered) {
+ for (const agent of agents) {
+ const id = agent === 'pi' ? member.id.replace(/^xai\//, '') : member.id;
+ const xai = fromFile.providers.find(p => p.id === 'xai')!;
+ if (!deriveAvailableModels({ ...fromFile, providers: [xai] }, agent).some(m => m.id === id)) {
+ throw new Error(`Serialized catalog missing ${agent}/${member.id}`);
+ }
+ }
+ }
+ setXaiDiscoveredModels(candidate.discovered);
+ const active = getActiveCatalog();
+ const provider = active.providers.find(p => p.id === 'xai')!;
+ const rows = candidate.discovered.map(member => {
+ const modelRows = Object.fromEntries(agents.map(agent => [agent, provider.models[agent]?.find(
+ m => m.id === (agent === 'pi' ? member.id.replace(/^xai\//, '') : member.id))]));
+ const comparison = modelProtocolComparison(provider, modelRows);
+ return { modelId: member.id, harnesses: Object.fromEntries(agents.map(agent => {
+ const model = modelRows[agent];
+ const descriptor = deriveAvailableModels({ ...active, providers: [provider] }, agent).find(m => m.id === model?.id);
+ if (!model || !descriptor) throw new Error(`Import missing ${agent}/${member.id}`);
+ if (comparison.forAgent(agent)?.mode === 'compatibility' && model.defaultEnabled === true) {
+ throw new Error(`Compatibility route incorrectly enabled: ${agent}/${member.id}`);
+ }
+ const quote = providerReferencePriceQuote('xai', member.id, active.modelRegistry, { agent, officialOnly: true, at: candidate.observedAt });
+ return [agent, { ...descriptor, protocol: comparison.forAgent(agent), apiReferencePrice: quote ?? null }];
+ })) };
+ });
+ return { rows, importedModels: rows.length, harnessProjections: rows.length * agents.length,
+ complete: candidate.gaps.every(g => !g.fields.length), gaps: candidate.gaps, evidence: candidate.evidence,
+ generationRequests: 0, verification: 'active-catalog + picker descriptors + reference-price resolver; no GUI or inference' };
+}