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(pi): honor Cindy Server catalog protocol authority (#3627)

Chris Zhang77e6bdfeb7fe
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
index a036cda5da..15b194b49f 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogXdAvailability.test.ts
@@ -17,6 +17,7 @@ import {
getActiveCatalog,
getXdGatewayModels,
isXdGatewayPaymentRequiredRoute,
+ resolveXdPiGatewayApi,
resolveXdPiGatewayWireProtocol,
setActiveCatalog,
setAnthropicDiscoveredModels,
@@ -165,43 +166,146 @@ describe('XD 网关权威模型清单重建', () => {
});
});
- it('Pi 在 cindy provider 内接受 v3 显式协议,并过滤缺失协议的模型', () => {
- setActiveCatalog(BUNDLED_CATALOG);
+ it('按 Cindy Server > 本地 Pi 表 > Cindy AI Gateway 的顺序解析 API', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as typeof BUNDLED_CATALOG;
+ catalog.presets = [
+ ...(catalog.presets ?? []),
+ {
+ id: 'server-moonshot-test',
+ name: 'Server Moonshot Test',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://server.example/anthropic',
+ wireProtocol: 'anthropic-messages',
+ models: [{ id: 'kimi-k3', name: 'Kimi K3' }],
+ },
+ },
+ },
+ ];
+ const registryEntry = catalog.modelRegistry?.models.find(
+ (entry) =>
+ entry.id === 'moonshotai/kimi-k3' ||
+ entry.routes.some((route) => route.providerId === 'xd' && route.modelId === 'moonshot/kimi-k3'),
+ );
+ if (!registryEntry) throw new Error('missing Kimi registry fixture');
+ registryEntry.routes = [
+ { providerId: 'xd', modelId: 'moonshot/kimi-k3', agents: ['claude-code', 'codex'] },
+ {
+ providerId: 'server-moonshot-test',
+ modelId: 'kimi-k3',
+ agents: ['claude-code', 'codex'],
+ },
+ ];
+ setActiveCatalog(catalog, { authorityCatalog: catalog });
setXdGatewayModels([
{
- id: 'messages-model',
+ id: 'moonshot/kimi-k3',
+ agents: ['claude-code', 'codex', 'pi'],
+ perAgent: { pi: { wireProtocol: 'openai-responses' } },
+ },
+ {
+ id: 'claude-opus-5',
+ agents: ['claude-code', 'codex', 'pi'],
+ perAgent: { pi: { wireProtocol: 'openai-responses' } },
+ },
+ {
+ id: 'gpt-5.6-sol',
agents: ['claude-code', 'codex', 'pi'],
perAgent: { pi: { wireProtocol: 'anthropic-messages' } },
},
{
- id: 'responses-model',
+ id: 'google/gemini-3.7-flash',
agents: ['claude-code', 'codex', 'pi'],
perAgent: { pi: { wireProtocol: 'openai-responses' } },
},
{
- id: 'missing-wire',
+ id: 'future-unmapped-model',
agents: ['claude-code', 'codex', 'pi'],
+ perAgent: { pi: { wireProtocol: 'openai-responses' } },
},
{
- id: 'claude-only-model',
- agents: ['claude-code'],
- perAgent: { 'claude-code': { wireProtocol: 'anthropic-messages' } },
+ id: 'future-unsupported-api',
+ agents: ['pi'],
+ perAgent: { pi: { wireProtocol: 'future-protocol' as never } },
+ },
+ {
+ id: 'gemini-3.6-flash',
+ agents: ['codex'],
+ perAgent: { codex: { wireProtocol: 'openai-responses' } },
},
]);
- expect(resolveXdPiGatewayWireProtocol('messages-model')).toBe('anthropic-messages');
- expect(resolveXdPiGatewayWireProtocol('responses-model')).toBe('openai-responses');
- expect(resolveXdPiGatewayWireProtocol('responses-model[1m]')).toBe('openai-responses');
- expect(resolveXdPiGatewayWireProtocol('missing-wire')).toBeNull();
- expect(resolveXdPiGatewayWireProtocol('claude-only-model')).toBeUndefined();
- expect(resolveXdPiGatewayWireProtocol('unknown-model')).toBeUndefined();
- expect(xdModels('pi').map((model) => model.id)).toEqual([
- 'messages-model',
- 'responses-model',
+ // Cindy Server beats both local Kimi Completions metadata and Gateway Responses.
+ expect(resolveXdPiGatewayApi('moonshot/kimi-k3')).toBe('anthropic-messages');
+ expect(resolveXdPiGatewayWireProtocol('moonshot/kimi-k3')).toBe('anthropic-messages');
+ // With no server declaration, the version-matched local table beats Gateway hints.
+ expect(resolveXdPiGatewayApi('claude-opus-5')).toBe('anthropic-messages');
+ expect(resolveXdPiGatewayApi('gpt-5.6-sol')).toBe('openai-responses');
+ expect(resolveXdPiGatewayApi('google/gemini-3.7-flash')).toBe('google-generative-ai');
+ expect(resolveXdPiGatewayWireProtocol('google/gemini-3.7-flash')).toBeNull();
+ // Gateway is consulted only when both higher-priority sources are absent.
+ expect(resolveXdPiGatewayApi('future-unmapped-model')).toBe('openai-responses');
+ expect(resolveXdPiGatewayApi('future-unsupported-api')).toBeNull();
+ expect(resolveXdPiGatewayApi('gemini-3.6-flash')).toBeUndefined();
+ expect(xdModels('pi')).toMatchObject([
+ { id: 'moonshot/kimi-k3', piApi: 'anthropic-messages' },
+ { id: 'claude-opus-5', piApi: 'anthropic-messages' },
+ { id: 'gpt-5.6-sol', piApi: 'openai-responses' },
+ { id: 'google/gemini-3.7-flash', piApi: 'google-generative-ai' },
+ { id: 'future-unmapped-model', piApi: 'openai-responses' },
+ { id: 'future-unsupported-api' },
]);
+ });
+
+ it('Cindy Server 的精确 retired tombstone 会隐藏滞后的 Gateway Pi 成员', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as typeof BUNDLED_CATALOG;
+ catalog.modelRegistry = {
+ schemaVersion: 2,
+ updatedAt: '2026-08-29T00:00:00.000Z',
+ models: [
+ {
+ id: 'canonical/kimi-k3',
+ name: 'Kimi K3',
+ status: 'retired',
+ routes: [
+ { providerId: 'xd', modelId: 'moonshot/kimi-k3', agents: ['claude-code', 'codex'] },
+ ],
+ },
+ ],
+ };
+ setActiveCatalog(catalog, { authorityCatalog: catalog });
+ setXdGatewayModels([
+ {
+ id: 'moonshot/kimi-k3',
+ agents: ['claude-code', 'codex', 'pi'],
+ perAgent: { pi: { wireProtocol: 'openai-responses' } },
+ },
+ ]);
+
+ expect(resolveXdPiGatewayApi('moonshot/kimi-k3')).toBeNull();
+ expect(xdModels('pi')).toEqual([]);
+ expect(xdModels('codex').map((model) => model.id)).toEqual(['moonshot/kimi-k3']);
+ });
+
+ it('Cindy AI Gateway 只决定账号成员,不会覆盖高优先级 API 或凭其它 agent 擅自投影', () => {
+ setActiveCatalog(BUNDLED_CATALOG);
+ setXdGatewayModels([
+ {
+ id: 'claude-opus-5',
+ agents: ['claude-code', 'codex', 'pi'],
+ perAgent: { pi: { wireProtocol: 'openai-responses' } },
+ },
+ {
+ id: 'google/gemini-3.6-flash',
+ agents: ['codex'],
+ perAgent: { codex: { wireProtocol: 'openai-responses' } },
+ },
+ ]);
+
+ expect(resolveXdPiGatewayApi('claude-opus-5')).toBe('anthropic-messages');
+ expect(resolveXdPiGatewayApi('google/gemini-3.6-flash')).toBeUndefined();
expect(xdModels('pi')).toMatchObject([
- { id: 'messages-model', piApi: 'anthropic-messages' },
- { id: 'responses-model', piApi: 'openai-responses' },
+ { id: 'claude-opus-5', piApi: 'anthropic-messages' },
]);
});
@@ -347,32 +451,32 @@ describe('XD 网关权威模型清单重建', () => {
setActiveCatalog(BUNDLED_CATALOG);
setXdGatewayModels([
{
- id: 'gateway-vision',
+ id: 'google/gemini-3.7-flash',
agents: ['pi'],
perAgent: { pi: { wireProtocol: 'openai-responses' } },
modalities: { input: ['text', 'image'], output: ['text'] },
},
{
- id: 'gateway-text',
+ id: 'qwen/qwen3.8-27b',
agents: ['pi'],
perAgent: { pi: { wireProtocol: 'openai-responses' } },
modalities: { input: ['text'], output: ['text'] },
},
{
- id: 'gateway-unknown',
+ id: 'qwen/qwen3.8-flash',
agents: ['pi'],
perAgent: { pi: { wireProtocol: 'openai-responses' } },
},
]);
const pi = deriveAvailableModels(getActiveCatalog(), 'pi');
- expect(pi.find((model) => model.id === 'gateway-vision')).toMatchObject({
+ expect(pi.find((model) => model.id === 'google/gemini-3.7-flash')).toMatchObject({
supportsImageInput: true,
});
- expect(pi.find((model) => model.id === 'gateway-text')).toMatchObject({
+ expect(pi.find((model) => model.id === 'qwen/qwen3.8-27b')).toMatchObject({
supportsImageInput: false,
});
- expect(pi.find((model) => model.id === 'gateway-unknown')).not.toHaveProperty(
+ expect(pi.find((model) => model.id === 'qwen/qwen3.8-flash')).not.toHaveProperty(
'supportsImageInput',
);
});
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 6f0b14a16e..218a797dcd 100644
--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
@@ -248,27 +248,33 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {
model('shared-default-route', {
name: 'Subscription Shared',
contextWindow: 128_000,
+ efforts: ['low'],
+ defaultEffort: 'low',
}),
];
xd!.models.pi = [
model('shared-default-route', {
name: 'XD Shared',
contextWindow: 200_000,
+ efforts: ['high'],
+ defaultEffort: 'high',
}),
];
expect(resolvePiGatewayDescriptorProviderId(null)).toBe('xd');
expect(resolvePiGatewayDescriptorProviderId('cindy')).toBe('xd');
- expect(resolvePiGatewayDescriptorProviderId('openai')).toBe('openai');
+ expect(resolvePiGatewayDescriptorProviderId('openai')).toBe('xd');
expect(
resolvePiRuntimeModelDescriptor(
catalog,
- resolvePiGatewayDescriptorProviderId(null),
+ resolvePiGatewayDescriptorProviderId('openai'),
'shared-default-route',
),
).toMatchObject({
displayName: 'XD Shared',
contextWindow: 200_000,
+ efforts: ['high'],
+ defaultEffort: 'high',
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
index 98b9a7924d..9dac659d34 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
@@ -45,6 +45,7 @@ vi.mock('../claude-fast-mode-log', () => ({
import {
createModelRoutingTransform,
+ piGatewayRequestAgent,
setClaudeProxyGatewayKeyReader,
setClaudeProxyOwnerBoundaryPendingChecker,
setClaudeProxyOwnerScopeKeyReader,
@@ -62,6 +63,17 @@ import {
resetPiProxySessionsForTest,
} from '../pi-proxy-session-auth';
+describe('Pi Gateway request front door', () => {
+ it.each([
+ ['/v1/messages', 'claude-code'],
+ ['/v1/responses', 'codex'],
+ ['/v1/chat/completions', 'codex'],
+ ['/v1beta/models/gemini-3.6-flash:streamGenerateContent', 'codex'],
+ ] as const)('routes %s through the Gateway %s credential surface', (url, agent) => {
+ expect(piGatewayRequestAgent(url)).toBe(agent);
+ });
+});
+
const SESSION_HEADER = { 'x-claude-code-session-id': 'sdk-grok' };
function ctxWith(headers: Record<string, string>, url = '/v1/messages') {
@@ -516,6 +528,90 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
});
});
+ it.each([
+ ['/v1/messages', { 'x-api-key': 'sk-gw', authorization: 'Bearer sk-gw' }],
+ ['/v1/responses', { authorization: 'Bearer sk-gw' }],
+ ['/v1/chat/completions', { authorization: 'Bearer sk-gw' }],
+ ['/v1beta/models/google/gemini-3.6-flash:streamGenerateContent', { authorization: 'Bearer sk-gw' }],
+ ] as const)(
+ 'routes a cindy Gateway Pi request on %s through the matching Claude/Codex surface',
+ async (url, headerOverride) => {
+ setClaudeProxyGatewayKeyReader(() => 'sk-gw');
+ setSessionProvider('sess-pi', 'xd');
+ registerPiProxySession('sess-pi', 'gateway-session-secret', () => null);
+ const decision = createModelRoutingTransform()(
+ { model: 'gateway-model' },
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'gateway-session-secret',
+ ...(url.includes('/v1beta/')
+ ? { 'x-goog-api-key': 'cindy-pi-provider-auth-placeholder' }
+ : {}),
+ }, url),
+ );
+
+ await expect(Promise.resolve(decision)).resolves.toEqual({
+ headerOverride,
+ headerDelete: [
+ ...(url.includes('/v1beta/') ? ['x-goog-api-key'] : []),
+ 'x-cindy-pi-session-id',
+ 'x-cindy-pi-session-token',
+ 'x-cindy-pi-provider-id',
+ ],
+ });
+ },
+ );
+
+ it('strips Google placeholder auth even when the live Gateway key is temporarily unavailable', async () => {
+ setClaudeProxyGatewayKeyReader(() => null);
+ setSessionProvider('sess-pi', 'xd');
+ registerPiProxySession('sess-pi', 'gateway-session-secret', () => null);
+ const decision = createModelRoutingTransform()(
+ { model: 'google/gemini-3.6-flash' },
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'gateway-session-secret',
+ 'x-goog-api-key': 'stale-gateway-key',
+ }, '/v1beta/models/google/gemini-3.6-flash:streamGenerateContent'),
+ );
+
+ await expect(Promise.resolve(decision)).resolves.toEqual({
+ headerDelete: [
+ 'x-goog-api-key',
+ 'x-cindy-pi-session-id',
+ 'x-cindy-pi-session-token',
+ 'x-cindy-pi-provider-id',
+ ],
+ });
+ });
+
+ it('routes a provider-null cindy Subagent by its API instead of inheriting the Anthropic parent', async () => {
+ setClaudeProxyGatewayKeyReader(() => 'sk-gw');
+ setSessionProvider('sess-pi', 'anthropic');
+ registerPiProxySession(
+ 'sess-pi',
+ 'gateway-subagent-secret',
+ () => null,
+ { scope: 'subagent-route' },
+ );
+ const decision = createModelRoutingTransform()(
+ { model: 'moonshotai/kimi-k3' },
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'gateway-subagent-secret',
+ }, '/v1/chat/completions'),
+ );
+
+ await expect(Promise.resolve(decision)).resolves.toEqual({
+ headerOverride: { authorization: 'Bearer sk-gw' },
+ headerDelete: [
+ 'x-cindy-pi-session-id',
+ 'x-cindy-pi-session-token',
+ 'x-cindy-pi-provider-id',
+ ],
+ });
+ });
+
it('routes an Anthropic Subagent by its pinned provider instead of the OpenAI parent route', async () => {
setClaudeProxyGatewayKeyReader(() => 'sk-gw');
setSessionProvider('sess-pi', 'openai');
diff --git a/apps/desktop/src/main/maker-host/__tests__/piGatewayModelCatalog.test.ts b/apps/desktop/src/main/maker-host/__tests__/piGatewayModelCatalog.test.ts
new file mode 100644
index 0000000000..9095320342
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/piGatewayModelCatalog.test.ts
@@ -0,0 +1,244 @@
+import { describe, expect, it } from 'vitest';
+
+import type { Catalog } from '@cindy/model-providers';
+
+import {
+ resolveBundledPiGatewayModelProfile,
+ resolveCatalogPiGatewayModelApi,
+} from '../pi-gateway-model-catalog.js';
+
+const currentGatewayModelsByApi = {
+ 'anthropic-messages': [
+ 'claude-opus-5',
+ 'claude-fable-5',
+ 'claude-opus-4-8',
+ 'claude-opus-4-7',
+ 'claude-opus-4-6',
+ 'claude-sonnet-5',
+ 'claude-sonnet-4-6',
+ 'claude-haiku-4-5',
+ 'claude-haiku-4-5-20251001',
+ ],
+ 'openai-responses': [
+ 'codex/gpt-5.6-luna',
+ 'codex/gpt-5.6-sol',
+ 'codex/gpt-5.6-terra',
+ 'codex/gpt-5.5',
+ 'codex/gpt-5.4',
+ 'codex/gpt-5.4-mini',
+ 'codex/gpt-5.5:auto',
+ 'gpt-5.6-luna',
+ 'gpt-5.6-sol',
+ 'gpt-5.6-terra',
+ 'gpt-5.5',
+ 'gpt-5.4',
+ 'gpt-5.4-mini',
+ 'gpt-5.4-nano',
+ 'meta/muse-spark-1.2',
+ 'x-ai-grok/grok-4.6',
+ 'x-ai/grok-4.5',
+ 'x-ai/grok-4.6',
+ ],
+ 'openai-completions': [
+ 'qwen/qwen3.7-max',
+ 'moonshot/kimi-k3',
+ 'z-ai/glm-5.1',
+ 'z-ai/glm-5.2',
+ 'z-ai/glm-5.3',
+ 'deepseek/deepseek-v4-pro',
+ 'deepseek/deepseek-v4-flash',
+ 'moonshotai/kimi-k2.6',
+ 'deepseek/deepseek-v4-flash-vision-exp',
+ 'qwen/qwen3.8-27b',
+ 'qwen/qwen3.8-flash',
+ 'qwen/qwen3.8-max',
+ 'tencent/hy3',
+ 'z-ai/glm-5.3-flash',
+ ],
+ 'google-generative-ai': [
+ 'google/gemini-3.7-flash',
+ 'gemini-3.6-flash',
+ 'gemini-3.5-flash',
+ 'gemini-3.1-pro-preview',
+ 'gemini-3-flash-preview',
+ ],
+} as const;
+
+function serverCatalog(args: {
+ presets: Array<{
+ id: string;
+ protocol: 'anthropic-messages' | 'openai-responses' | 'openai-chat';
+ modelId: string;
+ }>;
+ routes?: Array<{ providerId: string; modelId: string }>;
+ gatewayModelId?: string;
+}): Catalog {
+ return {
+ version: '3',
+ providers: [],
+ presets: args.presets.map(({ id, protocol, modelId }) => ({
+ id,
+ name: id,
+ runtimes: {
+ pi: {
+ baseUrl: `https://${id}.example/v1`,
+ wireProtocol: protocol,
+ models: [{ id: modelId, name: modelId }],
+ },
+ },
+ })),
+ ...(args.routes
+ ? {
+ modelRegistry: {
+ schemaVersion: 2,
+ updatedAt: '2026-08-29T00:00:00.000Z',
+ models: [
+ {
+ id: 'canonical/model',
+ name: 'Model',
+ routes: [
+ {
+ providerId: 'xd',
+ modelId: args.gatewayModelId ?? 'gateway/model',
+ agents: ['claude-code', 'codex'],
+ },
+ ...args.routes.map((route) => ({
+ ...route,
+ agents: ['claude-code', 'codex'] as const,
+ })),
+ ],
+ },
+ ],
+ },
+ }
+ : {}),
+ } as Catalog;
+}
+
+describe('Cindy Server Pi Gateway catalog authority', () => {
+ it('uses a registry-linked server preset before any exact namespaced alternative', () => {
+ const catalog = serverCatalog({
+ gatewayModelId: 'moonshot/kimi-k3',
+ routes: [{ providerId: 'moonshot-kimi-global', modelId: 'kimi-k3' }],
+ presets: [
+ {
+ id: 'moonshot-kimi-global',
+ protocol: 'anthropic-messages',
+ modelId: 'kimi-k3',
+ },
+ { id: 'openrouter', protocol: 'openai-chat', modelId: 'moonshot/kimi-k3' },
+ ],
+ });
+ expect(resolveCatalogPiGatewayModelApi(catalog, 'moonshot/kimi-k3')).toBe(
+ 'anthropic-messages',
+ );
+ });
+
+ it('does not borrow an exact namespaced id without a registry provider route', () => {
+ const catalog = serverCatalog({
+ presets: [{ id: 'openrouter', protocol: 'openai-chat', modelId: 'z-ai/glm-5.2' }],
+ });
+ expect(resolveCatalogPiGatewayModelApi(catalog, 'z-ai/glm-5.2')).toBeUndefined();
+ });
+
+ it('fails closed on conflicting server declarations for one registry identity', () => {
+ const catalog = serverCatalog({
+ routes: [
+ { providerId: 'provider-a', modelId: 'model' },
+ { providerId: 'provider-b', modelId: 'model' },
+ ],
+ presets: [
+ { id: 'provider-a', protocol: 'anthropic-messages', modelId: 'model' },
+ { id: 'provider-b', protocol: 'openai-chat', modelId: 'model' },
+ ],
+ });
+ expect(resolveCatalogPiGatewayModelApi(catalog, 'gateway/model')).toBeNull();
+ });
+
+ it('never borrows a bare model id from an unrelated server preset', () => {
+ const catalog = serverCatalog({
+ presets: [{ id: 'provider-a', protocol: 'anthropic-messages', modelId: 'same-id' }],
+ });
+ expect(resolveCatalogPiGatewayModelApi(catalog, 'same-id')).toBeUndefined();
+ });
+
+ it('fails closed when Cindy Server retires an exact XD Registry identity', () => {
+ const catalog = serverCatalog({
+ gatewayModelId: 'moonshot/kimi-k3',
+ routes: [{ providerId: 'moonshot-kimi-global', modelId: 'kimi-k3' }],
+ presets: [
+ { id: 'moonshot-kimi-global', protocol: 'anthropic-messages', modelId: 'kimi-k3' },
+ ],
+ });
+ catalog.modelRegistry!.models[0]!.status = 'retired';
+ expect(resolveCatalogPiGatewayModelApi(catalog, 'moonshot/kimi-k3')).toBeNull();
+ });
+
+ it('requires an exact XD route even when a Registry canonical id matches the Gateway id', () => {
+ const catalog = serverCatalog({
+ gatewayModelId: 'different-gateway-id',
+ routes: [{ providerId: 'provider-a', modelId: 'model' }],
+ presets: [{ id: 'provider-a', protocol: 'anthropic-messages', modelId: 'model' }],
+ });
+ expect(resolveCatalogPiGatewayModelApi(catalog, 'canonical/model')).toBeUndefined();
+ });
+});
+
+describe('Pi Gateway version-matched local supplement catalog', () => {
+ it('returns the exact Kimi native API and complete tool replay compatibility', () => {
+ expect(resolveBundledPiGatewayModelProfile('moonshotai/kimi-k3')).toMatchObject({
+ api: 'openai-completions',
+ compat: {
+ maxTokensField: 'max_tokens',
+ thinkingFormat: 'openai',
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: 'kimi',
+ },
+ thinkingLevelMap: {
+ low: 'low',
+ high: 'high',
+ max: 'max',
+ },
+ });
+ });
+
+ it.each([
+ ['anthropic/claude-opus-5', 'anthropic-messages'],
+ ['codex/gpt-5.5:auto', 'openai-responses'],
+ ['google/gemini-3.6-flash', 'google-generative-ai'],
+ ['deepseek/deepseek-v4-pro', 'openai-completions'],
+ ['qwen/qwen3.8-flash', 'openai-completions'],
+ ['z-ai/glm-5.3-flash', 'openai-completions'],
+ ] as const)('resolves %s from the local Pi model table', (modelId, api) => {
+ expect(resolveBundledPiGatewayModelProfile(modelId)).toMatchObject({ api });
+ });
+
+ it('can supplement every current Gateway identity when Cindy Server has no exact declaration', () => {
+ const resolved = Object.entries(currentGatewayModelsByApi).flatMap(([api, modelIds]) =>
+ modelIds.map((modelId) => ({
+ modelId,
+ expectedApi: api,
+ actualApi: resolveBundledPiGatewayModelProfile(modelId)?.api,
+ })),
+ );
+ expect(resolved).toHaveLength(46);
+ expect(resolved.filter((entry) => entry.actualApi !== entry.expectedApi)).toEqual([]);
+ });
+
+ it('uses canonical provider identity and never borrows compat across providers', () => {
+ expect(resolveBundledPiGatewayModelProfile('z-ai/glm-5.2')).toMatchObject({
+ api: 'openai-completions',
+ compat: { thinkingFormat: 'zai', zaiToolStream: true },
+ thinkingLevelMap: { low: 'high', medium: 'high', high: 'high', max: 'max' },
+ });
+ expect(resolveBundledPiGatewayModelProfile('z-ai/glm-5.1')).toEqual({
+ api: 'openai-completions',
+ });
+ });
+
+ it('fails closed for identities absent from the local allowlist, including known bare aliases', () => {
+ expect(resolveBundledPiGatewayModelProfile('vendor/future-model')).toBeUndefined();
+ expect(resolveBundledPiGatewayModelProfile('unknown/gpt-5.4')).toBeUndefined();
+ expect(resolveBundledPiGatewayModelProfile('unknown/grok-4.6')).toBeUndefined();
+ });
+});
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 9e352303c8..a9de71b25a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -38,9 +38,10 @@ import {
resolvePiBundledApiByModelId,
resolvePiBundledModelById,
resolvePiCindyGatewayModelApi,
+ resolvePiCindyGatewayModelSpec,
type PiBundledModelInfo,
} from '../pi-host.js';
-import { setXdGatewayModels } from '../active-catalog.js';
+import { setActiveCatalog, setXdGatewayModels } from '../active-catalog.js';
type Cfg = Parameters<typeof buildPiNativeProvidersFromConfigs>[0][number];
@@ -67,31 +68,152 @@ const piBundledModel = (
});
afterEach(() => {
+ setActiveCatalog(BUNDLED_CATALOG);
setXdGatewayModels([]);
});
describe('resolvePiCindyGatewayModelApi', () => {
- it('uses the exact XD model protocol even while the session is on a BYOM provider', () => {
+ it('keeps a Registry-linked Cindy Server protocol above local and Gateway metadata', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ catalog.presets = [
+ ...(catalog.presets ?? []),
+ {
+ id: 'server-moonshot-test',
+ name: 'Server Moonshot Test',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://server.example/anthropic',
+ wireProtocol: 'anthropic-messages',
+ models: [{ id: 'kimi-k3', name: 'Kimi K3' }],
+ },
+ },
+ },
+ ];
+ catalog.modelRegistry = {
+ schemaVersion: 2,
+ updatedAt: '2026-08-29T00:00:00.000Z',
+ models: [
+ {
+ id: 'canonical/kimi-k3',
+ name: 'Kimi K3',
+ routes: [
+ { providerId: 'xd', modelId: 'moonshot/kimi-k3', agents: ['claude-code', 'codex'] },
+ {
+ providerId: 'server-moonshot-test',
+ modelId: 'kimi-k3',
+ agents: ['claude-code', 'codex'],
+ },
+ ],
+ },
+ ],
+ };
+ setActiveCatalog(catalog, { authorityCatalog: catalog });
setXdGatewayModels([
{
- id: 'gateway-messages',
+ id: 'moonshot/kimi-k3',
agents: ['pi'],
- perAgent: { pi: { wireProtocol: 'anthropic-messages' } },
+ perAgent: { pi: { wireProtocol: 'openai-responses' } },
},
+ ]);
+
+ expect(resolvePiCindyGatewayModelApi('xd', 'moonshot/kimi-k3')).toBe(
+ 'anthropic-messages',
+ );
+ expect(resolvePiCindyGatewayModelSpec('xd', 'moonshot/kimi-k3')).toEqual({
+ api: 'anthropic-messages',
+ });
+ });
+
+ it('uses the exact local Pi API regardless of Gateway hints or selected BYOM provider', () => {
+ setXdGatewayModels([
{
- id: 'gateway-responses',
+ id: 'claude-opus-5',
agents: ['pi'],
perAgent: { pi: { wireProtocol: 'openai-responses' } },
},
+ {
+ id: 'gpt-5.6-sol',
+ agents: ['pi'],
+ perAgent: { pi: { wireProtocol: 'anthropic-messages' } },
+ },
]);
- expect(resolvePiCindyGatewayModelApi('third-party-byom', 'gateway-messages')).toBe(
+ expect(resolvePiCindyGatewayModelApi('third-party-byom', 'claude-opus-5')).toBe(
'anthropic-messages',
);
- expect(resolvePiCindyGatewayModelApi('third-party-byom', 'gateway-responses')).toBe(
+ expect(resolvePiCindyGatewayModelApi('third-party-byom', 'gpt-5.6-sol')).toBe(
'openai-responses',
);
});
+
+ it('uses static client config, but never Desktop-probed metadata, for a remote Pi executable', () => {
+ setXdGatewayModels([
+ {
+ id: 'moonshot/kimi-k3',
+ agents: ['pi'],
+ perAgent: { pi: { wireProtocol: 'openai-responses' } },
+ },
+ ]);
+
+ expect(resolvePiCindyGatewayModelApi('xd', 'moonshot/kimi-k3', { remote: true })).toBe(
+ 'openai-completions',
+ );
+ expect(resolvePiCindyGatewayModelSpec('xd', 'moonshot/kimi-k3', { remote: true })).toMatchObject({
+ api: 'openai-completions',
+ compat: {
+ maxTokensField: 'max_tokens',
+ thinkingFormat: 'openai',
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: 'kimi',
+ },
+ });
+ });
+
+ it('keeps local Kimi Completions authoritative over the Gateway hint', () => {
+ setXdGatewayModels([
+ {
+ id: 'moonshot/kimi-k3',
+ agents: ['claude-code', 'codex', 'pi'],
+ perAgent: { pi: { wireProtocol: 'openai-responses' } },
+ },
+ ]);
+
+ expect(resolvePiCindyGatewayModelApi('xd', 'moonshot/kimi-k3')).toBe(
+ 'openai-completions',
+ );
+ expect(resolvePiCindyGatewayModelSpec('xd', 'moonshot/kimi-k3')).toMatchObject({
+ api: 'openai-completions',
+ compat: {
+ maxTokensField: 'max_tokens',
+ thinkingFormat: 'openai',
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: 'kimi',
+ },
+ });
+ });
+
+ it.each([undefined, 'openai-completions'] as const)(
+ 'uses local Kimi compat when the Gateway hint is %s',
+ (wireProtocol) => {
+ setXdGatewayModels([
+ {
+ id: 'moonshot/kimi-k3',
+ agents: ['claude-code', 'codex', 'pi'],
+ ...(wireProtocol ? { perAgent: { pi: { wireProtocol } } } : {}),
+ },
+ ]);
+
+ expect(resolvePiCindyGatewayModelSpec('xd', 'moonshot/kimi-k3')).toMatchObject({
+ api: 'openai-completions',
+ compat: {
+ maxTokensField: 'max_tokens',
+ thinkingFormat: 'openai',
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: 'kimi',
+ },
+ });
+ },
+ );
});
describe('buildPiNativeProvidersFromConfigs', () => {
@@ -348,16 +470,16 @@ describe('buildPiNativeProvidersFromConfigs', () => {
});
const bundledPiPath = path.join(process.cwd(), 'apps/pi-bin/darwin-arm64/pi');
- it('caches a null fallback when the PI probe temp directory cannot be created', async () => {
+ it('retries a transient null PI probe instead of caching it for the process lifetime', async () => {
const binaryPath = path.join(process.cwd(), 'pi-temp-dir-probe-failure');
const mkdtempSpy = vi
.spyOn(fsp, 'mkdtemp')
- .mockRejectedValueOnce(new Error('temporary directory unavailable'));
+ .mockRejectedValue(new Error('temporary directory unavailable'));
try {
await expect(readPiBundledModels(binaryPath)).resolves.toBeNull();
await expect(readPiBundledModels(binaryPath)).resolves.toBeNull();
- expect(mkdtempSpy).toHaveBeenCalledTimes(1);
+ expect(mkdtempSpy).toHaveBeenCalledTimes(2);
} finally {
mkdtempSpy.mockRestore();
}
@@ -369,7 +491,7 @@ describe('buildPiNativeProvidersFromConfigs', () => {
const catalog = await readPiBundledModels(bundledPiPath);
expect(catalog?.get('openai-codex')?.get('gpt-5.6-sol')?.api).toBe('openai-codex-responses');
expect(catalog?.get('xai')?.get('grok-4.5')?.api).toBe('openai-responses');
- expect(catalog?.get('xai')?.get('grok-build-0.1')?.api).toBe('openai-completions');
+ expect(catalog?.get('xai')?.get('grok-build-0.1')?.api).toBe('openai-responses');
const anthropicModels = [...(catalog?.get('anthropic')?.values() ?? [])];
expect(anthropicModels.length).toBeGreaterThan(0);
expect(anthropicModels.every((model) => model.api === 'anthropic-messages')).toBe(true);
@@ -380,6 +502,33 @@ describe('buildPiNativeProvidersFromConfigs', () => {
});
});
+ it.skipIf(
+ process.platform !== 'darwin' || process.arch !== 'arm64' || !existsSync(bundledPiPath),
+ )('uses the exact Pi binary to enrich first-party Gateway profiles without remote API input', async () => {
+ await readPiBundledModels(bundledPiPath);
+ setXdGatewayModels([
+ { id: 'claude-opus-5', agents: ['pi'] },
+ { id: 'gpt-5.6-sol', agents: ['pi'] },
+ { id: 'google/gemini-3.7-flash', agents: ['pi'] },
+ ]);
+
+ expect(resolvePiCindyGatewayModelSpec('xd', 'claude-opus-5')).toMatchObject({
+ api: 'anthropic-messages',
+ compat: { forceAdaptiveThinking: true, supportsStrictTools: true },
+ });
+ expect(resolvePiCindyGatewayModelSpec('xd', 'gpt-5.6-sol')).toMatchObject({
+ api: 'openai-responses',
+ compat: {
+ supportsOpenAIGrammarTools: true,
+ supportsAdditionalTools: true,
+ supportsToolSearch: true,
+ },
+ });
+ expect(resolvePiCindyGatewayModelSpec('xd', 'google/gemini-3.7-flash')).toMatchObject({
+ api: 'google-generative-ai',
+ });
+ });
+
it('overlays host subscriptions onto PI native providers and keeps piApi sparse', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
const anthropic = catalog.providers.find((provider) => provider.id === 'anthropic')!;
@@ -1101,7 +1250,7 @@ describe('buildPiNativeProvidersFromConfigs', () => {
expect(provider?.models[0]?.api).toBeUndefined();
});
- it('preserves PI bundled metadata when a daily annotation corrects an existing protocol', () => {
+ it('drops PI bundled serializer metadata when a daily annotation corrects the protocol', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
const xai = catalog.providers.find((provider) => provider.id === 'xai')!;
xai.models.pi = [
@@ -1131,12 +1280,60 @@ describe('buildPiNativeProvidersFromConfigs', () => {
expect(provider?.models[0]).toMatchObject({
wireId: 'grok-corrected',
api: 'openai-responses',
- name: 'PI Bundled Name',
- contextWindow: 500_000,
- maxTokens: 64_000,
- cost: bundled.cost,
- compat: bundled.compat,
+ name: 'Daily Name',
+ contextWindow: 1_000_000,
+ reasoning: true,
+ thinkingLevelMap: {
+ minimal: null,
+ low: null,
+ medium: null,
+ high: 'high',
+ xhigh: null,
+ max: null,
+ },
+ });
+ expect(provider?.models[0]?.maxTokens).toBeUndefined();
+ expect(provider?.models[0]?.cost).toBeUndefined();
+ expect(provider?.models[0]?.compat).toBeUndefined();
+ expect(provider?.models[0]?.headers).toBeUndefined();
+ });
+
+ it('does not apply official Responses metadata to an xAI protocol correction to Completions', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ const xai = catalog.providers.find((provider) => provider.id === 'xai')!;
+ xai.models.pi = [
+ {
+ id: 'xai/grok-4.6',
+ name: 'Corrected Grok 4.6',
+ contextWindow: 1_000_000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ piApi: 'openai-completions',
+ },
+ ];
+ const bundled = piBundledModel('grok-4.6', 'openai-responses', {
+ thinkingLevelMap: { low: 'low', medium: 'medium', high: 'high', xhigh: 'xhigh' },
+ compat: { supportsReasoningEffort: true },
+ });
+
+ const model = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ new Map([['xai', new Map([[bundled.id, bundled]])]]),
+ ).providers.find((candidate) => candidate.id === 'xai')?.models[0];
+
+ expect(model).toMatchObject({
+ api: 'openai-completions',
+ thinkingLevelMap: {
+ minimal: null,
+ low: null,
+ medium: null,
+ high: 'high',
+ xhigh: null,
+ max: null,
+ },
});
+ expect(model?.compat).toBeUndefined();
});
it('maps each explicitly configured wire protocol to the Pi API form', () => {
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index bae127d842..9ea94a9b2a 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -36,6 +36,7 @@ import {
type CatalogXdMediaKind,
type CatalogModel,
type CustomProviderConfig,
+ type PiModelApi,
type Provider,
type ProviderWireProtocol,
} from '@cindy/model-providers';
@@ -43,6 +44,11 @@ import {
import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import { CHATGPT_MODEL_PREFIX } from '../../shared/subscriptionModels.js';
import { projectUnverifiedCatalogFallbackForBuildRegion } from './provider-access-policy.js';
+import {
+ isCatalogPiGatewayModelRetired,
+ resolveBundledPiGatewayModelProfile,
+ resolveCatalogPiGatewayModelApi,
+} from './pi-gateway-model-catalog.js';
import {
applyLocalConsumerOverrides,
applyLocalOverridesToRoot,
@@ -66,6 +72,8 @@ import {
/** OSS / bundled 加载来的基础目录;null = 尚未加载(回落 BUNDLED_CATALOG)。 */
let base: Catalog | null = null;
+/** Exact accepted Cindy Server/local/LKG snapshot before bundled compatibility backfill. */
+let piGatewayAuthorityCatalog: Catalog | null = null;
/** 当前基础目录是否由本次配置的 Catalog 真源明确证明;fallback 只保兼容元数据。 */
let baseCapabilityEvidence: CatalogCapabilityEvidence = 'fallback';
/** XD media fields inherited from bundled rather than proven by the current source. */
@@ -131,7 +139,7 @@ export interface XdGatewayAgentOverride {
defaultEffort?: string | null;
supportsFastMode?: boolean;
defaultEnabled?: boolean;
- wireProtocol?: Extract<ProviderWireProtocol, 'anthropic-messages' | 'openai-responses'>;
+ wireProtocol?: PiModelApi;
}
/**
@@ -318,31 +326,88 @@ function preserveNonGrok46DiscoveryEfforts(
});
}
+function isPiModelApi(value: unknown): value is PiModelApi {
+ return (
+ value === 'anthropic-messages' ||
+ value === 'openai-responses' ||
+ value === 'openai-completions' ||
+ value === 'google-generative-ai'
+ );
+}
+
+function resolveXdPiGatewayServerModelApi(model: XdGatewayModelInfo): PiModelApi | null | undefined {
+ return piGatewayAuthorityCatalog
+ ? resolveCatalogPiGatewayModelApi(piGatewayAuthorityCatalog, model.id)
+ : undefined;
+}
+
+function resolveXdPiGatewayHintModelApi(model: XdGatewayModelInfo): PiModelApi | null {
+ const gatewayApi: unknown = model.perAgent?.pi?.wireProtocol;
+ return isPiModelApi(gatewayApi) ? gatewayApi : null;
+}
+
+function resolveXdPiGatewayModelApi(model: XdGatewayModelInfo): PiModelApi | null {
+ // Source authority is deliberate and must not be inverted:
+ // Cindy Server downloaded Catalog > version-matched local Pi table > Cindy AI Gateway hint.
+ const catalogApi = resolveXdPiGatewayServerModelApi(model);
+ if (catalogApi !== undefined) return catalogApi;
+ const localApi = resolveBundledPiGatewayModelProfile(model.id)?.api;
+ if (localApi !== undefined) return localApi;
+ return resolveXdPiGatewayHintModelApi(model);
+}
+
function xdGatewayTargetAgents(model: XdGatewayModelInfo): AgentKind[] {
- return (model.agents ?? []).filter((agent) => {
- if (agent !== 'pi') return true;
- const wireProtocol = model.perAgent?.pi?.wireProtocol;
- return wireProtocol === 'anthropic-messages' || wireProtocol === 'openai-responses';
- });
+ // Pi's exact binary catalog is probed only when a session starts, after capabilities are built.
+ // Keep declared Pi membership provisional here unless Cindy Server has an exact Registry
+ // tombstone; the final resolver removes or rejects any other unsafe Gateway route, while same-id
+ // subscription/BYOM models remain usable.
+ const serverRetired =
+ piGatewayAuthorityCatalog !== null &&
+ isCatalogPiGatewayModelRetired(piGatewayAuthorityCatalog, model.id);
+ return (model.agents ?? []).filter((agent) => agent !== 'pi' || !serverRetired);
}
-/**
- * XD 下发模型给 Pi 时的真实 wire protocol。
- *
- * Pi provider 始终叫 `cindy`;这里只读取 v3 服务端给该模型的 transport,供
- * models.json 写入模型级 `api`。三态语义:非 XD Pi 模型返回 undefined;XD Pi 模型
- * 缺失或协议非法返回 null,由 maker-core fail closed;有效配置返回服务端声明值。
- */
-export function resolveXdPiGatewayWireProtocol(
- modelId: string,
-): Extract<ProviderWireProtocol, 'anthropic-messages' | 'openai-responses'> | null | undefined {
+/** Resolve only Cindy Server's highest-priority protocol declaration. */
+export function resolveXdPiGatewayServerApi(modelId: string): PiModelApi | null | undefined {
+ const normalized = modelId.replace(/\[1m\]$/, '');
+ const gatewayModel = xdGatewayModels.find((model) => model.id === normalized);
+ if (!gatewayModel?.agents?.includes('pi')) return undefined;
+ return resolveXdPiGatewayServerModelApi(gatewayModel);
+}
+
+/** Resolve only Cindy AI Gateway's last-priority protocol hint. */
+export function resolveXdPiGatewayHintApi(modelId: string): PiModelApi | null | undefined {
+ const normalized = modelId.replace(/\[1m\]$/, '');
+ const gatewayModel = xdGatewayModels.find((model) => model.id === normalized);
+ if (!gatewayModel?.agents?.includes('pi')) return undefined;
+ return resolveXdPiGatewayHintModelApi(gatewayModel);
+}
+
+/** Resolve Pi API in Cindy Server > local Pi table > Cindy AI Gateway order. */
+export function resolveXdPiGatewayApi(modelId: string): PiModelApi | null | undefined {
const normalized = modelId.replace(/\[1m\]$/, '');
const gatewayModel = xdGatewayModels.find((model) => model.id === normalized);
if (!gatewayModel?.agents?.includes('pi')) return undefined;
- const wireProtocol = gatewayModel.perAgent?.pi?.wireProtocol;
- return wireProtocol === 'anthropic-messages' || wireProtocol === 'openai-responses'
- ? wireProtocol
- : null;
+ return resolveXdPiGatewayModelApi(gatewayModel);
+}
+
+/** Legacy wire vocabulary for HTTP-only consumers that cannot represent Google's native API. */
+export function resolveXdPiGatewayWireProtocol(
+ modelId: string,
+): ProviderWireProtocol | null | undefined {
+ const api = resolveXdPiGatewayApi(modelId);
+ switch (api) {
+ case 'anthropic-messages':
+ return 'anthropic-messages';
+ case 'openai-responses':
+ return 'openai-responses';
+ case 'openai-completions':
+ return 'openai-chat';
+ case 'google-generative-ai':
+ return null;
+ default:
+ return api;
+ }
}
/** 派生 XD 中「仅 claude-code 面(投影给 Claude)、无 codex 原生」的模型 id 集合。 */
@@ -1161,6 +1226,7 @@ function computeMerged(): Catalog {
const defaultEnabled = ov.defaultEnabled ?? gm.defaultEnabled;
const cost = effectiveGatewayModelCost(gm);
const contextWindow = ov.contextWindow ?? gm.contextWindow;
+ const piApi = agent === 'pi' ? resolveXdPiGatewayModelApi(gm) : undefined;
const merged: CatalogModel = {
id: gm.id,
...(gm.availability ? { availability: gm.availability } : {}),
@@ -1185,9 +1251,9 @@ function computeMerged(): Catalog {
...(gm.icon !== undefined ? { icon: gm.icon } : {}),
...(cost ? { cost } : {}),
...(gm.modalities !== undefined ? { modalities: gm.modalities } : {}),
- // Pi 的协议是 Model Access 按模型下发的权威路由元数据。重建 CatalogModel 时
- // 必须一并投影,否则模型虽然保留在 Pi tab,统一路由器却会因协议缺失而 fail closed。
- ...(agent === 'pi' && ov.wireProtocol ? { piApi: ov.wireProtocol } : {}),
+ // Unknown pre-probe Pi routes stay provisional; models.json only emits a route after the
+ // current binary/server/local/Gateway resolver produces one of the supported APIs.
+ ...(agent === 'pi' && piApi ? { piApi } : {}),
};
models[agent]!.push(merged);
}
@@ -1245,6 +1311,7 @@ export function getCatalogModelContextWindow(
/** 由 host 的目录加载器(ensureActiveCatalogLoaded)在拉取成功后写入基础目录。 */
function installActiveCatalog(
catalog: Catalog,
+ authorityCatalog: Catalog | null,
capabilityEvidence: CatalogCapabilityEvidence,
unverifiedXdMediaKinds: readonly CatalogXdMediaKind[],
force: boolean,
@@ -1256,6 +1323,7 @@ function installActiveCatalog(
base !== null &&
baseCapabilityEvidence === capabilityEvidence &&
isDeepStrictEqual(baseUnverifiedXdMediaKinds, nextUnverifiedXdMediaKinds) &&
+ isDeepStrictEqual(piGatewayAuthorityCatalog, authorityCatalog) &&
isDeepStrictEqual(base, catalog)
) {
return false;
@@ -1264,6 +1332,7 @@ function installActiveCatalog(
catalog.modelRegistry ?? previous.modelRegistry ?? trustedCustomProviderRegistry;
trustedCustomProviderRegistry = projectionRegistry;
base = catalog;
+ piGatewayAuthorityCatalog = authorityCatalog;
baseCapabilityEvidence = capabilityEvidence;
baseUnverifiedXdMediaKinds = nextUnverifiedXdMediaKinds;
if (customConfigs) {
@@ -1278,6 +1347,7 @@ function installActiveCatalog(
export function setActiveCatalog(
catalog: Catalog,
options: {
+ authorityCatalog?: Catalog | null;
capabilityEvidence?: CatalogCapabilityEvidence;
unverifiedXdMediaKinds?: readonly CatalogXdMediaKind[];
} = {},
@@ -1285,6 +1355,7 @@ export function setActiveCatalog(
const capabilityEvidence = options.capabilityEvidence ?? 'current';
installActiveCatalog(
catalog,
+ options.authorityCatalog ?? null,
capabilityEvidence,
options.unverifiedXdMediaKinds ??
(capabilityEvidence === 'fallback' ? ['image', 'video', 'embedding'] : []),
@@ -1300,6 +1371,7 @@ export function setActiveCatalog(
export function commitActiveCatalogSnapshot(
catalog: Catalog,
options: {
+ authorityCatalog?: Catalog | null;
capabilityEvidence?: CatalogCapabilityEvidence;
unverifiedXdMediaKinds?: readonly CatalogXdMediaKind[];
} = {},
@@ -1307,6 +1379,7 @@ export function commitActiveCatalogSnapshot(
const capabilityEvidence = options.capabilityEvidence ?? 'current';
return installActiveCatalog(
catalog,
+ options.authorityCatalog ?? null,
capabilityEvidence,
options.unverifiedXdMediaKinds ??
(capabilityEvidence === 'fallback' ? ['image', 'video', 'embedding'] : []),
diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
index a6e76a58fe..c2f075a42e 100644
--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts
@@ -254,6 +254,56 @@ function headerValue(headers: Readonly<Record<string, string>>, name: string): s
return null;
}
+/**
+ * Pi chooses the payload API; the proxy only borrows Gateway's matching authenticated front door.
+ * Messages uses the Claude route, while Responses, Chat Completions, and native Gemini use the
+ * Codex/OpenAI route. The original URL and body remain untouched so Gateway performs no client-side
+ * protocol coercion.
+ */
+export function piGatewayRequestAgent(
+ requestUrl: string,
+): 'claude-code' | 'codex' {
+ try {
+ const pathname = new URL(requestUrl, 'http://127.0.0.1').pathname.replace(/\/+$/, '');
+ return pathname.endsWith('/messages') ? 'claude-code' : 'codex';
+ } catch {
+ return 'codex';
+ }
+}
+
+function sanitizePiGatewayDecision(
+ decision: RoutingDecision | null,
+ requestUrl: string,
+): RoutingDecision | null {
+ let pathname: string;
+ try {
+ pathname = new URL(requestUrl, 'http://127.0.0.1').pathname;
+ } catch {
+ return decision;
+ }
+ if (!pathname.includes('/v1beta/')) return decision;
+ // Pi must populate Google's SDK header to satisfy its local model schema, but for Cindy Gateway
+ // that value is only a process placeholder (or the Gateway bearer key), never a Google API key.
+ // Strip it even when auth routing produced no override (for example during a transient key read
+ // failure), so the default upstream can never receive the stale client-side credential.
+ return {
+ ...(decision ?? {}),
+ headerDelete: [
+ ...new Set([
+ ...(decision?.headerDelete ?? []),
+ 'x-goog-api-key',
+ ...(!decision
+ ? [
+ 'x-cindy-pi-session-id',
+ 'x-cindy-pi-session-token',
+ 'x-cindy-pi-provider-id',
+ ]
+ : []),
+ ]),
+ ],
+ };
+}
+
function isOwnerBoundaryPending(): boolean {
try {
return _isOwnerBoundaryPending();
@@ -509,7 +559,19 @@ export function createModelRoutingTransform(): RoutingTransform {
localHandler: getPiNativeSubscriptionHandler(piProviderId, piSessionId),
};
}
- const requestAgent = piSessionId ? 'pi' : 'claude-code';
+ const isPiGatewayRequest = Boolean(
+ piSessionId &&
+ (subagentRoute
+ ? piProviderId === null || piProviderId === 'xd'
+ : piProviderId === 'xd' ||
+ (piProviderId === null &&
+ (selectedPiProviderId === null || selectedPiProviderId === 'xd'))),
+ );
+ const requestAgent = piSessionId
+ ? isPiGatewayRequest
+ ? piGatewayRequestAgent(ctx.url)
+ : 'pi'
+ : 'claude-code';
// 后台活动检测(claude-session-background-activity):凡带 cc 会话标头的请求
// 都记一笔活动时刻。routingTransform 会处理无 body 控制面请求与 JSON 请求;
// 非 JSON 的 POST/PUT/PATCH 不经过这里,由响应侧 observer 兜底观察活动。
@@ -599,6 +661,15 @@ export function createModelRoutingTransform(): RoutingTransform {
const gatewayKey = _readGatewayKey();
+ if (subagentRoute && isPiGatewayRequest) {
+ // A `cindy` child route is provider-null by design. Route it by the request API instead of
+ // accidentally inheriting the parent session provider.
+ return sanitizePiGatewayDecision(
+ gatewayDefaultRouteDecision(requestAgent, gatewayKey) ?? unavailablePiProviderRoute('xd'),
+ ctx.url,
+ );
+ }
+
if (subagentRoute && piProviderId) {
// A provider-pinned child token is both the authorization boundary and
// the route source. Re-reading the parent session provider here would
@@ -616,7 +687,7 @@ export function createModelRoutingTransform(): RoutingTransform {
// 不在订阅直连供应商(xai / openai-cc)声明的 modelPrefixes 范围内 → 返回 null,
// 落到下方 ② 段 spawn 默认路由,分类器照常走网关/直连(issue #886)。
const perSession = resolveSessionRouteDecision(sessionId, requestAgent, gatewayKey, wireModel);
- const recordSelectedRoute = <T extends object | null>(route: T): T => {
+ const recordSelectedRoute = (route: RoutingDecision | null): RoutingDecision | null => {
if (
requestAgent === 'claude-code'
&& route
@@ -628,10 +699,13 @@ export function createModelRoutingTransform(): RoutingTransform {
selectedProviderId === 'xd' ? 'gateway' : 'subscription',
);
}
- return route;
+ return isPiGatewayRequest ? sanitizePiGatewayDecision(route, ctx.url) : route;
};
if (perSession instanceof Promise) return perSession.then(recordSelectedRoute);
if (perSession) return recordSelectedRoute(perSession);
+ if (isPiGatewayRequest && selectedProviderId === 'xd') {
+ return sanitizePiGatewayDecision(null, ctx.url);
+ }
}
// ①.5 隐式来源(sessionId 未反解出/未绑定供应商,或 ① 段 scope 门放行下来):按模型
@@ -734,7 +808,7 @@ export function createModelRoutingTransform(): RoutingTransform {
if (decision) {
// oauth-spawn 默认:全量换网关 key(防订阅 token 泄漏到网关)。
recordResolvedDefaultRoute('gateway');
- return decision;
+ return isPiGatewayRequest ? sanitizePiGatewayDecision(decision, ctx.url) : decision;
}
if (apiKeyHeader !== null) {
// 占位 key 且无网关 key:保持改动前行为(passthrough,上游 401)——下方的
diff --git a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
index 949b96ac02..fc63dcd21d 100644
--- a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
+++ b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
@@ -156,7 +156,10 @@ export function deriveAvailableModels(catalog: Catalog, agent: AgentKind): Model
const userProvider = provider.source === 'user';
if (!isModelSelectableForNewRoute(m, { userProvider })) continue;
const descriptor = toDescriptor(m, agent, {
- preserveExplicitPiEfforts: userProvider || (provider.id === 'xai' && isOfficialGrok46Id(m.id)),
+ preserveExplicitPiEfforts:
+ userProvider ||
+ provider.id === 'xd' ||
+ (provider.id === 'xai' && isOfficialGrok46Id(m.id)),
});
const previous = seen.get(m.id);
if (previous) {
@@ -203,7 +206,9 @@ export function resolvePiRuntimeModelDescriptor(
if (model && isAgentSelectableModel(model, { userProvider: provider.source === 'user' })) {
return toDescriptor(model, 'pi', {
preserveExplicitPiEfforts:
- provider.source === 'user' || (provider.id === 'xai' && isOfficialGrok46Id(model.id)),
+ provider.source === 'user' ||
+ provider.id === 'xd' ||
+ (provider.id === 'xai' && isOfficialGrok46Id(model.id)),
});
}
}
@@ -223,12 +228,12 @@ export function resolvePiRuntimeModelDescriptor(
return null;
}
-/** Pi 默认 gateway 的 v3 transport 来自 XD;描述符必须使用同一来源。 */
+/** `cindy` provider 始终代表 XD Gateway;其能力描述符不得继承当前订阅/BYOM。 */
export function resolvePiGatewayDescriptorProviderId(
providerId: string | null | undefined,
): string {
- const source = providerId?.trim();
- return !source || source === 'cindy' ? 'xd' : source;
+ void providerId;
+ return 'xd';
}
/**
diff --git a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
index a840aa540e..30a8750164 100644
--- a/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
+++ b/apps/desktop/src/main/maker-host/createDesktopProviderService.ts
@@ -483,6 +483,7 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {
const sourceKey = catalogSourceKey(source);
// 首次加载时顺手清掉旧版磁盘缓存孤儿(fire-and-forget,每进程一次)。
void cleanupLegacyCatalogCache();
+ let authorityCatalog: CatalogLoadResult['authorityCatalog'] = null;
let capabilityEvidence: CatalogCapabilityEvidence = 'fallback';
let unverifiedXdMediaKinds: CatalogLoadResult['unverifiedXdMediaKinds'] = [
'image',
@@ -490,12 +491,13 @@ export function ensureActiveCatalogLoaded(): Promise<Catalog> {
'embedding',
];
activeInflight = loadCatalog(source, io, (result) => {
+ authorityCatalog = result.authorityCatalog;
capabilityEvidence = result.capabilityEvidence;
unverifiedXdMediaKinds = result.unverifiedXdMediaKinds;
})
.then(async (catalog) => {
activeCatalogSourceKey = sourceKey;
- setActiveCatalog(catalog, { capabilityEvidence, unverifiedXdMediaKinds });
+ setActiveCatalog(catalog, { authorityCatalog, capabilityEvidence, unverifiedXdMediaKinds });
syncLocalCatalogOverridesIntoActiveCatalog();
getActiveCatalog();
logModelPlaneWarnings();
@@ -557,6 +559,7 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
setActiveCatalog(BUNDLED_CATALOG, { capabilityEvidence: 'fallback' });
broadcastReferenceModelPricing();
+ let authorityCatalog: CatalogLoadResult['authorityCatalog'] = null;
let capabilityEvidence: CatalogCapabilityEvidence = 'fallback';
let unverifiedXdMediaKinds: CatalogLoadResult['unverifiedXdMediaKinds'] = [
'image',
@@ -564,6 +567,7 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
'embedding',
];
const flight = loadCatalog(source, io, (result) => {
+ authorityCatalog = result.authorityCatalog;
capabilityEvidence = result.capabilityEvidence;
unverifiedXdMediaKinds = result.unverifiedXdMediaKinds;
})
@@ -575,7 +579,7 @@ export function reloadActiveCatalogForEndpointChange(): Promise<Catalog> {
return getActiveCatalog();
}
activeCatalogSourceKey = sourceKey;
- setActiveCatalog(catalog, { capabilityEvidence, unverifiedXdMediaKinds });
+ setActiveCatalog(catalog, { authorityCatalog, capabilityEvidence, unverifiedXdMediaKinds });
broadcastReferenceModelPricing();
return getActiveCatalog();
})
@@ -615,7 +619,7 @@ export async function refreshActiveCatalogFromSource(): Promise<Catalog> {
}
const generation = endpointReloadGeneration;
const flight = loadCatalogWithSource(sourceConfig, io)
- .then(({ catalog, source, capabilityEvidence, unverifiedXdMediaKinds }) => {
+ .then(({ catalog, authorityCatalog, source, capabilityEvidence, unverifiedXdMediaKinds }) => {
if (source === 'bundled') {
throw new Error('catalog refresh exhausted configured sources; keeping current snapshot');
}
@@ -639,6 +643,7 @@ export async function refreshActiveCatalogFromSource(): Promise<Catalog> {
// 选中 current 还是 fallback,都必须把完整快照与能力证据原子安装。
// commitActiveCatalogSnapshot 会保留完整快照与证据均相同的精确 no-op。
commitActiveCatalogSnapshot(catalog, {
+ authorityCatalog,
capabilityEvidence,
unverifiedXdMediaKinds,
});
@@ -663,7 +668,11 @@ export async function refreshActiveCatalogFromSource(): Promise<Catalog> {
return getActiveCatalog();
}
}
- commitActiveCatalogSnapshot(catalog, { capabilityEvidence, unverifiedXdMediaKinds });
+ commitActiveCatalogSnapshot(catalog, {
+ authorityCatalog,
+ capabilityEvidence,
+ unverifiedXdMediaKinds,
+ });
// computeMerged 在这里同步完成,确保告警属于刚提交的同一代目录;不能读取
// 上一代惰性缓存留下的 warnings。
const activeCatalog = getActiveCatalog();
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index b00e9ebc08..d9032ca40c 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1833,8 +1833,8 @@ export function getMaker(): Maker {
localOverrides: getLocalCatalogOverridesSnapshot(),
}),
resolvePiGatewayModelDescriptor: (providerId, modelId) => {
- // `cindy` / null 是 Pi 的默认 gateway 路由;其 wire 由 v3 XD runtime plan
- // 决定,因此描述符也必须锁定 XD,不能让复合 `cindy` 按目录顺序命中同 id 订阅模型。
+ // `cindy` 始终是 XD Gateway 路由;其成员、能力与显式 API 都由 Model Access
+ // 决定,不能随当前订阅/BYOM provider 命中同 id 的另一条目录记录。
return resolvePiRuntimeModelDescriptor(
getDesktopSelectableCatalog(),
resolvePiGatewayDescriptorProviderId(providerId),
diff --git a/apps/desktop/src/main/maker-host/pi-gateway-model-catalog.ts b/apps/desktop/src/main/maker-host/pi-gateway-model-catalog.ts
new file mode 100644
index 0000000000..1af39539b7
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/pi-gateway-model-catalog.ts
@@ -0,0 +1,275 @@
+import type {
+ Catalog,
+ PiModelApi,
+ ProviderRuntimeModelConfig,
+ ProviderWireProtocol,
+} from '@cindy/model-providers';
+import piModelCatalogJson from '@cindy/model-providers/pi-model-catalog' with { type: 'json' };
+
+export interface BundledPiGatewayModelProfile {
+ api: PiModelApi;
+ compat?: Record<string, unknown>;
+ samplingParams?: Record<string, unknown>;
+ thinkingLevelMap?: Record<string, string | null>;
+}
+
+interface PiCatalogRow extends BundledPiGatewayModelProfile {
+ id: string;
+ provider: string;
+}
+
+const catalog = piModelCatalogJson as unknown as {
+ providers: Record<string, PiCatalogRow[]>;
+};
+const rows = Object.values(catalog.providers).flat();
+
+const gatewayModelIdsByApi: Record<PiModelApi, ReadonlySet<string>> = {
+ 'anthropic-messages': new Set([
+ 'claude-fable-5',
+ 'claude-haiku-4-5',
+ 'claude-haiku-4-5-20251001',
+ 'claude-opus-4-6',
+ 'claude-opus-4-7',
+ 'claude-opus-4-8',
+ 'claude-opus-5',
+ 'claude-sonnet-4-6',
+ 'claude-sonnet-5',
+ 'anthropic/claude-opus-5',
+ ]),
+ 'openai-responses': new Set([
+ 'gpt-5.4',
+ 'gpt-5.4-mini',
+ 'gpt-5.4-nano',
+ 'gpt-5.5',
+ 'gpt-5.6-luna',
+ 'gpt-5.6-sol',
+ 'gpt-5.6-terra',
+ 'codex/gpt-5.4',
+ 'codex/gpt-5.4-mini',
+ 'codex/gpt-5.5',
+ 'codex/gpt-5.5:auto',
+ 'codex/gpt-5.6-luna',
+ 'codex/gpt-5.6-sol',
+ 'codex/gpt-5.6-terra',
+ 'meta/muse-spark-1.2',
+ 'x-ai-grok/grok-4.6',
+ 'x-ai/grok-4.5',
+ 'x-ai/grok-4.6',
+ ]),
+ 'openai-completions': new Set([
+ 'deepseek/deepseek-v4-flash',
+ 'deepseek/deepseek-v4-flash-vision-exp',
+ 'deepseek/deepseek-v4-pro',
+ 'moonshot/kimi-k3',
+ 'moonshotai/kimi-k2.6',
+ 'moonshotai/kimi-k3',
+ 'qwen/qwen3.7-max',
+ 'qwen/qwen3.8-27b',
+ 'qwen/qwen3.8-flash',
+ 'qwen/qwen3.8-max',
+ 'tencent/hy3',
+ 'z-ai/glm-5.1',
+ 'z-ai/glm-5.2',
+ 'z-ai/glm-5.3',
+ 'z-ai/glm-5.3-flash',
+ ]),
+ 'google-generative-ai': new Set([
+ 'gemini-3-flash-preview',
+ 'gemini-3.1-pro-preview',
+ 'gemini-3.5-flash',
+ 'gemini-3.6-flash',
+ 'google/gemini-3.6-flash',
+ 'google/gemini-3.7-flash',
+ ]),
+};
+
+function normalizeModelId(modelId: string): string {
+ return modelId.replace(/\[1m\]$/, '');
+}
+
+function piApiFromWireProtocol(protocol: ProviderWireProtocol | undefined): PiModelApi | undefined {
+ switch (protocol) {
+ case 'anthropic-messages':
+ return 'anthropic-messages';
+ case 'openai-responses':
+ return 'openai-responses';
+ case 'openai-chat':
+ return 'openai-completions';
+ default:
+ return undefined;
+ }
+}
+
+function catalogModelApi(
+ model: ProviderRuntimeModelConfig,
+ defaultProtocol: ProviderWireProtocol | undefined,
+): PiModelApi | undefined {
+ return model.piApi ?? piApiFromWireProtocol(model.route?.wireProtocol ?? defaultProtocol);
+}
+
+function collapseCatalogApis(apis: readonly PiModelApi[]): PiModelApi | null | undefined {
+ const distinct = [...new Set(apis)];
+ if (distinct.length === 0) return undefined;
+ return distinct.length === 1 ? distinct[0] : null;
+}
+
+function routedCatalogApis(
+ catalog: Catalog,
+ providerId: string,
+ modelId: string,
+): PiModelApi[] {
+ if (providerId === 'xd') return [];
+ const apis: PiModelApi[] = [];
+ const provider = catalog.providers.find((entry) => entry.id === providerId);
+ const providerModel = provider?.models.pi?.find((model) => model.id === modelId);
+ const providerApi = providerModel
+ ? catalogModelApi(providerModel, provider?.routing.pi?.wireProtocol)
+ : undefined;
+ if (providerApi) apis.push(providerApi);
+
+ const preset = catalog.presets?.find((entry) => entry.id === providerId);
+ const runtime = preset?.runtimes.pi;
+ const presetModel = runtime?.models.find((model) => model.id === modelId);
+ const presetApi = presetModel ? catalogModelApi(presetModel, runtime?.wireProtocol) : undefined;
+ if (presetApi) apis.push(presetApi);
+ return apis;
+}
+
+/**
+ * Resolve the Pi protocol declared by Cindy Server's downloaded Catalog.
+ *
+ * Only Registry-linked provider routes are identity proof. A matching model string in an unrelated
+ * preset/provider is not enough: aggregators and native providers can expose the same wire id over
+ * different protocols. Bare-id and standalone namespaced-id matching are therefore both forbidden.
+ *
+ * `null` means the server Catalog contains conflicting declarations for the same proven identity;
+ * callers must fail closed instead of falling through to a lower-priority source.
+ */
+function catalogPiGatewayRegistryEntries(catalog: Catalog, gatewayModelId: string) {
+ const normalized = normalizeModelId(gatewayModelId);
+ return (
+ catalog.modelRegistry?.models.filter((entry) =>
+ entry.routes.some((route) => route.providerId === 'xd' && route.modelId === normalized),
+ ) ?? []
+ );
+}
+
+/** True only for an exact XD Registry tombstone from Cindy Server. */
+export function isCatalogPiGatewayModelRetired(catalog: Catalog, gatewayModelId: string): boolean {
+ return catalogPiGatewayRegistryEntries(catalog, gatewayModelId).some(
+ (entry) => entry.status === 'retired',
+ );
+}
+
+export function resolveCatalogPiGatewayModelApi(
+ catalog: Catalog,
+ gatewayModelId: string,
+): PiModelApi | null | undefined {
+ const registryEntries = catalogPiGatewayRegistryEntries(catalog, gatewayModelId);
+ if (registryEntries.some((entry) => entry.status === 'retired')) return null;
+ const routed = registryEntries.flatMap((entry) =>
+ entry.routes.flatMap((route) => routedCatalogApis(catalog, route.providerId, route.modelId)),
+ );
+ return collapseCatalogApis(routed);
+}
+
+const gatewayCatalogIdentityOverrides = new Map<string, { provider: string; modelId: string }>([
+ ...[
+ 'claude-fable-5',
+ 'claude-haiku-4-5',
+ 'claude-haiku-4-5-20251001',
+ 'claude-opus-4-6',
+ 'claude-opus-4-7',
+ 'claude-opus-4-8',
+ 'claude-opus-5',
+ 'claude-sonnet-4-6',
+ 'claude-sonnet-5',
+ ].map((id) => [id, { provider: 'anthropic', modelId: id }] as const),
+ ['anthropic/claude-opus-5', { provider: 'anthropic', modelId: 'claude-opus-5' }],
+ ...[
+ 'gpt-5.4',
+ 'gpt-5.4-mini',
+ 'gpt-5.4-nano',
+ 'gpt-5.5',
+ 'gpt-5.6-luna',
+ 'gpt-5.6-sol',
+ 'gpt-5.6-terra',
+ ].flatMap((id) => [
+ [id, { provider: 'openai', modelId: id }] as const,
+ [`codex/${id}`, { provider: 'openai', modelId: id }] as const,
+ ]),
+ ['codex/gpt-5.5:auto', { provider: 'openai', modelId: 'gpt-5.5' }],
+ ...[
+ 'gemini-3-flash-preview',
+ 'gemini-3.1-pro-preview',
+ 'gemini-3.5-flash',
+ 'gemini-3.6-flash',
+ ].map((id) => [id, { provider: 'google', modelId: id }] as const),
+ ['google/gemini-3.6-flash', { provider: 'google', modelId: 'gemini-3.6-flash' }],
+ ['google/gemini-3.7-flash', { provider: 'google', modelId: 'gemini-3.7-flash' }],
+ ...['deepseek-v4-flash', 'deepseek-v4-flash-vision-exp', 'deepseek-v4-pro'].map(
+ (id) => [`deepseek/${id}`, { provider: 'deepseek', modelId: id }] as const,
+ ),
+ ['moonshot/kimi-k3', { provider: 'moonshotai', modelId: 'kimi-k3' }],
+ ['moonshotai/kimi-k2.6', { provider: 'moonshotai', modelId: 'kimi-k2.6' }],
+ ['moonshotai/kimi-k3', { provider: 'moonshotai', modelId: 'kimi-k3' }],
+ ...['qwen3.7-max', 'qwen3.8-27b', 'qwen3.8-flash', 'qwen3.8-max'].map(
+ (id) => [`qwen/${id}`, { provider: 'qwen-token-plan-cn', modelId: id }] as const,
+ ),
+ ...['glm-5.1', 'glm-5.2', 'glm-5.3', 'glm-5.3-flash'].map(
+ (id) => [`z-ai/${id}`, { provider: 'zai', modelId: id }] as const,
+ ),
+ ...['grok-4.5', 'grok-4.6'].flatMap((id) => [
+ [`x-ai/${id}`, { provider: 'xai', modelId: id }] as const,
+ [`x-ai-grok/${id}`, { provider: 'xai', modelId: id }] as const,
+ ]),
+]);
+
+function authoritativeGatewayApi(modelId: string): PiModelApi | undefined {
+ const normalized = normalizeModelId(modelId);
+ for (const [api, ids] of Object.entries(gatewayModelIdsByApi) as Array<
+ [PiModelApi, ReadonlySet<string>]
+ >) {
+ if (ids.has(normalized)) return api;
+ }
+ return undefined;
+}
+
+/** Preferred exact provider/model identity in Pi's complete bundled catalog. */
+export function resolveBundledPiGatewayCatalogIdentity(
+ modelId: string,
+): { provider: string; modelId: string } | undefined {
+ const normalized = normalizeModelId(modelId);
+ const explicit = gatewayCatalogIdentityOverrides.get(normalized);
+ if (explicit) return explicit;
+ const direct = rows.find((row) => `${row.provider}/${row.id}` === normalized);
+ return direct ? { provider: direct.provider, modelId: direct.id } : undefined;
+}
+
+/**
+ * Resolve the current Gateway model through Cindy's version-matched Pi table.
+ *
+ * Cindy Server's downloaded Catalog is checked before this function. This local table is the
+ * second authority and may only resolve exact, allowlisted identities. Cindy AI Gateway metadata
+ * is a last-resort hint after both higher-priority sources are absent. Unknown identities fail
+ * closed instead of guessing a provider or protocol.
+ */
+export function resolveBundledPiGatewayModelProfile(
+ modelId: string,
+): BundledPiGatewayModelProfile | undefined {
+ const identity = resolveBundledPiGatewayCatalogIdentity(modelId);
+ const matched = identity
+ ? rows.find((row) => row.provider === identity.provider && row.id === identity.modelId)
+ : undefined;
+ const api = matched?.api ?? authoritativeGatewayApi(modelId);
+ if (!api) return undefined;
+ // Never borrow compat by bare ID across providers. An allowlisted Gateway identity may still
+ // use its locally selected API, but provider-specific serialization metadata requires an exact
+ // canonical provider/model row (or the exact binary probe in pi-host).
+ return {
+ api,
+ ...(matched?.compat ? { compat: structuredClone(matched.compat) } : {}),
+ ...(matched?.samplingParams ? { samplingParams: structuredClone(matched.samplingParams) } : {}),
+ ...(matched?.thinkingLevelMap ? { thinkingLevelMap: { ...matched.thinkingLevelMap } } : {}),
+ };
+}
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index 252b037076..bb79a9f76a 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -8,7 +8,8 @@
* 从安全存储注入,models.json 不落任何真实订阅凭证。
* - endpoint:统一走 authenticated loopback proxy。PI 按供应商使用原生协议:
* Claude=Messages、ChatGPT=Codex Responses、SuperGrok=PI bundled API;host
- * 只注入凭证并原样转发。Cindy Gateway 继续按 Model Access v3 下发协议。
+ * 只注入凭证并原样转发。Cindy Gateway 的成员与显式 API 来自 Model Access;
+ * 版本匹配的 Pi 本地模型表只补足缺失 API 及协议一致的 compat。
* - 二进制:与 cc/codex 同链 —— splash prepare 经 agent-binaries 按 CDN manifest
* 的 pi 字段下载整目录 tar.gz 到 userData/pi/<version>/(SHA256 校验,清单一变
* 下次启动即换新)。dev 期使用 apps/pi-bin 中 pnpm install:pi 的产物;正式版
@@ -95,8 +96,13 @@ import { getRipgrepBinaryPath, claudeUpstreamEndpoint } from './runtime-configs.
import {
getActiveCatalog,
getLocalCatalogOverridesSnapshot,
- resolveXdPiGatewayWireProtocol,
+ resolveXdPiGatewayHintApi,
+ resolveXdPiGatewayServerApi,
} from './active-catalog.js';
+import {
+ resolveBundledPiGatewayCatalogIdentity,
+ resolveBundledPiGatewayModelProfile,
+} from './pi-gateway-model-catalog.js';
import { isExclusiveXaiModelId } from '../../shared/subscriptionModels.js';
import { resolvePiRuntimeModelDescriptor } from './catalog-to-descriptors.js';
import { resolveManagedPiPackageResources } from './pi-package-store.js';
@@ -133,6 +139,7 @@ export type PiListedModelIds = ReadonlyMap<string, ReadonlySet<string>>;
const piBundledModelsByBinary = new Map<string, Promise<PiBundledModelCatalog | null>>();
const listedIdsByCatalog = new WeakMap<PiBundledModelCatalog, PiListedModelIds>();
+let latestPiBundledModelCatalog: PiBundledModelCatalog | null = null;
export function listedPiModelIds(
catalog: PiBundledModelCatalog | undefined,
@@ -378,7 +385,12 @@ export async function readPiBundledModels(
binaryPath: string,
): Promise<PiBundledModelCatalog | null> {
const cached = piBundledModelsByBinary.get(binaryPath);
- if (cached) return cached;
+ if (cached) {
+ const catalog = await cached;
+ latestPiBundledModelCatalog = catalog;
+ if (catalog === null) piBundledModelsByBinary.delete(binaryPath);
+ return catalog;
+ }
const pending = (async () => {
let configDir: string | undefined;
try {
@@ -456,7 +468,12 @@ export async function readPiBundledModels(
}
})();
piBundledModelsByBinary.set(binaryPath, pending);
- return pending;
+ const catalog = await pending;
+ latestPiBundledModelCatalog = catalog;
+ // A temp-dir/timeout/parse failure is transient evidence, not a permanent property of this
+ // binary. Keep successful probes cached, but let the next session retry a null result.
+ if (catalog === null) piBundledModelsByBinary.delete(binaryPath);
+ return catalog;
}
function catalogCostForPiNative(cost: {
@@ -606,6 +623,15 @@ export function buildPiSubscriptionNativeProviders(
const officialModel = sourceProviderId === 'xai' ? officialXaiById.get(wireId) : undefined;
const officialThinking = officialXaiThinkingSpec(officialModel);
const capabilityCorrection = xaiOfficialCapabilityCorrection(bundledModel, officialModel);
+ const finalMetadataApi = isProtocolCorrection
+ ? model.piApi
+ : isXaiCatalogAddition
+ ? (model.piApi ?? officialModel?.api ?? bundledModel?.api ?? 'openai-responses')
+ : (bundledModel?.api ?? model.piApi ?? officialModel?.api);
+ const compatibleOfficialThinking =
+ officialModel?.api === finalMetadataApi ? officialThinking : null;
+ const compatibleCapabilityCorrection =
+ capabilityCorrection?.api === finalMetadataApi ? capabilityCorrection : null;
const isRegistryBaselineOverlay = sourceProviderId === 'openai' && !!bundledModel;
const catalogCost = catalogCostForPiNative(model.cost);
if (isRegistryBaselineOverlay) {
@@ -641,10 +667,12 @@ export function buildPiSubscriptionNativeProviders(
: {}),
};
}
- const preserved = isProtocolCorrection ? bundledModel : contextProfileTemplate;
+ // A protocol correction must not preserve the old serializer profile. compat, headers,
+ // thinking, or sampling metadata from a different API would create an unsafe hybrid.
+ const preserved = contextProfileTemplate;
const thinkingLevelMap =
- capabilityCorrection?.thinkingLevelMap
- ?? officialThinking?.thinkingLevelMap
+ compatibleCapabilityCorrection?.thinkingLevelMap
+ ?? compatibleOfficialThinking?.thinkingLevelMap
?? (preserved?.thinkingLevelMap
? { ...preserved.thinkingLevelMap }
: model.efforts.length > 0
@@ -685,8 +713,8 @@ export function buildPiSubscriptionNativeProviders(
? { maxTokens: model.maxOutput }
: {}),
reasoning:
- capabilityCorrection?.reasoning
- ?? officialThinking?.reasoning
+ compatibleCapabilityCorrection?.reasoning
+ ?? compatibleOfficialThinking?.reasoning
?? preserved?.reasoning
?? model.efforts.length > 0,
...(preserved?.input
@@ -701,10 +729,10 @@ export function buildPiSubscriptionNativeProviders(
? { cost: catalogCost }
: {}),
...(preserved?.headers ? { headers: { ...preserved.headers } } : {}),
- ...(capabilityCorrection?.compat
- ? { compat: capabilityCorrection.compat }
- : isXaiCatalogAddition && officialThinking?.compat
- ? { compat: officialThinking.compat }
+ ...(compatibleCapabilityCorrection?.compat
+ ? { compat: compatibleCapabilityCorrection.compat }
+ : compatibleOfficialThinking?.compat
+ ? { compat: compatibleOfficialThinking.compat }
: preserved?.compat
? { compat: structuredClone(preserved.compat) }
: {}),
@@ -1462,11 +1490,103 @@ export async function buildXaiPiNativeProvider(
};
}
+function isPiGatewayModelApi(api: PiBundledModelInfo['api']): api is PiModelApi {
+ return (
+ api === 'anthropic-messages' ||
+ api === 'openai-responses' ||
+ api === 'openai-completions' ||
+ api === 'google-generative-ai'
+ );
+}
+
+function resolveProbedPiGatewayModel(modelId: string): PiBundledModelInfo | undefined {
+ const normalized = modelId.replace(/\[1m\]$/, '');
+ const identity = resolveBundledPiGatewayCatalogIdentity(normalized);
+ if (identity) {
+ const matched = latestPiBundledModelCatalog?.get(identity.provider)?.get(identity.modelId);
+ if (matched) return matched;
+ }
+ // Future namespaced models may use Pi's exact provider/model identity without a client alias.
+ // This is an exact pair lookup, never a bare-id or family guess.
+ const slash = normalized.indexOf('/');
+ if (slash <= 0) return undefined;
+ return latestPiBundledModelCatalog
+ ?.get(normalized.slice(0, slash))
+ ?.get(normalized.slice(slash + 1));
+}
+
export function resolvePiCindyGatewayModelApi(
_selectedProviderId: string | null | undefined,
modelId: string,
-): 'anthropic-messages' | 'openai-responses' | null | undefined {
- return resolveXdPiGatewayWireProtocol(modelId);
+ context?: { remote: boolean },
+): PiModelApi | null | undefined {
+ // Gateway membership remains the account-availability gate, but its protocol is the last hint.
+ const gatewayApi = resolveXdPiGatewayHintApi(modelId);
+ if (gatewayApi === undefined) return undefined;
+ const serverApi = resolveXdPiGatewayServerApi(modelId);
+ if (serverApi !== undefined) return serverApi;
+ // The Desktop binary is not evidence about a different Pi executable on an SSH host. Remote
+ // sessions skip that probe but still use this client version's explicit static configuration
+ // before the last-priority Gateway hint.
+ if (context?.remote) return resolveBundledPiGatewayModelProfile(modelId)?.api ?? gatewayApi;
+ const probed = resolveProbedPiGatewayModel(modelId);
+ if (probed) return isPiGatewayModelApi(probed.api) ? probed.api : null;
+ return resolveBundledPiGatewayModelProfile(modelId)?.api ?? gatewayApi;
+}
+
+export function resolvePiCindyGatewayModelSpec(
+ _selectedProviderId: string | null | undefined,
+ modelId: string,
+ context?: { remote: boolean },
+): Pick<
+ PiNativeModelSpec,
+ 'api' | 'compat' | 'samplingParams' | 'thinkingLevelMap'
+> | null | undefined {
+ const api = resolvePiCindyGatewayModelApi(_selectedProviderId, modelId, context);
+ if (api === undefined || api === null) return api;
+ const bundled = resolveBundledPiGatewayModelProfile(modelId);
+ // Remote execution never receives metadata from the Desktop binary probe. The version-matched
+ // static client profile remains the second authority and is injected only when its API matches.
+ if (context?.remote) {
+ return {
+ api,
+ ...(bundled?.api === api && bundled.compat
+ ? { compat: structuredClone(bundled.compat) }
+ : {}),
+ ...(bundled?.api === api && bundled.samplingParams
+ ? { samplingParams: structuredClone(bundled.samplingParams) }
+ : {}),
+ ...(bundled?.api === api && bundled.thinkingLevelMap
+ ? { thinkingLevelMap: { ...bundled.thinkingLevelMap } }
+ : {}),
+ };
+ }
+ const probed = resolveProbedPiGatewayModel(modelId);
+ // Provider quirks are API-specific. Local metadata may fill omissions only when it agrees with
+ // the final API; never apply stale compat across a protocol change. The exact current binary
+ // probe takes precedence over the checked-in snapshot when both match that API.
+ const compatibleBundled = bundled?.api === api ? bundled : undefined;
+ const compatibleProbed = probed?.api === api ? probed : undefined;
+ return {
+ api,
+ ...(compatibleProbed?.compat ?? compatibleBundled?.compat
+ ? { compat: structuredClone(compatibleProbed?.compat ?? compatibleBundled?.compat) }
+ : {}),
+ ...(compatibleProbed?.samplingParams ?? compatibleBundled?.samplingParams
+ ? {
+ samplingParams: structuredClone(
+ compatibleProbed?.samplingParams ?? compatibleBundled?.samplingParams,
+ ),
+ }
+ : {}),
+ ...(compatibleProbed?.thinkingLevelMap ?? compatibleBundled?.thinkingLevelMap
+ ? {
+ thinkingLevelMap: {
+ ...(compatibleProbed?.thinkingLevelMap ?? compatibleBundled?.thinkingLevelMap),
+ },
+ }
+ : {}),
+ };
}
/** BYOM:读 DB 自定义 provider + safeStorage key → pi 原生 provider spec。IO 外壳,逻辑在上面。 */
@@ -1495,7 +1615,10 @@ export async function resolvePiNativeProviders(ctx: {
throw new PiNativeProviderProxyNotReadyError();
}
const piBinaryPath = resolvePiBinaryPath();
- const bundledModels = piBinaryPath ? await readPiBundledModels(piBinaryPath) : null;
+ // Never treat the Desktop executable as the catalog of a different remote Pi binary.
+ const bundledModels = !ctx.remoteHostId && piBinaryPath
+ ? await readPiBundledModels(piBinaryPath)
+ : null;
let subscriptions: PiNativeProvidersResult = { providers: [], env: {} };
if (!ctx?.remoteHostId && compatProxyReady) {
const retainedOpenAiModel =
@@ -1736,9 +1859,10 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null {
resolvePiRuntimeModelDescriptor: opts.resolvePiRuntimeModelDescriptor,
resolvePiGatewayModelDescriptor: opts.resolvePiGatewayModelDescriptor,
// `cindy` is the gateway fallback block even when the session starts on a subscription or
- // BYOM provider. Its model protocol must therefore come from the exact XD model, never from
- // the currently selected provider's endpoint default.
+ // BYOM provider. Its explicit protocol comes from the exact XD model; the local Pi table only
+ // fills a remote omission and never inherits the currently selected provider's endpoint.
resolvePiGatewayModelApi: resolvePiCindyGatewayModelApi,
+ resolvePiGatewayModelSpec: resolvePiCindyGatewayModelSpec,
getGhostRosterPrompt: opts.getGhostRosterPrompt,
resolvePiProjectTrustInput: opts.resolvePiProjectTrustInput,
resolvePiVisionBridgeEnv: opts.resolvePiVisionBridgeEnv,
diff --git a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
index 1a221c9e82..62d13eb866 100644
--- a/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
+++ b/apps/desktop/src/main/model-access/__tests__/modelsSyncRefresh.test.ts
@@ -117,7 +117,12 @@ describe('parseModelsSyncPayload', () => {
expect(lastKnownGood).toEqual([{ id: 'last-known-model' }]);
});
- it.each(['openai-responses', 'anthropic-messages'] as const)(
+ it.each([
+ 'anthropic-messages',
+ 'openai-responses',
+ 'openai-completions',
+ 'google-generative-ai',
+ ] as const)(
'reads v5 Pi %s routing and filters future agent kinds without rejecting the catalog',
(piWireProtocol) => {
const payload = {
diff --git a/apps/desktop/src/shared/modelAccess.ts b/apps/desktop/src/shared/modelAccess.ts
index 4dfd60d32d..56727a4931 100644
--- a/apps/desktop/src/shared/modelAccess.ts
+++ b/apps/desktop/src/shared/modelAccess.ts
@@ -99,8 +99,12 @@ export interface ModelAccessAgentOverride {
defaultEffort?: string | null;
supportsFastMode?: boolean;
defaultEnabled?: boolean;
- /** v3/v4 runtime transport; required by the contract for every listed Agent. */
- wireProtocol?: 'anthropic-messages' | 'openai-responses';
+ /** v3+ runtime transport; Pi accepts every native API while Claude/Codex stay fixed. */
+ wireProtocol?:
+ | 'anthropic-messages'
+ | 'openai-responses'
+ | 'openai-completions'
+ | 'google-generative-ai';
}
export interface ModelGroupTieredPricing {
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 7566f02bc7..5c5da57354 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -247,6 +247,12 @@ export interface PiRemoteFileOps {
listDir(dir: string): Promise<string[]>;
}
+/** Gateway rows carry only host-resolved API/compat metadata, never a native provider endpoint. */
+export type PiGatewayModelSpec = Pick<
+ PiNativeModelSpec,
+ 'api' | 'compat' | 'samplingParams' | 'thinkingLevelMap'
+>;
+
/**
* BYOM:一个**原生 pi provider**(用户自定义/本地模型)—— 直连用户端点,不经 Cindy 的
* anthropic-compat 代理(设计原则:pi 主导,禁双重转义)。host 从 custom-provider-store
@@ -666,19 +672,23 @@ export interface AgentDeps {
) => ModelDescriptor | null;
/**
- * Pi-only:解析 `cindy` gateway 内某模型应使用的 PI API。provider 仍保持 `cindy`,
- * 但同一 model id 可能同时存在于 XD 与订阅来源,必须同时按当前会话来源落实 wire
- * protocol,不能只按 model id 猜。三态语义:
- * - `openai-responses`:Model Access v3 明确指定的 Cindy AI Pi 路由;
- * - `anthropic-messages`:非 XD compat proxy 路由;
- * - `null`:模型属于 Cindy AI Pi 目录,但协议缺失或不匹配,Pi fail closed;
- * - `undefined`:当前来源未声明该模型的 Pi 协议;不得写入 `cindy` gateway 块。
+ * Pi-only:按 Cindy Server > 执行环境本地 Pi 目录 > Gateway hint 解析 `cindy` API。
+ * `remote` 让 host 在无法探测实际远端 Pi 时跳过本机目录,禁止跨二进制借 metadata。
+ * null = 已知 Gateway Pi 模型但无法安全解析;undefined = 不属于 Gateway Pi 目录。
*/
resolvePiGatewayModelApi?: (
providerId: string | null | undefined,
modelId: string,
+ context?: { remote: boolean },
) => PiNativeApi | null | undefined;
+ /** Host-resolved model-specific PI compatibility metadata for the Gateway block. */
+ resolvePiGatewayModelSpec?: (
+ providerId: string | null | undefined,
+ modelId: string,
+ context?: { remote: boolean },
+ ) => PiGatewayModelSpec | null | undefined;
+
/**
* Host-provided capability descriptor additions.
*
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
index cb7ae72883..cf3c51200c 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-agent.integration.test.ts
@@ -529,6 +529,76 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it(
+ 'sends the locally selected Gateway Kimi API with matching compat to /v1/chat/completions',
+ { timeout: 60_000 },
+ async () => {
+ const deps = buildDeps();
+ deps.capabilityAdditions = {
+ ...deps.capabilityAdditions,
+ availableModels: [
+ ...(deps.capabilityAdditions?.availableModels ?? []),
+ {
+ id: 'moonshotai/kimi-k3',
+ displayName: 'Kimi K3',
+ contextWindow: 1_000_000,
+ efforts: ['low', 'high', 'max'],
+ defaultEffort: 'max',
+ },
+ ],
+ };
+ deps.resolvePiGatewayModelApi = (_providerId, modelId) =>
+ modelId === 'moonshotai/kimi-k3' ? 'openai-completions' : 'anthropic-messages';
+ deps.resolvePiGatewayModelSpec = (_providerId, modelId) =>
+ modelId === 'moonshotai/kimi-k3'
+ ? {
+ api: 'openai-completions',
+ compat: {
+ maxTokensField: 'max_tokens',
+ thinkingFormat: 'openai',
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: 'kimi',
+ },
+ thinkingLevelMap: { low: 'low', high: 'high', max: 'max' },
+ }
+ : { api: 'anthropic-messages' };
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-agent-kimi-cwd-'));
+ let handle: AgentSessionHandle | null = null;
+ const requestsBefore = seenRequests.length;
+ scriptedResponses.push(chatCompletionsStreamBody('pong from kimi gateway', 'moonshotai/kimi-k3'));
+ try {
+ handle = await new PiAgent(deps).startSession({
+ sessionId: 'itest-kimi-session',
+ workingDir,
+ model: 'moonshotai/kimi-k3',
+ providerId: 'xd',
+ effort: 'max',
+ });
+ const events: AgentEvent[] = [];
+ const collected = (async () => {
+ for await (const event of handle!.events()) {
+ events.push(event);
+ if (event.type === 'done') break;
+ }
+ })();
+
+ await handle.send({ type: 'user', content: 'ping kimi' });
+ await collected;
+
+ const requests = seenRequests.slice(requestsBefore);
+ expect(requests.some((request) => request.url === '/v1/chat/completions')).toBe(true);
+ expect(requests.some((request) => request.url === '/v1/responses')).toBe(false);
+ expect(events.some((event) =>
+ event.type === 'text'
+ && (event.data as { text?: string }).text?.includes('pong from kimi gateway'),
+ )).toBe(true);
+ } finally {
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ },
+ );
+
it(
'uses the bundled openai-codex adapter for a host subscription model',
{ timeout: 60_000 },
@@ -682,7 +752,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
);
it(
- 'uses PI bundled xAI APIs as the baseline for Responses and Chat Completions models',
+ 'uses the current PI bundled xAI Responses API for both official models',
{ timeout: 60_000 },
async () => {
const deps = buildDeps();
@@ -764,8 +834,8 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
await run(
'itest-native-xai-completions',
'xai/grok-build-0.1',
- chatCompletionsStreamBody('pong from xai completions', 'grok-build-0.1'),
- '/v1/chat/completions',
+ responsesStreamBody('pong from xai responses', 'grok-build-0.1'),
+ '/v1/responses',
);
},
);
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 1607a79e7c..91fd459993 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
@@ -212,7 +212,7 @@ describe('Pi provider-aware model routing', () => {
}>;
}>;
};
- expect(apiResolver).toHaveBeenCalledWith('openai', 'shared-model');
+ expect(apiResolver).toHaveBeenCalledWith('openai', 'shared-model', { remote: false });
expect(descriptorResolver).toHaveBeenCalledWith('openai', 'shared-model');
expect(models.providers.cindy?.models.find((model) => model.id === 'shared-model')).toMatchObject({
name: 'Subscription Shared',
@@ -225,7 +225,7 @@ describe('Pi provider-aware model routing', () => {
expect(models.providers['native-b']?.models.some((model) => model.id === 'shared-model')).toBe(true);
await expect(handle.setModel!('shared-model', { providerId: 'xd' })).rejects.toThrow(
- /restart the Pi session to change provider wire protocol/,
+ /restart the Pi session to change provider API/,
);
expect(captured.requests).not.toContainEqual({
type: 'set_model',
@@ -1040,7 +1040,7 @@ describe('Pi provider-aware model routing', () => {
gatewayApi = 'openai-responses';
captured.requests.length = 0;
await expect(handle.setModel!('shared-model', { providerId: 'xd' })).rejects.toThrow(
- /restart the Pi session to change provider wire protocol/,
+ /restart the Pi session to change provider API/,
);
expect(captured.requests.filter((request) => request.type === 'set_model')).toEqual([]);
await handle.close();
@@ -1627,6 +1627,7 @@ describe('Pi provider-aware model routing', () => {
],
},
resolvePiAgentHome: () => agentHome,
+ resolvePiGatewayModelApi: () => 'anthropic-messages',
resolveRemotePiBinaryPath: async () => '/remote/pi',
getRemotePiFileOps: () => ({
mkdirp: async () => {},
@@ -2055,7 +2056,14 @@ describe('Pi provider-aware model routing', () => {
await handle.close();
});
- it('keeps provider cindy while applying a model-level Responses API and /v1 base URL', async () => {
+ it.each([
+ ['anthropic-messages', 'messages-model', undefined],
+ ['openai-responses', 'responses-model', 'http://127.0.0.1:9988/v1'],
+ ['openai-completions', 'moonshotai/kimi-k3', 'http://127.0.0.1:9988/v1'],
+ ['google-generative-ai', 'google/gemini-3.6-flash', 'http://127.0.0.1:9988/v1beta'],
+ ] as const)(
+ 'keeps provider cindy while emitting Gateway API %s',
+ async (api, modelId, baseUrl) => {
const deps: AgentDeps = {
auth: {
getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
@@ -2069,8 +2077,8 @@ describe('Pi provider-aware model routing', () => {
capabilityAdditions: {
availableModels: [
{
- id: 'responses-model',
- displayName: 'Responses Model',
+ id: modelId,
+ displayName: modelId,
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
@@ -2078,14 +2086,26 @@ describe('Pi provider-aware model routing', () => {
],
},
resolvePiAgentHome: () => agentHome,
- resolvePiGatewayModelApi: (_providerId, modelId) =>
- modelId === 'responses-model' ? 'openai-responses' : 'anthropic-messages',
+ resolvePiGatewayModelApi: () => api,
+ resolvePiGatewayModelSpec: () => ({
+ api,
+ ...(api === 'openai-completions'
+ ? {
+ compat: {
+ maxTokensField: 'max_tokens',
+ thinkingFormat: 'openai',
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: 'kimi',
+ },
+ }
+ : {}),
+ }),
};
const handle = await new PiAgent(deps).startSession({
- sessionId: 'gateway-responses-model',
+ sessionId: `gateway-${api}`,
workingDir: cwd,
- model: 'responses-model',
+ model: modelId,
providerId: 'xd',
});
@@ -2096,15 +2116,33 @@ describe('Pi provider-aware model routing', () => {
) as {
providers: Record<string, {
api: string;
- models: Array<{ id: string; api?: string; baseUrl?: string }>;
+ models: Array<{
+ id: string;
+ api?: string;
+ baseUrl?: string;
+ headers?: Record<string, string>;
+ compat?: Record<string, unknown>;
+ }>;
}>;
};
expect(models.providers.cindy?.api).toBe('anthropic-messages');
- expect(models.providers.cindy?.models.find((model) => model.id === 'responses-model'))
- .toMatchObject({
- api: 'openai-responses',
- baseUrl: 'http://127.0.0.1:9988/v1',
+ const model = models.providers.cindy?.models.find((candidate) => candidate.id === modelId);
+ expect(model).toMatchObject({ api });
+ expect(model?.baseUrl).toBe(baseUrl);
+ if (api === 'openai-completions') {
+ expect(model?.compat).toMatchObject({
+ maxTokensField: 'max_tokens',
+ thinkingFormat: 'openai',
+ requiresReasoningContentOnAssistantMessages: true,
+ deferredToolsMode: 'kimi',
});
+ }
+ if (api === 'google-generative-ai') {
+ expect(model?.headers).toEqual({
+ authorization: 'Bearer $CINDY_PI_API_KEY',
+ 'x-goog-api-key': '$CINDY_PI_API_KEY',
+ });
+ }
await handle.close();
});
@@ -2170,7 +2208,7 @@ describe('Pi provider-aware model routing', () => {
await handle.close();
});
- it('still fails closed when an XD Pi model has no valid v3 wire protocol', async () => {
+ it('omits an unsupported Gateway route without aborting a same-id BYOM session', async () => {
const deps: AgentDeps = {
auth: {
getState: async () => ({ authenticated: true, identity: 'test', authSource: 'api-key' as const }),
@@ -2184,8 +2222,8 @@ describe('Pi provider-aware model routing', () => {
capabilityAdditions: {
availableModels: [
{
- id: 'invalid-xd-model',
- displayName: 'Invalid XD Model',
+ id: 'shared-future-model',
+ displayName: 'Shared Future Model',
contextWindow: 200_000,
efforts: [],
defaultEffort: null,
@@ -2194,15 +2232,34 @@ describe('Pi provider-aware model routing', () => {
},
resolvePiAgentHome: () => agentHome,
resolvePiGatewayModelApi: () => null,
+ resolvePiNativeProviders: async () => ({
+ providers: [
+ {
+ id: 'my-local',
+ name: 'My Local',
+ baseUrl: 'http://127.0.0.1:11434/v1',
+ api: 'openai-completions',
+ models: [{ id: 'shared-future-model' }],
+ },
+ ],
+ env: {},
+ }),
};
- await expect(new PiAgent(deps).startSession({
- sessionId: 'invalid-xd-v3-wire',
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'unsupported-xd-same-id-byom',
workingDir: cwd,
- model: 'invalid-xd-model',
- providerId: 'xd',
- })).rejects.toThrow(/Model Access v3 did not provide a Pi wire protocol/);
- expect(captured.args).toEqual([]);
+ model: 'shared-future-model',
+ providerId: 'my-local',
+ });
+ const models = JSON.parse(
+ readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),
+ ) as { providers: Record<string, { models: Array<{ id: string }> }> };
+ expect(models.providers.cindy?.models.find((model) => model.id === 'shared-future-model'))
+ .toBeUndefined();
+ expect(models.providers['my-local']?.models.find((model) => model.id === 'shared-future-model'))
+ .toMatchObject({ id: 'shared-future-model' });
+ await handle.close();
});
it('reconciles a stale persisted effort to the selected BYOM model default before startup', async () => {
@@ -2471,6 +2528,63 @@ describe('Pi provider-aware model routing', () => {
resolvePiNativeProviders,
});
+ it('omits remote Google Gateway routes that cannot sanitize x-goog-api-key', async () => {
+ const remoteStub: import('../transport.js').PiTransport = {
+ writeLine: async () => {},
+ onLine: () => () => {},
+ onStderr: () => () => {},
+ onClose: () => () => {},
+ close: async () => {},
+ pid: 4321,
+ isClosed: () => false,
+ remoteBinaryPath: '/remote/pi',
+ killRemoteSession: async () => {},
+ };
+ const written = new Map<string, string>();
+ const modelId = 'google/gemini-3.6-flash';
+ const base = byomDeps(async () => ({ providers: [], env: {} }), [
+ {
+ id: modelId,
+ displayName: 'Gemini 3.6 Flash',
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ]);
+ const agent = new PiAgent({
+ ...base,
+ runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
+ resolvePiGatewayModelApi: () => 'google-generative-ai',
+ resolvePiGatewayModelSpec: () => ({ api: 'google-generative-ai' }),
+ resolveRemotePiBinaryPath: async () => '/remote/pi',
+ getRemotePiTransport: async () => remoteStub,
+ getRemotePiFileOps: () => ({
+ mkdirp: async () => {},
+ writeFile: async (filePath, content) => {
+ written.set(filePath, content);
+ },
+ stat: async () => ({ isFile: true }),
+ rm: async () => {},
+ listDir: async () => [],
+ }),
+ });
+
+ await expect(agent.startSession({
+ sessionId: 'remote-google-header-sanitizer',
+ workingDir: cwd,
+ model: modelId,
+ providerId: 'xd',
+ remoteHostId: 'remote-host',
+ })).rejects.toThrow(/\[PI_GATEWAY_PROTOCOL_UNAVAILABLE\]/);
+ const modelsJson = [...written.entries()].find(([filePath]) => filePath.endsWith('models.json'))?.[1];
+ expect(modelsJson).toBeTruthy();
+ expect(modelsJson).not.toContain('x-goog-api-key');
+ const models = JSON.parse(modelsJson!) as {
+ providers: Record<string, { models: Array<{ id: string }> }>;
+ };
+ expect(models.providers.cindy?.models).toEqual([]);
+ });
+
function installPlanModeExtension(): void {
const extension = path.join(path.dirname(path.join(agentHome, 'pi')), 'examples', 'extensions', 'plan-mode', 'index.ts');
mkdirSync(path.dirname(extension), { recursive: true });
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 226146cf91..1a953dc91e 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -68,6 +68,7 @@ import {
type MainOwnedSendContext,
type PiExtraSpawnConfig,
type PiExtensionUiStrings,
+ type PiNativeApi,
type PiNativeModelSpec,
type PiNativeProviderSpec,
type PiSubagentRunnerLaunchRequest,
@@ -230,6 +231,11 @@ const PI_PROVIDER_ID = 'cindy';
// 路由,必须在本会话解析出的 nativeProviders 里;缺席时不得静默回落网关(见 startSession /
// setModel 的 fail-closed)。xAI 已改走 Pi 原生 provider,同样必须解析成功。
const NON_BYOM_PROVIDER_IDS = new Set([PI_PROVIDER_ID, 'xd', 'openai', 'anthropic']);
+
+function isExplicitPiGatewayProviderId(providerId: string | null | undefined): boolean {
+ return providerId === null || providerId === 'xd' || providerId === PI_PROVIDER_ID;
+}
+
const PI_API_KEY_ENV = 'CINDY_PI_API_KEY';
const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';
const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';
@@ -336,12 +342,33 @@ const PI_PROMPT_ACCEPTANCE_PROGRESS_EVENTS = new Set([
/** 分支摘要同样可能触发一次完整 LLM 调用。 */
const PI_BRANCH_NAVIGATION_TIMEOUT_MS = 600_000;
-/** PI 的 OpenAI Responses client 以 baseUrl 为 `/v1` 根;Anthropic client 则自行追加 `/v1/messages`。 */
-function piResponsesBaseUrl(endpoint: string): string {
+/** PI 的 OpenAI client 以 baseUrl 为 `/v1` 根;Anthropic client 则自行追加 `/v1/messages`。 */
+function piOpenAiBaseUrl(endpoint: string): string {
const trimmed = endpoint.replace(/\/+$/, '');
return trimmed.endsWith('/v1') ? trimmed : `${trimmed}/v1`;
}
+type PiGatewayApi = Exclude<PiNativeApi, 'openai-codex-responses'>;
+
+function isPiGatewayApi(value: PiNativeApi | null | undefined): value is PiGatewayApi {
+ return (
+ value === 'anthropic-messages' ||
+ value === 'openai-responses' ||
+ value === 'openai-completions' ||
+ value === 'google-generative-ai'
+ );
+}
+
+function piGatewayModelBaseUrl(endpoint: string, api: PiGatewayApi): string | undefined {
+ if (api === 'anthropic-messages') return undefined;
+ if (api !== 'google-generative-ai') return piOpenAiBaseUrl(endpoint);
+ const trimmed = endpoint.replace(/\/+$/, '');
+ if (trimmed.endsWith('/v1beta')) return trimmed;
+ return trimmed.endsWith('/v1')
+ ? `${trimmed.slice(0, -'/v1'.length)}/v1beta`
+ : `${trimmed}/v1beta`;
+}
+
class PiImageInputUnsupportedError extends Error {
readonly code = PI_IMAGE_INPUT_UNSUPPORTED_CODE;
@@ -1420,7 +1447,7 @@ export class PiAgent extends BaseAgent {
} = {},
): Promise<{
gatewayImageInputByModel: Map<string, boolean>;
- gatewayApiByModel: Map<string, 'anthropic-messages' | 'openai-responses'>;
+ gatewayApiByModel: Map<string, PiGatewayApi>;
/** models.json + settings.json 内容 sha256 —— 远端 daemon 启动身份的一部分。 */
modelsJsonHash: string;
}> {
@@ -1448,38 +1475,71 @@ export class PiAgent extends BaseAgent {
? [...publicModels, retainedRuntimeModel]
: publicModels;
const gatewayImageInputByModel = new Map<string, boolean>();
- const gatewayApiByModel = new Map<string, 'anthropic-messages' | 'openai-responses'>();
+ const gatewayApiByModel = new Map<string, PiGatewayApi>();
const models = runtimeModels.flatMap((publicModel: ModelDescriptor) => {
// availableModels 为跨 provider 拍平的公开能力;BYOM 同 id 冲突时 effort
// 会按设计收敛成交集。cindy gateway 块则代表内置路由,必须回查其
// provider-aware 描述符,不能被同名 non-reasoning BYOM 清空 reasoning。
// host 未注入 resolver 或只有 BYOM 条目时保留旧 flat fallback。
const m = this.deps.resolvePiGatewayModelDescriptor?.(gatewayProviderId, publicModel.id) ?? publicModel;
- const resolvedApi = this.deps.resolvePiGatewayModelApi?.(gatewayProviderId, m.id);
+ const resolverContext = { remote: opts.remote === true };
+ const resolvedSpec = this.deps.resolvePiGatewayModelSpec?.(gatewayProviderId, m.id, resolverContext);
+ const resolvedApi = resolvedSpec?.api ?? this.deps.resolvePiGatewayModelApi?.(
+ gatewayProviderId,
+ m.id,
+ resolverContext,
+ );
if (
+ resolvedSpec === null ||
resolvedApi === null ||
- (resolvedApi !== undefined && resolvedApi !== 'anthropic-messages' && resolvedApi !== 'openai-responses')
+ (resolvedApi !== undefined && !isPiGatewayApi(resolvedApi))
) {
- throw new Error(`Model Access v3 did not provide a Pi wire protocol for model: ${m.id}`);
+ // Fail this Gateway member closed without aborting unrelated subscription/BYOM sessions
+ // that happen to expose the same flattened model id.
+ return [];
}
- // undefined means no protocol was declared for this concrete gateway route. Native
+ // undefined means Model Access did not declare this concrete Gateway membership. Native
// subscription/BYOM models remain in their own provider blocks; normal sessions must not
- // copy them into `cindy` under a guessed Claude protocol. Offline fork only needs Pi to
- // parse a historical JSONL file and never sends a model request, so it gets a local-only
- // structural placeholder.
+ // copy them into `cindy`. Offline fork only parses historical JSONL and gets a structural
+ // placeholder without creating a live request route.
if (resolvedApi === undefined && !opts.offlineValidationOnly) return [];
const api = resolvedApi ?? 'anthropic-messages';
+ if (opts.remote && api === 'google-generative-ai') {
+ // Pi's Google SDK synthesizes x-goog-api-key from the provider key. Local sessions pass
+ // through the Cindy proxy, which strips that header; remote sessions currently bypass the
+ // proxy and would leak the Gateway credential as a second auth header. Fail this route
+ // closed until remote Pi can use an equivalent header-sanitizing forwarder.
+ this.deps.logger.warn('pi: remote Google Gateway route disabled without header sanitizer', {
+ modelId: m.id,
+ });
+ return [];
+ }
+ const modelBaseUrl = endpoint ? piGatewayModelBaseUrl(endpoint, api) : undefined;
gatewayApiByModel.set(m.id, api);
const supportsImageInput = m.supportsImageInput === true;
gatewayImageInputByModel.set(m.id, supportsImageInput);
return [{
id: m.id,
name: m.displayName,
- // Pi 0.83 支持同一 provider 下逐模型覆盖 API/baseUrl。provider 身份仍是
- // `cindy`;Model Access v3 让 PI 固定命中 Gateway 的 `/v1/responses` 前门。
- // 该前门可由 Gateway 翻译到不同上游,不代表底层模型原生实现 Responses。
+ // Pi 0.83 支持同一 provider 下逐模型覆盖 API/baseUrl。Host 按 Cindy Server >
+ // 本地 Pi 目录 > Cindy AI Gateway 顺序解析 API,并仅注入协议一致的 compat。
api,
- ...(api === 'openai-responses' && endpoint ? { baseUrl: piResponsesBaseUrl(endpoint) } : {}),
+ ...(modelBaseUrl ? { baseUrl: modelBaseUrl } : {}),
+ ...(api === 'google-generative-ai'
+ ? {
+ headers: {
+ authorization: `Bearer $${PI_API_KEY_ENV}`,
+ 'x-goog-api-key': `$${PI_API_KEY_ENV}`,
+ },
+ }
+ : {}),
+ ...(resolvedSpec?.thinkingLevelMap
+ ? { thinkingLevelMap: { ...resolvedSpec.thinkingLevelMap } }
+ : {}),
+ ...(resolvedSpec?.compat ? { compat: structuredClone(resolvedSpec.compat) } : {}),
+ ...(resolvedSpec?.samplingParams
+ ? { samplingParams: structuredClone(resolvedSpec.samplingParams) }
+ : {}),
reasoning: m.efforts.length > 0,
input: supportsImageInput ? ['text', 'image'] : ['text'],
// Model Access v3 requires this value; never replace the server limit with a client guess.
@@ -1499,7 +1559,7 @@ export class PiAgent extends BaseAgent {
name: 'Cindy AI',
baseUrl: endpoint ?? 'http://127.0.0.1:0',
// Structural provider default for Pi's models.json schema only. Every selectable Cindy
- // gateway model above carries its authoritative model-level api from Model Access v3.
+ // gateway model above carries its resolved model-level API.
api: 'anthropic-messages',
apiKey: `$${PI_API_KEY_ENV}`,
// 本地 loopback compat proxy 用 session headers 做订阅 OAuth 注入;远端打真上游
@@ -1943,8 +2003,14 @@ export class PiAgent extends BaseAgent {
// authority; adding a guessed gateway candidate can make a bare alias pick
// the current `cindy` provider and leak an invalid unnamespaced model id.
const routedGatewaySubagentModels = gatewaySubagentModels.filter((model) => {
- const api = this.deps.resolvePiGatewayModelApi?.(PI_PROVIDER_ID, model.id);
- return api === 'anthropic-messages' || api === 'openai-responses';
+ const resolverContext = { remote };
+ const spec = this.deps.resolvePiGatewayModelSpec?.(PI_PROVIDER_ID, model.id, resolverContext);
+ const api = spec?.api ?? this.deps.resolvePiGatewayModelApi?.(
+ PI_PROVIDER_ID,
+ model.id,
+ resolverContext,
+ );
+ return spec !== null && isPiGatewayApi(api);
});
const gatewaySubagentRouteKey = 'cindy-gateway';
const gatewaySubagentProxyToken =
@@ -2176,6 +2242,17 @@ export class PiAgent extends BaseAgent {
authProviderId,
{ remote, fileOps, contextWindow: startupContextWindow, piCompactionPct: sessionPiAutoCompactPct },
);
+ const explicitlyRequestedGateway = isExplicitPiGatewayProviderId(opts.providerId);
+ if (
+ explicitlyRequestedGateway &&
+ initialProvider === PI_PROVIDER_ID &&
+ !gatewayApiByModel.has(opts.model)
+ ) {
+ throw new Error(
+ `[PI_GATEWAY_PROTOCOL_UNAVAILABLE] Cindy Gateway has no safe Pi route for model '${opts.model}'` +
+ (remote ? ' in a remote session' : ''),
+ );
+ }
const bashPackageHome = joinRemotePosixPath(configHome, 'bash-package-home');
await mkdirp(bashPackageHome);
const sessionDir = joinRemotePosixPath(agentHome, 'sessions');
@@ -4854,26 +4931,35 @@ export class PiAgent extends BaseAgent {
const routeProviderId = nextRequestedProviderId !== undefined
? nextRequestedProviderId
: mutableProviderId;
- const resolvedApi = this.deps.resolvePiGatewayModelApi?.(routeProviderId, nextModel);
+ const resolverContext = { remote };
+ const resolvedSpec = this.deps.resolvePiGatewayModelSpec?.(
+ routeProviderId,
+ nextModel,
+ resolverContext,
+ );
+ const resolvedApi = resolvedSpec?.api ?? this.deps.resolvePiGatewayModelApi?.(
+ routeProviderId,
+ nextModel,
+ resolverContext,
+ );
if (
+ resolvedSpec === null ||
resolvedApi === null ||
- (resolvedApi !== undefined &&
- resolvedApi !== 'anthropic-messages' &&
- resolvedApi !== 'openai-responses')
+ (resolvedApi !== undefined && !isPiGatewayApi(resolvedApi))
) {
throw new Error(
- `Model Access v3 did not provide a Pi wire protocol for model: ${nextModel}`,
+ `No supported Gateway Pi API is available for model: ${nextModel}`,
);
}
if (resolvedApi === undefined) {
- throw new Error(`Pi wire protocol is not configured for model: ${nextModel}`);
+ throw new Error(`Pi API is not configured for model: ${nextModel}`);
}
const desiredApi = resolvedApi;
const configuredApi = gatewayApiByModel.get(nextModel);
if (configuredApi && configuredApi !== desiredApi) {
throw new Error(
`pi: provider switch for model '${nextModel}' requires API '${desiredApi}', but this session ` +
- `started with '${configuredApi}'; restart the Pi session to change provider wire protocol.`,
+ `started with '${configuredApi}'; restart the Pi session to change provider API.`,
);
}
};
diff --git a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
index 9ef5f6b642..d4127dc11f 100644
--- a/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
+++ b/packages/model-providers/src/__tests__/modelAccessValidator.test.ts
@@ -409,7 +409,7 @@ describe('model access catalog contract', () => {
);
});
- it('accepts v3 Pi with either explicit gateway wire protocol', () => {
+ it('treats Pi wireProtocol as a forward-compatible last-priority hint while keeping Claude and Codex fixed', () => {
const piModel = {
...VALID_V3_RESPONSE.models[0],
agents: ['claude-code', 'codex', 'pi'],
@@ -418,19 +418,32 @@ describe('model access catalog contract', () => {
pi: { wireProtocol: 'openai-responses' },
},
} as const;
- expect(parseListModelsResponse({ ...VALID_V3_RESPONSE, models: [piModel] }).ok).toBe(true);
+ for (const wireProtocol of [
+ 'anthropic-messages',
+ 'openai-responses',
+ 'openai-completions',
+ 'google-generative-ai',
+ ] as const) {
+ expect(
+ parseListModelsResponse({
+ ...VALID_V3_RESPONSE,
+ models: [{
+ ...piModel,
+ perAgent: { ...piModel.perAgent, pi: { wireProtocol } },
+ }],
+ }).ok,
+ ).toBe(true);
+ }
expect(
parseListModelsResponse({
...VALID_V3_RESPONSE,
- models: [
- {
- ...piModel,
- perAgent: {
- ...piModel.perAgent,
- pi: { wireProtocol: 'anthropic-messages' },
- },
+ models: [{
+ ...piModel,
+ perAgent: {
+ 'claude-code': { wireProtocol: 'anthropic-messages' },
+ codex: { wireProtocol: 'openai-responses' },
},
- ],
+ }],
}).ok,
).toBe(true);
expectReject(
@@ -440,18 +453,40 @@ describe('model access catalog contract', () => {
expectReject(
{
...VALID_V3_RESPONSE,
- models: [
- {
- ...piModel,
- perAgent: {
- ...piModel.perAgent,
- codex: { wireProtocol: 'anthropic-messages' },
- },
+ models: [{
+ ...piModel,
+ perAgent: {
+ ...piModel.perAgent,
+ codex: { wireProtocol: 'anthropic-messages' },
},
- ],
+ }],
},
'response.models[0].perAgent.codex.wireProtocol must be openai-responses',
);
+ expect(
+ parseListModelsResponse({
+ ...VALID_V3_RESPONSE,
+ models: [{
+ ...piModel,
+ perAgent: {
+ ...piModel.perAgent,
+ pi: { wireProtocol: 'future-protocol' },
+ },
+ }],
+ }).ok,
+ ).toBe(true);
+ for (const wireProtocol of ['', 42, { api: 'openai-responses' }]) {
+ expectReject(
+ {
+ ...VALID_V3_RESPONSE,
+ models: [{
+ ...piModel,
+ perAgent: { ...piModel.perAgent, pi: { wireProtocol } },
+ }],
+ },
+ 'response.models[0].perAgent.pi.wireProtocol must be a non-empty string',
+ );
+ }
});
it('requires complete runtime metadata in v3 without changing v2', () => {
diff --git a/packages/model-providers/src/__tests__/source-registry.test.ts b/packages/model-providers/src/__tests__/source-registry.test.ts
index 4e17d8571f..bb59ca5b6f 100644
--- a/packages/model-providers/src/__tests__/source-registry.test.ts
+++ b/packages/model-providers/src/__tests__/source-registry.test.ts
@@ -570,18 +570,21 @@ describe('loadCatalog', () => {
capabilityEvidence: 'current',
unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
catalog: { version: 'test' },
+ authorityCatalog: { version: 'test' },
});
expect(remote).toMatchObject({
source: 'remote',
capabilityEvidence: 'current',
unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
catalog: { version: 'test' },
+ authorityCatalog: { version: 'test' },
});
expect(bundled).toEqual({
source: 'bundled',
capabilityEvidence: 'fallback',
unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
catalog: BUNDLED_CATALOG,
+ authorityCatalog: null,
});
});
@@ -650,6 +653,9 @@ describe('loadCatalog', () => {
for (const loaded of [local, remote, cache]) {
expect(loaded.catalog.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi)
.toEqual(bundledPreset.runtimes.pi);
+ expect(
+ loaded.authorityCatalog?.presets?.find((preset) => preset.id === 'deepseek')?.runtimes.pi,
+ ).toBeUndefined();
}
const currentLoaded = await loadCatalogWithSource(
@@ -836,6 +842,7 @@ describe('loadCatalog', () => {
capabilityEvidence: 'fallback',
unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
catalog: BUNDLED_CATALOG,
+ authorityCatalog: null,
});
});
@@ -902,6 +909,7 @@ describe('loadCatalog', () => {
source: 'remote',
capabilityEvidence: 'fallback',
catalog: { version: 'test' },
+ authorityCatalog: null,
});
});
it('falls back from invalid public API payload to legacy OSS before bundled', async () => {
@@ -957,6 +965,7 @@ describe('loadCatalog', () => {
expect(result.capabilityEvidence).toBe('fallback');
expect(result.catalog.version).toBe('test');
expect(result.catalog).not.toHaveProperty('cindyModelMeta');
+ expect(result.authorityCatalog).toBeNull();
});
it('shares one remote budget across the public API and legacy OSS fallback', async () => {
@@ -1072,6 +1081,7 @@ describe('loadCatalog', () => {
capabilityEvidence: 'fallback',
unverifiedXdMediaKinds: ['image', 'video', 'embedding'],
catalog: BUNDLED_CATALOG,
+ authorityCatalog: null,
});
expect((Object.prototype as { polluted?: unknown }).polluted).toBeUndefined();
});
diff --git a/packages/model-providers/src/modelAccessBean.ts b/packages/model-providers/src/modelAccessBean.ts
index 1e8f9f806c..9a644b359a 100644
--- a/packages/model-providers/src/modelAccessBean.ts
+++ b/packages/model-providers/src/modelAccessBean.ts
@@ -22,7 +22,12 @@ export const MODEL_ACCESS_AGENTS = ['claude-code', 'codex', 'pi'] as const;
export type ModelAgent = (typeof MODEL_ACCESS_AGENTS)[number];
export type ModelAccessV2Agent = (typeof MODEL_ACCESS_V2_AGENTS)[number];
-export const MODEL_ACCESS_WIRE_PROTOCOLS = ['anthropic-messages', 'openai-responses'] as const;
+export const MODEL_ACCESS_WIRE_PROTOCOLS = [
+ 'anthropic-messages',
+ 'openai-responses',
+ 'openai-completions',
+ 'google-generative-ai',
+] as const;
export type ModelAccessWireProtocol = (typeof MODEL_ACCESS_WIRE_PROTOCOLS)[number];
export const MODEL_ACCESS_MEDIA_CAPABILITIES = [
diff --git a/packages/model-providers/src/modelAccessValidator.ts b/packages/model-providers/src/modelAccessValidator.ts
index 326d5aea85..c0bf5cdd58 100644
--- a/packages/model-providers/src/modelAccessValidator.ts
+++ b/packages/model-providers/src/modelAccessValidator.ts
@@ -577,7 +577,19 @@ function modelEntryError(
isModelEffort(value.defaultEffort) ? value.defaultEffort : null,
);
if (error) return error;
- if (isPlainObject(override) && override.wireProtocol !== undefined) {
+ if (
+ agent === 'pi' &&
+ isPlainObject(override) &&
+ override.wireProtocol !== undefined &&
+ (typeof override.wireProtocol !== 'string' || override.wireProtocol.trim().length === 0)
+ ) {
+ return `${path}.perAgent.pi.wireProtocol must be a non-empty string when present`;
+ }
+ if (
+ agent !== 'pi' &&
+ isPlainObject(override) &&
+ override.wireProtocol !== undefined
+ ) {
if (!isModelAccessWireProtocol(override.wireProtocol)) {
return `${path}.perAgent.${agent}.wireProtocol must be a supported wire protocol`;
}
@@ -593,6 +605,10 @@ function modelEntryError(
schemaVersion === MODEL_ACCESS_CATALOG_SCHEMA_VERSION
) {
for (const agent of supportedAgents) {
+ // Pi accepts a missing/future string here because Cindy Server and the local Pi catalog are
+ // higher authorities; an unsupported last-priority Gateway hint only closes that model route.
+ // Claude and Codex have no such fallback and remain strict contract requirements.
+ if (agent === 'pi') continue;
const override = isPlainObject(value.perAgent) ? value.perAgent[agent] : undefined;
if (!isPlainObject(override) || !isModelAccessWireProtocol(override.wireProtocol)) {
return `${path}.perAgent.${agent}.wireProtocol is required when ${path}.agents includes ${agent}`;
diff --git a/packages/model-providers/src/source.ts b/packages/model-providers/src/source.ts
index a8985315dd..aad6ef8092 100644
--- a/packages/model-providers/src/source.ts
+++ b/packages/model-providers/src/source.ts
@@ -76,6 +76,12 @@ const ALL_XD_MEDIA_KINDS: readonly CatalogXdMediaKind[] = [
export interface CatalogLoadResult {
catalog: Catalog;
+ /**
+ * Exact validated source snapshot before bundled compatibility backfill. `null` means no Cindy
+ * Server/local/LKG snapshot was accepted. Consumers must use this field, never `catalog`, when
+ * they need to distinguish an explicit source declaration from a bundled supplement.
+ */
+ authorityCatalog: Catalog | null;
source: CatalogLoadSource;
/**
* `current` means this exact snapshot came from the configured current catalog source
@@ -521,6 +527,7 @@ export async function loadCatalogWithSource(
log(io, 'info', 'loaded catalog from local path', { path: cfg.localPath });
return {
catalog: mergeWithBundled(parsed),
+ authorityCatalog: parsed,
source: 'local',
capabilityEvidence: 'current',
unverifiedXdMediaKinds: unverifiedXdMediaKindsForPrimary(parsed),
@@ -617,6 +624,8 @@ export async function loadCatalogWithSource(
log(io, 'info', 'loaded catalog from remote', { url: logUrl });
return {
catalog: mergeWithBundled(parsed),
+ // The migration OSS fallback is compatibility data, not the daily Cindy Server source.
+ authorityCatalog: allowLegacyModelMeta ? null : parsed,
source: 'remote',
capabilityEvidence,
unverifiedXdMediaKinds:
@@ -643,6 +652,8 @@ export async function loadCatalogWithSource(
log(io, 'info', 'loaded last-known-good catalog snapshot', { url: logUrl });
return {
catalog: mergeWithBundled(parsed),
+ // A cached legacy OSS snapshot stays below the local Pi protocol authorities.
+ authorityCatalog: allowLegacyModelMeta ? null : parsed,
source: 'cache',
capabilityEvidence: 'fallback',
unverifiedXdMediaKinds: ALL_XD_MEDIA_KINDS,
@@ -662,6 +673,7 @@ export async function loadCatalogWithSource(
log(io, 'info', 'using bundled catalog');
return {
catalog: BUNDLED_CATALOG,
+ authorityCatalog: null,
source: 'bundled',
capabilityEvidence: 'fallback',
unverifiedXdMediaKinds: ALL_XD_MEDIA_KINDS,