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): route models through native protocols

Chris42ffcffcef04
diff --git a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
index a1f5e9429c..c265619bd7 100644
--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts
@@ -99,12 +99,39 @@ describe('active-catalog discovered augment', () => {
expect(openaiIds('pi')).toContain('chatgpt/gpt-5.7');
});
+ it('applies a daily PI protocol annotation only after OpenAI discovery proves the model exists', () => {
+ const catalog = bundledWithoutRegistry();
+ const openai = catalog.providers.find((provider) => provider.id === 'openai')!;
+ openai.models.pi = [
+ {
+ ...fake('chatgpt/gpt-5.7'),
+ piApi: 'openai-responses',
+ },
+ ];
+ setActiveCatalog(catalog);
+
+ expect(openaiIds('pi')).not.toContain('chatgpt/gpt-5.7');
+
+ setDiscoveredCodexModels([fake('gpt-5.7')]);
+ const projected = getActiveCatalog().providers.find((provider) => provider.id === 'openai')
+ ?.models.pi?.find((candidate) => candidate.id === 'chatgpt/gpt-5.7');
+ expect(projected).toMatchObject({ piApi: 'openai-responses' });
+ });
+
it('SuperGrok 静态清单投影到独立 Pi 通道', () => {
setActiveCatalog(BUNDLED_CATALOG);
const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');
expect(xai?.agents).toContain('pi');
expect(xai?.routing.pi?.modelPrefixes).toEqual(['xai/']);
- expect(xai?.models.pi).toEqual(xai?.models['claude-code']);
+ expect(xai?.models.pi?.map((model) => {
+ const copy = { ...model };
+ delete copy.piApi;
+ return copy;
+ })).toEqual(xai?.models['claude-code']);
+ expect(xai?.models.pi?.find((model) => model.id === 'xai/grok-4.20')?.piApi)
+ .toBe('openai-responses');
+ expect(xai?.models.pi?.find((model) => model.id === 'xai/grok-code-fast')?.piApi)
+ .toBe('openai-completions');
});
it('bridge 投影剔除 max/ultra:codex 侧保留、claude-code 侧封顶 xhigh(issue #352)', () => {
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 3ee7030ab7..3aa674250b 100644
--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts
@@ -61,8 +61,8 @@ import {
const SESSION_HEADER = { 'x-claude-code-session-id': 'sdk-grok' };
-function ctxWith(headers: Record<string, string>) {
- return { reqId: 1, method: 'POST', url: '/v1/messages', headers } as never;
+function ctxWith(headers: Record<string, string>, url = '/v1/messages') {
+ return { reqId: 1, method: 'POST', url, headers } as never;
}
describe('cc routingTransform — xAI 会话的辅助请求回落默认路由 (issue #886)', () => {
@@ -188,10 +188,99 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
'x-api-key',
'x-cindy-pi-session-id',
'x-cindy-pi-session-token',
+ 'x-cindy-pi-provider-id',
],
});
});
+ it.each([
+ ['openai', '/codex/responses'],
+ ['xai', '/v1/responses'],
+ ['xai', '/v1/chat/completions'],
+ ] as const)('routes native %s PI requests to a local raw forwarder at %s', (providerId, url) => {
+ setSessionProvider('sess-pi', providerId);
+ registerPiProxySession('sess-pi', 'session-secret');
+ const decision = createModelRoutingTransform()(
+ undefined,
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'session-secret',
+ 'x-cindy-pi-provider-id': providerId,
+ }, url),
+ );
+
+ expect(decision).toEqual({ localHandler: expect.any(Function) });
+ });
+
+ it('rejects a native provider header that does not match the Cindy session provider', async () => {
+ setSessionProvider('sess-pi', 'anthropic');
+ registerPiProxySession('sess-pi', 'session-secret');
+ const decision = await createModelRoutingTransform()(
+ undefined,
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'session-secret',
+ 'x-cindy-pi-provider-id': 'openai',
+ }, '/codex/responses'),
+ );
+ const response = {
+ status: 0,
+ body: '',
+ writeHead(status: number) { this.status = status; },
+ end(body: string) { this.body = body; },
+ };
+
+ await decision?.localHandler?.({ res: response } as never);
+
+ expect(response.status).toBe(403);
+ expect(response.body).toContain('pi_provider_mismatch');
+ });
+
+ it('rejects a missing native provider header for an OpenAI PI session', async () => {
+ setSessionProvider('sess-pi', 'openai');
+ registerPiProxySession('sess-pi', 'session-secret');
+ const decision = await createModelRoutingTransform()(
+ undefined,
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'session-secret',
+ }, '/codex/responses'),
+ );
+ const response = {
+ status: 0,
+ body: '',
+ writeHead(status: number) { this.status = status; },
+ end(body: string) { this.body = body; },
+ };
+
+ await decision?.localHandler?.({ res: response } as never);
+
+ expect(response.status).toBe(403);
+ expect(response.body).toContain('pi_provider_mismatch');
+ });
+
+ it('does not send an authenticated Anthropic PI request through the legacy prefix bridge', async () => {
+ setClaudeProxyGatewayKeyReader(() => 'sk-gw');
+ setSessionProvider('sess-pi', 'anthropic');
+ registerPiProxySession('sess-pi', 'session-secret');
+ setProviderOAuthTokenReader((providerId, agent) =>
+ providerId === 'anthropic' && agent === 'pi' ? Promise.resolve('pi-claude-token') : null,
+ );
+ const decision = createModelRoutingTransform()(
+ { model: 'chatgpt/gpt-5.6-sol' },
+ ctxWith({
+ 'x-cindy-pi-session-id': 'sess-pi',
+ 'x-cindy-pi-session-token': 'session-secret',
+ 'x-cindy-pi-provider-id': 'anthropic',
+ 'x-api-key': 'cindy-pi-provider-auth-placeholder',
+ }),
+ );
+
+ await expect(Promise.resolve(decision)).resolves.toMatchObject({
+ upstreamOverride: 'https://api.anthropic.com',
+ });
+ });
+
it('rejects a forged session id before provider credentials can be selected', async () => {
setSessionProvider('sess-pi', 'anthropic');
registerPiProxySession('sess-pi', 'real-secret');
@@ -221,7 +310,11 @@ describe('pi routingTransform — xdt session header selects the Pi provider rou
ctxWith({ 'x-cindy-pi-session-token': 'orphaned-secret' }),
));
expect(decision).toMatchObject({
- headerDelete: ['x-cindy-pi-session-id', 'x-cindy-pi-session-token'],
+ headerDelete: [
+ 'x-cindy-pi-session-id',
+ 'x-cindy-pi-session-token',
+ 'x-cindy-pi-provider-id',
+ ],
});
expect(decision?.headerOverride).not.toHaveProperty('x-cindy-pi-session-token');
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
index 800e34f52a..e4eafc8e20 100644
--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
@@ -178,6 +178,46 @@ describe('validateCustomProviderConfig (per-runtime)', () => {
}
});
+ it('accepts supported per-model piApi values only on a Pi runtime', () => {
+ for (const piApi of [
+ 'anthropic-messages',
+ 'openai-responses',
+ 'openai-completions',
+ 'google-generative-ai',
+ ]) {
+ expect(validateCustomProviderConfig({
+ id: 'pi-api',
+ name: 'Pi API',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://example.com/v1',
+ models: [{ id: 'm', name: 'M', piApi }],
+ },
+ },
+ }).ok).toBe(true);
+ }
+ expect(validateCustomProviderConfig({
+ id: 'bad-pi-api',
+ name: 'Bad Pi API',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://example.com/v1',
+ models: [{ id: 'm', name: 'M', piApi: 'claude-v1' }],
+ },
+ },
+ }).ok).toBe(false);
+ expect(validateCustomProviderConfig({
+ id: 'wrong-runtime-pi-api',
+ name: 'Wrong runtime Pi API',
+ runtimes: {
+ codex: {
+ baseUrl: 'https://example.com/v1',
+ models: [{ id: 'm', name: 'M', piApi: 'openai-responses' }],
+ },
+ },
+ }).ok).toBe(false);
+ });
+
it('accepts only explicit, non-empty, valid Pi reasoning effort capabilities', () => {
const config = (model: Record<string, unknown>, agent: 'pi' | 'codex' = 'pi') => ({
id: 'reasoning-provider',
@@ -394,6 +434,32 @@ describe('custom-provider-store CRUD (per-runtime)', () => {
]);
});
+ it('round-trips a per-model Pi protocol correction', async () => {
+ mountDb();
+ await createCustomProvider({
+ id: 'deepseek-pi',
+ name: 'DeepSeek Pi',
+ auth: { method: 'none' },
+ runtimes: {
+ pi: {
+ baseUrl: 'https://api.deepseek.com',
+ wireProtocol: 'openai-responses',
+ models: [{
+ id: 'deepseek-v4-pro',
+ name: 'DeepSeek V4 Pro',
+ piApi: 'openai-responses',
+ }],
+ },
+ },
+ });
+
+ expect((await getCustomProvider('deepseek-pi'))?.runtimes.pi?.models).toEqual([{
+ id: 'deepseek-v4-pro',
+ name: 'DeepSeek V4 Pro',
+ piApi: 'openai-responses',
+ }]);
+ });
+
it('round-trips an explicit Chat Completions protocol', async () => {
mountDb();
await createCustomProvider({
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 265fb0028c..f64738fe7e 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -3,6 +3,10 @@
* 覆盖:wire protocol → pi api 映射、apiKey/none/oauth 三态、缺 key 跳过、env key 名。
*/
import { describe, expect, it, vi } from 'vitest';
+import { existsSync } from 'node:fs';
+import path from 'node:path';
+
+import { BUNDLED_CATALOG, type Catalog } from '@cindy/model-providers';
import { derivePiRuntimeFromClaudeRuntime } from '../../../shared/piRuntimeInitialization.js';
@@ -14,7 +18,16 @@ vi.mock('electron', () => ({
},
}));
-import { buildPiNativeProvidersFromConfigs, piNativeKeyEnvVar } from '../pi-host.js';
+import {
+ buildPiNativeProvidersFromConfigs,
+ buildPiSubscriptionNativeProviders,
+ parsePiListModels,
+ piNativeKeyEnvVar,
+ readPiBundledModels,
+ resolvePiBundledApiByModelId,
+ resolvePiBundledModelById,
+ type PiBundledModelInfo,
+} from '../pi-host.js';
type Cfg = Parameters<typeof buildPiNativeProvidersFromConfigs>[0][number];
@@ -24,7 +37,194 @@ const piRuntime = (over: Partial<NonNullable<Cfg['runtimes']['pi']>> = {}) => ({
...over,
});
+const piBundledModel = (
+ id: string,
+ api: PiBundledModelInfo['api'],
+ over: Partial<PiBundledModelInfo> = {},
+): PiBundledModelInfo => ({
+ id,
+ api,
+ name: id,
+ reasoning: true,
+ input: ['text'],
+ contextWindow: 272_000,
+ maxTokens: 128_000,
+ ...over,
+});
+
describe('buildPiNativeProvidersFromConfigs', () => {
+ it('reads exact provider/model IDs from PI list output', () => {
+ const parsed = parsePiListModels([
+ 'provider model context max-out thinking images',
+ 'openai-codex gpt-5.6-sol 272K 128K yes yes',
+ 'openai-codex gpt-5.6-terra 272K 128K yes yes',
+ '',
+ ].join('\n'));
+ expect([...parsed.get('openai-codex') ?? []]).toEqual(['gpt-5.6-sol', 'gpt-5.6-terra']);
+ });
+
+ const bundledPiPath = path.join(process.cwd(), 'apps/pi-bin/darwin-arm64/pi');
+ it.skipIf(process.platform !== 'darwin' || process.arch !== 'arm64' || !existsSync(bundledPiPath))(
+ 'reads full APIs from the exact bundled PI binary without network access',
+ async () => {
+ 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');
+ const anthropicModels = [...catalog?.get('anthropic')?.values() ?? []];
+ expect(anthropicModels.length).toBeGreaterThan(0);
+ expect(anthropicModels.every((model) => model.api === 'anthropic-messages')).toBe(true);
+ expect(resolvePiBundledApiByModelId(catalog ?? undefined, 'glm-5.2'))
+ .toBe('openai-completions');
+ expect(catalog?.get('zai')?.get('glm-5.2')).toMatchObject({
+ api: 'openai-completions',
+ baseUrl: 'https://api.z.ai/api/coding/paas/v4',
+ });
+ },
+ );
+
+ 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')!;
+ const openai = catalog.providers.find((provider) => provider.id === 'openai')!;
+ const xai = catalog.providers.find((provider) => provider.id === 'xai')!;
+ anthropic.models.pi = [{
+ id: 'claude-opus-5', name: 'Claude Opus 5', contextWindow: 1_000_000,
+ efforts: ['high'], defaultEffort: 'high', piApi: 'anthropic-messages',
+ }];
+ openai.models.pi = [
+ {
+ id: 'chatgpt/gpt-5.6-sol', name: 'GPT-5.6 Sol', contextWindow: 272_000,
+ efforts: ['low', 'high'], defaultEffort: 'high', piApi: 'openai-responses',
+ },
+ {
+ id: 'chatgpt/gpt-5.7', name: 'GPT-5.7', contextWindow: 272_000,
+ efforts: ['low', 'high'], defaultEffort: 'high', piApi: 'openai-responses',
+ },
+ ];
+ xai.models.pi = [
+ {
+ id: 'xai/grok-4.5', name: 'Grok 4.5', contextWindow: 1_000_000,
+ efforts: ['high'], defaultEffort: 'high', piApi: 'openai-responses',
+ },
+ {
+ id: 'xai/grok-4.20', name: 'Grok 4.20', contextWindow: 1_000_000,
+ efforts: ['high'], defaultEffort: 'high', piApi: 'openai-responses',
+ },
+ ];
+
+ const { providers, env } = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ new Map([
+ ['anthropic', new Map([
+ ['claude-opus-5', piBundledModel('claude-opus-5', 'anthropic-messages')],
+ ])],
+ ['openai-codex', new Map([
+ ['gpt-5.6-sol', piBundledModel('gpt-5.6-sol', 'openai-codex-responses')],
+ ])],
+ ['xai', new Map([
+ ['grok-4.5', piBundledModel('grok-4.5', 'openai-responses')],
+ ])],
+ ]),
+ );
+
+ expect(providers.map((provider) => provider.id)).toEqual([
+ 'anthropic',
+ 'openai-codex',
+ 'xai',
+ ]);
+ expect(providers[0]).toMatchObject({
+ sourceProviderId: 'anthropic',
+ baseUrl: 'http://127.0.0.1:4567/',
+ inheritModels: true,
+ models: [{ id: 'claude-opus-5', wireId: 'claude-opus-5' }],
+ });
+ expect(providers[1]).toMatchObject({
+ sourceProviderId: 'openai',
+ baseUrl: 'http://127.0.0.1:4567/',
+ inheritModels: true,
+ models: [
+ {
+ id: 'chatgpt/gpt-5.6-sol',
+ wireId: 'gpt-5.6-sol',
+ },
+ {
+ id: 'chatgpt/gpt-5.7',
+ wireId: 'gpt-5.7',
+ catalogAddition: true,
+ },
+ ],
+ });
+ expect(providers[1]?.models[0]?.api).toBeUndefined();
+ expect(providers[1]?.models[0]?.catalogAddition).toBeUndefined();
+ const withoutProbe = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ ).providers;
+ expect(withoutProbe.find((provider) => provider.id === 'openai-codex')
+ ?.models.every((model) => model.catalogAddition === undefined)).toBe(true);
+ expect(withoutProbe.find((provider) => provider.id === 'xai')
+ ?.models.every((model) => model.api === undefined)).toBe(true);
+ expect(providers[2]).toMatchObject({
+ sourceProviderId: 'xai',
+ baseUrl: 'http://127.0.0.1:4567/v1',
+ inheritModels: true,
+ models: [
+ { id: 'xai/grok-4.5', wireId: 'grok-4.5' },
+ { id: 'xai/grok-4.20', wireId: 'grok-4.20', api: 'openai-responses' },
+ ],
+ });
+ expect(providers[2]?.models[0]?.api).toBeUndefined();
+ const proxyJwt = env[providers[1]!.apiKeyEnvVar!];
+ expect(proxyJwt).toMatch(/^[^.]+\.[^.]+\.$/);
+ expect(proxyJwt).not.toContain('Bearer');
+ for (const provider of providers) {
+ expect(provider.headers).toMatchObject({
+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
+ 'x-cindy-pi-provider-id': provider.sourceProviderId,
+ });
+ }
+ });
+
+ it('preserves PI bundled metadata when a daily annotation corrects an existing protocol', () => {
+ 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-corrected',
+ name: 'Daily Name',
+ contextWindow: 1_000_000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ piApi: 'openai-responses',
+ }];
+ const bundled = piBundledModel('grok-corrected', 'openai-completions', {
+ name: 'PI Bundled Name',
+ contextWindow: 500_000,
+ maxTokens: 64_000,
+ cost: { input: 2, output: 6, cacheRead: 0.3, cacheWrite: 0 },
+ compat: { supportsStrictTools: true },
+ });
+
+ const provider = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ new Map([['xai', new Map([[bundled.id, bundled]])]]),
+ ).providers.find((candidate) => candidate.id === 'xai');
+
+ 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,
+ });
+ });
+
it('turns a Claude-derived wizard runtime and copied Pi key into a callable native provider', () => {
const derived = derivePiRuntimeFromClaudeRuntime({
baseUrl: 'https://api.example/anthropic',
@@ -75,6 +275,71 @@ describe('buildPiNativeProvidersFromConfigs', () => {
}
});
+ it('uses PI bundled protocol knowledge before the legacy unknown-BYOM default', () => {
+ const bundled = new Map([
+ ['zai', new Map([
+ ['glm-5.2', piBundledModel('glm-5.2', 'openai-completions', {
+ baseUrl: 'https://api.z.ai/api/coding/paas/v4',
+ })],
+ ])],
+ ['zai-coding-cn', new Map([
+ ['glm-5.2', piBundledModel('glm-5.2', 'openai-completions', {
+ baseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4',
+ })],
+ ])],
+ ]);
+ expect(resolvePiBundledApiByModelId(bundled, 'glm-5.2')).toBe('openai-completions');
+ expect(resolvePiBundledModelById(
+ bundled,
+ 'glm-5.2',
+ 'https://open.bigmodel.cn/api/anthropic',
+ )?.baseUrl).toBe('https://open.bigmodel.cn/api/coding/paas/v4');
+
+ const { providers } = buildPiNativeProvidersFromConfigs(
+ [{
+ id: 'zhipu-glm-cn',
+ name: 'Zhipu GLM',
+ auth: { method: 'none' },
+ runtimes: {
+ pi: piRuntime({
+ baseUrl: 'https://open.bigmodel.cn/api/anthropic',
+ models: [
+ { id: 'glm-5.2', name: 'GLM-5.2' },
+ { id: 'glm-5.3', name: 'GLM-5.3', piApi: 'anthropic-messages' },
+ ],
+ }),
+ },
+ }],
+ () => null,
+ undefined,
+ bundled,
+ );
+
+ expect(providers[0]).toMatchObject({
+ api: 'openai-completions',
+ models: [
+ {
+ id: 'glm-5.2',
+ baseUrl: 'https://open.bigmodel.cn/api/coding/paas/v4',
+ },
+ { id: 'glm-5.3', api: 'anthropic-messages' },
+ ],
+ });
+ expect(providers[0]?.models[0]?.api).toBeUndefined();
+ });
+
+ it('does not infer ambiguous duplicate model ids from PI bundled providers', () => {
+ const bundled = new Map([
+ ['provider-a', new Map([
+ ['same-id', piBundledModel('same-id', 'anthropic-messages')],
+ ])],
+ ['provider-b', new Map([
+ ['same-id', piBundledModel('same-id', 'openai-responses')],
+ ])],
+ ]);
+ expect(resolvePiBundledApiByModelId(bundled, 'same-id')).toBeUndefined();
+ });
+
it('keyless (none) → no env, no apiKeyEnvVar (models.json writes dummy)', () => {
const { providers, env } = buildPiNativeProvidersFromConfigs(
[{ id: 'ollama', name: 'Ollama', auth: { method: 'none' }, runtimes: { pi: piRuntime() } }],
@@ -205,6 +470,32 @@ describe('buildPiNativeProvidersFromConfigs', () => {
]);
});
+ it('maps a per-model piApi correction into the native model spec', () => {
+ const { providers } = buildPiNativeProvidersFromConfigs(
+ [{
+ id: 'deepseek',
+ name: 'DeepSeek',
+ auth: { method: 'none' },
+ runtimes: {
+ pi: piRuntime({
+ wireProtocol: 'openai-responses',
+ models: [{
+ id: 'deepseek-v4-pro',
+ name: 'DeepSeek V4 Pro',
+ piApi: 'openai-responses',
+ }],
+ }),
+ },
+ }],
+ () => null,
+ );
+
+ expect(providers[0]?.models[0]).toMatchObject({
+ id: 'deepseek-v4-pro',
+ api: 'openai-responses',
+ });
+ });
+
it('maps an explicit Responses reasoning capability and supported efforts into Pi', () => {
const { providers } = buildPiNativeProvidersFromConfigs(
[
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
new file mode 100644
index 0000000000..7751d81ec1
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@ -0,0 +1,210 @@
+import { EventEmitter } from 'node:events';
+import { describe, expect, it, vi } from 'vitest';
+
+vi.mock('electron', () => ({
+ app: { getPath: () => '/tmp/cindy-pi-native-forwarding-test' },
+}));
+
+vi.mock('../logger-adapter.js', () => ({
+ createMakerLogger: () => {
+ const make = (): Record<string, unknown> => ({
+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),
+ child: vi.fn(() => make()),
+ });
+ return make();
+ },
+ desktopMakerLogger: {
+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),
+ child: vi.fn(() => ({
+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),
+ child: vi.fn(),
+ })),
+ },
+}));
+
+import {
+ getPiNativeSubscriptionHandler,
+ type PiNativeSubscriptionHandlerDeps,
+} from '../anthropic-responses-bridge-host.js';
+
+function responseRecorder() {
+ const response = new EventEmitter() as EventEmitter & {
+ destroyed: boolean;
+ headersSent: boolean;
+ status: number;
+ headers: Record<string, string>;
+ chunks: Buffer[];
+ writeHead: (status: number, headers?: Record<string, string>) => void;
+ write: (chunk: Uint8Array | string) => boolean;
+ end: (chunk?: Uint8Array | string) => void;
+ };
+ response.destroyed = false;
+ response.headersSent = false;
+ response.status = 0;
+ response.headers = {};
+ response.chunks = [];
+ response.writeHead = (status, headers = {}) => {
+ response.status = status;
+ response.headers = headers;
+ response.headersSent = true;
+ };
+ response.write = (chunk) => {
+ response.chunks.push(Buffer.from(chunk));
+ return true;
+ };
+ response.end = (chunk) => {
+ if (chunk !== undefined) response.chunks.push(Buffer.from(chunk));
+ };
+ return response;
+}
+
+function deps(overrides: Partial<PiNativeSubscriptionHandlerDeps> = {}): PiNativeSubscriptionHandlerDeps {
+ return {
+ fetch: vi.fn(async () => new Response('ok', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ })) as PiNativeSubscriptionHandlerDeps['fetch'],
+ getChatgptAuth: vi.fn(async () => ({ accessToken: 'host-openai-token', accountId: 'account-1' })),
+ getGrokToken: vi.fn(async () => 'host-xai-token'),
+ invalidateChatgpt: vi.fn(async () => false),
+ invalidateXai: vi.fn(async () => 'ignored' as const),
+ recordXaiRateLimit: vi.fn(),
+ ...overrides,
+ };
+}
+
+describe('PI native subscription forwarding', () => {
+ it('forwards Codex Responses bytes unchanged with host-owned ChatGPT auth', async () => {
+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {
+ status: 200,
+ headers: { 'content-type': 'text/event-stream' },
+ }));
+ const injected = deps({ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'] });
+ const handler = getPiNativeSubscriptionHandler('openai', 'session-1', injected);
+ const rawBody = Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x01]);
+ const res = responseRecorder();
+
+ await handler({
+ rawBody,
+ parsedBody: undefined,
+ ctx: {
+ reqId: 1,
+ method: 'POST',
+ url: '/codex/responses',
+ headers: {
+ 'content-type': 'application/json',
+ 'content-encoding': 'zstd',
+ authorization: 'Bearer placeholder-that-must-not-leak',
+ },
+ },
+ res,
+ } as never);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchMock.mock.calls[0]!;
+ expect(url).toBe('https://chatgpt.com/backend-api/codex/responses');
+ expect(init?.headers).toMatchObject({
+ authorization: 'Bearer host-openai-token',
+ 'chatgpt-account-id': 'account-1',
+ 'content-encoding': 'zstd',
+ 'content-type': 'application/json',
+ });
+ expect(Buffer.from(init?.body as Uint8Array)).toEqual(rawBody);
+ expect(JSON.stringify(init?.headers)).not.toContain('placeholder-that-must-not-leak');
+ expect(res.status).toBe(200);
+ expect(Buffer.concat(res.chunks).toString('utf8')).toContain('event: done');
+ });
+
+ it('forwards xAI Chat Completions natively and invalidates the failed host token', async () => {
+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('{"error":"expired"}', {
+ status: 401,
+ headers: { 'content-type': 'application/json' },
+ }));
+ const invalidateXai = vi.fn(async () => 'ignored' as const);
+ const injected = deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ invalidateXai,
+ });
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-2', injected);
+ const rawBody = Buffer.from('{"model":"grok-build-0.1"}');
+ const res = responseRecorder();
+
+ await handler({
+ rawBody,
+ parsedBody: undefined,
+ ctx: {
+ reqId: 2,
+ method: 'POST',
+ url: '/v1/chat/completions',
+ headers: { 'content-type': 'application/json' },
+ },
+ res,
+ } as never);
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ 'https://api.x.ai/v1/chat/completions',
+ expect.objectContaining({
+ headers: expect.objectContaining({ authorization: 'Bearer host-xai-token' }),
+ }),
+ );
+ expect(invalidateXai).toHaveBeenCalledWith(expect.objectContaining({
+ status: 401,
+ failedAccessToken: 'host-xai-token',
+ }));
+ expect(res.status).toBe(401);
+ expect(Buffer.concat(res.chunks).toString('utf8')).toContain('expired');
+ });
+
+ it('records only xAI rate-limit headers that are actually present', async () => {
+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) =>
+ new Response('event: done\n\n', {
+ status: 200,
+ headers: {
+ 'content-type': 'text/event-stream',
+ 'x-ratelimit-remaining-requests': '9',
+ },
+ }));
+ const recordXaiRateLimit = vi.fn();
+ const injected = deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ recordXaiRateLimit,
+ });
+ const handler = getPiNativeSubscriptionHandler('xai', 'session-rate', injected);
+ const res = responseRecorder();
+
+ await handler({
+ rawBody: Buffer.from('{}'),
+ parsedBody: {},
+ ctx: {
+ reqId: 4,
+ method: 'POST',
+ url: '/v1/responses',
+ headers: { 'content-type': 'application/json' },
+ },
+ res,
+ } as never);
+
+ expect(recordXaiRateLimit).toHaveBeenCalledWith({
+ limitRequests: undefined,
+ remainingRequests: 9,
+ limitTokens: undefined,
+ remainingTokens: undefined,
+ });
+ });
+
+ it('rejects unsupported native paths without contacting an upstream', async () => {
+ const injected = deps();
+ const handler = getPiNativeSubscriptionHandler('openai', 'session-3', injected);
+ const res = responseRecorder();
+
+ await handler({
+ rawBody: Buffer.alloc(0),
+ parsedBody: undefined,
+ ctx: { reqId: 3, method: 'GET', url: '/models', headers: {} },
+ res,
+ } as never);
+
+ expect(injected.fetch).not.toHaveBeenCalled();
+ expect(res.status).toBe(404);
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index 52ebb14ed8..e717dbfff1 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -466,6 +466,40 @@ function withEmptyModels(p: Provider): Provider {
function computeMerged(): Catalog {
const b = base ?? BUNDLED_CATALOG;
+ // Dynamic OpenAI/Anthropic roots are rebuilt from discovery/registry below,
+ // but the daily OSS catalog may carry sparse PI protocol annotations. Keep
+ // only that metadata and apply it after existence has been independently
+ // proven; these entries never create a selectable model by themselves.
+ const piApiByProvider = new Map<string, Map<string, NonNullable<CatalogModel['piApi']>>>();
+ for (const provider of b.providers) {
+ const annotationSources = [
+ ...(provider.models.pi ?? []),
+ ...(provider.id === 'xai' ? (provider.models['claude-code'] ?? []) : []),
+ ];
+ for (const model of annotationSources) {
+ if (!model.piApi) continue;
+ const byModel = piApiByProvider.get(provider.id) ?? new Map();
+ byModel.set(model.id, model.piApi);
+ if (provider.id === 'openai' && model.id.startsWith(CHATGPT_MODEL_PREFIX)) {
+ byModel.set(model.id.slice(CHATGPT_MODEL_PREFIX.length), model.piApi);
+ }
+ piApiByProvider.set(provider.id, byModel);
+ }
+ }
+ const applyPiApiAnnotations = (
+ providerId: string,
+ models: CatalogModel[],
+ ): CatalogModel[] => {
+ const annotations = piApiByProvider.get(providerId);
+ if (!annotations || annotations.size === 0) return models;
+ return models.map((model) => {
+ const rawId = providerId === 'openai' && model.id.startsWith(CHATGPT_MODEL_PREFIX)
+ ? model.id.slice(CHATGPT_MODEL_PREFIX.length)
+ : model.id;
+ const piApi = annotations.get(model.id) ?? annotations.get(rawId);
+ return piApi && model.piApi !== piApi ? { ...model, piApi } : model;
+ });
+ };
// registry 消费计划(实体化/overlay/retired/bridge 门控)一次算好;单 route 的
// 作者错误隔离进 warnings,由刷新路径读走打日志,不拖垮其余条目。
const plan = planRegistryRoots(b.modelRegistry);
@@ -551,7 +585,14 @@ function computeMerged(): Catalog {
localOverrides,
plan.warnings,
);
- return projectCodexModelsToBridges(withRoot, excluded, prepareClaudeModel);
+ const projected = projectCodexModelsToBridges(withRoot, excluded, prepareClaudeModel);
+ return {
+ ...projected,
+ models: {
+ ...projected.models,
+ pi: applyPiApiAnnotations('openai', projected.models.pi ?? []),
+ },
+ };
}
if (p.id === 'anthropic') {
const seed = anthropicModels.length > 0 ? anthropicModels : (p.models['claude-code'] ?? []);
@@ -579,7 +620,15 @@ function computeMerged(): Catalog {
),
)
.map((model) => ({ ...model, supportsFastMode: false }));
- return { ...p, models: { ...p.models, 'claude-code': root, codex: codexBridge, pi: root } };
+ return {
+ ...p,
+ models: {
+ ...p.models,
+ 'claude-code': root,
+ codex: codexBridge,
+ pi: applyPiApiAnnotations('anthropic', root),
+ },
+ };
}
if (p.id === 'xai') {
const claudeRoot = assembleRoot(
@@ -590,14 +639,22 @@ function computeMerged(): Catalog {
true,
);
const codexRoot = assembleRoot('xai', 'codex', p.models.codex ?? [], plan, true);
+ const stripPiApi = (model: CatalogModel): CatalogModel => {
+ if (model.piApi === undefined) return model;
+ const rest = { ...model };
+ delete rest.piApi;
+ return rest;
+ };
return {
...p,
models: {
...p.models,
- 'claude-code': claudeRoot,
- codex: codexRoot,
+ 'claude-code': claudeRoot.map(stripPiApi),
+ codex: codexRoot.map(stripPiApi),
// Pi 恒定镜像 claude-code root(拿满 root 能力,如 grok-4.20 的 xhigh 档)。
- ...(p.agents.includes('pi') ? { pi: claudeRoot } : {}),
+ ...(p.agents.includes('pi')
+ ? { pi: applyPiApiAnnotations('xai', claudeRoot) }
+ : {}),
},
};
}
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 c0eb226eb1..8a0a739d54 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
@@ -41,7 +41,10 @@ import {
import { ANTHROPIC_DIRECT_UPSTREAM, CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY, anthropicCatalogModelIds, isAnthropicWireModel } from './claude-gateway-config.js';
import { getActiveCatalog } from './active-catalog.js';
-import { getResponsesBridgeHandler } from './anthropic-responses-bridge-host.js';
+import {
+ getPiNativeSubscriptionHandler,
+ getResponsesBridgeHandler,
+} from './anthropic-responses-bridge-host.js';
import { getSessionEffort, getSessionFastMode } from './session-effort-store.js';
import { isSubscriptionDirectModel } from '../../shared/subscriptionModels.js';
import {
@@ -187,6 +190,48 @@ export function createModelRoutingTransform(): RoutingTransform {
};
}
const piSessionId = claimedPiSessionId;
+ const piProviderId = piSessionId
+ ? headerValue(ctx.headers, 'x-cindy-pi-provider-id')
+ : null;
+ const selectedPiProviderId = piSessionId ? getSessionProvider(piSessionId) : null;
+ if (
+ piSessionId
+ && (
+ (piProviderId !== null && piProviderId !== selectedPiProviderId)
+ || (
+ (selectedPiProviderId === 'openai' || selectedPiProviderId === 'xai')
+ && piProviderId !== selectedPiProviderId
+ )
+ )
+ ) {
+ // A valid loopback session token authorizes only the provider selected by
+ // that Cindy session. Do not let a child process/extension swap this
+ // internal header and borrow another connected subscription credential.
+ return {
+ localHandler: async ({ res }) => {
+ const payload = JSON.stringify({
+ type: 'error',
+ error: {
+ type: 'authorization_error',
+ code: 'pi_provider_mismatch',
+ message: 'PI proxy provider does not match the session provider.',
+ },
+ });
+ res.writeHead(403, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ });
+ res.end(payload);
+ },
+ };
+ }
+ if (piSessionId && (piProviderId === 'openai' || piProviderId === 'xai')) {
+ return {
+ // PI has already built the provider-native request. The local handler
+ // only authenticates and forwards it; no Claude protocol bridge runs.
+ localHandler: getPiNativeSubscriptionHandler(piProviderId, piSessionId),
+ };
+ }
const requestAgent = piSessionId ? 'pi' : 'claude-code';
// 后台活动检测(claude-session-background-activity):凡带 cc 会话标头的请求
// 都记一笔活动时刻。routingTransform 会处理无 body 控制面请求与 JSON 请求;
@@ -215,7 +260,7 @@ export function createModelRoutingTransform(): RoutingTransform {
// 放在最前:优先级高于 per-session 供应商与 spawn 默认路由。
// ⚠ 本分支是订阅直连的**唯一注册点**:整块摘掉 = 订阅前缀请求 passthrough 到默认上游
// (预期 400/502,fail-open),不需要 revert 其它代码。
- if (isSubscriptionDirectModel(wireModel)) {
+ if (!piSessionId && isSubscriptionDirectModel(wireModel)) {
const bridgeHandler = getResponsesBridgeHandler();
if (!bridgeHandler) {
log.warn('订阅前缀模型但 responses handler 不可用,passthrough(该请求预期会 400)', { wireModel });
@@ -319,7 +364,8 @@ export function createModelRoutingTransform(): RoutingTransform {
const decision = route(body, ctx);
const hasInternalPiHeader =
headerValue(ctx.headers, 'x-cindy-pi-session-id') !== null
- || headerValue(ctx.headers, 'x-cindy-pi-session-token') !== null;
+ || headerValue(ctx.headers, 'x-cindy-pi-session-token') !== null
+ || headerValue(ctx.headers, 'x-cindy-pi-provider-id') !== null;
if (!hasInternalPiHeader) return decision;
const stripInternalPiHeaders = (
resolved: RoutingDecision | null,
@@ -332,6 +378,7 @@ export function createModelRoutingTransform(): RoutingTransform {
...(resolved?.headerDelete ?? []),
'x-cindy-pi-session-id',
'x-cindy-pi-session-token',
+ 'x-cindy-pi-provider-id',
]),
],
};
diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index eec7efbaa7..5f8e8da2e2 100644
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@ -22,6 +22,7 @@ import { app } from 'electron';
import fsp from 'node:fs/promises';
import path from 'node:path';
+import type { LocalRequestHandler } from '@cindy/anthropic-compat-proxy';
import { createResponsesHandler, type BridgeProviderConfig, type ResponsesBridgeHandler } from '@cindy/anthropic-responses-bridge';
import { createMakerLogger } from './logger-adapter.js';
@@ -324,3 +325,206 @@ export function getResponsesBridgeHandler(): ResponsesBridgeHandler | null {
}
return _handler;
}
+
+type PiNativeSubscriptionProvider = 'openai' | 'xai';
+
+export interface PiNativeSubscriptionHandlerDeps {
+ fetch: typeof outboundFetch;
+ getChatgptAuth: typeof getChatgptBridgeAuth;
+ getGrokToken: typeof getGrokAccessToken;
+ invalidateChatgpt: typeof invalidateChatgptBridgeAuth;
+ invalidateXai: typeof invalidateXaiBridgeAuth;
+ recordXaiRateLimit: typeof recordXaiRateLimitSnapshot;
+}
+
+const defaultPiNativeSubscriptionHandlerDeps: PiNativeSubscriptionHandlerDeps = {
+ fetch: outboundFetch,
+ getChatgptAuth: getChatgptBridgeAuth,
+ getGrokToken: getGrokAccessToken,
+ invalidateChatgpt: invalidateChatgptBridgeAuth,
+ invalidateXai: invalidateXaiBridgeAuth,
+ recordXaiRateLimit: recordXaiRateLimitSnapshot,
+};
+
+function piNativeUpstreamUrl(
+ providerId: PiNativeSubscriptionProvider,
+ requestUrl: string,
+): string | null {
+ let pathname: string;
+ try {
+ pathname = new URL(requestUrl, 'http://127.0.0.1').pathname;
+ } catch {
+ return null;
+ }
+ if (providerId === 'openai') {
+ return pathname === '/codex/responses'
+ ? 'https://chatgpt.com/backend-api/codex/responses'
+ : null;
+ }
+ const normalized = pathname.startsWith('/v1/') ? pathname : `/v1${pathname}`;
+ return normalized === '/v1/responses' || normalized === '/v1/chat/completions'
+ ? `https://api.x.ai${normalized}`
+ : null;
+}
+
+function nativeResponseHeaders(response: Response): Record<string, string> {
+ const headers: Record<string, string> = {};
+ response.headers.forEach((value, name) => {
+ const lower = name.toLowerCase();
+ if (
+ lower === 'content-type'
+ || lower === 'cache-control'
+ || lower === 'retry-after'
+ || lower === 'x-request-id'
+ || lower.startsWith('x-ratelimit-')
+ || lower.startsWith('openai-')
+ ) {
+ headers[lower] = value;
+ }
+ });
+ return headers;
+}
+
+function finiteRateLimitHeader(headers: Headers, name: string): number | undefined {
+ const raw = headers.get(name);
+ if (raw === null || raw.trim().length === 0) return undefined;
+ const value = Number(raw);
+ return Number.isFinite(value) ? value : undefined;
+}
+
+function recordNativeXaiRateLimit(
+ headers: Headers,
+ record: typeof recordXaiRateLimitSnapshot,
+): void {
+ const info = {
+ limitRequests: finiteRateLimitHeader(headers, 'x-ratelimit-limit-requests'),
+ remainingRequests: finiteRateLimitHeader(headers, 'x-ratelimit-remaining-requests'),
+ limitTokens: finiteRateLimitHeader(headers, 'x-ratelimit-limit-tokens'),
+ remainingTokens: finiteRateLimitHeader(headers, 'x-ratelimit-remaining-tokens'),
+ };
+ if (Object.values(info).some((value) => value !== undefined)) {
+ record(info);
+ }
+}
+
+async function pipeNativeResponse(response: Response, res: Parameters<LocalRequestHandler>[0]['res']): Promise<void> {
+ res.writeHead(response.status, nativeResponseHeaders(response));
+ if (!response.body) {
+ res.end();
+ return;
+ }
+ const reader = response.body.getReader();
+ try {
+ while (!res.destroyed) {
+ const chunk = await reader.read();
+ if (chunk.done) break;
+ if (!res.write(Buffer.from(chunk.value))) {
+ await new Promise<void>((resolve) => {
+ const done = (): void => {
+ res.off('drain', done);
+ res.off('close', done);
+ resolve();
+ };
+ res.once('drain', done);
+ res.once('close', done);
+ });
+ }
+ }
+ } finally {
+ await reader.cancel().catch(() => undefined);
+ }
+ if (!res.destroyed) res.end();
+}
+
+/**
+ * Forward an already-native PI request. Unlike getResponsesBridgeHandler this
+ * performs no Messages/Responses conversion: PI constructs the provider's
+ * native payload, while the host only swaps placeholder loopback credentials
+ * for the connected account credential.
+ */
+export function getPiNativeSubscriptionHandler(
+ providerId: PiNativeSubscriptionProvider,
+ sessionId: string,
+ deps: PiNativeSubscriptionHandlerDeps = defaultPiNativeSubscriptionHandlerDeps,
+): LocalRequestHandler {
+ return async ({ rawBody, ctx, res }) => {
+ const upstreamUrl = piNativeUpstreamUrl(providerId, ctx.url);
+ if (ctx.method !== 'POST' || !upstreamUrl) {
+ res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
+ res.end(JSON.stringify({ error: { message: 'Unsupported PI subscription endpoint.' } }));
+ return;
+ }
+ const controller = new AbortController();
+ const abortOnClose = (): void => controller.abort();
+ res.once('close', abortOnClose);
+ try {
+ let accessToken: string;
+ let headers: Record<string, string>;
+ if (providerId === 'openai') {
+ const auth = await deps.getChatgptAuth();
+ accessToken = auth.accessToken;
+ headers = buildChatgptBridgeHeaders({
+ accessToken,
+ accountId: auth.accountId,
+ sessionId,
+ });
+ } else {
+ accessToken = await deps.getGrokToken();
+ headers = { authorization: `Bearer ${accessToken}` };
+ }
+ headers['content-type'] = ctx.headers['content-type'] ?? 'application/json';
+ headers.accept = ctx.headers.accept ?? 'text/event-stream';
+ const contentEncoding = ctx.headers['content-encoding'];
+ if (contentEncoding) headers['content-encoding'] = contentEncoding;
+
+ const response = await deps.fetch(upstreamUrl, {
+ method: 'POST',
+ headers,
+ body: new Uint8Array(rawBody),
+ signal: controller.signal,
+ });
+ if (providerId === 'xai' && response.ok) {
+ recordNativeXaiRateLimit(response.headers, deps.recordXaiRateLimit);
+ }
+ if (!response.ok) {
+ const errorBody = Buffer.from(await response.arrayBuffer());
+ const errorText = errorBody.toString('utf8');
+ if (providerId === 'openai') {
+ await deps.invalidateChatgpt({
+ status: response.status,
+ body: errorText,
+ failedAccessToken: accessToken,
+ });
+ } else {
+ await deps.invalidateXai({
+ status: response.status,
+ body: errorText,
+ failedAccessToken: accessToken,
+ });
+ }
+ res.writeHead(response.status, nativeResponseHeaders(response));
+ res.end(errorBody);
+ return;
+ }
+ await pipeNativeResponse(response, res);
+ } catch (err) {
+ if (controller.signal.aborted || res.headersSent || res.destroyed) return;
+ log.warn('PI native subscription forwarding failed', {
+ providerId,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ res.writeHead(502, {
+ 'content-type': 'application/json; charset=utf-8',
+ 'cache-control': 'no-store',
+ });
+ res.end(JSON.stringify({
+ error: {
+ type: 'upstream_error',
+ message: err instanceof Error ? err.message : String(err),
+ },
+ }));
+ } finally {
+ res.off('close', abortOnClose);
+ }
+ };
+}
diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.ts
index 13307a80c5..9943b3d155 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts
@@ -21,6 +21,7 @@ import type {
CustomProviderRuntimeConfig,
OAuthProviderDescriptor,
PiReasoningEffort,
+ PiModelApi,
ProviderRuntimeModelConfig,
} from '@cindy/model-providers';
import {
@@ -28,6 +29,7 @@ import {
isLoopbackProviderUrl,
isProviderRequestPath,
PI_REASONING_EFFORTS,
+ PI_MODEL_APIS,
} from '@cindy/model-providers';
import { getDbClient } from '../localDb/client/current.js';
@@ -59,6 +61,10 @@ function isPiReasoningEffort(value: unknown): value is PiReasoningEffort {
);
}
+function isPiModelApi(value: unknown): value is PiModelApi {
+ return typeof value === 'string' && (PI_MODEL_APIS as readonly string[]).includes(value);
+}
+
function parseStoredPiReasoningCapability(
agent: AgentKind,
model: Record<string, unknown>,
@@ -143,6 +149,9 @@ function validateRuntime(agent: string, rt: unknown): ValidationResult {
if (mm.supportsImageInput !== undefined && typeof mm.supportsImageInput !== 'boolean') {
return invalid(`runtime '${agent}' model.supportsImageInput must be a boolean`);
}
+ if (mm.piApi !== undefined && (agent !== 'pi' || !isPiModelApi(mm.piApi))) {
+ return invalid(`runtime '${agent}' model.piApi invalid`);
+ }
const hasReasoningCapability = mm.reasoning !== undefined || mm.reasoningEfforts !== undefined;
if (hasReasoningCapability && agent !== 'pi') {
return invalid(`runtime '${agent}' reasoning capability is only supported for pi models`);
@@ -376,6 +385,7 @@ function normalizeRuntime(
.map((m) => ({
id: m.id.trim(),
name: m.name.trim(),
+ ...(agent === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
@@ -517,6 +527,7 @@ function parseRuntimes(raw: string): Partial<Record<AgentKind, CustomProviderRun
.map((m) => ({
id: String(m.id),
name: String(m.name ?? ''),
+ ...(agent === 'pi' && isPiModelApi(m.piApi) ? { piApi: m.piApi } : {}),
...(typeof m.contextWindow === 'number'
&& Number.isFinite(m.contextWindow)
&& m.contextWindow > 0
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index d98e8d0147..d9f63483bd 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -6,9 +6,9 @@
* - 凭证:按会话来源复用 Cindy AI / Claude.ai / ChatGPT / SuperGrok 既有连接态。
* pi 子进程只拿网关 key或无权限占位 key;订阅 OAuth 由本地 compat proxy
* 从安全存储注入,models.json 不落任何真实订阅凭证。
- * - endpoint:统一走 anthropic-compat-proxy。pi 说标准 Anthropic Messages,
- * proxy 按 x-cindy-pi-session-id 读取会话来源;ChatGPT / Grok 由现有
- * Responses bridge 翻译,Claude / Cindy AI 走透明 Anthropic 路由。
+ * - endpoint:统一走 authenticated loopback proxy。PI 按供应商使用原生协议:
+ * Claude=Messages、ChatGPT=Codex Responses、SuperGrok=PI bundled API;host
+ * 只注入凭证并原样转发。Cindy Gateway 继续按 Model Access v3 下发协议。
* - 二进制:与 cc/codex 同链 —— splash prepare 经 agent-binaries 按 CDN manifest
* 的 pi 字段下载整目录 tar.gz 到 userData/pi/<version>/(SHA256 校验,清单一变
* 下次启动即换新)。dev 期使用 apps/pi-bin 中 pnpm install:pi 的产物;正式版
@@ -16,6 +16,9 @@
* 对 Cindy 启动零影响。
*/
+import { execFile, spawn } from 'node:child_process';
+import fsp from 'node:fs/promises';
+import os from 'node:os';
import path from 'node:path';
import { app } from 'electron';
@@ -25,18 +28,22 @@ import type {
AuthAdapterOptions,
PiMcpServerRef,
PiNativeApi,
+ PiNativeModelSpec,
PiNativeProviderSpec,
PiNativeProvidersResult,
} from '@cindy/maker-core';
import { PI_REASONING_EFFORTS } from '@cindy/model-providers';
-import type { PiReasoningEffort, ProviderWireProtocol } from '@cindy/model-providers';
+import type { Catalog, PiReasoningEffort, ProviderWireProtocol } from '@cindy/model-providers';
import { getReadyBinaryPath } from '../agent-binaries/index.js';
import { getPiExtraSpawnConfig } from '../mcp-integrations/piEnvironment.js';
import { listCustomProvidersWithSecureHeaders } from './custom-provider-header-secrets.js';
import { readCustomProviderKey } from '../secrets/providerSecretStore.js';
import { desktopCodexAuthAdapter, readClaudeApiKey } from './auth-adapters.js';
-import { getClaudeEndpoint } from './anthropic-compat-proxy-host.js';
+import {
+ getClaudeEndpoint,
+ isAnthropicCompatProxyHandleReady,
+} from './anthropic-compat-proxy-host.js';
import { hasClaudeAiOAuth } from './claude-credentials-store.js';
import { hasGrokOAuthLogin } from './grok-oauth-login.js';
import hostSystemPrompt from './host-system-prompt.md?raw';
@@ -49,12 +56,413 @@ import {
getDesktopMcpToolApprovalPresentation,
} from './mcp-tool-approval-policy.js';
import { getRipgrepBinaryPath, claudeUpstreamEndpoint } from './runtime-configs.js';
-import { resolveXdPiGatewayWireProtocol } from './active-catalog.js';
+import { getActiveCatalog, resolveXdPiGatewayWireProtocol } from './active-catalog.js';
const log = createLogger('pi-host');
const PI_API_KEY_ENV = 'CINDY_PI_API_KEY';
const PI_PROVIDER_AUTH_PLACEHOLDER_KEY = 'cindy-pi-provider-auth-placeholder';
+const PI_OPENAI_PROXY_KEY_ENV = 'CINDY_PI_OPENAI_PROXY_KEY';
+const PI_PROVIDER_HEADER = 'x-cindy-pi-provider-id';
+
+export interface PiBundledModelInfo {
+ id: string;
+ api: PiNativeApi;
+ baseUrl?: string;
+ name: string;
+ reasoning: boolean;
+ thinkingLevelMap?: PiNativeModelSpec['thinkingLevelMap'];
+ input: Array<'text' | 'image'>;
+ contextWindow: number;
+ maxTokens: number;
+ cost?: PiNativeModelSpec['cost'];
+ headers?: Record<string, string>;
+ compat?: Record<string, unknown>;
+}
+
+export type PiBundledModelCatalog = ReadonlyMap<string, ReadonlyMap<string, PiBundledModelInfo>>;
+
+const piBundledModelsByBinary = new Map<string, Promise<PiBundledModelCatalog | null>>();
+const PI_NATIVE_APIS = new Set<PiNativeApi>([
+ 'anthropic-messages',
+ 'openai-responses',
+ 'openai-completions',
+ 'google-generative-ai',
+ 'openai-codex-responses',
+]);
+
+/**
+ * PI's native ChatGPT adapter extracts account_id from its API key before it
+ * sends a request. This unsigned placeholder contains no credential; the
+ * authenticated loopback proxy replaces it with the real host-owned token and
+ * account id before forwarding upstream.
+ */
+function piOpenaiProxyPlaceholderJwt(): string {
+ const encode = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString('base64url');
+ return `${encode({ alg: 'none', typ: 'JWT' })}.${encode({
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'cindy-pi-proxy' },
+ })}.`;
+}
+
+function appendEndpointPath(endpoint: string, suffix: string): string {
+ return `${endpoint.replace(/\/+$/, '')}/${suffix.replace(/^\/+/, '')}`;
+}
+
+function piSubscriptionHeaders(providerId: string): Record<string, string> {
+ return {
+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
+ [PI_PROVIDER_HEADER]: providerId,
+ };
+}
+
+export function parsePiListModels(stdout: string): ReadonlyMap<string, ReadonlySet<string>> {
+ const byProvider = new Map<string, Set<string>>();
+ for (const line of stdout.split(/\r?\n/)) {
+ const [providerId, modelId] = line.trim().split(/\s+/);
+ if (!providerId || !modelId || providerId === 'provider') continue;
+ const models = byProvider.get(providerId) ?? new Set<string>();
+ models.add(modelId);
+ byProvider.set(providerId, models);
+ }
+ return byProvider;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return !!value && typeof value === 'object' && !Array.isArray(value);
+}
+
+function parsePiBundledModel(value: unknown): PiBundledModelInfo | null {
+ if (!isRecord(value)) return null;
+ if (
+ typeof value.id !== 'string'
+ || typeof value.provider !== 'string'
+ || typeof value.api !== 'string'
+ || !PI_NATIVE_APIS.has(value.api as PiNativeApi)
+ ) return null;
+ const thinkingLevelMap = isRecord(value.thinkingLevelMap)
+ ? Object.fromEntries(
+ Object.entries(value.thinkingLevelMap).filter((entry): entry is [string, string | null] =>
+ entry[1] === null || typeof entry[1] === 'string'),
+ )
+ : undefined;
+ const input = Array.isArray(value.input)
+ ? value.input.filter((item): item is 'text' | 'image' => item === 'text' || item === 'image')
+ : [];
+ const rawCost = isRecord(value.cost) ? value.cost : null;
+ const cost = rawCost
+ && ['input', 'output', 'cacheRead', 'cacheWrite'].every((key) => typeof rawCost[key] === 'number')
+ ? {
+ input: rawCost.input as number,
+ output: rawCost.output as number,
+ cacheRead: rawCost.cacheRead as number,
+ cacheWrite: rawCost.cacheWrite as number,
+ }
+ : undefined;
+ const headers = isRecord(value.headers)
+ ? Object.fromEntries(
+ Object.entries(value.headers).filter((entry): entry is [string, string] => typeof entry[1] === 'string'),
+ )
+ : undefined;
+ return {
+ id: value.id,
+ api: value.api as PiNativeApi,
+ ...(typeof value.baseUrl === 'string' && value.baseUrl.length > 0
+ ? { baseUrl: value.baseUrl }
+ : {}),
+ name: typeof value.name === 'string' ? value.name : value.id,
+ reasoning: value.reasoning === true,
+ ...(thinkingLevelMap && Object.keys(thinkingLevelMap).length > 0 ? { thinkingLevelMap } : {}),
+ input: input.length > 0 ? input : ['text'],
+ contextWindow: typeof value.contextWindow === 'number' && value.contextWindow > 0
+ ? value.contextWindow
+ : 128_000,
+ maxTokens: typeof value.maxTokens === 'number' && value.maxTokens > 0 ? value.maxTokens : 16_000,
+ ...(cost ? { cost } : {}),
+ ...(headers && Object.keys(headers).length > 0 ? { headers } : {}),
+ ...(isRecord(value.compat) ? { compat: structuredClone(value.compat) } : {}),
+ };
+}
+
+async function readPiAvailableModels(
+ binaryPath: string,
+ configDir: string,
+ childEnv: NodeJS.ProcessEnv,
+ initialProvider: string,
+ initialModel: string,
+): Promise<PiBundledModelCatalog> {
+ const child = spawn(binaryPath, [
+ '--mode', 'rpc',
+ '--provider', initialProvider,
+ '--model', initialModel,
+ '--no-session',
+ '--no-extensions',
+ '--no-skills',
+ '--no-prompt-templates',
+ '--no-themes',
+ ], {
+ cwd: configDir,
+ env: childEnv,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true,
+ });
+ return new Promise<PiBundledModelCatalog>((resolve, reject) => {
+ let settled = false;
+ let buffered = '';
+ const timer = setTimeout(() => finish(new Error('PI catalog RPC timed out')), 5_000);
+ const finish = (error: Error | null, catalog?: PiBundledModelCatalog): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ child.stdin.end();
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGTERM');
+ if (error) reject(error);
+ else resolve(catalog ?? new Map());
+ };
+ child.once('error', (error) => finish(error));
+ child.once('exit', (code, signal) => {
+ if (!settled) finish(new Error(`PI catalog RPC exited before response (${code ?? signal ?? 'unknown'})`));
+ });
+ child.stdout.on('data', (chunk: Buffer) => {
+ buffered += chunk.toString('utf8');
+ if (buffered.length > 8 * 1024 * 1024) {
+ finish(new Error('PI catalog RPC output exceeded limit'));
+ return;
+ }
+ let newline = buffered.indexOf('\n');
+ while (newline >= 0) {
+ const line = buffered.slice(0, newline).trim();
+ buffered = buffered.slice(newline + 1);
+ newline = buffered.indexOf('\n');
+ if (!line) continue;
+ let message: unknown;
+ try {
+ message = JSON.parse(line);
+ } catch {
+ continue;
+ }
+ if (
+ !isRecord(message)
+ || message.type !== 'response'
+ || message.command !== 'get_available_models'
+ || message.success !== true
+ || !isRecord(message.data)
+ || !Array.isArray(message.data.models)
+ ) continue;
+ const catalog = new Map<string, Map<string, PiBundledModelInfo>>();
+ for (const rawModel of message.data.models) {
+ if (!isRecord(rawModel) || typeof rawModel.provider !== 'string') continue;
+ const model = parsePiBundledModel(rawModel);
+ if (!model) continue;
+ const providerModels = catalog.get(rawModel.provider) ?? new Map();
+ providerModels.set(model.id, model);
+ catalog.set(rawModel.provider, providerModels);
+ }
+ finish(null, catalog);
+ return;
+ }
+ });
+ child.stdin.write(`${JSON.stringify({ type: 'get_available_models' })}\n`, (error) => {
+ if (error) finish(error);
+ });
+ });
+}
+
+async function readPiCatalogProbeEnv(binaryPath: string): Promise<Record<string, string>> {
+ try {
+ const providersDoc = await fsp.readFile(
+ path.join(path.dirname(binaryPath), 'docs', 'providers.md'),
+ 'utf8',
+ );
+ const env: Record<string, string> = {};
+ for (const line of providersDoc.split(/\r?\n/)) {
+ const cells = line.split('|');
+ if (cells.length < 4) continue;
+ for (const match of cells[2]!.matchAll(/`([A-Z][A-Z0-9_]+)`/g)) {
+ env[match[1]!] = 'cindy-pi-catalog-probe';
+ }
+ }
+ return env;
+ } catch {
+ // Single-file PI distributions may omit docs. The explicit provider
+ // overrides below still give subscriptions a safe baseline; models absent
+ // from that reduced probe require a daily piApi annotation.
+ return {};
+ }
+}
+
+export async function readPiBundledModels(
+ binaryPath: string,
+): Promise<PiBundledModelCatalog | null> {
+ const cached = piBundledModelsByBinary.get(binaryPath);
+ if (cached) return cached;
+ const pending = (async () => {
+ const configDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-pi-catalog-'));
+ try {
+ // Placeholder keys only make bundled providers visible to the offline
+ // catalog commands; no credential or network request is involved.
+ await fsp.writeFile(path.join(configDir, 'models.json'), JSON.stringify({
+ providers: {
+ anthropic: {
+ baseUrl: 'http://127.0.0.1:1',
+ apiKey: 'cindy-pi-catalog-probe',
+ },
+ 'openai-codex': {
+ baseUrl: 'http://127.0.0.1:1',
+ apiKey: piOpenaiProxyPlaceholderJwt(),
+ },
+ xai: {
+ baseUrl: 'http://127.0.0.1:1/v1',
+ apiKey: 'cindy-pi-catalog-probe',
+ },
+ },
+ }));
+ const childEnv: NodeJS.ProcessEnv = {
+ ...await readPiCatalogProbeEnv(binaryPath),
+ PI_CODING_AGENT_DIR: configDir,
+ PI_OFFLINE: '1',
+ };
+ for (const name of ['PATH', 'TMPDIR', 'TEMP', 'TMP', 'SystemRoot', 'WINDIR', 'PATHEXT']) {
+ if (process.env[name]) childEnv[name] = process.env[name];
+ }
+ const stdout = await new Promise<string>((resolve, reject) => {
+ execFile(
+ binaryPath,
+ ['--list-models'],
+ {
+ encoding: 'utf8',
+ env: childEnv,
+ maxBuffer: 1024 * 1024,
+ timeout: 5_000,
+ windowsHide: true,
+ },
+ (error, output) => error ? reject(error) : resolve(output),
+ );
+ });
+ const listed = parsePiListModels(stdout);
+ const preferredProviders = ['openai-codex', 'xai', 'anthropic'];
+ const initialProvider = preferredProviders.find((providerId) => listed.get(providerId)?.size);
+ const initialModel = initialProvider ? [...listed.get(initialProvider)!][0] : undefined;
+ if (!initialProvider || !initialModel) return null;
+ const catalog = await readPiAvailableModels(
+ binaryPath,
+ configDir,
+ childEnv,
+ initialProvider,
+ initialModel,
+ );
+ return catalog.size > 0 ? catalog : null;
+ } catch (err) {
+ log.warn('readPiBundledModels: PI catalog probe failed; daily PI annotations disabled', {
+ message: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ } finally {
+ await fsp.rm(configDir, { recursive: true, force: true }).catch(() => undefined);
+ }
+ })();
+ piBundledModelsByBinary.set(binaryPath, pending);
+ return pending;
+}
+
+/**
+ * Overlay Cindy's host-managed subscription endpoints onto PI's bundled
+ * provider catalog. No model is copied into models.json unless the daily Cindy
+ * catalog explicitly carries a piApi correction/addition; the version-matched
+ * PI binary remains the baseline authority for model-specific APIs and quirks.
+ */
+export function buildPiSubscriptionNativeProviders(
+ catalog: Catalog,
+ endpoint: string,
+ bundledModelsByProvider?: PiBundledModelCatalog,
+): PiNativeProvidersResult {
+ const providers: PiNativeProviderSpec[] = [];
+ const env: Record<string, string> = {
+ [PI_OPENAI_PROXY_KEY_ENV]: piOpenaiProxyPlaceholderJwt(),
+ };
+ const add = (
+ sourceProviderId: 'anthropic' | 'openai' | 'xai',
+ piProviderId: string,
+ name: string,
+ baseUrl: string,
+ stripPrefix?: string,
+ ): void => {
+ const source = catalog.providers.find((provider) => provider.id === sourceProviderId);
+ const models = source?.models.pi ?? [];
+ if (models.length === 0) return;
+ providers.push({
+ id: piProviderId,
+ sourceProviderId,
+ name,
+ baseUrl,
+ inheritModels: true,
+ ...(sourceProviderId === 'openai' ? { apiKeyEnvVar: PI_OPENAI_PROXY_KEY_ENV } : {}),
+ headers: piSubscriptionHeaders(sourceProviderId),
+ models: models.map((model) => {
+ const wireId = stripPrefix && model.id.startsWith(stripPrefix)
+ ? model.id.slice(stripPrefix.length)
+ : model.id;
+ const bundledModels = bundledModelsByProvider?.get(piProviderId);
+ const bundledModel = bundledModels?.get(wireId);
+ const isAnnotatedAddition = !!model.piApi && !!bundledModels && !bundledModel;
+ const isProtocolCorrection = sourceProviderId !== 'openai'
+ && !!model.piApi
+ && !!bundledModel
+ && bundledModel.api !== model.piApi;
+ const preserved = isProtocolCorrection ? bundledModel : undefined;
+ return {
+ id: model.id,
+ wireId,
+ // ChatGPT subscription uses PI's specialized openai-codex adapter. A
+ // portable piApi marks a daily catalog addition here. Existing models
+ // stay untouched so their full bundled compat/pricing metadata survives;
+ // only IDs proven absent from this exact PI binary are added.
+ ...(sourceProviderId === 'openai'
+ && isAnnotatedAddition
+ ? { catalogAddition: true }
+ : {}),
+ ...(sourceProviderId !== 'openai'
+ && model.piApi
+ && (isAnnotatedAddition || isProtocolCorrection)
+ ? { api: model.piApi }
+ : {}),
+ name: preserved?.name ?? model.name,
+ contextWindow: preserved?.contextWindow ?? model.contextWindow,
+ ...(preserved?.maxTokens
+ ? { maxTokens: preserved.maxTokens }
+ : model.maxOutput
+ ? { maxTokens: model.maxOutput }
+ : {}),
+ reasoning: preserved?.reasoning ?? model.efforts.length > 0,
+ ...(preserved?.input
+ ? { input: [...preserved.input] }
+ : model.supportsImageInput === true
+ ? { input: ['text', 'image'] as Array<'text' | 'image'> }
+ : {}),
+ ...(preserved?.thinkingLevelMap
+ ? { thinkingLevelMap: { ...preserved.thinkingLevelMap } }
+ : model.efforts.length > 0
+ ? {
+ thinkingLevelMap: Object.fromEntries(
+ PI_REASONING_EFFORTS.map((effort) => [
+ effort,
+ model.efforts.includes(effort) ? effort : null,
+ ]),
+ ),
+ }
+ : {}),
+ ...(preserved?.cost ? { cost: { ...preserved.cost } } : {}),
+ ...(preserved?.headers ? { headers: { ...preserved.headers } } : {}),
+ ...(preserved?.compat ? { compat: structuredClone(preserved.compat) } : {}),
+ };
+ }),
+ });
+ };
+ add('anthropic', 'anthropic', 'Anthropic', endpoint);
+ add('openai', 'openai-codex', 'OpenAI (ChatGPT)', endpoint, 'chatgpt/');
+ add('xai', 'xai', 'xAI (SuperGrok)', appendEndpointPath(endpoint, 'v1'), 'xai/');
+ return { providers, env };
+}
/**
* 订阅 OAuth provider:网关 `cindy` 块经 compat proxy 用安全存储里的 OAuth 服务这些模型,
@@ -244,6 +652,64 @@ function wireProtocolToPiApi(wp: ProviderWireProtocol | undefined): PiNativeApi
}
}
+/**
+ * Resolve the protocol already known by the exact bundled PI build. Presets use
+ * Cindy provider ids, which intentionally do not have to match PI provider ids,
+ * so the stable join key here is the model id. Conflicting duplicate ids are
+ * ambiguous and must fall through to an explicit catalog/runtime declaration.
+ */
+export function resolvePiBundledApiByModelId(
+ catalog: PiBundledModelCatalog | undefined,
+ modelId: string,
+): PiNativeApi | undefined {
+ let resolved: PiNativeApi | undefined;
+ for (const models of catalog?.values() ?? []) {
+ const model = models.get(modelId);
+ if (!model) continue;
+ if (resolved !== undefined && resolved !== model.api) return undefined;
+ resolved = model.api;
+ }
+ return resolved;
+}
+
+function urlOrigin(value: string | undefined): string | null {
+ if (!value) return null;
+ try {
+ return new URL(value).origin;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Pick the bundled PI entry belonging to the same upstream origin. This keeps
+ * both protocol and endpoint together: copying a Claude-compatible preset URL
+ * while borrowing PI's OpenAI protocol would be just another broken hybrid.
+ */
+export function resolvePiBundledModelById(
+ catalog: PiBundledModelCatalog | undefined,
+ modelId: string,
+ sourceBaseUrl?: string,
+): PiBundledModelInfo | undefined {
+ const candidates: PiBundledModelInfo[] = [];
+ for (const models of catalog?.values() ?? []) {
+ const model = models.get(modelId);
+ if (model) candidates.push(model);
+ }
+ if (candidates.length === 0) return undefined;
+ const sourceOrigin = urlOrigin(sourceBaseUrl);
+ if (sourceOrigin) {
+ const sameOrigin = candidates.filter((model) => urlOrigin(model.baseUrl) === sourceOrigin);
+ if (sameOrigin.length === 1) return sameOrigin[0];
+ const exactBaseUrl = sameOrigin.filter((model) => model.baseUrl === sourceBaseUrl);
+ if (exactBaseUrl.length === 1) return exactBaseUrl[0];
+ }
+ const first = candidates[0]!;
+ return candidates.every((model) => model.api === first.api && model.baseUrl === first.baseUrl)
+ ? first
+ : undefined;
+}
+
/** env 变量名(该 provider 的 api key):CINDY_PI_KEY_<ID>,ID 规整成 [A-Z0-9_]。 */
export function piNativeKeyEnvVar(providerId: string): string {
return `CINDY_PI_KEY_${providerId.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}`;
@@ -276,12 +742,14 @@ export function buildPiNativeProvidersFromConfigs(
supportsImageInput?: boolean;
reasoning?: boolean;
reasoningEfforts?: PiReasoningEffort[];
+ piApi?: PiNativeApi;
}>;
};
};
}>,
readKey: (providerId: string, agent: string) => string | null,
onSkip?: (id: string, reason: string) => void,
+ bundledModelsByProvider?: PiBundledModelCatalog,
): PiNativeProvidersResult {
const providers: PiNativeProviderSpec[] = [];
const env: Record<string, string> = {};
@@ -332,23 +800,56 @@ export function buildPiNativeProvidersFromConfigs(
env[apiKeyEnvVar] = key;
}
}
+ const runtimeApi = rt.wireProtocol
+ ? wireProtocolToPiApi(rt.wireProtocol)
+ : undefined;
+ // Protocol authority, in order: per-model daily correction/addition,
+ // explicit endpoint protocol, exact PI bundled model knowledge, then the
+ // legacy BYOM default for genuinely unknown hand-written models. This keeps
+ // unannotated existing preset models on PI's own table instead of silently
+ // absorbing them into OpenAI Chat Completions.
+ const bundledModels = rt.models.map((model) =>
+ !model.piApi && !runtimeApi
+ ? resolvePiBundledModelById(bundledModelsByProvider, model.id, rt.baseUrl)
+ : undefined);
+ const modelApis = rt.models.map((model, index) =>
+ model.piApi
+ ?? runtimeApi
+ ?? bundledModels[index]?.api
+ ?? resolvePiBundledApiByModelId(bundledModelsByProvider, model.id)
+ ?? 'openai-completions');
+ const providerApi = runtimeApi ?? modelApis[0] ?? 'openai-completions';
providers.push({
id: cfg.id,
name: cfg.name,
baseUrl: rt.baseUrl,
- api: wireProtocolToPiApi(rt.wireProtocol),
+ api: providerApi,
apiKeyEnvVar,
...(headers && Object.keys(headers).length > 0 ? { headers } : {}),
- models: rt.models.map((m) => {
+ models: rt.models.map((m, index) => {
const supportedEfforts = new Set(m.reasoningEfforts ?? []);
+ const modelApi = modelApis[index]!;
+ const bundledModel = bundledModels[index];
return {
id: m.id,
- name: m.name,
- contextWindow: m.contextWindow,
- ...(m.supportsImageInput === true
+ ...(m.piApi || modelApi !== providerApi ? { api: modelApi } : {}),
+ ...(bundledModel?.baseUrl ? { baseUrl: bundledModel.baseUrl } : {}),
+ name: bundledModel?.name ?? m.name,
+ contextWindow: bundledModel?.contextWindow ?? m.contextWindow,
+ ...(bundledModel?.maxTokens ? { maxTokens: bundledModel.maxTokens } : {}),
+ ...(bundledModel?.input
+ ? { input: [...bundledModel.input] }
+ : m.supportsImageInput === true
? { input: ['text', 'image'] as Array<'text' | 'image'> }
: {}),
- ...(m.reasoning === true
+ ...(bundledModel?.reasoning
+ ? {
+ reasoning: true,
+ ...(bundledModel.thinkingLevelMap
+ ? { thinkingLevelMap: { ...bundledModel.thinkingLevelMap } }
+ : {}),
+ }
+ : m.reasoning === true
? {
reasoning: true,
thinkingLevelMap: Object.fromEntries(
@@ -359,6 +860,9 @@ export function buildPiNativeProvidersFromConfigs(
),
}
: {}),
+ ...(bundledModel?.cost ? { cost: { ...bundledModel.cost } } : {}),
+ ...(bundledModel?.headers ? { headers: { ...bundledModel.headers } } : {}),
+ ...(bundledModel?.compat ? { compat: structuredClone(bundledModel.compat) } : {}),
};
}),
});
@@ -371,14 +875,24 @@ async function resolvePiNativeProviders(ctx?: {
workingDir?: string;
remoteHostId?: string | null;
}): Promise<PiNativeProvidersResult> {
+ const piBinaryPath = resolvePiBinaryPath();
+ const bundledModels = piBinaryPath ? await readPiBundledModels(piBinaryPath) : null;
+ let subscriptions: PiNativeProvidersResult = { providers: [], env: {} };
+ if (!ctx?.remoteHostId && isAnthropicCompatProxyHandleReady()) {
+ subscriptions = buildPiSubscriptionNativeProviders(
+ getActiveCatalog(),
+ getClaudeEndpoint(),
+ bundledModels ?? undefined,
+ );
+ }
let configs;
try {
configs = await listCustomProvidersWithSecureHeaders();
} catch (err) {
- log.warn('resolvePiNativeProviders: listCustomProviders failed, gateway-only', {
+ log.warn('resolvePiNativeProviders: listCustomProviders failed, subscription providers only', {
message: err instanceof Error ? err.message : String(err),
});
- return { providers: [], env: {} };
+ return subscriptions;
}
const isRemote = Boolean(ctx?.remoteHostId);
// 远端会话:本地 loopback 端点(本机 Ollama/vLLM)远端够不到。
@@ -397,9 +911,27 @@ async function resolvePiNativeProviders(ctx?: {
}
}
}
- return buildPiNativeProvidersFromConfigs(configs, readCustomProviderKey, (id, reason) => {
- log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason });
- });
+ const custom = buildPiNativeProvidersFromConfigs(
+ configs,
+ readCustomProviderKey,
+ (id, reason) =>
+ log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason }),
+ bundledModels ?? undefined,
+ );
+ const reserved = new Set(subscriptions.providers.map((provider) => provider.id));
+ return {
+ providers: [
+ ...subscriptions.providers,
+ ...custom.providers.filter((provider) => {
+ if (!reserved.has(provider.id)) return true;
+ log.warn('resolvePiNativeProviders: custom provider collides with native subscription provider', {
+ id: provider.id,
+ });
+ return false;
+ }),
+ ],
+ env: { ...subscriptions.env, ...custom.env },
+ };
}
/** baseUrl 是否指向本机 loopback(与本机 proxy 同判定,远端会话不可达)。
@@ -519,10 +1051,8 @@ getMcpToolApprovalPresentation: getDesktopMcpToolApprovalPresentation,
resolvePiGatewayModelDescriptor: opts.resolvePiGatewayModelDescriptor,
resolvePiGatewayModelApi: (providerId, modelId) => {
const source = providerId?.trim();
- // Anthropic / OpenAI / xAI 订阅都经既有 compat proxy Messages 前门。即使它们与 XD
- // 共享 model id,也不能被 XD v3 的 Responses 配置覆盖;models.json 是每会话隔离的,
- // 因此按本次实际来源生成。自定义 BYOM 走独立 native provider,此分支只配置它不使用
- // 的 cindy 块,并保持 Messages 安全默认。
+ // 本地订阅走上面的 PI 原生 provider;cindy 块只是同一会话切回 Gateway 时的备用块。
+ // 即使订阅与 XD 共享 model id,也不能借用 XD v3 的协议字段。
if (source && source !== 'cindy' && source !== 'xd') return 'anthropic-messages';
return resolveXdPiGatewayWireProtocol(modelId);
},
diff --git a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
index 5d3bff84b4..1aba15e451 100644
--- a/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
+++ b/apps/desktop/src/renderer/components/settings/AddProviderWizard.tsx
@@ -786,6 +786,7 @@ export function AddProviderWizard({
return {
id: m.id,
name: m.name,
+ ...(agent === 'pi' && presetModel?.piApi ? { piApi: presetModel.piApi } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
...(presetModel?.supportsImageInput === true ? { supportsImageInput: true } : {}),
...(presetModel?.reasoning === true && presetModel.reasoningEfforts?.length
diff --git a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
index 1847060095..d0283255aa 100644
--- a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
+++ b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx
@@ -1108,6 +1108,7 @@ export function CustomProviderDialog({
.map((m) => ({
id: m.id.trim(),
name: m.name.trim(),
+ ...(agent === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
@@ -1132,6 +1133,7 @@ export function CustomProviderDialog({
return {
id: m.id,
name: cur?.name || m.name,
+ ...(agent === 'pi' && cur?.piApi ? { piApi: cur.piApi } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
...(cur?.defaultEnabled === false ? { defaultEnabled: false } : {}),
...(cur?.supportsImageInput === true ? { supportsImageInput: true } : {}),
@@ -1196,9 +1198,11 @@ export function CustomProviderDialog({
const supportsImageInput = latest ? latest.supportsImageInput : m.supportsImageInput;
const reasoning = latest ? latest.reasoning : m.reasoning;
const reasoningEfforts = latest ? latest.reasoningEfforts : m.reasoningEfforts;
+ const piApi = latest ? latest.piApi : m.piApi;
return {
id: m.id,
name: latest?.name.trim() ? latest.name.trim() : m.name,
+ ...(picker.agent === 'pi' && piApi ? { piApi } : {}),
...(contextWindow !== undefined ? { contextWindow } : {}),
...(defaultEnabled === false ? { defaultEnabled: false } : {}),
...(supportsImageInput === true ? { supportsImageInput: true } : {}),
@@ -1213,6 +1217,7 @@ export function CustomProviderDialog({
merged.push({
id,
name: m.name.trim() || id,
+ ...(picker.agent === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
@@ -1341,6 +1346,7 @@ export function CustomProviderDialog({
.map((m) => ({
id: m.id.trim(),
name: m.name.trim(),
+ ...(a === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
...(m.contextWindow !== undefined ? { contextWindow: m.contextWindow } : {}),
...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),
...(m.supportsImageInput === true ? { supportsImageInput: true } : {}),
diff --git a/apps/desktop/src/renderer/lib/customProviders.ts b/apps/desktop/src/renderer/lib/customProviders.ts
index 8a46226886..38090eaf35 100644
--- a/apps/desktop/src/renderer/lib/customProviders.ts
+++ b/apps/desktop/src/renderer/lib/customProviders.ts
@@ -113,6 +113,7 @@ export function customProviderModelConfigFromCatalogModel(
| 'contextWindowExplicit'
| 'defaultEnabled'
| 'supportsImageInput'
+ | 'piApi'
> &
Partial<Pick<CatalogModel, 'efforts'>>,
agent?: AgentKind,
@@ -126,6 +127,7 @@ export function customProviderModelConfigFromCatalogModel(
return {
id: model.id,
name: model.name,
+ ...(agent === 'pi' && model.piApi ? { piApi: model.piApi } : {}),
...(model.contextWindowExplicit === true || model.contextWindow !== DEFAULT_CUSTOM_CONTEXT_WINDOW
? { contextWindow: model.contextWindow }
: {}),
diff --git a/apps/desktop/src/shared/piRuntimeInitialization.ts b/apps/desktop/src/shared/piRuntimeInitialization.ts
index 0d04635313..391cf532c6 100644
--- a/apps/desktop/src/shared/piRuntimeInitialization.ts
+++ b/apps/desktop/src/shared/piRuntimeInitialization.ts
@@ -10,6 +10,7 @@ export function savedCustomProviderModelShape(
return {
id: model.id.trim(),
name: model.name.trim(),
+ ...(includePiCapabilities && model.piApi ? { piApi: model.piApi } : {}),
...(model.contextWindow !== undefined ? { contextWindow: model.contextWindow } : {}),
...(model.defaultEnabled === false ? { defaultEnabled: false } : {}),
...(includePiCapabilities && model.supportsImageInput === true
diff --git a/packages/anthropic-compat-proxy/src/server.test.ts b/packages/anthropic-compat-proxy/src/server.test.ts
index f898f4c265..29ba1ebd12 100644
--- a/packages/anthropic-compat-proxy/src/server.test.ts
+++ b/packages/anthropic-compat-proxy/src/server.test.ts
@@ -1,4 +1,9 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
+import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
import { gzipSync } from 'node:zlib';
import { EventEmitter } from 'node:events';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -25,6 +30,15 @@ import { listenOnAvailableLoopbackPort } from './test-loopback-server.js';
import { createThreadStripController } from './thread-strip-controller.js';
import type { ProxyHandle } from './types.js';
+const TEST_REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+const TEST_PI_BINARY = path.join(
+ TEST_REPO_ROOT,
+ 'apps',
+ 'pi-bin',
+ `${process.platform}-${process.arch}`,
+ process.platform === 'win32' ? 'pi.exe' : 'pi',
+);
+
function startFakeUpstream(
handler: (reqIndex: number, body: string, res: ServerResponse) => void,
): Promise<{ url: string; bodies: string[]; headers: Array<Record<string, string>>; paths: string[]; close: () => Promise<void> }> {
@@ -1812,6 +1826,161 @@ describe('anthropic-compat-proxy empty-assistant-message recovery (moonshot/kimi
});
describe('anthropic-compat-proxy localHandler(路由决策交本地 handler,不转发上游)', () => {
+ it.skipIf(!existsSync(TEST_PI_BINARY))(
+ 'real PI zstd request crosses the proxy parse boundary and reaches the raw local handler',
+ { timeout: 30_000 },
+ async () => {
+ const gateway = await startFakeUpstream((_i, _b, res) => {
+ res.writeHead(500);
+ res.end('default upstream must not be reached');
+ });
+ upstreamClose = gateway.close;
+ let seen: { raw: Buffer; encoding: string | undefined; parsed: unknown; url: string } | null = null;
+ let resolveSeen: (() => void) | null = null;
+ const seenPromise = new Promise<void>((resolve) => { resolveSeen = resolve; });
+ proxy = await createAnthropicCompatProxy({
+ upstream: gateway.url,
+ transformRequest: [],
+ routingTransform: (body, ctx) => {
+ if (ctx.headers['x-native-route'] !== 'openai') return null;
+ return {
+ localHandler: async ({ rawBody, parsedBody, res }) => {
+ seen = {
+ raw: Buffer.from(rawBody),
+ encoding: ctx.headers['content-encoding'],
+ parsed: parsedBody,
+ url: ctx.url,
+ };
+ resolveSeen?.();
+ res.writeHead(401, { 'content-type': 'application/json' });
+ res.end('{"error":{"message":"intentional test stop"}}');
+ },
+ };
+ },
+ });
+ const configHome = mkdtempSync(path.join(tmpdir(), 'pi-zstd-proxy-e2e-'));
+ const encode = (value: unknown): string => Buffer.from(JSON.stringify(value)).toString('base64url');
+ const placeholderJwt = `${encode({ alg: 'none', typ: 'JWT' })}.${encode({
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'cindy-pi-proxy' },
+ })}.`;
+ let child: ChildProcessWithoutNullStreams | null = null;
+ try {
+ writeFileSync(path.join(configHome, 'models.json'), JSON.stringify({
+ providers: {
+ 'openai-codex': {
+ baseUrl: proxy.url,
+ apiKey: '$CINDY_PI_OPENAI_PROXY_KEY',
+ headers: { 'x-native-route': 'openai' },
+ models: [{
+ id: 'gpt-cindy-zstd-test',
+ name: 'GPT Cindy zstd test',
+ reasoning: false,
+ input: ['text'],
+ contextWindow: 128_000,
+ maxTokens: 16_000,
+ }],
+ },
+ },
+ }));
+ writeFileSync(path.join(configHome, 'settings.json'), JSON.stringify({ transport: 'sse' }));
+ child = spawn(TEST_PI_BINARY, [
+ '--provider', 'openai-codex',
+ '--model', 'gpt-cindy-zstd-test',
+ '--no-session',
+ '--no-tools',
+ '--no-extensions',
+ '--no-skills',
+ '--no-prompt-templates',
+ '--no-context-files',
+ '--mode', 'rpc',
+ ], {
+ cwd: TEST_REPO_ROOT,
+ env: {
+ ...process.env,
+ PI_CODING_AGENT_DIR: configHome,
+ CINDY_PI_OPENAI_PROXY_KEY: placeholderJwt,
+ },
+ });
+ let stderr = '';
+ child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8'); });
+ child.stdin.write(JSON.stringify({ id: 'test-prompt', type: 'prompt', message: 'ping' }) + '\n');
+ let reachTimeout: NodeJS.Timeout | undefined;
+ try {
+ await Promise.race([
+ seenPromise,
+ new Promise<never>((_resolve, reject) => {
+ reachTimeout = setTimeout(
+ () => reject(new Error(`real PI did not reach proxy: ${stderr}`)),
+ 10_000,
+ );
+ }),
+ ]);
+ } finally {
+ if (reachTimeout) clearTimeout(reachTimeout);
+ }
+
+ expect(seen).not.toBeNull();
+ expect(seen?.url).toBe('/codex/responses');
+ expect(seen?.encoding).toBe('zstd');
+ expect(seen?.parsed).toBeUndefined();
+ expect([...seen!.raw.subarray(0, 4)]).toEqual([0x28, 0xb5, 0x2f, 0xfd]);
+ expect(gateway.bodies).toHaveLength(0);
+ } finally {
+ if (child && child.exitCode === null && child.signalCode === null) {
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(() => {
+ if (child?.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
+ resolve();
+ }, 1_000);
+ child!.once('close', () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ child!.kill('SIGTERM');
+ });
+ }
+ rmSync(configHome, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it('JSON content-type with compressed bytes still routes by headers and preserves raw body', async () => {
+ const gateway = await startFakeUpstream((_i, _b, res) => { res.writeHead(200); res.end('{}'); });
+ upstreamClose = gateway.close;
+ const compressed = gzipSync(Buffer.from(JSON.stringify({ model: 'gpt-native' })));
+ let seen: Buffer | null = null;
+ proxy = await createAnthropicCompatProxy({
+ upstream: gateway.url,
+ transformRequest: [],
+ routingTransform: (body, ctx) => {
+ expect(body).toBeUndefined();
+ if (ctx.headers['x-native-route'] !== 'openai') return null;
+ return {
+ localHandler: async ({ rawBody, parsedBody, res }) => {
+ seen = Buffer.from(rawBody);
+ expect(parsedBody).toBeUndefined();
+ res.writeHead(204);
+ res.end();
+ },
+ };
+ },
+ });
+
+ const response = await fetch(`${proxy.url}/codex/responses`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ 'content-encoding': 'gzip',
+ 'x-native-route': 'openai',
+ },
+ body: compressed,
+ });
+
+ expect(response.status).toBe(204);
+ expect(seen).toEqual(compressed);
+ expect(gateway.bodies).toHaveLength(0);
+ });
+
it('命中 handler:收到原始字节 + 已解析 body + ctx,自写响应(含 SSE 流式),上游零请求', async () => {
const gateway = await startFakeUpstream((_i, _b, res) => { res.writeHead(200); res.end('{}'); });
upstreamClose = gateway.close;
diff --git a/packages/anthropic-compat-proxy/src/server.ts b/packages/anthropic-compat-proxy/src/server.ts
index 1c5f7e88a2..248939da55 100644
--- a/packages/anthropic-compat-proxy/src/server.ts
+++ b/packages/anthropic-compat-proxy/src/server.ts
@@ -1703,6 +1703,13 @@ export async function createAnthropicCompatProxy(opts: ProxyOptions): Promise<Pr
if (opts.routingTransform && contentType.toLowerCase().startsWith('application/json')) {
try {
rawParsed = JSON.parse(rawBody.toString('utf8'));
+ } catch {
+ // Some native clients (notably PI's ChatGPT adapter) send compressed
+ // JSON while keeping content-type=application/json. Header/path based
+ // routing must still run; the selected local handler receives rawBody
+ // and can forward it byte-for-byte without parsing.
+ }
+ try {
const maybeDecision = opts.routingTransform(rawParsed, requestCtx);
decision = isPromiseLike<RoutingDecision | null>(maybeDecision)
? await maybeDecision
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index 05a2164a9f..7d43083973 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -178,13 +178,24 @@ export type PiNativeApi =
| 'anthropic-messages'
| 'openai-responses'
| 'openai-completions'
- | 'google-generative-ai';
+ | 'google-generative-ai'
+ /** PI's native ChatGPT subscription adapter; not a portable BYOM protocol. */
+ | 'openai-codex-responses';
export type PiNativeThinkingLevel = Exclude<Effort, 'ultra'>;
/** BYOM:写进 pi models.json 的一个模型(原生 provider 块内)。 */
export interface PiNativeModelSpec {
+ /** Cindy/public model id used by provider-aware routing and the UI. */
id: string;
+ /** PI provider's native model id; omitted when it is identical to id. */
+ wireId?: string;
+ /** Sparse models.json override/addition; absent means retain PI's bundled model entry. */
+ api?: PiNativeApi;
+ /** Per-model native endpoint retained from PI's bundled provider table. */
+ baseUrl?: string;
+ /** Add a model missing from PI's bundled catalog while inheriting the provider's bundled API. */
+ catalogAddition?: boolean;
name?: string;
reasoning?: boolean;
/** Pi models.json 的 provider-specific thinking level 映射;null 明确禁用该档。 */
@@ -192,6 +203,16 @@ export interface PiNativeModelSpec {
contextWindow?: number;
maxTokens?: number;
input?: Array<'text' | 'image'>;
+ /** Preserve bundled accounting metadata when a protocol correction replaces a model entry. */
+ cost?: {
+ input: number;
+ output: number;
+ cacheRead: number;
+ cacheWrite: number;
+ };
+ /** Preserve model-specific request metadata on a required full-entry replacement. */
+ headers?: Record<string, string>;
+ compat?: Record<string, unknown>;
}
/**
@@ -219,11 +240,16 @@ export interface PiRemoteFileOps {
* 解析产出;PiAgent 写进 models.json 的独立 provider 块,并按 model→provider 路由 set_model。
*/
export interface PiNativeProviderSpec {
- /** provider id(slug,禁与网关 provider `cindy` 撞名)。 */
+ /** PI provider id(slug,禁与网关 provider `cindy` 撞名)。 */
id: string;
+ /** Cindy catalog provider id; defaults to id for BYOM providers. */
+ sourceProviderId?: string;
name: string;
baseUrl: string;
- api: PiNativeApi;
+ /** BYOM provider default. Omitted only when inheriting PI's bundled provider catalog. */
+ api?: PiNativeApi;
+ /** Keep PI's bundled models and serialize only models carrying an explicit api override. */
+ inheritModels?: boolean;
/**
* 存放该 provider api key 的 env 变量名;models.json 用 `$<envVar>` 插值引用(与网关
* CINDY_PI_API_KEY 同机制,密钥只进子进程 env、不落盘)。keyless(本机 Ollama 等)留空 →
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 32e3574f6a..0a5f8d12b4 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
@@ -260,6 +260,35 @@ function responsesStreamBody(text: string, model: string): string {
]);
}
+/** 最小 OpenAI Chat Completions SSE 流:验证 PI 内置模型表的 completions 分配。 */
+function chatCompletionsStreamBody(text: string, model: string): string {
+ return [
+ `data: ${JSON.stringify({
+ id: 'chatcmpl_pi_native_1',
+ object: 'chat.completion.chunk',
+ created: 1,
+ model,
+ choices: [{ index: 0, delta: { role: 'assistant', content: '' }, finish_reason: null }],
+ })}\n\n`,
+ `data: ${JSON.stringify({
+ id: 'chatcmpl_pi_native_1',
+ object: 'chat.completion.chunk',
+ created: 1,
+ model,
+ choices: [{ index: 0, delta: { content: text }, finish_reason: null }],
+ })}\n\n`,
+ `data: ${JSON.stringify({
+ id: 'chatcmpl_pi_native_1',
+ object: 'chat.completion.chunk',
+ created: 1,
+ model,
+ choices: [{ index: 0, delta: {}, finish_reason: 'stop' }],
+ usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 },
+ })}\n\n`,
+ 'data: [DONE]\n\n',
+ ].join('');
+}
+
/** 让"模型"发起一次工具调用的 SSE 流(stop_reason=tool_use)。 */
function anthropicToolUseBody(toolName: string, input: Record<string, unknown>): string {
return sse([
@@ -307,6 +336,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
url: string;
auth: string | undefined;
sessionId: string | undefined;
+ providerId: string | undefined;
body: string;
}> = [];
// 权限测试用的脚本化响应队列:非空时按序出队,空了回落默认 pong 文本。
@@ -322,6 +352,7 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
url: req.url ?? '',
auth: (req.headers['x-api-key'] as string | undefined) ?? (req.headers.authorization as string | undefined),
sessionId: req.headers['x-cindy-pi-session-id'] as string | undefined,
+ providerId: req.headers['x-cindy-pi-provider-id'] as string | undefined,
body,
});
res.writeHead(200, {
@@ -484,6 +515,247 @@ describe.skipIf(!piAvailable)('PiAgent integration (real pi binary + fake gatewa
},
);
+ it(
+ 'uses the bundled openai-codex adapter for a host subscription model',
+ { timeout: 60_000 },
+ async () => {
+ const deps = buildDeps();
+ deps.capabilityAdditions = {
+ ...deps.capabilityAdditions,
+ availableModels: [
+ ...(deps.capabilityAdditions?.availableModels ?? []),
+ {
+ id: 'chatgpt/gpt-cindy-daily-test',
+ displayName: 'GPT Daily Catalog Test',
+ contextWindow: 272_000,
+ efforts: ['low', 'high'],
+ defaultEffort: 'high',
+ },
+ ],
+ };
+ const encode = (value: unknown): string =>
+ Buffer.from(JSON.stringify(value)).toString('base64url');
+ const placeholderJwt = `${encode({ alg: 'none', typ: 'JWT' })}.${encode({
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'cindy-pi-proxy' },
+ })}.`;
+ deps.resolvePiNativeProviders = async () => ({
+ providers: [{
+ id: 'openai-codex',
+ sourceProviderId: 'openai',
+ name: 'OpenAI (ChatGPT)',
+ baseUrl: endpoint,
+ inheritModels: true,
+ apiKeyEnvVar: 'CINDY_PI_OPENAI_PROXY_KEY',
+ headers: {
+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
+ 'x-cindy-pi-provider-id': 'openai',
+ },
+ models: [{
+ id: 'chatgpt/gpt-cindy-daily-test',
+ wireId: 'gpt-cindy-daily-test',
+ catalogAddition: true,
+ contextWindow: 272_000,
+ maxTokens: 32_000,
+ }],
+ }],
+ env: { CINDY_PI_OPENAI_PROXY_KEY: placeholderJwt },
+ });
+ const agent = new PiAgent(deps);
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-agent-native-codex-cwd-'));
+ let handle: AgentSessionHandle | null = null;
+ const requestsBefore = seenRequests.length;
+ scriptedResponses.push(responsesStreamBody('pong from native codex', 'gpt-cindy-daily-test'));
+ try {
+ handle = await agent.startSession({
+ sessionId: 'itest-native-codex-session',
+ workingDir,
+ model: 'chatgpt/gpt-cindy-daily-test',
+ providerId: 'openai',
+ effort: 'high',
+ });
+ 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 native codex' });
+ await collected;
+
+ const nativeRequests = seenRequests.slice(requestsBefore);
+ expect(nativeRequests.some((request) => request.url === '/codex/responses')).toBe(true);
+ expect(nativeRequests.some((request) => request.url === '/v1/messages')).toBe(false);
+ expect(events.some((event) =>
+ event.type === 'text'
+ && (event.data as { text?: string }).text?.includes('pong from native codex'),
+ )).toBe(true);
+ } finally {
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it(
+ 'uses PI native Anthropic Messages for a host Claude subscription model',
+ { timeout: 60_000 },
+ async () => {
+ const deps = buildDeps();
+ deps.capabilityAdditions = {
+ ...deps.capabilityAdditions,
+ availableModels: [
+ ...(deps.capabilityAdditions?.availableModels ?? []),
+ {
+ id: 'claude-opus-5',
+ displayName: 'Claude Opus 5',
+ contextWindow: 1_000_000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ },
+ ],
+ };
+ deps.resolvePiNativeProviders = async () => ({
+ providers: [{
+ id: 'anthropic',
+ sourceProviderId: 'anthropic',
+ name: 'Anthropic',
+ baseUrl: endpoint,
+ inheritModels: true,
+ headers: {
+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
+ 'x-cindy-pi-provider-id': 'anthropic',
+ },
+ models: [{ id: 'claude-opus-5', wireId: 'claude-opus-5' }],
+ }],
+ env: {},
+ });
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-agent-native-anthropic-cwd-'));
+ let handle: AgentSessionHandle | null = null;
+ const requestsBefore = seenRequests.length;
+ scriptedResponses.push(anthropicStreamBody('pong from native anthropic'));
+ try {
+ handle = await new PiAgent(deps).startSession({
+ sessionId: 'itest-native-anthropic-session',
+ workingDir,
+ model: 'claude-opus-5',
+ providerId: 'anthropic',
+ effort: 'high',
+ });
+ const collected = (async () => {
+ for await (const event of handle!.events()) {
+ if (event.type === 'done') break;
+ }
+ })();
+
+ await handle.send({ type: 'user', content: 'ping native anthropic' });
+ await collected;
+
+ expect(seenRequests.slice(requestsBefore)).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ url: '/v1/messages',
+ providerId: 'anthropic',
+ }),
+ ]));
+ } finally {
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ },
+ );
+
+ it(
+ 'uses PI bundled xAI APIs as the baseline for Responses and Chat Completions models',
+ { timeout: 60_000 },
+ async () => {
+ const deps = buildDeps();
+ deps.capabilityAdditions = {
+ ...deps.capabilityAdditions,
+ availableModels: [
+ ...(deps.capabilityAdditions?.availableModels ?? []),
+ {
+ id: 'xai/grok-4.5', displayName: 'Grok 4.5', contextWindow: 1_000_000,
+ efforts: ['high'], defaultEffort: 'high',
+ },
+ {
+ id: 'xai/grok-build-0.1', displayName: 'Grok Build', contextWindow: 256_000,
+ efforts: [], defaultEffort: null,
+ },
+ ],
+ };
+ deps.resolvePiNativeProviders = async () => ({
+ providers: [{
+ id: 'xai',
+ sourceProviderId: 'xai',
+ name: 'xAI (SuperGrok)',
+ baseUrl: `${endpoint}/v1`,
+ inheritModels: true,
+ headers: {
+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',
+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',
+ 'x-cindy-pi-provider-id': 'xai',
+ },
+ models: [
+ { id: 'xai/grok-4.5', wireId: 'grok-4.5' },
+ { id: 'xai/grok-build-0.1', wireId: 'grok-build-0.1' },
+ ],
+ }],
+ env: {},
+ });
+ const agent = new PiAgent(deps);
+
+ const run = async (
+ sessionId: string,
+ model: string,
+ response: string,
+ expectedPath: string,
+ ): Promise<void> => {
+ const workingDir = mkdtempSync(path.join(tmpdir(), 'pi-agent-native-xai-cwd-'));
+ let handle: AgentSessionHandle | null = null;
+ const requestsBefore = seenRequests.length;
+ scriptedResponses.push(response);
+ try {
+ handle = await agent.startSession({
+ sessionId,
+ workingDir,
+ model,
+ providerId: 'xai',
+ ...(model.endsWith('grok-4.5') ? { effort: 'high' as const } : {}),
+ });
+ const collected = (async () => {
+ for await (const event of handle!.events()) {
+ if (event.type === 'done') break;
+ }
+ })();
+ await handle.send({ type: 'user', content: 'ping native xai' });
+ await collected;
+ const requests = seenRequests.slice(requestsBefore);
+ expect(requests.some((request) => request.url === expectedPath)).toBe(true);
+ expect(requests.some((request) => request.url === '/v1/messages')).toBe(false);
+ } finally {
+ await handle?.close();
+ rmSync(workingDir, { recursive: true, force: true });
+ }
+ };
+
+ await run(
+ 'itest-native-xai-responses',
+ 'xai/grok-4.5',
+ responsesStreamBody('pong from xai responses', 'grok-4.5'),
+ '/v1/responses',
+ );
+ await run(
+ 'itest-native-xai-completions',
+ 'xai/grok-build-0.1',
+ chatCompletionsStreamBody('pong from xai completions', 'grok-build-0.1'),
+ '/v1/chat/completions',
+ );
+ },
+ );
+
it(
'accepts a turn permission policy in ask, rejects it in Full Access, and honors steer cancellation before RPC',
{ timeout: 60_000 },
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 495d892550..cca40066a5 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
@@ -203,6 +203,129 @@ describe('Pi provider-aware model routing', () => {
await nativeHandle.close();
});
+ it('routes host subscriptions through PI native providers and wire model ids', async () => {
+ const authProviderIds: Array<string | null | undefined> = [];
+ const availableModels: ModelDescriptor[] = [
+ {
+ id: 'chatgpt/gpt-cindy-daily-test', displayName: 'GPT Daily', contextWindow: 272_000,
+ efforts: ['low', 'high'], defaultEffort: 'high',
+ },
+ {
+ id: 'xai/grok-4.5', displayName: 'Grok 4.5', contextWindow: 1_000_000,
+ efforts: ['high'], defaultEffort: 'high',
+ },
+ {
+ id: 'xai/grok-4.20', displayName: 'Grok 4.20', contextWindow: 1_000_000,
+ efforts: ['high'], defaultEffort: 'high',
+ },
+ {
+ id: 'claude-opus-5', displayName: 'Claude Opus 5', contextWindow: 1_000_000,
+ efforts: ['high'], defaultEffort: 'high',
+ },
+ ];
+ const deps: AgentDeps = {
+ auth: {
+ getState: async (options) => {
+ authProviderIds.push(options?.providerId);
+ return { authenticated: true, identity: 'test', authSource: 'oauth' as const };
+ },
+ triggerLogin: async () => ({ authenticated: true }),
+ logout: async () => {},
+ getAuthEnv: async () => ({}),
+ },
+ runtimeConfig: { endpoint: 'http://127.0.0.1:9988' },
+ binaryPath: path.join(agentHome, 'pi'),
+ logger: noopLogger,
+ capabilityAdditions: { availableModels },
+ resolvePiAgentHome: () => agentHome,
+ resolvePiGatewayModelApi: () => 'openai-responses',
+ resolvePiNativeProviders: async () => ({
+ providers: [
+ {
+ id: 'anthropic', sourceProviderId: 'anthropic', name: 'Anthropic',
+ baseUrl: 'http://127.0.0.1:9988', inheritModels: true,
+ models: [{ id: 'claude-opus-5', wireId: 'claude-opus-5' }],
+ },
+ {
+ id: 'openai-codex', sourceProviderId: 'openai', name: 'OpenAI',
+ baseUrl: 'http://127.0.0.1:9988', inheritModels: true,
+ apiKeyEnvVar: 'CINDY_PI_OPENAI_PROXY_KEY',
+ models: [{
+ id: 'chatgpt/gpt-cindy-daily-test',
+ wireId: 'gpt-cindy-daily-test',
+ catalogAddition: true,
+ contextWindow: 272_000,
+ maxTokens: 32_000,
+ }],
+ },
+ {
+ id: 'xai', sourceProviderId: 'xai', name: 'xAI',
+ baseUrl: 'http://127.0.0.1:9988/v1', inheritModels: true,
+ models: [
+ { id: 'xai/grok-4.5', wireId: 'grok-4.5' },
+ {
+ id: 'xai/grok-4.20', wireId: 'grok-4.20', api: 'openai-responses',
+ contextWindow: 1_000_000, maxTokens: 64_000,
+ cost: { input: 2, output: 6, cacheRead: 0.3, cacheWrite: 0 },
+ compat: { supportsStrictTools: true },
+ },
+ ],
+ },
+ ],
+ env: { CINDY_PI_OPENAI_PROXY_KEY: 'placeholder-jwt' },
+ }),
+ };
+
+ const handle = await new PiAgent(deps).startSession({
+ sessionId: 'native-subscription-routing',
+ workingDir: cwd,
+ model: 'chatgpt/gpt-cindy-daily-test',
+ providerId: 'openai',
+ effort: 'high',
+ });
+
+ expect(authProviderIds).toEqual(['openai']);
+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 4))
+ .toEqual(['--provider', 'openai-codex', '--model', 'gpt-cindy-daily-test']);
+ const configHome = captured.env.PI_CODING_AGENT_DIR as string;
+ const models = JSON.parse(readFileSync(path.join(configHome, 'models.json'), 'utf8')) as {
+ providers: Record<string, { api?: string; models?: Array<{ id: string; api?: string }> }>;
+ };
+ expect(models.providers.anthropic).not.toHaveProperty('api');
+ expect(models.providers.anthropic?.models).toBeUndefined();
+ expect(models.providers['openai-codex']).not.toHaveProperty('api');
+ expect(models.providers['openai-codex']?.models).toEqual([
+ expect.objectContaining({ id: 'gpt-cindy-daily-test' }),
+ ]);
+ expect(models.providers['openai-codex']?.models?.[0]).not.toHaveProperty('api');
+ expect(models.providers.xai).not.toHaveProperty('api');
+ expect(models.providers.xai?.models).toEqual([
+ expect.objectContaining({
+ id: 'grok-4.20',
+ api: 'openai-responses',
+ cost: { input: 2, output: 6, cacheRead: 0.3, cacheWrite: 0 },
+ compat: { supportsStrictTools: true },
+ }),
+ ]);
+ expect(JSON.parse(readFileSync(path.join(configHome, 'settings.json'), 'utf8')))
+ .toEqual({ transport: 'sse' });
+ expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'native-subscription-routing'), 'utf8')))
+ .toEqual({ model: 'gpt-cindy-daily-test', provider: 'openai-codex' });
+
+ await handle.setModel!('xai/grok-4.5', { providerId: 'xai' });
+ expect(captured.requests).toContainEqual({
+ type: 'set_model', provider: 'xai', modelId: 'grok-4.5',
+ });
+ expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'native-subscription-routing'), 'utf8')))
+ .toEqual({ model: 'grok-4.5', provider: 'xai' });
+
+ await handle.setModel!('claude-opus-5', { providerId: 'anthropic' });
+ expect(captured.requests).toContainEqual({
+ type: 'set_model', provider: 'anthropic', modelId: 'claude-opus-5',
+ });
+ await handle.close();
+ });
+
it('keeps built-in gateway reasoning when a same-id non-reasoning BYOM empties the flat effort intersection', async () => {
const resolver = vi.fn((_providerId: string | null | undefined, modelId: string) => {
if (modelId !== 'shared-model') return null;
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index be43e58b86..b18ff9e9cd 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -749,27 +749,43 @@ export class PiAgent extends BaseAgent {
this.deps.logger.warn('pi: native provider id collides with gateway provider "cindy" — skipped', { id: np.id });
continue;
}
- providers[np.id] = {
- name: np.name,
- baseUrl: np.baseUrl,
- api: np.api,
- // keyless(本机 Ollama 等)也要给 dummy key,否则 pi /model 不显示该模型。
- apiKey: np.apiKeyEnvVar ? `$${np.apiKeyEnvVar}` : 'pi-native-keyless',
- ...(np.headers && Object.keys(np.headers).length > 0 ? { headers: np.headers } : {}),
- models: np.models.map((m) => ({
- id: m.id,
+ const nativeModels = (np.inheritModels
+ ? np.models.filter((model) => model.api !== undefined || model.catalogAddition === true)
+ : np.models).map((m) => ({
+ id: m.wireId ?? m.id,
name: m.name ?? m.id,
+ ...(m.api ? { api: m.api } : {}),
+ ...(m.baseUrl ? { baseUrl: m.baseUrl } : {}),
reasoning: m.reasoning ?? false,
...(m.thinkingLevelMap ? { thinkingLevelMap: { ...m.thinkingLevelMap } } : {}),
input: m.input ?? ['text'],
contextWindow: m.contextWindow && m.contextWindow > 0 ? m.contextWindow : 128_000,
maxTokens: m.maxTokens && m.maxTokens > 0 ? m.maxTokens : 16_000,
- })),
+ ...(m.cost ? { cost: { ...m.cost } } : {}),
+ ...(m.headers ? { headers: { ...m.headers } } : {}),
+ ...(m.compat ? { compat: structuredClone(m.compat) } : {}),
+ }));
+ if (!np.inheritModels && !np.api) {
+ throw new Error(`pi: native provider '${np.id}' has no default api`);
+ }
+ providers[np.id] = {
+ name: np.name,
+ baseUrl: np.baseUrl,
+ ...(np.api ? { api: np.api } : {}),
+ // keyless(本机 Ollama 等)也要给 dummy key,否则 pi /model 不显示该模型。
+ apiKey: np.apiKeyEnvVar ? `$${np.apiKeyEnvVar}` : 'pi-native-keyless',
+ ...(np.headers && Object.keys(np.headers).length > 0 ? { headers: np.headers } : {}),
+ ...(nativeModels.length > 0 ? { models: nativeModels } : {}),
};
}
const modelsJsonPath = joinRemotePosixPath(agentHome, 'models.json');
const modelsJsonContent = JSON.stringify({ providers }, null, 2) + '\n';
const modelsJsonHash = createHash('sha256').update(modelsJsonContent).digest('hex');
+ const settingsJsonPath = joinRemotePosixPath(agentHome, 'settings.json');
+ // The native ChatGPT adapter prefers WebSocket in auto mode. Cindy's
+ // authenticated loopback proxy is an HTTP/SSE boundary, so pin SSE for the
+ // isolated embedded runtime. Other PI providers ignore this transport knob.
+ const settingsJsonContent = JSON.stringify({ transport: 'sse' }, null, 2) + '\n';
if (!opts.preview) {
// 诊断(排查 LAZY_CREATE_FAILED):远端写前留痕 —— 确认 writeModelsJson 是否
// 执行、endpoint 是否有值、路径形态。
@@ -784,12 +800,14 @@ export class PiAgent extends BaseAgent {
await opts.fileOps.mkdirp(agentHome);
// fileOps 远端写入内部已 umask 077(创建即 600,无 TOCTOU —— R5 H-1)。
await opts.fileOps.writeFile(modelsJsonPath, modelsJsonContent);
+ await opts.fileOps.writeFile(settingsJsonPath, settingsJsonContent);
this.deps.logger.info?.('pi writeModelsJson done', { modelsJsonPath });
} else {
await fs.mkdir(agentHome, { recursive: true });
// 控制面文件:显式 600,防同机其他用户读 BYOM baseUrl / provider 路由
// (R5 安全审计 H-5)。
await fs.writeFile(modelsJsonPath, modelsJsonContent, { mode: 0o600 });
+ await fs.writeFile(settingsJsonPath, settingsJsonContent, { mode: 0o600 });
}
}
return {
@@ -840,6 +858,13 @@ export class PiAgent extends BaseAgent {
.filter((provider) => provider.id !== PI_PROVIDER_ID)
.map((provider) => [provider.id, provider] as const),
);
+ const nativeProviderBySourceId = new Map(
+ nativeProviders
+ .filter((provider) => provider.id !== PI_PROVIDER_ID)
+ .map((provider) => [provider.sourceProviderId ?? provider.id, provider] as const),
+ );
+ const nativeProviderForSource = (providerId: string): PiNativeProviderSpec | undefined =>
+ nativeProviderBySourceId.get(providerId) ?? nativeProviderById.get(providerId);
// providerId 是模型来源的主键;同名模型可同时存在于 Cindy 网关和多个 BYOM provider。
// 三态语义(与 session-provider-store 对齐):
// - 显式 BYOM id → 该 native provider(经上面的 model-combo fail-closed 校验);
@@ -852,7 +877,7 @@ export class PiAgent extends BaseAgent {
providerId?: string | null,
): string => {
if (providerId) {
- const native = nativeProviderById.get(providerId);
+ const native = nativeProviderForSource(providerId);
return native?.models.some((candidate) => candidate.id === model)
? native.id
: PI_PROVIDER_ID;
@@ -860,9 +885,21 @@ export class PiAgent extends BaseAgent {
if (providerId === null) return PI_PROVIDER_ID;
return nativeProviders.find(
(provider) => provider.id !== PI_PROVIDER_ID
+ && (
+ provider.sourceProviderId === undefined
+ || (provider.sourceProviderId === 'openai' && model.startsWith('chatgpt/'))
+ || (provider.sourceProviderId === 'xai' && model.startsWith('xai/'))
+ )
&& provider.models.some((candidate) => candidate.id === model),
)?.id ?? PI_PROVIDER_ID;
};
+ const resolveWireModel = (providerId: string, model: string): string =>
+ nativeProviderById
+ .get(providerId)
+ ?.models.find((candidate) => candidate.id === model)
+ ?.wireId ?? model;
+ const resolveSourceProvider = (providerId: string): string =>
+ nativeProviderById.get(providerId)?.sourceProviderId ?? providerId;
// 显式 BYOM 路由必须 fail closed:当调用方钉了一个既非 Cindy 网关(cindy/xd)也非
// 订阅直连(openai/anthropic/xai)的自定义/本地 provider 时,该来源必须在本次解析出的
// nativeProviders 里。若原生解析失败(配置/safeStorage 暂时读不到)或该 provider 缺席,
@@ -883,7 +920,7 @@ export class PiAgent extends BaseAgent {
): providerId is string => {
if (!providerId || NON_BYOM_PROVIDER_IDS.has(providerId)) return false;
if (resolveFailed) return true;
- const native = nativeProviderById.get(providerId);
+ const native = nativeProviderForSource(providerId);
return !native || !native.models.some((candidate) => candidate.id === model);
};
if (explicitByomUnresolvable(opts.providerId, opts.model, nativeResolveFailed)) {
@@ -919,13 +956,14 @@ export class PiAgent extends BaseAgent {
}
}
}
+ const initialWireModel = resolveWireModel(initialProvider, opts.model);
// 先解析 native provider 再做 auth:老会话/远端控制端可能没有持久化 providerId,
// 仍必须能从 model→provider 映射识别纯 BYOM,不能误落 Cindy gateway 登录门。
// startup effort 快照也使用同一来源,因此必须在快照 resolver 之前完成初始化。
const authProviderId =
opts.providerId ??
(initialProvider !== PI_PROVIDER_ID
- ? initialProvider
+ ? resolveSourceProvider(initialProvider)
: opts.model.startsWith('chatgpt/')
? 'openai'
: opts.model.startsWith('xai/')
@@ -941,7 +979,7 @@ export class PiAgent extends BaseAgent {
);
const runtimeProviderId =
opts.providerId === undefined && initialProvider !== PI_PROVIDER_ID
- ? initialProvider
+ ? resolveSourceProvider(initialProvider)
: opts.providerId;
const mayResolveRuntimeModel = publicRuntimeModel !== undefined || !!opts.resumeSessionId;
const selectedRuntimeModel = mayResolveRuntimeModel
@@ -1406,7 +1444,7 @@ export class PiAgent extends BaseAgent {
// 但文件缺失让扩展 fail-closed(不派发);后续每次 setModel 都会重试写
// (writeSubagentRuntimeFile 由 subagentRuntimeWriteChain 串行), 文件恢复
// 可写即自动恢复。
- if (subagentRoutingEnabled && !(await writeSubagentRuntimeFile({ model: opts.model, provider: initialProvider }))) {
+ if (subagentRoutingEnabled && !(await writeSubagentRuntimeFile({ model: initialWireModel, provider: initialProvider }))) {
this.deps.logger.warn('pi subagent initial runtime snapshot write failed — routing stays enabled, will retry on next model set', {
sessionId: opts.sessionId,
});
@@ -1594,7 +1632,7 @@ export class PiAgent extends BaseAgent {
'--no-extensions',
'--session-dir', sessionDir,
'--provider', initialProvider,
- '--model', opts.model,
+ '--model', initialWireModel,
...(reviewMode ? ['--tools', 'read,grep,find,ls'] : []),
...(appendSystemPrompt.length > 0 ? ['--append-system-prompt', appendSystemPrompt] : []),
'--extension', bridgeExtensionPath,
@@ -1612,6 +1650,7 @@ export class PiAgent extends BaseAgent {
// follow-up send)同口径。清空只认 turn 终态,由 send 预检覆盖为最新值。
let activeTurnPermissionPolicy: TurnPermissionPolicy | null = null;
let mutableModel = opts.model;
+ let mutableWireModel = initialWireModel;
// Pi RPC 实际选中的 provider。与用于宿主鉴权/审阅元数据的 mutableProviderId 分开:
// null/订阅来源会归一到 cindy,setModel 未显式传来源时也必须跟随本次解析结果。
let mutablePiProviderId = initialProvider;
@@ -2268,6 +2307,7 @@ export class PiAgent extends BaseAgent {
);
}
const provider = resolveProviderForModel(model, requestedProviderId);
+ const wireModel = resolveWireModel(provider, model);
if (provider === PI_PROVIDER_ID) {
const routeProviderId = requestedProviderId !== undefined
? requestedProviderId
@@ -2318,8 +2358,8 @@ export class PiAgent extends BaseAgent {
// 所以这一步落的是**带 pending 标记的**新路由:内容已经就位(证明可写、内容可回滚),但
// 扩展见到 `pending: true` 就拒绝派发。等待窗口里一个子进程都起不来,既不会用未确认的新
// 路由、也不会用与父不一致的旧路由;确认后再清掉标记放行。
- const previousSnapshot = { model: mutableModel, provider: mutablePiProviderId };
- if (!(await writeSubagentRuntimeFile({ model, provider, pending: true }))) {
+ const previousSnapshot = { model: mutableWireModel, provider: mutablePiProviderId };
+ if (!(await writeSubagentRuntimeFile({ model: wireModel, provider, pending: true }))) {
throw new Error(
'pi: 无法持久化子代理路由快照,已取消本次模型切换(避免父会话切到新 provider 而子代理仍按旧路由派发)。'
+ '请检查运行目录是否可写后重试。',
@@ -2327,7 +2367,7 @@ export class PiAgent extends BaseAgent {
}
let resp;
try {
- resp = await proc.request({ type: 'set_model', provider, modelId: model });
+ resp = await proc.request({ type: 'set_model', provider, modelId: wireModel });
} catch (err) {
// RPC **reject / 超时 / 写 stdin 失败 / 进程已退出**:与 `success:false` 有本质区别 ——
// 那种情况我们**知道**没生效,可以回滚;这里我们**不知道** pi 侧到底切没切。
@@ -2396,13 +2436,14 @@ export class PiAgent extends BaseAgent {
// pi 已确认 → 清掉 pending 标记放行派发。写失败时**不**抛错:模型切换本身确实成功了,
// 谎报失败会让上层与 UI 状态和 pi 真实状态背离。代价是这个会话的子代理一直被 pending
// 挡住(可见的降级、拒绝时有明确文案),而它是安全方向 —— 绝不会把委派发到错误 endpoint。
- if (!(await writeSubagentRuntimeFile({ model, provider }))) {
+ if (!(await writeSubagentRuntimeFile({ model: wireModel, provider }))) {
deps.logger.error(
'pi: model switch confirmed but the subagent routing snapshot stayed pending; '
+ 'subagent delegation stays disabled for this session (fail-closed)',
);
}
mutableModel = model;
+ mutableWireModel = wireModel;
mutablePiProviderId = provider;
activeEffortSnapshot = nextEffortSnapshot;
if (setOpts && Object.hasOwn(setOpts, 'providerId')) {
diff --git a/packages/model-providers/catalog/providers.json b/packages/model-providers/catalog/providers.json
index 067e5889a1..7d0faea65e 100644
--- a/packages/model-providers/catalog/providers.json
+++ b/packages/model-providers/catalog/providers.json
@@ -78,6 +78,7 @@
{
"id": "xai/grok-4.20-multi-agent-0309",
"name": "Grok 4.20 Multi-Agent",
+ "piApi": "openai-responses",
"group": "grok",
"sortOrder": 52,
"description": "xAI Grok 4.20 multi-agent model,1M 上下文(SuperGrok 订阅直连)",
@@ -90,6 +91,7 @@
{
"id": "xai/grok-4.20-0309-reasoning",
"name": "Grok 4.20 Reasoning",
+ "piApi": "openai-responses",
"group": "grok",
"sortOrder": 53,
"description": "xAI Grok 4.20 reasoning model,1M 上下文(SuperGrok 订阅直连)",
@@ -102,6 +104,7 @@
{
"id": "xai/grok-4.20-0309-non-reasoning",
"name": "Grok 4.20 Non-Reasoning",
+ "piApi": "openai-responses",
"group": "grok",
"sortOrder": 54,
"description": "xAI Grok 4.20 non-reasoning model,1M 上下文(SuperGrok 订阅直连)",
@@ -114,6 +117,7 @@
{
"id": "xai/grok-4.20",
"name": "Grok 4.20 Legacy Alias",
+ "piApi": "openai-responses",
"group": "grok",
"sortOrder": 98,
"description": "旧版兼容 alias;新会话请使用明确的 Grok 4.20 model ID",
@@ -126,6 +130,7 @@
{
"id": "xai/grok-code-fast",
"name": "Grok Code Fast (Deprecated)",
+ "piApi": "openai-completions",
"group": "grok",
"sortOrder": 99,
"description": "旧版兼容 alias;新会话请使用 grok-build-0.1",
@@ -312,6 +317,25 @@
}
],
"modelsUrl": "https://api.deepseek.com/models"
+ },
+ "pi": {
+ "baseUrl": "https://api.deepseek.com",
+ "wireProtocol": "openai-responses",
+ "models": [
+ {
+ "id": "deepseek-v4-flash",
+ "name": "DeepSeek V4 Flash",
+ "contextWindow": 1000000,
+ "piApi": "openai-responses"
+ },
+ {
+ "id": "deepseek-v4-pro",
+ "name": "DeepSeek V4 Pro",
+ "contextWindow": 1000000,
+ "piApi": "openai-responses"
+ }
+ ],
+ "modelsUrl": "https://api.deepseek.com/models"
}
}
},
diff --git a/packages/model-providers/src/__tests__/catalog.test.ts b/packages/model-providers/src/__tests__/catalog.test.ts
index 6516d1cdad..9052fd3c77 100644
--- a/packages/model-providers/src/__tests__/catalog.test.ts
+++ b/packages/model-providers/src/__tests__/catalog.test.ts
@@ -171,6 +171,25 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
expect(() => parseCatalog(bad)).toThrow(/icon/);
});
+ it('accepts the four portable piApi values and rejects unknown PI protocols', () => {
+ for (const piApi of [
+ 'anthropic-messages',
+ 'openai-responses',
+ 'openai-completions',
+ 'google-generative-ai',
+ ] as const) {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ catalog.providers.find((provider) => provider.id === 'xai')!
+ .models['claude-code']![0]!.piApi = piApi;
+ expect(() => parseCatalog(catalog)).not.toThrow();
+ }
+
+ const bad = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ (bad.providers.find((provider) => provider.id === 'xai')!
+ .models['claude-code']![0] as unknown as Record<string, unknown>).piApi = 'claude-v1';
+ expect(() => parseCatalog(bad)).toThrow(/piApi/);
+ });
+
it('ships custom-provider presets (OSS 热更的第三方模板)', () => {
const presets = BUNDLED_CATALOG.presets ?? [];
expect(presets.length).toBeGreaterThan(0);
@@ -195,6 +214,13 @@ describe('bundled catalog validity (dynamic-first contract)', () => {
openrouter?.runtimes['claude-code']?.models.find((m) => m.id === 'deepseek/deepseek-v4-pro')
?.contextWindow,
).toBe(1_000_000);
+ expect(deepseek?.runtimes.pi).toMatchObject({
+ wireProtocol: 'openai-responses',
+ models: [
+ { id: 'deepseek-v4-flash', piApi: 'openai-responses' },
+ { id: 'deepseek-v4-pro', piApi: 'openai-responses' },
+ ],
+ });
});
it('Kimi Code(编程计划)预设的每个模型都带 contextWindow(k3 缺失曾回落 200K)', () => {
diff --git a/packages/model-providers/src/__tests__/presets.test.ts b/packages/model-providers/src/__tests__/presets.test.ts
index 9c3fe6e1a5..3db1c5aa68 100644
--- a/packages/model-providers/src/__tests__/presets.test.ts
+++ b/packages/model-providers/src/__tests__/presets.test.ts
@@ -45,6 +45,31 @@ const VALID_PRESET = {
};
describe('sanitizePresets', () => {
+ it('preserves valid per-model piApi only for supported PI protocol names', () => {
+ const valid = {
+ ...VALID_PRESET,
+ id: 'pi-api',
+ runtimes: {
+ pi: {
+ baseUrl: 'https://example.com/v1',
+ wireProtocol: 'openai-responses',
+ models: [{ id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro', piApi: 'openai-responses' }],
+ },
+ },
+ };
+ expect(sanitizePresets([valid])).toEqual([valid]);
+ expect(sanitizePresets([{
+ ...valid,
+ id: 'bad-pi-api',
+ runtimes: {
+ pi: {
+ ...valid.runtimes.pi,
+ models: [{ id: 'x', name: 'X', piApi: 'claude-v1' }],
+ },
+ },
+ }])).toEqual([]);
+ });
+
it('accepts explicit Pi reasoning metadata and rejects ambiguous capability declarations', () => {
const piReasoning = {
...VALID_PRESET,
diff --git a/packages/model-providers/src/builtin.ts b/packages/model-providers/src/builtin.ts
index ca6be02e9a..2d6e0fac5b 100644
--- a/packages/model-providers/src/builtin.ts
+++ b/packages/model-providers/src/builtin.ts
@@ -25,7 +25,7 @@ import catalogJson from '../catalog/providers.json' with { type: 'json' };
import modelRegistryJson from '../catalog/model-registry.json' with { type: 'json' };
import type { ModelRegistry } from './modelAccessBean.js';
-import type { Catalog, Provider } from './types.js';
+import type { Catalog, CatalogModel, Provider } from './types.js';
/** 仓内 v2 目录文件(xai 清单 + presets;同一文件发布到 OSS `cfg/providers.json`)。 */
const catalogFile = catalogJson as unknown as Catalog;
@@ -64,6 +64,14 @@ if (!xaiRaw) {
throw new Error('[model-providers] catalog/providers.json missing builtin provider "xai"');
}
const xaiFromCatalog = withVerifiedStaticWindows(xaiRaw);
+const withoutPiApi = (model: CatalogModel): CatalogModel => {
+ if (model.piApi === undefined) return model;
+ const rest = { ...model };
+ delete rest.piApi;
+ return rest;
+};
+const xaiClaudeModels = xaiFromCatalog.models['claude-code'] ?? [];
+const xaiCodexModels = xaiFromCatalog.models.codex ?? [];
/** xAI 静态清单同时供 Claude bridge、Codex 与 Pi bridge 使用。 */
const XAI_PROVIDER: Provider = {
@@ -77,7 +85,11 @@ const XAI_PROVIDER: Provider = {
},
models: {
...xaiFromCatalog.models,
- pi: xaiFromCatalog.models.pi ?? xaiFromCatalog.models['claude-code'] ?? [],
+ 'claude-code': xaiClaudeModels.map(withoutPiApi),
+ codex: xaiCodexModels.map(withoutPiApi),
+ // providers.json 的 piApi 只属于 Pi;源文件仍与 xAI 静态根同表维护,
+ // bundled 投影在这里拆开,避免协议注解污染 Claude/Codex 快照契约。
+ pi: xaiFromCatalog.models.pi ?? xaiClaudeModels,
},
};
diff --git a/packages/model-providers/src/catalog.ts b/packages/model-providers/src/catalog.ts
index 70447c2469..f4e9b6288e 100644
--- a/packages/model-providers/src/catalog.ts
+++ b/packages/model-providers/src/catalog.ts
@@ -10,7 +10,7 @@
import { parseModelRegistry } from './modelAccessValidator.js';
-import { PI_REASONING_EFFORTS } from './types.js';
+import { PI_MODEL_APIS, PI_REASONING_EFFORTS } from './types.js';
import type {
Catalog,
Provider,
@@ -42,6 +42,10 @@ function isEffort(v: unknown): v is Effort {
return typeof v === 'string' && (EFFORTS as readonly string[]).includes(v);
}
+function isPiModelApi(v: unknown): boolean {
+ return typeof v === 'string' && (PI_MODEL_APIS as readonly string[]).includes(v);
+}
+
function hasValidPresetReasoningCapability(
agent: AgentKind,
model: Record<string, unknown>,
@@ -85,6 +89,9 @@ function validateAccess(p: Provider): void {
function validateModel(m: CatalogModel, providerId: string): void {
assert(typeof m.id === 'string' && m.id.length > 0, `model.id missing in provider '${providerId}'`);
assert(typeof m.name === 'string' && m.name.length > 0, `model.name missing for '${m.id}'`);
+ if (m.piApi !== undefined) {
+ assert(isPiModelApi(m.piApi), `model.piApi invalid for '${m.id}'`);
+ }
assert(typeof m.contextWindow === 'number' && m.contextWindow > 0, `model.contextWindow invalid for '${m.id}'`);
assert(Array.isArray(m.efforts), `model.efforts must be array for '${m.id}'`);
assert(m.efforts.every(isEffort), `model.efforts has invalid value for '${m.id}'`);
@@ -413,6 +420,7 @@ function isValidPreset(v: unknown): v is ProviderPreset {
const mm = m as Record<string, unknown>;
if (typeof mm.id !== 'string' || mm.id.length === 0) return false;
if (typeof mm.name !== 'string' || mm.name.length === 0) return false;
+ if (mm.piApi !== undefined && !isPiModelApi(mm.piApi)) return false;
if (
mm.contextWindow !== undefined
&& (typeof mm.contextWindow !== 'number' || !Number.isFinite(mm.contextWindow) || mm.contextWindow <= 0)
diff --git a/packages/model-providers/src/index.ts b/packages/model-providers/src/index.ts
index 28c89d8b28..349195924f 100644
--- a/packages/model-providers/src/index.ts
+++ b/packages/model-providers/src/index.ts
@@ -25,6 +25,7 @@ export type {
CustomProviderRuntimeConfig,
ProviderRuntimeModelConfig,
PiReasoningEffort,
+ PiModelApi,
ProviderPreset,
ProviderPresetRuntime,
PresetSortRegion,
@@ -33,7 +34,7 @@ export type {
OAuthProviderDescriptor,
} from './types.js';
-export { PI_REASONING_EFFORTS } from './types.js';
+export { PI_MODEL_APIS, PI_REASONING_EFFORTS } from './types.js';
export { resolveCodexCompatibilityWireProtocol } from './codexCompatibility.js';
diff --git a/packages/model-providers/src/types.ts b/packages/model-providers/src/types.ts
index 2b8851e5b2..b24b3107ab 100644
--- a/packages/model-providers/src/types.ts
+++ b/packages/model-providers/src/types.ts
@@ -29,6 +29,19 @@ export type Effort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max' | '
export const PI_REASONING_EFFORTS = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const;
export type PiReasoningEffort = (typeof PI_REASONING_EFFORTS)[number];
+/**
+ * PI models.json understands these four portable inference protocols. The
+ * provider-level wireProtocol remains the default for an endpoint; piApi is a
+ * sparse per-model override for newly released models or protocol corrections.
+ */
+export const PI_MODEL_APIS = [
+ 'anthropic-messages',
+ 'openai-responses',
+ 'openai-completions',
+ 'google-generative-ai',
+] as const;
+export type PiModelApi = (typeof PI_MODEL_APIS)[number];
+
/** Provider runtime 上游实际接受的推理 wire protocol。 */
export type ProviderWireProtocol =
| 'anthropic-messages'
@@ -223,6 +236,8 @@ export interface ModelCost {
export interface CatalogModel {
/** 与 maker-core 现有 model id 一致(如 'claude-opus-4-8' / 'gpt-5.5' / 'codex/gpt-5.5')。 */
id: string;
+ /** Sparse PI protocol override; absence means use PI's bundled model catalog. */
+ piApi?: PiModelApi;
/** 展示名(= maker-core ModelDescriptor.displayName)。 */
name: string;
description?: string;
@@ -475,6 +490,8 @@ export interface Provider {
export interface ProviderRuntimeModelConfig {
id: string;
name: string;
+ /** Per-model PI protocol override; provider wireProtocol remains the fallback. */
+ piApi?: PiModelApi;
contextWindow?: number;
/** 模型未被用户显式开关时的可见性;缺省保持历史行为(默认可见)。 */
defaultEnabled?: boolean;
diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.ts
index 8b8c44ca42..1d4647c0c4 100644
--- a/packages/model-providers/src/user-provider.ts
+++ b/packages/model-providers/src/user-provider.ts
@@ -64,6 +64,7 @@ function toCatalogModel(
return {
id: m.id,
name: m.name,
+ ...(agent === 'pi' && m.piApi ? { piApi: m.piApi } : {}),
contextWindow: m.contextWindow ?? DEFAULT_CUSTOM_CONTEXT_WINDOW,
// 用户自己填了才算显式声明;走 DEFAULT_CUSTOM_CONTEXT_WINDOW 兜底的不标记 ——
// 那是「仅用于展示」的保守默认,不能拿去收敛运行期上报的窗口。