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(model-routing): 修复 Grok 4.6 协议与凭证路由 (#3182)

Chris Zhangec41931fc042
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 cb449fc715..d2879e6849 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
@@ -128,6 +128,7 @@ describe('active-catalog discovered augment', () => {
const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
expect(xai?.agents).toContain('pi');
expect(xai?.routing.pi?.upstream).toBe('https://api.x.ai/v1');
+ expect(xai?.models.pi?.find((model) => model.id === 'grok-4.6')?.piApi).toBe('openai-responses');
expect(xai?.models.pi?.map((model) => model.id)).toEqual([
'grok-4.3',
'grok-4.5',
@@ -144,8 +145,8 @@ describe('active-catalog discovered augment', () => {
defaultEffort: 'high',
});
expect(xai?.models.pi?.find((model) => model.id === 'grok-4.3')).toMatchObject({
- efforts: [],
- defaultEffort: null,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'medium',
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
index 90701d62ed..6f0b14a16e 100644
--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
@@ -105,7 +105,12 @@ function injectedCatalog(): Catalog {
describe('deriveAvailableModels — dynamic-first catalog contract', () => {
it('publishes Pi effort controls only when the official catalog has an explicit thinking map', () => {
const pi = deriveAvailableModels(BUNDLED_CATALOG, 'pi');
- expect(pi.find((m) => m.id === 'grok-4.3')?.efforts).toEqual([]);
+ expect(pi.find((m) => m.id === 'grok-4.3')?.efforts).toEqual([
+ 'minimal',
+ 'low',
+ 'medium',
+ 'high',
+ ]);
expect(pi.find((m) => m.id === 'grok-4.5')?.efforts).toEqual([
'minimal',
'low',
@@ -188,8 +193,8 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {
const flat = flatModels.filter((m) => m.id === 'grok-4.3');
expect(flat).toHaveLength(1);
expect(flat[0]).toMatchObject({
- efforts: [],
- defaultEffort: null,
+ efforts: ['low'],
+ defaultEffort: 'low',
});
expect(
resolvePiRuntimeModelDescriptor(catalog, 'colliding-reasoning', 'grok-4.3'),
diff --git a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
index 05f8e17cd8..fb7307a98d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-const state = vi.hoisted(() => ({ loggedIn: false, sharedSkillRefreshes: 0 }));
+const state = vi.hoisted(() => ({ loggedIn: false, proxyReady: true, sharedSkillRefreshes: 0 }));
vi.mock('electron', () => ({
app: {
@@ -56,15 +56,29 @@ vi.mock('../grok-oauth-login.js', () => ({
peekGrokAccessToken: () => (state.loggedIn ? 'grok-test-token' : null),
recoverGrokAuthAfterRejection: async () => 'superseded' as const,
}));
+vi.mock('../anthropic-compat-proxy-host.js', () => ({
+ getClaudeEndpoint: () => 'http://127.0.0.1:18765',
+ isAnthropicCompatProxyHandleReady: () => state.proxyReady,
+}));
import { desktopPiAuthAdapter, resolvePiNativeProviders } from '../pi-host.js';
describe('Pi pure BYOM auth without a Cindy account', () => {
beforeEach(() => {
state.loggedIn = false;
+ state.proxyReady = true;
state.sharedSkillRefreshes = 0;
});
+ it('fails closed when an official SuperGrok route has no local compat proxy', async () => {
+ state.proxyReady = false;
+ await expect(resolvePiNativeProviders({
+ workingDir: '/tmp/project',
+ providerId: 'xai',
+ model: 'grok-4.6',
+ })).rejects.toThrow('local compatibility proxy is not ready');
+ });
+
it('refreshes local shared skills before provider resolution and skips remote homes', async () => {
await resolvePiNativeProviders({
workingDir: '/tmp/project',
@@ -118,9 +132,9 @@ describe('Pi pure BYOM auth without a Cindy account', () => {
expect(resolved.providers).toContainEqual(
expect.objectContaining({
- id: 'cindy-byom-xai',
+ id: 'xai',
sourceProviderId: 'xai',
- baseUrl: expect.not.stringContaining('private-xai.example'),
+ baseUrl: 'http://127.0.0.1:18765/v1',
}),
);
expect(resolved.providers).toContainEqual(
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 1fb77072fe..9e352303c8 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -269,8 +269,8 @@ describe('buildPiNativeProvidersFromConfigs', () => {
expect(providers).toHaveLength(1);
expect(providers[0]).toMatchObject({
id: 'xai',
- baseUrl: 'http://127.0.0.1:18765',
- api: 'anthropic-messages',
+ baseUrl: 'http://127.0.0.1:18765/v1',
+ api: 'openai-responses',
apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',
headers: {
'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
@@ -280,7 +280,8 @@ describe('buildPiNativeProvidersFromConfigs', () => {
modelIdAliases: { 'grok-4.6': 'xai/grok-4.6' },
});
expect(providers[0]?.models.find((model) => model.id === 'xai/grok-4.6')).toMatchObject({
- api: 'anthropic-messages',
+ wireId: 'grok-4.6',
+ api: 'openai-responses',
contextWindow: 500_000,
maxTokens: 500_000,
input: ['text', 'image'],
@@ -292,8 +293,6 @@ describe('buildPiNativeProvidersFromConfigs', () => {
xhigh: 'xhigh',
},
compat: {
- supportsStore: false,
- supportsDeveloperRole: false,
supportsReasoningEffort: true,
},
});
@@ -306,8 +305,8 @@ describe('buildPiNativeProvidersFromConfigs', () => {
const { providers } = await buildXaiPiNativeProvider('grok-4.6', false, true);
expect(providers[0]).toMatchObject({
id: 'xai',
- baseUrl: `http://127.0.0.1:${PI_XAI_COMPAT_FORWARD_PORT}`,
- api: 'anthropic-messages',
+ baseUrl: `http://127.0.0.1:${PI_XAI_COMPAT_FORWARD_PORT}/v1`,
+ api: 'openai-responses',
headers: {
'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
@@ -318,6 +317,10 @@ describe('buildPiNativeProvidersFromConfigs', () => {
remotePort: PI_XAI_COMPAT_FORWARD_PORT,
},
});
+ expect(providers[0]?.models.find((model) => model.id === 'xai/grok-4.6')).toMatchObject({
+ wireId: 'grok-4.6',
+ api: 'openai-responses',
+ });
});
it('adds a private conservative xAI descriptor only when resuming a historical namespaced id', async () => {
@@ -325,8 +328,9 @@ describe('buildPiNativeProvidersFromConfigs', () => {
const { providers } = await buildXaiPiNativeProvider('xai/grok-retired', true);
expect(providers[0]?.models.find((model) => model.id === 'xai/grok-retired')).toEqual({
id: 'xai/grok-retired',
+ wireId: 'grok-retired',
name: 'xai/grok-retired',
- api: 'anthropic-messages',
+ api: 'openai-responses',
});
expect(providers[0]?.modelIdAliases?.['grok-retired']).toBe('xai/grok-retired');
});
@@ -369,9 +373,7 @@ describe('buildPiNativeProvidersFromConfigs', () => {
const anthropicModels = [...(catalog?.get('anthropic')?.values() ?? [])];
expect(anthropicModels.length).toBeGreaterThan(0);
expect(anthropicModels.every((model) => model.api === 'anthropic-messages')).toBe(true);
- expect(resolvePiBundledApiByModelId(catalog ?? undefined, 'glm-5.2')).toBe(
- 'openai-completions',
- );
+ expect(resolvePiBundledApiByModelId(catalog ?? undefined, 'glm-5.2')).toBe('openai-completions');
expect(catalog?.get('zai')?.get('glm-5.2')).toMatchObject({
api: 'openai-completions',
baseUrl: 'https://api.z.ai/api/coding/paas/v4',
@@ -633,7 +635,9 @@ describe('buildPiNativeProvidersFromConfigs', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
const xai = catalog.providers.find((provider) => provider.id === 'xai');
expect(xai?.models.pi?.some((model) => model.id === 'grok-4.6')).toBe(true);
- expect(xai?.models.pi?.find((model) => model.id === 'grok-4.6')?.piApi).toBeUndefined();
+ expect(xai?.models.pi?.find((model) => model.id === 'grok-4.6')?.piApi).toBe(
+ 'openai-responses',
+ );
const { providers } = buildPiSubscriptionNativeProviders(
catalog,
@@ -654,13 +658,13 @@ describe('buildPiNativeProvidersFromConfigs', () => {
expect(xaiProvider?.models.find((model) => model.id === 'grok-4.6')?.api).toBe('openai-responses');
expect(xaiProvider?.models.find((model) => model.id === 'grok-4.5')?.catalogAddition).toBeUndefined();
expect(xaiProvider?.models.find((model) => model.id === 'grok-4.3')?.catalogAddition).toBeUndefined();
- expect(xaiProvider?.models.find((model) => model.id === 'grok-4.3')?.api).toBeUndefined();
+ expect(xaiProvider?.models.find((model) => model.id === 'grok-4.3')?.api).toBe('openai-responses');
expect(xaiProvider?.models.find((model) => model.id === 'grok-build-0.1')?.catalogAddition).toBeUndefined();
});
- it('does not mark SuperGrok models as catalog additions when the PI probe is unavailable', () => {
+ it('keeps exact SuperGrok protocol annotations when the PI probe is unavailable', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
- expect(catalog.providers.find((provider) => provider.id === 'xai')?.models.pi?.find((model) => model.id === 'grok-4.6')?.piApi).toBeUndefined();
+ expect(catalog.providers.find((provider) => provider.id === 'xai')?.models.pi?.find((model) => model.id === 'grok-4.6')?.piApi).toBe('openai-responses');
const { providers } = buildPiSubscriptionNativeProviders(
catalog,
@@ -668,8 +672,12 @@ describe('buildPiNativeProvidersFromConfigs', () => {
);
const xaiProvider = providers.find((provider) => provider.id === 'xai');
- expect(xaiProvider?.models.find((model) => model.id === 'grok-4.6')?.catalogAddition).toBeUndefined();
- expect(xaiProvider?.models.find((model) => model.id === 'grok-4.5')?.catalogAddition).toBeUndefined();
+ expect(xaiProvider?.models.find((model) => model.id === 'grok-4.6')).toMatchObject({
+ api: 'openai-responses',
+ });
+ expect(xaiProvider?.models.find((model) => model.id === 'grok-4.5')).toMatchObject({
+ api: 'openai-responses',
+ });
});
it('does not mark SuperGrok models as catalog additions when the probe has no xAI baseline', () => {
@@ -731,7 +739,7 @@ describe('buildPiNativeProvidersFromConfigs', () => {
.find((provider) => provider.id === 'xai')
?.models.find((model) => model.wireId === 'grok-4.6' || model.id === 'grok-4.6');
expect(grok).toMatchObject({
- api: 'openai-completions',
+ api: 'openai-responses',
reasoning: true,
thinkingLevelMap: {
low: 'low',
@@ -985,7 +993,7 @@ describe('buildPiNativeProvidersFromConfigs', () => {
});
});
- it('writes pinned-Pi-missing Grok 4.6 as an openai-responses catalog addition', () => {
+ it('writes pinned-Pi-missing Grok 4.6 using the official openai-responses API', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
const xai = catalog.providers.find((provider) => provider.id === 'xai')!;
xai.models.pi = [
@@ -1001,7 +1009,7 @@ describe('buildPiNativeProvidersFromConfigs', () => {
const provider = buildPiSubscriptionNativeProviders(
catalog,
'http://127.0.0.1:4567/',
- new Map([['xai', new Map([['grok-4.5', piBundledModel('grok-4.5', 'openai-responses')]])]]),
+ new Map([['xai', new Map([['grok-4.5', piBundledModel('grok-4.5', 'openai-completions')]])]]),
new Map([['xai', new Set(['grok-4.5'])]]),
).providers.find((candidate) => candidate.id === 'xai');
expect(provider?.models).toEqual([
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 1c4783282f..e4fa0dbb1d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@ -773,6 +773,38 @@ describe('PI native subscription forwarding', () => {
});
});
+ it('labels pre-response xAI failures with the real provider and endpoint', async () => {
+ const injected = deps({
+ fetch: vi.fn(async () => {
+ throw Object.assign(new TypeError('fetch failed'), { cause: { code: 'ENOTFOUND' } });
+ }) as PiNativeSubscriptionHandlerDeps['fetch'],
+ });
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-network-error', injected);
+ const res = responseRecorder();
+
+ await handler({
+ rawBody: Buffer.from('{"model":"grok-4.6"}'),
+ parsedBody: { model: 'grok-4.6' },
+ ctx: {
+ reqId: 14,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res,
+ } as never);
+
+ expect(res.status).toBe(502);
+ expect(JSON.parse(Buffer.concat(res.chunks).toString('utf8'))).toMatchObject({
+ error: {
+ type: 'upstream_error',
+ provider: 'xai',
+ endpoint: 'https://api.x.ai/v1/responses',
+ message: 'xAI/Grok upstream request failed: fetch failed',
+ },
+ });
+ });
+
it('rejects unsupported native paths without contacting an upstream', async () => {
const injected = deps();
const handler = getPiNativeSubscriptionHandler('openai', 'session-3', injected);
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 8c355dfb84..6e751ea8e3 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
@@ -43,6 +43,7 @@ import { buildChatgptBridgeHeaders } from './chatgpt-bridge-headers.js';
import { recordXaiRateLimitSnapshot } from '../usageBroadcaster.js';
import { XAI_X_SEARCH_TOOL_TYPE, xaiServerSideTools } from './xai-server-side-tools.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from '../../shared/subscriptionModels.js';
+import { describeErrorChain } from '../utils/errorChain.js';
const zstdCompressAsync = promisify(zstdCompress);
const zstdDecompressAsync = promisify(zstdDecompress);
@@ -753,9 +754,14 @@ export function getPiNativeSubscriptionHandler(
// which destroys the client response so PI observes a transport failure
// instead of accepting a cleanly-ended truncated stream.
if (res.headersSent) throw err;
+ const detail = describeErrorChain(err);
+ const providerLabel = providerId === 'xai' ? 'xAI/Grok' : 'OpenAI/ChatGPT';
log.warn('PI native subscription forwarding failed', {
providerId,
- err: err instanceof Error ? err.message : String(err),
+ endpoint: upstream.url,
+ wireProtocol: upstream.wireProtocol,
+ requestPath: ctx.url,
+ detail,
});
res.writeHead(502, {
'content-type': 'application/json; charset=utf-8',
@@ -764,7 +770,9 @@ export function getPiNativeSubscriptionHandler(
res.end(JSON.stringify({
error: {
type: 'upstream_error',
- message: err instanceof Error ? err.message : String(err),
+ provider: providerId,
+ endpoint: upstream.url,
+ message: `${providerLabel} upstream request failed: ${err instanceof Error ? err.message : String(err)}`,
},
}));
} finally {
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 659ba575a0..7ee3b7b3fc 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -24,6 +24,7 @@ import { app } from 'electron';
import {
PiAgent,
+ PiNativeProviderProxyNotReadyError,
type AgentDeps,
type AuthAdapter,
type AuthState,
@@ -95,6 +96,7 @@ import {
getLocalCatalogOverridesSnapshot,
resolveXdPiGatewayWireProtocol,
} from './active-catalog.js';
+import { isExclusiveXaiModelId } from '../../shared/subscriptionModels.js';
import { resolvePiRuntimeModelDescriptor } from './catalog-to-descriptors.js';
import { resolveManagedPiPackageResources } from './pi-package-store.js';
import { mutateAuthorizedPiManagedPackage } from './pi-managed-package-mutation.js';
@@ -159,7 +161,13 @@ function piOpenaiProxyPlaceholderJwt(): string {
}
function appendEndpointPath(endpoint: string, suffix: string): string {
- return `${endpoint.replace(/\/+$/, '')}/${suffix.replace(/^\/+/, '')}`;
+ const url = new URL(endpoint);
+ const normalizedSuffix = `/${suffix.replace(/^\/+/, '').replace(/\/+$/, '')}`;
+ const pathname = url.pathname.replace(/\/+$/, '');
+ if (!pathname.endsWith(normalizedSuffix)) {
+ url.pathname = `${pathname}${normalizedSuffix}`;
+ }
+ return url.toString().replace(/\/$/, '');
}
function piSubscriptionHeaders(providerId: string): Record<string, string> {
@@ -658,14 +666,14 @@ export function buildPiSubscriptionNativeProviders(
? { catalogAddition: true }
: {}),
...(isXaiCatalogAddition
- ? { api: model.piApi ?? 'openai-responses' }
- : capabilityCorrection
- ? { api: capabilityCorrection.api }
+ ? { api: model.piApi ?? officialModel?.api ?? bundledModel?.api ?? 'openai-responses' }
: sourceProviderId !== 'openai' &&
model.piApi &&
(isAnnotatedAddition || isProtocolCorrection)
? { api: model.piApi }
- : {}),
+ : capabilityCorrection
+ ? { api: capabilityCorrection.api }
+ : {}),
name: isContextProfileAddition ? model.name : (preserved?.name ?? model.name),
contextWindow: isContextProfileAddition
? model.contextWindow
@@ -1389,9 +1397,10 @@ export async function buildXaiPiNativeProvider(
),
})),
id: `xai/${catalogModel.id}`,
- // Keep the xai/ prefix on the wire so the existing compat proxy selects its Responses
- // bridge, which refreshes OAuth per request, recovers 401/403, and injects x_search.
- api: 'anthropic-messages' as const,
+ wireId: catalogModel.id,
+ // Keep the exact API from Pi's catalog. The host forwarder authenticates and forwards both
+ // native shapes without sending the request through the Claude Messages bridge.
+ api: catalogModel.piApi ?? officialById.get(catalogModel.id)?.api ?? 'openai-responses',
}));
const aliases = Object.fromEntries(
catalogModels.flatMap((candidate) => [
@@ -1407,7 +1416,12 @@ export async function buildXaiPiNativeProvider(
}
// Resume compatibility only: preserve the historical id and route it through the same
// proxy without asserting unverified vision/reasoning capabilities or publishing it.
- models.push({ id: namespacedModel, name: namespacedModel, api: 'anthropic-messages' });
+ models.push({
+ id: namespacedModel,
+ wireId: piNativeModelId('xai', namespacedModel),
+ name: namespacedModel,
+ api: 'openai-responses',
+ });
aliases[model] = namespacedModel;
aliases[piNativeModelId('xai', model)] = namespacedModel;
}
@@ -1422,10 +1436,10 @@ export async function buildXaiPiNativeProvider(
const endpoint = new URL(getClaudeEndpoint());
endpoint.hostname = '127.0.0.1';
endpoint.port = String(PI_XAI_COMPAT_FORWARD_PORT);
- return endpoint.toString().replace(/\/$/, '');
+ return appendEndpointPath(endpoint.toString(), 'v1');
})()
- : getClaudeEndpoint(),
- api: 'anthropic-messages',
+ : appendEndpointPath(getClaudeEndpoint(), 'v1'),
+ api: 'openai-responses',
apiKeyEnvVar: PI_XAI_PROXY_API_KEY_ENV,
headers: {
'x-cindy-pi-session-id': `$${PI_SESSION_ID_ENV}`,
@@ -1469,10 +1483,21 @@ export async function resolvePiNativeProviders(ctx: {
// before the process snapshots its global skills. Remote Pi has a different HOME/root.
await desktopClaudeAuthAdapter.ensureSharedGlobalSkills();
}
+ const compatProxyReady = isAnthropicCompatProxyHandleReady();
+ const selectedOfficialXai =
+ ctx.providerId === 'xai' || (ctx.providerId == null && isExclusiveXaiModelId(ctx.model));
+ if (selectedOfficialXai && !compatProxyReady) {
+ log.error('resolvePiNativeProviders: SuperGrok requires the local compat proxy', {
+ providerId: ctx.providerId ?? null,
+ model: ctx.model,
+ remoteHostId: ctx.remoteHostId ?? null,
+ });
+ throw new PiNativeProviderProxyNotReadyError();
+ }
const piBinaryPath = resolvePiBinaryPath();
const bundledModels = piBinaryPath ? await readPiBundledModels(piBinaryPath) : null;
let subscriptions: PiNativeProvidersResult = { providers: [], env: {} };
- if (!ctx?.remoteHostId && isAnthropicCompatProxyHandleReady()) {
+ if (!ctx?.remoteHostId && compatProxyReady) {
const retainedOpenAiModel =
ctx.resumeSessionId && ctx.providerId === 'openai'
? resolvePiRuntimeModelDescriptor(getActiveCatalog(), 'openai', ctx.model, {
@@ -1535,9 +1560,10 @@ export async function resolvePiNativeProviders(ctx: {
// SuperGrok provenance/forwarding path there; locally the version-matched PI
// native provider above remains the protocol authority.
// inheritModels xai 现在带占位 apiKey,Pi getAvailable() 才能看见 grok-4.6。
- // 不要再塞一份 overlay xai:reserved id 会被改名成 cindy-byom-xai,Messages
- // 请求打到 PI native handler 会 404 Unsupported PI subscription endpoint。
+ // 不要再塞一份 overlay xai:reserved id 会被改名成 cindy-byom-xai;
+ // 请求打到 PI native handler 会走错误的 provider 身份并返回 404。
if (
+ compatProxyReady &&
!subscriptions.providers.some((provider) => provider.id === 'xai') &&
(ctx.providerId === 'xai' || hasGrokOAuthLogin())
) {
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index c5c165b79b..2d9ad55f3d 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -291,6 +291,21 @@ export interface PiNativeProvidersResult {
env: Record<string, string>;
}
+/**
+ * The host could not construct the first-party Pi provider because its local
+ * compatibility proxy is not ready. This is a fatal startup condition for
+ * every SuperGrok route, including provider-less and legacy sessions; it must
+ * not be converted into a silent fallback to the Cindy gateway.
+ */
+export class PiNativeProviderProxyNotReadyError extends Error {
+ readonly code = 'PI_NATIVE_PROVIDER_PROXY_NOT_READY';
+
+ constructor(message = 'SuperGrok Pi provider unavailable: local compatibility proxy is not ready') {
+ super(message);
+ this.name = 'PiNativeProviderProxyNotReadyError';
+ }
+}
+
/**
* pi MCP 桥的 per-session 身份上下文(host 用它在 bridge 上注册当前 pi 会话)。
*
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index 0fdc436a79..2f18cdf49e 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -85,7 +85,7 @@ vi.mock('../rpc-client.js', () => {
import { PiAgent } from '../index.js';
import { PiRpcRequestTimeoutError } from '../rpc-client.js';
-import type { AgentDeps } from '../../base-agent.js';
+import { PiNativeProviderProxyNotReadyError, type AgentDeps } from '../../base-agent.js';
import type { ModelDescriptor } from '../../../types/capabilities.js';
import type { Logger } from '../../../interfaces/logger.js';
@@ -1504,6 +1504,24 @@ describe('Pi provider-aware model routing', () => {
expect(captured.args).toEqual([]);
});
+ it('surfaces a first-party Pi proxy-not-ready failure for provider-less and legacy Grok sessions', async () => {
+ const proxyNotReady = new PiNativeProviderProxyNotReadyError();
+ const agent = new PiAgent(byomDeps(async () => {
+ throw proxyNotReady;
+ }, [
+ { id: 'grok-4.6', displayName: 'Grok 4.6', contextWindow: 500_000, efforts: [], defaultEffort: null },
+ ]));
+
+ for (const [index, model] of ['grok-4.6', 'xai/grok-4.6'].entries()) {
+ await expect(agent.startSession({
+ sessionId: `providerless-grok-proxy-not-ready-${index}`,
+ workingDir: cwd,
+ model,
+ })).rejects.toBe(proxyNotReady);
+ }
+ expect(captured.args).toEqual([]);
+ });
+
it('fails closed when an explicit xAI selection cannot build the Pi native provider', async () => {
const deps: AgentDeps = {
auth: {
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 4877c4c145..768763fd24 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -58,6 +58,7 @@ import {
BaseAgent,
MAIN_OWNED_SEND_CONTEXT,
PiManagedPackageMutationCancelledError,
+ PiNativeProviderProxyNotReadyError,
TurnDispatchRejectedError,
TurnDispatchUnconfirmedError,
TurnPermissionPolicyUnsupportedError,
@@ -1353,6 +1354,7 @@ export class PiAgent extends BaseAgent {
nativeProviders = resolved?.providers ?? [];
nativeEnv = resolved?.env ?? {};
} catch (err) {
+ if (err instanceof PiNativeProviderProxyNotReadyError) throw err;
nativeResolveFailed = true;
this.deps.logger.warn('pi resolvePiNativeProviders failed', {
message: err instanceof Error ? err.message : String(err),
diff --git a/packages/model-providers/catalog/pi-model-catalog.json b/packages/model-providers/catalog/pi-model-catalog.json
index dd680ae987..828155eef9 100644
--- a/packages/model-providers/catalog/pi-model-catalog.json
+++ b/packages/model-providers/catalog/pi-model-catalog.json
@@ -1,5 +1,5 @@
{
- "generatedAt": "2026-08-13T02:13:00.000Z",
+ "generatedAt": "2026-08-20T08:58:50.000Z",
"providers": {
"deepseek": [
{
@@ -1372,9 +1372,12 @@
{
"id": "grok-4.3",
"name": "Grok 4.3",
- "api": "openai-completions",
+ "api": "openai-responses",
"provider": "xai",
"baseUrl": "https://api.x.ai/v1",
+ "compat": {
+ "supportsLongCacheRetention": false
+ },
"reasoning": true,
"input": [
"text",
@@ -1388,10 +1391,14 @@
},
"contextWindow": 1000000,
"maxTokens": 30000,
- "compat": {
- "supportsStore": false,
- "supportsDeveloperRole": false,
- "supportsReasoningEffort": false
+ "thinkingLevelMap": {
+ "off": "none",
+ "minimal": null,
+ "low": "low",
+ "medium": "medium",
+ "high": "high",
+ "xhigh": null,
+ "max": null
}
},
{
@@ -1429,9 +1436,13 @@
{
"id": "grok-4.6",
"name": "Grok 4.6",
- "api": "openai-completions",
+ "api": "openai-responses",
"provider": "xai",
"baseUrl": "https://api.x.ai/v1",
+ "compat": {
+ "supportsLongCacheRetention": false,
+ "supportsReasoningEffort": true
+ },
"reasoning": true,
"input": [
"text",
@@ -1445,11 +1456,6 @@
},
"contextWindow": 500000,
"maxTokens": 500000,
- "compat": {
- "supportsStore": false,
- "supportsDeveloperRole": false,
- "supportsReasoningEffort": true
- },
"thinkingLevelMap": {
"off": null,
"minimal": null,
@@ -1463,9 +1469,12 @@
{
"id": "grok-build-0.1",
"name": "Grok Build 0.1",
- "api": "openai-completions",
+ "api": "openai-responses",
"provider": "xai",
"baseUrl": "https://api.x.ai/v1",
+ "compat": {
+ "supportsLongCacheRetention": false
+ },
"reasoning": true,
"input": [
"text",
@@ -1479,10 +1488,9 @@
},
"contextWindow": 256000,
"maxTokens": 256000,
- "compat": {
- "supportsStore": false,
- "supportsDeveloperRole": false,
- "supportsReasoningEffort": false
+ "thinkingLevelMap": {
+ "off": null,
+ "minimal": null
}
}
],
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index 892165afb1..38224fa988 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -5,7 +5,11 @@
"id": "xai",
"name": "xAI",
"source": "builtin",
- "agents": ["claude-code", "codex", "pi"],
+ "agents": [
+ "claude-code",
+ "codex",
+ "pi"
+ ],
"auth": {
"method": "oauth"
},
@@ -33,7 +37,9 @@
"claude-code": {
"upstream": "https://api.x.ai/v1",
"authStrategy": "oauth-passthrough",
- "modelPrefixes": ["xai/"]
+ "modelPrefixes": [
+ "xai/"
+ ]
},
"codex": {
"upstream": "https://api.x.ai/v1",
@@ -47,11 +53,13 @@
"originator",
"session_id"
],
- "modelPrefixes": ["xai/"]
+ "modelPrefixes": [
+ "xai/"
+ ]
},
"pi": {
"upstream": "https://api.x.ai/v1",
- "wireProtocol": "anthropic-messages",
+ "wireProtocol": "openai-responses",
"authStrategy": "provider-oauth-header",
"headerDelete": [
"chatgpt-account-id",
@@ -70,7 +78,11 @@
"sortOrder": 48,
"description": "xAI Grok 4.6 旗舰,编码/agent 任务,500k 上下文(SuperGrok 订阅直连)",
"contextWindow": 500000,
- "efforts": ["low", "medium", "high"],
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
"defaultEffort": "high",
"status": "active"
},
@@ -81,7 +93,11 @@
"sortOrder": 49,
"description": "xAI Grok 4.5,编码/agent 任务,500k 上下文(SuperGrok 订阅直连)",
"contextWindow": 500000,
- "efforts": ["low", "medium", "high"],
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
"defaultEffort": "high",
"status": "active"
},
@@ -92,7 +108,11 @@
"sortOrder": 51,
"description": "xAI Grok 4.3 通用旗舰,1M 上下文(SuperGrok 订阅直连)",
"contextWindow": 1000000,
- "efforts": ["low", "medium", "high"],
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
"defaultEffort": "high",
"status": "active"
},
@@ -151,7 +171,12 @@
"sortOrder": 98,
"description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID",
"contextWindow": 1000000,
- "efforts": ["low", "medium", "high", "xhigh"],
+ "efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
"defaultEffort": "high",
"status": "deprecated",
"defaultEnabled": false
@@ -177,7 +202,11 @@
"sortOrder": 48,
"description": "xAI Grok 4.6 旗舰,编码/agent 任务,500k 上下文(SuperGrok 订阅直连)",
"contextWindow": 500000,
- "efforts": ["low", "medium", "high"],
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
"defaultEffort": "high",
"status": "active"
},
@@ -188,7 +217,11 @@
"sortOrder": 49,
"description": "xAI Grok 4.5,编码/agent 任务,500k 上下文(SuperGrok 订阅直连)",
"contextWindow": 500000,
- "efforts": ["low", "medium", "high"],
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
"defaultEffort": "high",
"status": "active"
},
@@ -199,7 +232,11 @@
"sortOrder": 51,
"description": "xAI Grok 4.3 通用旗舰,1M 上下文(SuperGrok 订阅直连)",
"contextWindow": 1000000,
- "efforts": ["low", "medium", "high"],
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
"defaultEffort": "high",
"status": "active"
},
@@ -258,7 +295,11 @@
"sortOrder": 98,
"description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID",
"contextWindow": 1000000,
- "efforts": ["low", "medium", "high"],
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
"defaultEffort": "high",
"status": "deprecated",
"defaultEnabled": false
@@ -280,12 +321,17 @@
{
"id": "grok-4.3",
"name": "Grok 4.3",
+ "piApi": "openai-responses",
"group": "grok",
"sortOrder": 49,
"contextWindow": 1000000,
"maxOutput": 30000,
- "efforts": [],
- "defaultEffort": null,
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
+ "defaultEffort": "medium",
"status": "active",
"supportsImageInput": true,
"cost": {
@@ -298,11 +344,16 @@
{
"id": "grok-4.5",
"name": "Grok 4.5",
+ "piApi": "openai-responses",
"group": "grok",
"sortOrder": 50,
"contextWindow": 500000,
"maxOutput": 500000,
- "efforts": ["low", "medium", "high"],
+ "efforts": [
+ "low",
+ "medium",
+ "high"
+ ],
"defaultEffort": "medium",
"status": "active",
"supportsImageInput": true,
@@ -316,11 +367,17 @@
{
"id": "grok-4.6",
"name": "Grok 4.6",
+ "piApi": "openai-responses",
"group": "grok",
"sortOrder": 51,
"contextWindow": 500000,
"maxOutput": 500000,
- "efforts": ["low", "medium", "high", "xhigh"],
+ "efforts": [
+ "low",
+ "medium",
+ "high",
+ "xhigh"
+ ],
"defaultEffort": "high",
"status": "active",
"supportsImageInput": true,
@@ -334,6 +391,7 @@
{
"id": "grok-build-0.1",
"name": "Grok Build 0.1",
+ "piApi": "openai-responses",
"group": "grok",
"sortOrder": 52,
"contextWindow": 256000,
@@ -462,7 +520,11 @@
"name": "DeepSeek V4 Flash",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["low", "high", "max"],
+ "reasoningEfforts": [
+ "low",
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -470,7 +532,10 @@
"name": "DeepSeek V4 Pro",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
}
]
@@ -686,7 +751,11 @@
"contextWindow": 1048576,
"supportsImageInput": true,
"reasoning": true,
- "reasoningEfforts": ["low", "high", "max"],
+ "reasoningEfforts": [
+ "low",
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "max"
}
]
@@ -800,7 +869,11 @@
"contextWindow": 1048576,
"supportsImageInput": true,
"reasoning": true,
- "reasoningEfforts": ["low", "high", "max"],
+ "reasoningEfforts": [
+ "low",
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "max"
}
]
@@ -866,7 +939,11 @@
"contextWindow": 1048576,
"supportsImageInput": true,
"reasoning": true,
- "reasoningEfforts": ["low", "high", "max"],
+ "reasoningEfforts": [
+ "low",
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -875,7 +952,11 @@
"contextWindow": 262144,
"supportsImageInput": true,
"reasoning": true,
- "reasoningEfforts": ["low", "high", "max"],
+ "reasoningEfforts": [
+ "low",
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1181,7 +1262,10 @@
"name": "DeepSeek V4 Flash",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1189,7 +1273,10 @@
"name": "DeepSeek V4 Flash 0731",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1197,7 +1284,10 @@
"name": "DeepSeek V4 Pro",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1205,7 +1295,10 @@
"name": "GLM-5",
"contextWindow": 202752,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1213,7 +1306,10 @@
"name": "GLM-5.1",
"contextWindow": 202752,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1221,7 +1317,10 @@
"name": "GLM-5.2",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1271,7 +1370,11 @@
"contextWindow": 1000000,
"supportsImageInput": true,
"reasoning": true,
- "reasoningEfforts": ["low", "medium", "xhigh"],
+ "reasoningEfforts": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
"reasoningDefaultEffort": "medium"
}
]
@@ -1470,7 +1573,10 @@
"name": "DeepSeek V4 Flash",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1478,7 +1584,10 @@
"name": "DeepSeek V4 Flash 0731",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1486,7 +1595,10 @@
"name": "DeepSeek V4 Pro",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1494,7 +1606,10 @@
"name": "GLM-5",
"contextWindow": 202752,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1502,7 +1617,10 @@
"name": "GLM-5.1",
"contextWindow": 202752,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1510,7 +1628,10 @@
"name": "GLM-5.2",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["high", "max"],
+ "reasoningEfforts": [
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "high"
},
{
@@ -1560,7 +1681,11 @@
"contextWindow": 1000000,
"supportsImageInput": true,
"reasoning": true,
- "reasoningEfforts": ["low", "medium", "xhigh"],
+ "reasoningEfforts": [
+ "low",
+ "medium",
+ "xhigh"
+ ],
"reasoningDefaultEffort": "medium"
}
]
@@ -1812,7 +1937,12 @@
"name": "GLM-5.2",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["low", "medium", "high", "max"],
+ "reasoningEfforts": [
+ "low",
+ "medium",
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "medium"
},
{
@@ -1882,7 +2012,12 @@
"name": "GLM-5.2",
"contextWindow": 1000000,
"reasoning": true,
- "reasoningEfforts": ["low", "medium", "high", "max"],
+ "reasoningEfforts": [
+ "low",
+ "medium",
+ "high",
+ "max"
+ ],
"reasoningDefaultEffort": "medium"
},
{
diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.ts
index d5b06a02b5..f9995138c8 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -145,6 +145,7 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
expect((xai.models.codex ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_IDS);
expect((xai.models.pi ?? []).map((m) => m.id)).toEqual(EXPECTED_XAI_PI_IDS);
expect(xai.models.pi?.find((m) => m.id === 'grok-4.6')).toMatchObject({
+ piApi: 'openai-responses',
contextWindow: 500_000,
maxOutput: 500_000,
supportsImageInput: true,
diff --git a/packages/model-providers/src/__tests__/piCatalogCorrections.test.ts b/packages/model-providers/src/__tests__/piCatalogCorrections.test.ts
index 60c616d8fd..ad49fd71a9 100644
--- a/packages/model-providers/src/__tests__/piCatalogCorrections.test.ts
+++ b/packages/model-providers/src/__tests__/piCatalogCorrections.test.ts
@@ -51,4 +51,12 @@ describe('Pi xAI catalog corrections', () => {
defaultEffort: 'high',
});
});
+
+ it('keeps every online xAI Pi protocol aligned with the imported Pi catalog', () => {
+ const online = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')?.models.pi;
+ expect(online).toBeDefined();
+ expect(Object.fromEntries(online!.map((model) => [model.id, model.piApi]))).toEqual(
+ Object.fromEntries(piCatalog.providers.xai.map((model) => [model.id, model.api])),
+ );
+ });
});
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index e2906e7792..f9bd91eb58 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -182,6 +182,99 @@ describe('mergeWithBundled', () => {
]);
});
+ it('backfills the bundled SuperGrok Pi runtime when a legacy v2 xAI block masks it', () => {
+ const bundledXai = structuredClone(
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ );
+ const legacyXai = structuredClone(bundledXai);
+ legacyXai.agents = legacyXai.agents.filter((agent) => agent !== 'pi');
+ delete legacyXai.routing.pi;
+ delete legacyXai.models.pi;
+
+ const merged = mergeWithBundled({ version: '2', providers: [legacyXai] });
+ const xai = merged.providers.find((provider) => provider.id === 'xai');
+
+ expect(xai?.agents).toContain('pi');
+ expect(xai?.routing.pi).toEqual(bundledXai.routing.pi);
+ expect(xai?.models.pi).toEqual(bundledXai.models.pi);
+ });
+
+ it('does not invent a SuperGrok Pi runtime for current or differently routed xAI providers', () => {
+ const bundledXai = structuredClone(
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ );
+ const withoutPi = structuredClone(bundledXai);
+ withoutPi.agents = withoutPi.agents.filter((agent) => agent !== 'pi');
+ delete withoutPi.routing.pi;
+ delete withoutPi.models.pi;
+
+ const current = mergeWithBundled({
+ version: BUNDLED_CATALOG.version,
+ providers: [withoutPi],
+ }).providers.find((provider) => provider.id === 'xai');
+ expect(current?.agents).not.toContain('pi');
+ expect(current?.routing.pi).toBeUndefined();
+ expect(current?.models.pi).toBeUndefined();
+
+ const rerouted = mergeWithBundled({
+ version: '2',
+ providers: [{
+ ...withoutPi,
+ routing: {
+ ...withoutPi.routing,
+ codex: {
+ ...withoutPi.routing.codex!,
+ upstream: 'https://different.example.test/v1',
+ },
+ },
+ }],
+ }).providers.find((provider) => provider.id === 'xai');
+ expect(rerouted?.agents).not.toContain('pi');
+ expect(rerouted?.routing.pi).toBeUndefined();
+ expect(rerouted?.models.pi).toBeUndefined();
+ });
+
+ it.each([
+ { label: 'api access', access: { kind: 'api' } as const },
+ { label: 'managed access', access: { kind: 'managed' } as const },
+ { label: 'different subscription', access: { kind: 'subscription', product: 'OtherGrok' } as const },
+ ])('does not backfill SuperGrok Pi for explicit $label', ({ access }) => {
+ const bundledXai = structuredClone(
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ );
+ const legacyXai = structuredClone(bundledXai);
+ legacyXai.access = access;
+ legacyXai.agents = legacyXai.agents.filter((agent) => agent !== 'pi');
+ delete legacyXai.routing.pi;
+ delete legacyXai.models.pi;
+
+ const merged = mergeWithBundled({ version: '2', providers: [legacyXai] });
+ const xai = merged.providers.find((provider) => provider.id === 'xai');
+
+ expect(xai?.access).toEqual(access);
+ expect(xai?.agents).not.toContain('pi');
+ expect(xai?.routing.pi).toBeUndefined();
+ expect(xai?.models.pi).toBeUndefined();
+ });
+
+ it('keeps the SuperGrok Pi backfill when an old catalog explicitly repeats the same access', () => {
+ const bundledXai = structuredClone(
+ BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai')!,
+ );
+ const legacyXai = structuredClone(bundledXai);
+ legacyXai.access = { kind: 'subscription', product: 'SuperGrok' };
+ legacyXai.agents = legacyXai.agents.filter((agent) => agent !== 'pi');
+ delete legacyXai.routing.pi;
+ delete legacyXai.models.pi;
+
+ const merged = mergeWithBundled({ version: '2', providers: [legacyXai] });
+ const xai = merged.providers.find((provider) => provider.id === 'xai');
+
+ expect(xai?.agents).toContain('pi');
+ expect(xai?.routing.pi).toEqual(bundledXai.routing.pi);
+ expect(xai?.models.pi).toEqual(bundledXai.models.pi);
+ });
+
it('backfills access for an old primary catalog without mutating it', () => {
const merged = mergeWithBundled(MINIMAL);
expect(MINIMAL.providers[0].access).toBeUndefined();
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index 4710cf88c2..93d167c60f 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -166,8 +166,21 @@ function allowsLegacyPiRuntimeBackfill(primary: Catalog): boolean {
}
/** 只给仍保持 bundled 鉴权与上游路由形状的旧条目迁移 access,不能仅凭 provider id 猜计费。 */
+function allowsBundledAccessInheritance(
+ primaryAccess: Provider['access'],
+ bundledAccess: Provider['access'],
+): boolean {
+ if (primaryAccess === undefined) return true;
+ if (bundledAccess === undefined || primaryAccess.kind !== bundledAccess.kind) return false;
+ return (
+ primaryAccess.kind !== 'subscription' ||
+ (bundledAccess.kind === 'subscription' && primaryAccess.product === bundledAccess.product)
+ );
+}
+
function legacyAccessFor(primary: Provider, bundled: Provider): Provider['access'] {
if (primary.auth.method !== bundled.auth.method) return undefined;
+ if (!allowsBundledAccessInheritance(primary.access, bundled.access)) return undefined;
const sharedAgents = primary.agents.filter((agent) => bundled.agents.includes(agent));
if (sharedAgents.length === 0) return undefined;
const sameRoutes = sharedAgents.every((agent) => {
@@ -261,10 +274,26 @@ function backfillPresetMetadata(
*/
export function mergeWithBundled(primary: Catalog): Catalog {
const bundledById = new Map(BUNDLED_CATALOG.providers.map((p) => [p.id, p]));
+ const allowLegacyPiBackfill = allowsLegacyPiRuntimeBackfill(primary);
const withBundledMetadata = primary.providers.map((p) => {
const bundled = bundledById.get(p.id);
const bundledAccess = bundled ? legacyAccessFor(p, bundled) : undefined;
if (!bundled) return p;
+ // Pi became a first-class provider runtime in catalog v3. Production may still serve a v2
+ // xAI block that is otherwise the same SuperGrok subscription provider; whole-provider
+ // primary precedence would hide the newer bundled Pi route and models. Backfill the runtime
+ // only for a proven legacy snapshot with the unchanged subscription identity. Any partial Pi
+ // declaration or changed auth/upstream remains authoritative and is never guessed through.
+ const inheritPiRuntime =
+ allowLegacyPiBackfill &&
+ p.id === 'xai' &&
+ bundledAccess !== undefined &&
+ !p.agents.includes('pi') &&
+ p.routing.pi === undefined &&
+ p.models.pi === undefined &&
+ bundled.agents.includes('pi') &&
+ bundled.routing.pi !== undefined &&
+ bundled.models.pi !== undefined;
const inheritImage =
p.id === 'xai' &&
p.imageModels === undefined &&
@@ -293,6 +322,7 @@ export function mergeWithBundled(primary: Catalog): Catalog {
allowsBundledImageInheritance(p.access, bundledAccess);
if (
!(p.access === undefined && bundledAccess !== undefined) &&
+ !inheritPiRuntime &&
!inheritImage &&
!inheritVideo &&
!inheritEmbedding
@@ -302,6 +332,13 @@ export function mergeWithBundled(primary: Catalog): Catalog {
return {
...p,
...(p.access === undefined && bundledAccess !== undefined ? { access: bundledAccess } : {}),
+ ...(inheritPiRuntime
+ ? {
+ agents: [...p.agents, 'pi' as const],
+ routing: { ...p.routing, pi: bundled.routing.pi },
+ models: { ...p.models, pi: bundled.models.pi },
+ }
+ : {}),
...(inheritImage
? {
imageModels: bundled.imageModels,
@@ -340,7 +377,6 @@ export function mergeWithBundled(primary: Catalog): Catalog {
// 远端独有项按远端原序追加。避免旧远端的非空 presets 整段遮掉新版客户端内置条目。
const primaryPresets = primary.presets ?? [];
const bundledPresets = BUNDLED_CATALOG.presets ?? [];
- const allowLegacyPiBackfill = allowsLegacyPiRuntimeBackfill(primary);
const primaryPresetsById = new Map(primaryPresets.map((preset) => [preset.id, preset]));
const bundledPresetIds = new Set(bundledPresets.map((preset) => preset.id));
const presets = bundledPresets.map((bundled) => {
diff --git a/tools/pi/sync-model-catalog.mjs b/tools/pi/sync-model-catalog.mjs
index 12f7ca33b8..307282b484 100644
--- a/tools/pi/sync-model-catalog.mjs
+++ b/tools/pi/sync-model-catalog.mjs
@@ -118,11 +118,19 @@ function runtimeWireProtocol(providerId, models) {
function xaiCatalogModel(model, index) {
const efforts = supportedEfforts(model);
+ const piApi = model.api === 'openai-completions'
+ ? 'openai-completions'
+ : model.api === 'openai-responses'
+ ? 'openai-responses'
+ : model.api === 'anthropic-messages'
+ ? 'anthropic-messages'
+ : undefined;
return {
// Pi uses provider provenance, so its xAI model ids stay identical to Pi's official catalog.
// Claude/Codex keep the historical xai/ namespace in their own per-agent lists.
id: model.id,
name: model.name ?? model.id,
+ ...(piApi ? { piApi } : {}),
group: 'grok',
sortOrder: 49 + index,
contextWindow: model.contextWindow,
@@ -187,6 +195,10 @@ async function main() {
if (!xai.agents.includes('pi')) xai.agents.push('pi');
xai.routing.pi = {
upstream: 'https://api.x.ai/v1',
+ // The sync currently requires one provider-wide Pi protocol and fails closed on mixed
+ // model.api values. Per-model piApi records the exact model protocol, but supporting a
+ // mixed-protocol xAI catalog requires a separate sync-script change first.
+ wireProtocol: runtimeWireProtocol('xai', providers.xai),
authStrategy: 'provider-oauth-header',
headerDelete: ['chatgpt-account-id', 'openai-beta', 'originator', 'session_id'],
};