Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): reserve bundled provider runtime ids
Chris00e88d6040ef
diff --cc apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.tsindex c265619bd7,b12fb7aadb..db5b4ed249--- a/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/activeCatalogDiscovery.test.ts@@@ -99,39 -103,112 +103,126 @@@ describe('active-catalog discovered augexpect(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')++ 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 通道', () => {+ it('SuperGrok fallback keeps namespaced roots but projects bare Pi ids', () => {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?.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');+ expect(xai?.routing.pi?.upstream).toBe('https://api.x.ai/v1');+ expect(xai?.models.pi?.map((model) => model.id)).toEqual([+ 'grok-4.3',+ 'grok-4.5',+ 'grok-4.6',+ 'grok-build-0.1',+ ]);+ expect(xai?.models.pi).not.toEqual(xai?.models['claude-code']);+ });++ it('xAI account snapshot is authoritative and projects canonical ids per harness', () => {+ setActiveCatalog(BUNDLED_CATALOG);- setXaiDiscoveredModels([- { id: 'xai/grok-4.5' },- { id: 'xai/grok-4.6' },- ]);++ setXaiDiscoveredModels([{ id: 'xai/grok-4.5' }, { id: 'xai/grok-4.6' }]);+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');+ expect(xai?.models['claude-code']?.map((model) => model.id)).toEqual([+ 'xai/grok-4.5',+ 'xai/grok-4.6',+ ]);- expect(xai?.models.codex?.map((model) => model.id)).toEqual([- 'xai/grok-4.5',- 'xai/grok-4.6',- ]);++ expect(xai?.models.codex?.map((model) => model.id)).toEqual(['xai/grok-4.5', 'xai/grok-4.6']);+ expect(xai?.models.pi?.map((model) => model.id)).toEqual(['grok-4.5', 'grok-4.6']);+ expect(xai?.models.pi?.find((model) => model.id === 'grok-4.6')).toMatchObject({+ contextWindow: 500_000,+ supportsImageInput: true,+ });+ });++ it('xAI successful empty snapshot stays empty and does not leak static membership', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setXaiDiscoveredModels([]);+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');+ expect(xai?.models['claude-code']).toEqual([]);+ expect(xai?.models.codex).toEqual([]);+ expect(xai?.models.pi).toEqual([]);+ });++ it('xAI 媒体发现按官方存在性收敛,静态同 id 保持 first-wins', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setDiscoveredProviderMediaModels('xai', {+ imageModels: [+ { id: 'xai/grok-imagine-image', name: 'Remote Rename Must Not Win' },+ { id: 'xai/future-image', name: 'Future Image' },+ ],+ videoModels: [{ id: 'xai/future-video', name: 'Future Video' }],+ });+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');+ expect(xai?.imageModels).toContainEqual({+ id: 'xai/grok-imagine-image',+ name: 'Grok Imagine Image',+ });+ expect(xai?.imageModels).toContainEqual({ id: 'xai/future-image', name: 'Future Image' });+ expect(xai?.videoModels).toContainEqual({ id: 'xai/future-video', name: 'Future Video' });+ expect(xai?.imageModels?.some((model) => model.id === 'xai/grok-imagine-image-quality')).toBe(+ false,+ );+ expect(xai?.videoModels?.some((model) => model.id === 'xai/grok-imagine-video')).toBe(false);+ });++ it('xAI 媒体发现不复活远端显式空清单', () => {+ const catalog = bundledWithoutRegistry();+ const xai = catalog.providers.find((provider) => provider.id === 'xai');+ if (!xai) throw new Error('fixture missing xai');+ xai.imageModels = [];+ xai.videoModels = [];+ setActiveCatalog(catalog);+ setDiscoveredProviderMediaModels('xai', {+ imageModels: [{ id: 'xai/future-image', name: 'Future Image' }],+ videoModels: [{ id: 'xai/future-video', name: 'Future Video' }],+ });+ const active = getActiveCatalog().providers.find((provider) => provider.id === 'xai');+ expect(active?.imageModels).toEqual([]);+ expect(active?.videoModels).toEqual([]);+ });++ it('xAI 媒体分类型更新时保留另一类上次成功快照', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setDiscoveredProviderMediaModels('xai', {+ imageModels: [{ id: 'xai/first-image', name: 'First Image' }],+ videoModels: [{ id: 'xai/first-video', name: 'First Video' }],+ });+ setDiscoveredProviderMediaModels('xai', {+ videoModels: [{ id: 'xai/second-video', name: 'Second Video' }],+ });+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');+ expect(xai?.imageModels).toEqual([{ id: 'xai/first-image', name: 'First Image' }]);+ expect(xai?.videoModels).toEqual([{ id: 'xai/second-video', name: 'Second Video' }]);+ });++ it('xAI 官方成功返回空清单时清掉该类旧型号', () => {+ setActiveCatalog(BUNDLED_CATALOG);+ setDiscoveredProviderMediaModels('xai', {+ imageModels: [],+ videoModels: [],+ });+ const xai = getActiveCatalog().providers.find((provider) => provider.id === 'xai');+ expect(xai?.imageModels).toEqual([]);+ expect(xai?.videoModels).toEqual([]);});it('bridge 投影剔除 max/ultra:codex 侧保留、claude-code 侧封顶 xhigh(issue #352)', () => {diff --cc apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.tsindex 6a8b801cb3,4a66cac45b..9d41a81f88--- a/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piByomNoCindyAuth.test.ts@@@ -19,13 -21,32 +21,37 @@@ vi.mock('../custom-provider-header-secrauth: { method: 'none' },runtimes: { pi: { baseUrl: 'http://127.0.0.1:11434/v1', models: [{ id: 'local-model' }] } },},+ {+ id: 'xai',+ name: 'Legacy custom xAI',+ auth: { method: 'apiKey' },+ runtimes: {+ pi: {+ baseUrl: 'https://private-xai.example/v1',+ models: [{ id: 'private-grok' }, { id: 'grok-4.6' }],+ },+ },+ },],}));- vi.mock('../../secrets/providerSecretStore.js', () => ({ readCustomProviderKey: () => null }));+ vi.mock('../../secrets/providerSecretStore.js', () => ({+ readCustomProviderKey: (providerId: string) =>+ providerId === 'xai' ? 'legacy-custom-key' : null,+ }));-vi.mock('../grok-oauth-login.js', () => ({ hasGrokOAuthLogin: () => grokOAuth.loggedIn }));++vi.mock('../grok-oauth-login.js', () => ({++ hasGrokOAuthLogin: () => grokOAuth.loggedIn,++ getGrokAccessToken: async () => 'grok-test-token',++ peekGrokAccessToken: () => (grokOAuth.loggedIn ? 'grok-test-token' : null),++ recoverGrokAuthAfterRejection: async () => 'superseded' as const,++}));- import { desktopPiAuthAdapter } from '../pi-host.js';+ import { desktopPiAuthAdapter, resolvePiNativeProviders } from '../pi-host.js';describe('Pi pure BYOM auth without a Cindy account', () => {+ beforeEach(() => {+ grokOAuth.loggedIn = false;+ });+it('authenticates the native provider and only uses an inert gateway placeholder', async () => {expect(await desktopPiAuthAdapter.getState({ providerId: 'local-keyless' })).toMatchObject({authenticated: true,@@@ -39,4 -60,57 +65,58 @@@errorReason: 'cindy_gateway_key_unavailable',});});++ it('keeps a legacy custom xai credential usable without a SuperGrok login', async () => {+ expect(await desktopPiAuthAdapter.getState({ providerId: 'custom:xai' })).toMatchObject({+ authenticated: true,+ identity: 'Legacy custom xAI',+ });+ expect(await desktopPiAuthAdapter.getState({ providerId: 'xai' })).toEqual({+ authenticated: false,+ errorReason: 'xai_oauth_unavailable',+ });+ });++ it('keeps an official xai resume on SuperGrok when a custom provider has the same model', async () => {+ grokOAuth.loggedIn = true;+ const resolved = await resolvePiNativeProviders({+ workingDir: '/tmp/project',+ providerId: 'xai',+ model: 'grok-4.6',+ resumeSessionId: '/tmp/pi/official-session.jsonl',+ });++ expect(resolved.providers).toContainEqual(+ expect.objectContaining({- id: 'xai',++ id: 'cindy-byom-xai',++ sourceProviderId: 'xai',+ baseUrl: expect.not.stringContaining('private-xai.example'),+ }),+ );+ expect(resolved.providers).toContainEqual(+ expect.objectContaining({+ id: 'custom:xai',+ baseUrl: 'https://private-xai.example/v1',+ }),+ );+ });++ it('restores a migrated custom:xai session from its saved endpoint after SuperGrok is connected', async () => {+ grokOAuth.loggedIn = true;+ const resolved = await resolvePiNativeProviders({+ workingDir: '/tmp/project',+ providerId: 'custom:xai',+ model: 'private-grok',+ resumeSessionId: '/tmp/pi/legacy-custom-session.jsonl',+ });++ expect(resolved.providers).toContainEqual(+ expect.objectContaining({+ id: 'custom:xai',+ baseUrl: 'https://private-xai.example/v1',+ models: expect.arrayContaining([expect.objectContaining({ id: 'private-grok' })]),+ }),+ );+ expect(Object.values(resolved.env)).toContain('legacy-custom-key');+ });});diff --cc apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.tsindex 8e23678c1f,9fb6e2344c..b3390c3d67--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts@@@ -20,15 -23,11 +28,18 @@@ vi.mock('electron', () => (}));import {+ buildXaiPiNativeProvider,buildPiNativeProvidersFromConfigs,+ buildPiSubscriptionNativeProviders,+ mergePiNativeProviderResults,+ parsePiListModels,+ PI_XAI_COMPAT_FORWARD_PORT,piNativeKeyEnvVar,+ piNativeModelId,+ readPiBundledModels,+ resolvePiBundledApiByModelId,+ resolvePiBundledModelById,+ type PiBundledModelInfo,} from '../pi-host.js';type Cfg = Parameters<typeof buildPiNativeProvidersFromConfigs>[0][number];@@@ -39,316 -38,215 +50,691 @@@ const piRuntime = (over: Partial<NonNul...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('keeps a legacy custom xai endpoint separate from the official SuperGrok provider', () => {+ const { providers, env } = buildPiNativeProvidersFromConfigs(- [{- id: 'xai',- name: 'Private xAI-compatible endpoint',- auth: { method: 'apiKey' },- runtimes: {- pi: piRuntime({- baseUrl: 'https://private-xai.example/v1',- models: [{ id: 'private-grok', name: 'Private Grok' }],- }),++ [++ {++ id: 'xai',++ name: 'Private xAI-compatible endpoint',++ auth: { method: 'apiKey' },++ runtimes: {++ pi: piRuntime({++ baseUrl: 'https://private-xai.example/v1',++ models: [{ id: 'private-grok', name: 'Private Grok' }],++ }),++ },+ },- }],++ ],+ (providerId) => (providerId === 'xai' ? 'legacy-custom-key' : null),+ );+ expect(providers).toEqual([+ expect.objectContaining({+ id: 'custom:xai',+ baseUrl: 'https://private-xai.example/v1',+ models: [expect.objectContaining({ id: 'private-grok' })],+ }),+ ]);+ expect(Object.values(env)).toContain('legacy-custom-key');+ });++ it('reuses exact Pi official metadata and preserves unmatched configured models', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'deepseek-local',- name: 'DeepSeek Local',- auth: { method: 'apiKey' },- runtimes: {- pi: piRuntime({- baseUrl: 'https://api.deepseek.com',- piCatalogProviderId: 'deepseek',- models: [- { id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' },- { id: 'models-url-only', name: 'Models URL Only', contextWindow: 64_000 },- ],- }),++ [++ {++ id: 'deepseek-local',++ name: 'DeepSeek Local',++ auth: { method: 'apiKey' },++ runtimes: {++ pi: piRuntime({++ baseUrl: 'https://api.deepseek.com',++ piCatalogProviderId: 'deepseek',++ models: [++ { id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' },++ { id: 'models-url-only', name: 'Models URL Only', contextWindow: 64_000 },++ ],++ }),++ },+ },- }],++ ],+ () => 'secret',+ );- expect(providers[0]).toMatchObject({ id: 'deepseek-local', baseUrl: 'https://api.deepseek.com' });++ expect(providers[0]).toMatchObject({++ id: 'deepseek-local',++ baseUrl: 'https://api.deepseek.com',++ api: 'openai-completions',++ });+ expect(providers[0]?.models[0]).toMatchObject({+ id: 'deepseek-v4-pro',- api: 'openai-completions',+ contextWindow: 1_000_000,+ maxTokens: 384_000,+ reasoning: true,+ thinkingLevelMap: { low: null, high: 'high', max: 'max' },+ });+ expect(providers[0]?.models[1]).toEqual({+ id: 'models-url-only',+ name: 'Models URL Only',+ contextWindow: 64_000,+ });+ });++ it('does not apply official per-model routing after the user changes endpoint or protocol', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'deepseek-proxy',- name: 'DeepSeek Proxy',- auth: { method: 'none' },- runtimes: {- pi: piRuntime({- baseUrl: 'https://proxy.example/anthropic',- wireProtocol: 'anthropic-messages',- piCatalogProviderId: 'deepseek',- models: [{ id: 'deepseek-v4-pro', name: 'Proxy DeepSeek', contextWindow: 64_000 }],- }),++ [++ {++ id: 'deepseek-proxy',++ name: 'DeepSeek Proxy',++ auth: { method: 'none' },++ runtimes: {++ pi: piRuntime({++ baseUrl: 'https://proxy.example/anthropic',++ wireProtocol: 'anthropic-messages',++ piCatalogProviderId: 'deepseek',++ models: [{ id: 'deepseek-v4-pro', name: 'Proxy DeepSeek', contextWindow: 64_000 }],++ }),++ },+ },- }],++ ],+ () => null,+ );+ expect(providers[0]).toMatchObject({+ baseUrl: 'https://proxy.example/anthropic',+ api: 'anthropic-messages',+ models: [{ id: 'deepseek-v4-pro', name: 'Proxy DeepSeek', contextWindow: 64_000 }],+ });+ expect(providers[0]?.models[0]).not.toHaveProperty('thinkingLevelMap');+ });++ it('preserves per-model headers from the official Pi catalog', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'kimi-coding-local',- name: 'Kimi Coding Local',- auth: { method: 'apiKey' },- runtimes: {- pi: piRuntime({- baseUrl: 'https://api.kimi.com/coding',- wireProtocol: 'anthropic-messages',- piCatalogProviderId: 'kimi-coding',- models: [{ id: 'k3', name: 'Kimi K3' }],- }),++ [++ {++ id: 'kimi-coding-local',++ name: 'Kimi Coding Local',++ auth: { method: 'apiKey' },++ runtimes: {++ pi: piRuntime({++ baseUrl: 'https://api.kimi.com/coding',++ wireProtocol: 'anthropic-messages',++ piCatalogProviderId: 'kimi-coding',++ models: [{ id: 'k3', name: 'Kimi K3' }],++ }),++ },+ },- }],++ ],+ () => 'secret',+ );+ expect(providers[0]?.models[0]).toMatchObject({+ id: 'k3',+ headers: { 'User-Agent': 'KimiCLI/1.5' },+ });+ });++ it('preserves explicit overrides for an exact official model after the catalog marker is cleared', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'deepseek-customized',- name: 'DeepSeek Customized',- auth: { method: 'apiKey' },- runtimes: {- pi: piRuntime({- baseUrl: 'https://api.deepseek.com',- wireProtocol: 'openai-chat',- models: [{- id: 'deepseek-v4-flash',- name: 'My DeepSeek Flash',- contextWindow: 64_000,- supportsImageInput: true,- reasoning: true,- reasoningEfforts: ['low'],- }],- }),++ [++ {++ id: 'deepseek-customized',++ name: 'DeepSeek Customized',++ auth: { method: 'apiKey' },++ runtimes: {++ pi: piRuntime({++ baseUrl: 'https://api.deepseek.com',++ wireProtocol: 'openai-chat',++ models: [++ {++ id: 'deepseek-v4-flash',++ name: 'My DeepSeek Flash',++ contextWindow: 64_000,++ supportsImageInput: true,++ reasoning: true,++ reasoningEfforts: ['low'],++ },++ ],++ }),++ },+ },- }],++ ],+ () => 'secret',+ );+ expect(providers[0]?.models[0]).toEqual({+ id: 'deepseek-v4-flash',+ name: 'My DeepSeek Flash',+ contextWindow: 64_000,+ input: ['text', 'image'],+ reasoning: true,+ thinkingLevelMap: {+ minimal: null,+ low: 'low',+ medium: null,+ high: null,+ xhigh: null,+ max: null,+ },+ });+ });++ it('maps historical xAI namespaced ids to Pi official bare ids', () => {+ expect(piNativeModelId('xai', 'xai/grok-4.6')).toBe('grok-4.6');+ expect(piNativeModelId('xai', 'grok-4.6')).toBe('grok-4.6');+ expect(piNativeModelId('deepseek', 'xai/grok-4.6')).toBe('xai/grok-4.6');+ });++ it('builds Grok 4.6 from the Pi official xAI catalog without losing protocol metadata', async () => {+ const { providers, env } = await buildXaiPiNativeProvider('xai/grok-4.6');+ expect(providers).toHaveLength(1);+ expect(providers[0]).toMatchObject({+ id: 'xai',+ baseUrl: 'http://127.0.0.1:18765',+ api: 'anthropic-messages',+ apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',+ headers: {+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',+ },+ modelIdAliases: { 'grok-4.6': 'xai/grok-4.6' },+ });+ expect(providers[0]?.models.find((model) => model.id === 'xai/grok-4.6')).toMatchObject({+ api: 'anthropic-messages',+ contextWindow: 500_000,+ maxTokens: 500_000,+ input: ['text', 'image'],+ reasoning: true,+ compat: {+ supportsStore: false,+ supportsDeveloperRole: false,+ supportsReasoningEffort: false,+ },+ });+ expect(env).toEqual({+ CINDY_PI_XAI_PROXY_API_KEY: 'cindy-pi-provider-auth-placeholder',+ });+ });++ it('projects remote xAI through an exact SSH reverse-forward to the Desktop compat proxy', async () => {+ const { providers } = await buildXaiPiNativeProvider('grok-4.6', false, true);+ expect(providers[0]).toMatchObject({+ id: 'xai',+ baseUrl: `http://127.0.0.1:${PI_XAI_COMPAT_FORWARD_PORT}`,+ api: 'anthropic-messages',+ hostProxyForward: {+ localUrl: 'http://127.0.0.1:18765',+ remotePort: PI_XAI_COMPAT_FORWARD_PORT,+ },+ });+ });++ it('adds a private conservative xAI descriptor only when resuming a historical namespaced id', async () => {+ await expect(buildXaiPiNativeProvider('xai/grok-retired')).rejects.toThrow(/does not contain/);+ const { providers } = await buildXaiPiNativeProvider('xai/grok-retired', true);+ expect(providers[0]?.models.find((model) => model.id === 'xai/grok-retired')).toEqual({+ id: 'xai/grok-retired',+ name: 'xai/grok-retired',+ api: 'anthropic-messages',+ });+ expect(providers[0]?.modelIdAliases?.['grok-retired']).toBe('xai/grok-retired');+ });+++ 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 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('caches a null fallback when the PI probe temp directory cannot be created', async () => {+ const binaryPath = path.join(process.cwd(), 'pi-temp-dir-probe-failure');- const mkdtempSpy = vi.spyOn(fsp, 'mkdtemp')++ const mkdtempSpy = vi++ .spyOn(fsp, 'mkdtemp')+ .mockRejectedValueOnce(new Error('temporary directory unavailable'));++ try {+ await expect(readPiBundledModels(binaryPath)).resolves.toBeNull();+ await expect(readPiBundledModels(binaryPath)).resolves.toBeNull();+ expect(mkdtempSpy).toHaveBeenCalledTimes(1);+ } finally {+ mkdtempSpy.mockRestore();+ }+ });+- 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.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',- }];++ 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.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',++ 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.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',++ 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')],- ])],++ [++ '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.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();+ 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('namespaces only colliding BYOM runtime ids and preserves their persisted source ids', () => {+ const collisions: Array<[string, string]> = [];+ const merged = mergePiNativeProviderResults(+ {- providers: [{- id: 'openai-codex',- sourceProviderId: 'openai',- name: 'OpenAI (ChatGPT)',- baseUrl: 'http://127.0.0.1:4567',- inheritModels: true,- models: [{ id: 'chatgpt/gpt-5.6-sol', wireId: 'gpt-5.6-sol' }],- }],++ providers: [++ {++ id: 'openai-codex',++ sourceProviderId: 'openai',++ name: 'OpenAI (ChatGPT)',++ baseUrl: 'http://127.0.0.1:4567',++ inheritModels: true,++ models: [{ id: 'chatgpt/gpt-5.6-sol', wireId: 'gpt-5.6-sol' }],++ },++ ],+ env: { CINDY_PI_OPENAI_PROXY_KEY: 'subscription-key' },+ },+ {+ providers: [+ {+ id: 'openai-codex',+ name: 'User OpenAI-compatible endpoint',+ baseUrl: 'https://user.example/v1',+ api: 'openai-completions',+ models: [{ id: 'local-model' }],+ },+ {+ id: 'cindy-byom-openai-codex',+ name: 'Existing custom provider',+ baseUrl: 'https://other.example/v1',+ api: 'openai-completions',+ models: [{ id: 'other-model' }],+ },+ ],+ env: { CINDY_PI_KEY_OPENAI_CODEX: 'custom-key' },+ },- (sourceProviderId, runtimeProviderId) => collisions.push([sourceProviderId, runtimeProviderId]),++ (sourceProviderId, runtimeProviderId) =>++ collisions.push([sourceProviderId, runtimeProviderId]),+ );++ expect(merged.providers.map((provider) => provider.id)).toEqual([+ 'openai-codex',+ 'cindy-byom-openai-codex-2',+ 'cindy-byom-openai-codex',+ ]);+ expect(merged.providers[1]).toMatchObject({+ id: 'cindy-byom-openai-codex-2',+ sourceProviderId: 'openai-codex',+ baseUrl: 'https://user.example/v1',+ models: [{ id: 'local-model' }],+ });+ expect(merged.providers[2]?.sourceProviderId).toBeUndefined();+ expect(merged.env).toEqual({+ CINDY_PI_OPENAI_PROXY_KEY: 'subscription-key',+ CINDY_PI_KEY_OPENAI_CODEX: 'custom-key',+ });+ expect(collisions).toEqual([['openai-codex', 'cindy-byom-openai-codex-2']]);+ });+++ it('namespaces bundled PI provider ids without active subscriptions and preserves BYOM routing', () => {++ const collisions: Array<[string, string]> = [];++ const customProviders = [++ {++ id: 'openai-codex',++ name: 'User OpenAI endpoint',++ baseUrl: 'https://openai-user.example/v1',++ api: 'openai-completions' as const,++ apiKeyEnvVar: 'CINDY_PI_KEY_OPENAI_CODEX',++ models: [{ id: 'openai-local' }],++ },++ {++ id: 'anthropic',++ name: 'User Anthropic endpoint',++ baseUrl: 'https://anthropic-user.example/v1',++ api: 'anthropic-messages' as const,++ apiKeyEnvVar: 'CINDY_PI_KEY_ANTHROPIC',++ models: [{ id: 'anthropic-local' }],++ },++ {++ id: 'xai',++ name: 'User xAI endpoint',++ baseUrl: 'https://xai-user.example/v1',++ api: 'openai-responses' as const,++ apiKeyEnvVar: 'CINDY_PI_KEY_XAI',++ models: [{ id: 'xai-local' }],++ },++ {++ id: 'cindy-byom-openai-codex',++ name: 'Existing custom provider',++ baseUrl: 'https://existing.example/v1',++ api: 'openai-completions' as const,++ models: [{ id: 'existing-local' }],++ },++ {++ id: 'safe-custom',++ name: 'Non-colliding provider',++ baseUrl: 'https://safe.example/v1',++ api: 'openai-completions' as const,++ models: [{ id: 'safe-local' }],++ },++ ];++ const env = {++ CINDY_PI_KEY_OPENAI_CODEX: 'openai-key',++ CINDY_PI_KEY_ANTHROPIC: 'anthropic-key',++ CINDY_PI_KEY_XAI: 'xai-key',++ };++++ const merged = mergePiNativeProviderResults(++ { providers: [], env: {} },++ { providers: customProviders, env },++ (sourceProviderId, runtimeProviderId) =>++ collisions.push([sourceProviderId, runtimeProviderId]),++ );++++ expect(merged.providers.map((provider) => provider.id)).toEqual([++ 'cindy-byom-openai-codex-2',++ 'cindy-byom-anthropic',++ 'cindy-byom-xai',++ 'cindy-byom-openai-codex',++ 'safe-custom',++ ]);++ expect(merged.providers.slice(0, 3)).toMatchObject([++ {++ sourceProviderId: 'openai-codex',++ baseUrl: 'https://openai-user.example/v1',++ api: 'openai-completions',++ apiKeyEnvVar: 'CINDY_PI_KEY_OPENAI_CODEX',++ models: [{ id: 'openai-local' }],++ },++ {++ sourceProviderId: 'anthropic',++ baseUrl: 'https://anthropic-user.example/v1',++ api: 'anthropic-messages',++ apiKeyEnvVar: 'CINDY_PI_KEY_ANTHROPIC',++ models: [{ id: 'anthropic-local' }],++ },++ {++ sourceProviderId: 'xai',++ baseUrl: 'https://xai-user.example/v1',++ api: 'openai-responses',++ apiKeyEnvVar: 'CINDY_PI_KEY_XAI',++ models: [{ id: 'xai-local' }],++ },++ ]);++ expect(merged.providers[3]?.sourceProviderId).toBeUndefined();++ expect(merged.providers[4]?.sourceProviderId).toBeUndefined();++ expect(merged.env).toEqual(env);++ expect(collisions).toEqual([++ ['openai-codex', 'cindy-byom-openai-codex-2'],++ ['anthropic', 'cindy-byom-anthropic'],++ ['xai', 'cindy-byom-xai'],++ ]);++ });+++ it('preserves daily additions and protocol annotations when PI probing fails or is empty', () => {+ 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-daily', name: 'Claude Daily', contextWindow: 200_000,- efforts: [], defaultEffort: null, piApi: 'anthropic-messages',- }];- openai.models.pi = [{- id: 'chatgpt/gpt-daily', name: 'GPT Daily', contextWindow: 200_000,- efforts: [], defaultEffort: null, piApi: 'openai-responses',- }];- xai.models.pi = [{- id: 'xai/grok-daily', name: 'Grok Daily', contextWindow: 200_000,- efforts: [], defaultEffort: null, piApi: 'openai-responses',- }];++ anthropic.models.pi = [++ {++ id: 'claude-daily',++ name: 'Claude Daily',++ contextWindow: 200_000,++ efforts: [],++ defaultEffort: null,++ piApi: 'anthropic-messages',++ },++ ];++ openai.models.pi = [++ {++ id: 'chatgpt/gpt-daily',++ name: 'GPT Daily',++ contextWindow: 200_000,++ efforts: [],++ defaultEffort: null,++ piApi: 'openai-responses',++ },++ ];++ xai.models.pi = [++ {++ id: 'xai/grok-daily',++ name: 'Grok Daily',++ contextWindow: 200_000,++ efforts: [],++ defaultEffort: null,++ piApi: 'openai-responses',++ },++ ];++ for (const bundled of [undefined, new Map()] as const) {+ const providers = buildPiSubscriptionNativeProviders(+ catalog,+ 'http://127.0.0.1:4567/',+ bundled,+ ).providers;- expect(providers.find((provider) => provider.id === 'anthropic')?.models[0])- .toMatchObject({ wireId: 'claude-daily', api: 'anthropic-messages' });- expect(providers.find((provider) => provider.id === 'openai-codex')?.models[0])- .toMatchObject({ wireId: 'gpt-daily', catalogAddition: true });- expect(providers.find((provider) => provider.id === 'xai')?.models[0])- .toMatchObject({ wireId: 'grok-daily', api: 'openai-responses' });++ expect(providers.find((provider) => provider.id === 'anthropic')?.models[0]).toMatchObject({++ wireId: 'claude-daily',++ api: 'anthropic-messages',++ });++ expect(providers.find((provider) => provider.id === 'openai-codex')?.models[0]).toMatchObject(++ { wireId: 'gpt-daily', catalogAddition: true },++ );++ expect(providers.find((provider) => provider.id === 'xai')?.models[0]).toMatchObject({++ wireId: 'grok-daily',++ api: 'openai-responses',++ });+ }+ });++ it('keeps missing daily rows while respecting models returned by a partial PI probe', () => {+ 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-known', name: 'Grok Known', contextWindow: 200_000,- efforts: [], defaultEffort: null, piApi: 'openai-responses',++ id: 'xai/grok-known',++ name: 'Grok Known',++ contextWindow: 200_000,++ efforts: [],++ defaultEffort: null,++ piApi: 'openai-responses',+ },+ {- id: 'xai/grok-added', name: 'Grok Added', contextWindow: 200_000,- efforts: [], defaultEffort: null, piApi: 'openai-responses',++ id: 'xai/grok-added',++ name: 'Grok Added',++ contextWindow: 200_000,++ efforts: [],++ defaultEffort: null,++ piApi: 'openai-responses',+ },+ ];+ const provider = buildPiSubscriptionNativeProviders(+ catalog,+ 'http://127.0.0.1:4567/',- new Map([['xai', new Map([- ['grok-known', piBundledModel('grok-known', 'openai-responses')],- ])]]),++ new Map([++ ['xai', new Map([['grok-known', piBundledModel('grok-known', 'openai-responses')]])],++ ]),+ ).providers.find((candidate) => candidate.id === 'xai');++ expect(provider?.models).toEqual([+ expect.objectContaining({ wireId: 'grok-known' }),+ expect.objectContaining({ wireId: 'grok-added', api: 'openai-responses' }),+ ]);+ expect(provider?.models[0]?.api).toBeUndefined();+ });++ 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',- }];++ 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',@@@ -392,193 -290,13 +778,240 @@@];for (const [wp, api] of cases) {const { providers } = buildPiNativeProvidersFromConfigs(-- [{ id: 'p', name: 'P', auth: { method: 'none' }, runtimes: { pi: piRuntime({ wireProtocol: wp as never }) } }],++ [++ {++ id: 'p',++ name: 'P',++ auth: { method: 'none' },++ runtimes: { pi: piRuntime({ wireProtocol: wp as never }) },++ },++ ],() => null,);expect(providers[0]?.api).toBe(api);}});+ it('fails closed for an unknown custom-provider wire protocol', () => {- expect(() => buildPiNativeProvidersFromConfigs(- [{- id: 'future',- name: 'Future',- auth: { method: 'none' },- runtimes: { pi: piRuntime({ wireProtocol: 'future-protocol' as never }) },- }],- () => null,- )).toThrow('Unsupported PI wire protocol: future-protocol');++ expect(() =>++ buildPiNativeProvidersFromConfigs(++ [++ {++ id: 'future',++ name: 'Future',++ auth: { method: 'none' },++ runtimes: { pi: piRuntime({ wireProtocol: 'future-protocol' as never }) },++ },++ ],++ () => null,++ ),++ ).toThrow('Unsupported PI wire protocol: future-protocol');+ });++ 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',- })],- ])],++ [++ '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');++ 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' },- ],- }),++ [++ {++ 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')],- ])],++ ['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('does not copy a unique same-named PI model across BYOM origins', () => {+ const bundledModel = piBundledModel('shared-model', 'anthropic-messages', {+ baseUrl: 'https://official.example/v1/messages',+ name: 'Official Name',+ compat: { supportsStrictTools: true },+ });+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'local-provider',- name: 'Local Provider',- auth: { method: 'none' },- runtimes: {- pi: piRuntime({- baseUrl: 'http://127.0.0.1:9000/v1',- models: [{ id: 'shared-model', name: 'Local Name' }],- }),++ [++ {++ id: 'local-provider',++ name: 'Local Provider',++ auth: { method: 'none' },++ runtimes: {++ pi: piRuntime({++ baseUrl: 'http://127.0.0.1:9000/v1',++ models: [{ id: 'shared-model', name: 'Local Name' }],++ }),++ },+ },- }],++ ],+ () => null,+ undefined,+ new Map([['official-provider', new Map([['shared-model', bundledModel]])]]),+ );++ expect(providers[0]).toMatchObject({+ baseUrl: 'http://127.0.0.1:9000/v1',+ api: 'openai-completions',+ models: [{ id: 'shared-model', name: 'Local Name' }],+ });+ expect(providers[0]?.models[0]?.baseUrl).toBeUndefined();+ expect(providers[0]?.models[0]?.compat).toBeUndefined();+ });++ it('keeps an explicit BYOM protocol and endpoint isolated from bundled model metadata', () => {+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'explicit-provider',- name: 'Explicit Provider',- auth: { method: 'none' },- runtimes: {- pi: piRuntime({- baseUrl: 'https://custom.example/v1',- wireProtocol: 'openai-responses',- models: [{ id: 'same-id', name: 'Custom Name' }],- }),++ [++ {++ id: 'explicit-provider',++ name: 'Explicit Provider',++ auth: { method: 'none' },++ runtimes: {++ pi: piRuntime({++ baseUrl: 'https://custom.example/v1',++ wireProtocol: 'openai-responses',++ models: [{ id: 'same-id', name: 'Custom Name' }],++ }),++ },+ },- }],++ ],+ () => null,+ undefined,- new Map([['bundled', new Map([- ['same-id', piBundledModel('same-id', 'anthropic-messages', {- baseUrl: 'https://other.example/v1',- name: 'Bundled Name',- })],- ])]]),++ new Map([++ [++ 'bundled',++ new Map([++ [++ 'same-id',++ piBundledModel('same-id', 'anthropic-messages', {++ baseUrl: 'https://other.example/v1',++ name: 'Bundled Name',++ }),++ ],++ ]),++ ],++ ]),+ );++ expect(providers[0]).toMatchObject({+ baseUrl: 'https://custom.example/v1',+ api: 'openai-responses',+ models: [{ id: 'same-id', name: 'Custom Name' }],+ });+ expect(providers[0]?.models[0]?.baseUrl).toBeUndefined();+ });++ it('falls back to completions when no unique same-origin PI candidate exists', () => {+ const bundled = new Map([- ['provider-a', new Map([- ['same-id', piBundledModel('same-id', 'anthropic-messages', {- baseUrl: 'https://same.example/anthropic',- })],- ])],- ['provider-b', new Map([- ['same-id', piBundledModel('same-id', 'openai-responses', {- baseUrl: 'https://same.example/openai',- })],- ])],++ [++ 'provider-a',++ new Map([++ [++ 'same-id',++ piBundledModel('same-id', 'anthropic-messages', {++ baseUrl: 'https://same.example/anthropic',++ }),++ ],++ ]),++ ],++ [++ 'provider-b',++ new Map([++ [++ 'same-id',++ piBundledModel('same-id', 'openai-responses', {++ baseUrl: 'https://same.example/openai',++ }),++ ],++ ]),++ ],+ ]);+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'ambiguous-provider',- name: 'Ambiguous Provider',- auth: { method: 'none' },- runtimes: {- pi: piRuntime({- baseUrl: 'https://same.example/proxy',- models: [{ id: 'same-id', name: 'Configured Name' }],- }),++ [++ {++ id: 'ambiguous-provider',++ name: 'Ambiguous Provider',++ auth: { method: 'none' },++ runtimes: {++ pi: piRuntime({++ baseUrl: 'https://same.example/proxy',++ models: [{ id: 'same-id', name: 'Configured Name' }],++ }),++ },+ },- }],++ ],+ () => null,+ undefined,+ bundled,+ );+- expect(resolvePiBundledModelById(bundled, 'same-id', 'https://same.example/proxy'))- .toBeUndefined();++ expect(++ resolvePiBundledModelById(bundled, 'same-id', 'https://same.example/proxy'),++ ).toBeUndefined();+ expect(providers[0]).toMatchObject({+ api: 'openai-completions',+ models: [{ id: 'same-id', name: 'Configured Name' }],+ });+ expect(providers[0]?.models[0]?.baseUrl).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() } }],@@@ -632,14 -350,14 +1065,16 @@@it('allows apiKey providers authenticated entirely by custom headers', () => {const { providers, env } = buildPiNativeProvidersFromConfigs(-- [{-- id: 'header-only',-- name: 'Header Only',-- auth: { method: 'apiKey' },-- runtimes: {-- pi: piRuntime({ headers: { Authorization: 'Bearer header-secret' } }),++ [++ {++ id: 'header-only',++ name: 'Header Only',++ auth: { method: 'apiKey' },++ runtimes: {++ pi: piRuntime({ headers: { Authorization: 'Bearer header-secret' } }),++ },},-- }],++ ],() => null,);@@@ -688,19 -406,19 +1123,21 @@@it('maps an explicit custom-model image capability into the Pi native model spec', () => {const { providers } = buildPiNativeProvidersFromConfigs(-- [{-- id: 'visual',-- name: 'Visual',-- auth: { method: 'none' },-- runtimes: {-- pi: piRuntime({-- models: [-- { id: 'vision', name: 'Vision', supportsImageInput: true },-- { id: 'legacy', name: 'Legacy' },-- ],-- }),++ [++ {++ id: 'visual',++ name: 'Visual',++ auth: { method: 'none' },++ runtimes: {++ pi: piRuntime({++ models: [++ { id: 'vision', name: 'Vision', supportsImageInput: true },++ { id: 'legacy', name: 'Legacy' },++ ],++ }),++ },},-- }],++ ],() => null,);expect(providers[0].models).toEqual([@@@ -709,58 -427,6 +1146,64 @@@]);});+ it('keeps an unedited preset per-model piApi correction in 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',- }],- }),++ [++ {++ 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.each([+ ['openai-chat', 'openai-completions'],+ ['anthropic-messages', 'anthropic-messages'],+ ] as const)(+ 'uses a saved explicit %s PI protocol after the dialog clears preset piApi',+ (wireProtocol, expectedApi) => {+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'deepseek',- name: 'DeepSeek',- auth: { method: 'none' },- runtimes: {- pi: piRuntime({- wireProtocol,- models: [{ id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' }],- }),++ [++ {++ id: 'deepseek',++ name: 'DeepSeek',++ auth: { method: 'none' },++ runtimes: {++ pi: piRuntime({++ wireProtocol,++ models: [{ id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' }],++ }),++ },+ },- }],++ ],+ () => null,+ );++ expect(providers[0]?.api).toBe(expectedApi);+ expect(providers[0]?.models[0]?.api).toBeUndefined();+ },+ );+it('maps an explicit Responses reasoning capability and supported efforts into Pi', () => {const { providers } = buildPiNativeProvidersFromConfigs([@@@ -805,4 -471,28 +1248,48 @@@{ id: 'legacy', name: 'Legacy', contextWindow: undefined },]);});++ it.each([+ ['deepseek-v4-pro', 'DeepSeek V4 Pro', false],+ ['kimi-k3', 'Kimi K3', true],+ ] as const)('maps %s exact reasoning levels and image capability into Pi', (id, name, visual) => {+ const { providers } = buildPiNativeProvidersFromConfigs(- [{- id: 'cn-provider', name: 'CN Provider', auth: { method: 'none' },- runtimes: { pi: piRuntime({ models: [{- id, name, ...(visual ? { supportsImageInput: true } : {}),- reasoning: true, reasoningEfforts: ['low', 'high', 'max'],- }] }) },- }],++ [++ {++ id: 'cn-provider',++ name: 'CN Provider',++ auth: { method: 'none' },++ runtimes: {++ pi: piRuntime({++ models: [++ {++ id,++ name,++ ...(visual ? { supportsImageInput: true } : {}),++ reasoning: true,++ reasoningEfforts: ['low', 'high', 'max'],++ },++ ],++ }),++ },++ },++ ],+ () => null,+ );+ expect(providers[0].models[0]).toEqual({- id, name, contextWindow: undefined,++ id,++ name,++ contextWindow: undefined,+ ...(visual ? { input: ['text', 'image'] } : {}),+ reasoning: true,+ thinkingLevelMap: {- minimal: null, low: 'low', medium: null, high: 'high', xhigh: null, max: 'max',++ minimal: null,++ low: 'low',++ medium: null,++ high: 'high',++ xhigh: null,++ max: 'max',+ },+ });+ });});diff --cc apps/desktop/src/main/maker-host/active-catalog.tsindex 135f2a6b42,b8952b834c..6d7955f81d--- a/apps/desktop/src/main/maker-host/active-catalog.ts+++ b/apps/desktop/src/main/maker-host/active-catalog.ts@@@ -177,9 -215,9 +215,7 @@@ export function resolveXdPiGatewayWirePmodelId: string,): Extract<ProviderWireProtocol, 'openai-responses'> | null | undefined {const normalized = modelId.replace(/\[1m\]$/, '');-- const gatewayModel = xdGatewayModels.find(-- (model) => model.id === normalized,-- );++ const gatewayModel = xdGatewayModels.find((model) => model.id === normalized);if (!gatewayModel?.agents?.includes('pi')) return undefined;const wireProtocol = gatewayModel.perAgent?.pi?.wireProtocol;return wireProtocol === 'openai-responses' ? wireProtocol : null;@@@ -488,6 -550,130 +544,127 @@@ function assembleRootreturn preserveDeclarationOrder ? out : sortModelsByOrder(out);}+ /** Registry / local override 只能补账号已返回的条目,不能重新实体化账号没有的成员。 */+ function assembleAuthoritativeRoot(+ providerId: string,+ agent: RootAgentKind,+ models: readonly CatalogModel[],+ plan: ModelPlaneRegistryPlan,+ ): CatalogModel[] {+ const memberIds = new Set(models.map((model) => model.id));+ return assembleRoot(providerId, agent, models, plan, true).filter((model) =>+ memberIds.has(model.id),+ );+ }++ function xaiCatalogModelById(+ provider: Provider,+ id: string,+ agent: AgentKind,+ ): CatalogModel | undefined {+ const bundled = BUNDLED_CATALOG.providers.find((entry) => entry.id === 'xai');+ if (agent === 'pi') {+ const bare = id.startsWith('xai/') ? id.slice('xai/'.length) : id;+ return (- provider.models.pi?.find((model) => model.id === bare)- ?? bundled?.models.pi?.find((model) => model.id === bare)++ provider.models.pi?.find((model) => model.id === bare) ??++ bundled?.models.pi?.find((model) => model.id === bare)+ );+ }+ return (- provider.models[agent]?.find((model) => model.id === id)- ?? bundled?.models[agent]?.find((model) => model.id === id)++ provider.models[agent]?.find((model) => model.id === id) ??++ bundled?.models[agent]?.find((model) => model.id === id)+ );+ }++ function materializeXaiAccountModels(+ provider: Provider,+ agent: RootAgentKind,+ discovered: readonly XaiDiscoveredModel[],+ ): CatalogModel[] {+ return discovered.map((entry, index) => {+ const catalogModel =- xaiCatalogModelById(provider, entry.id, agent)- ?? xaiCatalogModelById(provider, entry.id, 'pi');++ xaiCatalogModelById(provider, entry.id, agent) ??++ xaiCatalogModelById(provider, entry.id, 'pi');+ const registry = modelRegistryMetaFields('xai', agent, entry.id);+ const efforts = entry.efforts+ ? [...entry.efforts]+ : [...(registry?.efforts ?? catalogModel?.efforts ?? [])];+ const requestedDefault =+ entry.defaultEffort !== undefined+ ? entry.defaultEffort+ : (registry?.defaultEffort ?? catalogModel?.defaultEffort ?? null);+ const defaultEffort =+ requestedDefault !== null && efforts.includes(requestedDefault)+ ? requestedDefault+ : efforts.includes('high')+ ? 'high'+ : (efforts[efforts.length - 1] ?? null);+ const contextWindow =+ entry.contextWindow ?? registry?.contextWindow ?? catalogModel?.contextWindow ?? 200_000;+ const contextWindowVerified =+ entry.contextWindow !== undefined+ ? (entry.contextWindowVerified ?? true)+ : registry?.contextWindow !== undefined || catalogModel?.contextWindowVerified === true;+ return {+ ...catalogModel,+ id: entry.id,+ name: entry.name ?? registry?.name ?? catalogModel?.name ?? entry.id.slice('xai/'.length),+ ...(entry.description !== undefined+ ? { description: entry.description }+ : registry?.description !== undefined+ ? { description: registry.description }+ : {}),+ group: registry?.group ?? catalogModel?.group ?? 'grok',+ sortOrder: registry?.sortOrder ?? catalogModel?.sortOrder ?? 1_000 + index,+ contextWindow,+ ...(contextWindowVerified ? { contextWindowVerified: true } : {}),+ ...(entry.maxOutput !== undefined+ ? { maxOutput: entry.maxOutput }+ : registry?.maxOutput !== undefined+ ? { maxOutput: registry.maxOutput }+ : catalogModel?.maxOutput !== undefined+ ? { maxOutput: catalogModel.maxOutput }+ : {}),+ efforts,+ defaultEffort,+ ...(registry?.supportsFastMode !== undefined+ ? { supportsFastMode: registry.supportsFastMode }+ : {}),+ status: registry?.status ?? catalogModel?.status ?? 'active',+ defaultEnabled: registry?.defaultEnabled ?? catalogModel?.defaultEnabled ?? true,+ };+ });+ }++ function bundledXaiFallbackMembers(provider: Provider): XaiDiscoveredModel[] {+ return (provider.models.pi ?? []).map((model) => ({+ id: model.id.startsWith('xai/') ? model.id : `xai/${model.id}`,+ }));+ }+-function projectXaiPiModel(- provider: Provider,- model: CatalogModel,-): CatalogModel {++function projectXaiPiModel(provider: Provider, model: CatalogModel): CatalogModel {+ const bareId = model.id.startsWith('xai/') ? model.id.slice('xai/'.length) : model.id;+ const piMetadata = xaiCatalogModelById(provider, model.id, 'pi');+ return {+ ...model,+ ...piMetadata,+ id: bareId,+ name: model.name,+ description: model.description,+ group: model.group,+ sortOrder: model.sortOrder,+ contextWindow: model.contextWindow,+ ...(model.contextWindowVerified !== undefined+ ? { contextWindowVerified: model.contextWindowVerified }+ : {}),+ ...(model.maxOutput !== undefined ? { maxOutput: model.maxOutput } : {}),+ efforts: model.efforts,+ defaultEffort: model.defaultEffort,+ status: model.status,+ defaultEnabled: model.defaultEnabled,+ };+ }+/** 把 provider 的全部 per-agent 模型清单清零(保留身份卡);已为空则原样返回。 */function withEmptyModels(p: Provider): Provider {const entries = Object.entries(p.models) as [AgentKind, CatalogModel[]][];@@@ -499,40 -685,6 +676,38 @@@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 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 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);@@@ -653,41 -800,51 +830,68 @@@),).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(- 'xai',- 'claude-code',- p.models['claude-code'] ?? [],- plan,- true,- );- const codexRoot = assembleRoot('xai', 'codex', p.models.codex ?? [], plan, true);+ const useAccountMembership = xaiDiscoveredModels !== null;+ const accountModels = xaiDiscoveredModels ?? [];+ // The bundled-only fallback uses Pi's official list as its membership seed because it is+ // the freshest packaged xAI list (and currently carries Grok 4.6). A loaded server Catalog+ // remains the preceding fallback and keeps its own legacy static membership for old server+ // compatibility. Any successful account snapshot, including [], overrides both.+ const authoritativeMembers = useAccountMembership+ ? accountModels+ : b === BUNDLED_CATALOG || p === bundledXai+ ? bundledXaiFallbackMembers(p)+ : null;+ const claudeSeed = authoritativeMembers+ ? materializeXaiAccountModels(p, 'claude-code', authoritativeMembers)+ : (p.models['claude-code'] ?? []);+ const codexSeed = authoritativeMembers+ ? materializeXaiAccountModels(p, 'codex', authoritativeMembers)+ : (p.models.codex ?? []);+ const claudeRoot = authoritativeMembers+ ? assembleAuthoritativeRoot('xai', 'claude-code', claudeSeed, plan)+ : assembleRoot('xai', 'claude-code', claudeSeed, plan, true);+ const codexRoot = authoritativeMembers+ ? assembleAuthoritativeRoot('xai', 'codex', codexSeed, plan)+ : assembleRoot('xai', 'codex', codexSeed, plan, true);- const piModels = claudeRoot.map((model) => projectXaiPiModel(p, model));+ const stripPiApi = (model: CatalogModel): CatalogModel => {+ if (model.piApi === undefined) return model;+ const rest = { ...model };+ delete rest.piApi;+ return rest;+ };++ const piModels = applyPiApiAnnotations(++ 'xai',++ claudeRoot.map((model) => projectXaiPiModel(p, model)),++ );return {...p,+ agents: p.agents.includes('pi') ? p.agents : [...p.agents, 'pi' as AgentKind],+ routing: {+ ...p.routing,+ ...(p.routing.pi+ ? {}+ : bundledXai?.routing.pi+ ? {+ pi: bundledXai.routing.pi,+ }+ : {}),+ },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: applyPiApiAnnotations('xai', claudeRoot) }- : {}),+ pi: piModels,},};}@@@ -820,10 -986,11 +1033,9 @@@ export function commitModelPlaneFromCatconst incomingXai = catalog.providers.find((provider) => provider.id === 'xai');const providers =incomingXai && current.providers.some((provider) => provider.id === 'xai')-- ? current.providers.map((provider) =>- provider.id === 'xai' ? { ...provider, models: incomingXai.models } : provider,- provider.id === 'xai' ? incomingXai : provider,-- )++ ? current.providers.map((provider) => (provider.id === 'xai' ? incomingXai : provider)): current.providers;+ if (catalog.modelRegistry) trustedCustomProviderRegistry = catalog.modelRegistry;base = {...current,providers,diff --cc apps/desktop/src/main/maker-host/custom-provider-store.tsindex 9943b3d155,92eb6ff39e..2414f911a4--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts@@@ -29,7 -29,7 +30,8 @@@ importisLoopbackProviderUrl,isProviderRequestPath,PI_REASONING_EFFORTS,+ PI_MODEL_APIS,+ preservesPiCatalogModels,} from '@cindy/model-providers';import { getDbClient } from '../localDb/client/current.js';@@@ -47,22 -47,18 +49,18 @@@ const MAX_NAME_LEN = 60/** 验证结果:ok 或带 code + message(供 handler 映射成 throwIpcError)。 */export type ValidationResult =-- | { ok: true }-- | { ok: false; code: 'INVALID_PARAMS'; message: string };++ { ok: true } | { ok: false; code: 'INVALID_PARAMS'; message: string };function invalid(message: string): ValidationResult {return { ok: false, code: 'INVALID_PARAMS', message };}function isPiReasoningEffort(value: unknown): value is PiReasoningEffort {-- return (-- typeof value === 'string' &&-- (PI_REASONING_EFFORTS as readonly string[]).includes(value)-- );++ return typeof value === 'string' && (PI_REASONING_EFFORTS as readonly string[]).includes(value);+}++function isPiModelApi(value: unknown): value is PiModelApi {+ return typeof value === 'string' && (PI_MODEL_APIS as readonly string[]).includes(value);}function parseStoredPiReasoningCapability(@@@ -80,7 -76,15 +78,16 @@@) {return {};}- return { reasoning: true, reasoningEfforts: efforts };- const defaultEffort = isPiReasoningEffort(model.reasoningDefaultEffort)- && efforts.includes(model.reasoningDefaultEffort)- ? model.reasoningDefaultEffort- : undefined;++ const defaultEffort =++ isPiReasoningEffort(model.reasoningDefaultEffort) &&++ efforts.includes(model.reasoningDefaultEffort)++ ? model.reasoningDefaultEffort++ : undefined;+ return {+ reasoning: true,+ reasoningEfforts: efforts,+ ...(defaultEffort ? { reasoningDefaultEffort: defaultEffort } : {}),+ };}function validateNoAuthLoopbackBoundary(@@@ -117,10 -121,10 +124,7 @@@ function validateRuntime(agent: string} catch {return invalid(`runtime '${agent}' baseUrl is not a valid URL`);}-- if (-- r.requestPath !== undefined-- && !isProviderRequestPath(r.requestPath)-- ) {++ if (r.requestPath !== undefined && !isProviderRequestPath(r.requestPath)) {return invalid(`runtime '${agent}' requestPath invalid`);}if (!Array.isArray(r.models)) return invalid(`runtime '${agent}' models must be an array`);@@@ -134,12 -138,12 +138,10 @@@return invalid(`runtime '${agent}' model.name required`);}if (-- mm.contextWindow !== undefined-- && (-- typeof mm.contextWindow !== 'number'-- || !Number.isFinite(mm.contextWindow)-- || mm.contextWindow <= 0-- )++ mm.contextWindow !== undefined &&++ (typeof mm.contextWindow !== 'number' ||++ !Number.isFinite(mm.contextWindow) ||++ mm.contextWindow <= 0)) {return invalid(`runtime '${agent}' model.contextWindow must be a positive number`);}@@@ -149,10 -153,10 +151,13 @@@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;+ const hasReasoningCapability =- mm.reasoning !== undefined- || mm.reasoningEfforts !== undefined- || mm.reasoningDefaultEffort !== undefined;++ mm.reasoning !== undefined ||++ mm.reasoningEfforts !== undefined ||++ mm.reasoningDefaultEffort !== undefined;if (hasReasoningCapability && agent !== 'pi') {return invalid(`runtime '${agent}' reasoning capability is only supported for pi models`);}@@@ -169,16 -173,25 +174,24 @@@) {return invalid(`runtime '${agent}' model.reasoningEfforts invalid`);}- } else if (mm.reasoningEfforts !== undefined) {- return invalid(`runtime '${agent}' model.reasoningEfforts requires reasoning=true`);+ if (- mm.reasoningDefaultEffort !== undefined- && (- !isPiReasoningEffort(mm.reasoningDefaultEffort)- || !mm.reasoningEfforts.includes(mm.reasoningDefaultEffort)- )++ mm.reasoningDefaultEffort !== undefined &&++ (!isPiReasoningEffort(mm.reasoningDefaultEffort) ||++ !mm.reasoningEfforts.includes(mm.reasoningDefaultEffort))+ ) {+ return invalid(`runtime '${agent}' model.reasoningDefaultEffort invalid`);+ }+ } else if (mm.reasoningEfforts !== undefined || mm.reasoningDefaultEffort !== undefined) {+ return invalid(`runtime '${agent}' reasoning metadata requires reasoning=true`);}}if (r.wireProtocol !== undefined) {// Pi 是多协议 harness;Codex 也具备 Responses / Chat / Anthropic bridge。// Claude Code 只接受原生 Anthropic Messages。-- const allowed = agent === 'claude-code'-- ? ['anthropic-messages']-- : ['openai-responses', 'openai-chat', 'anthropic-messages'];++ const allowed =++ agent === 'claude-code'++ ? ['anthropic-messages']++ : ['openai-responses', 'openai-chat', 'anthropic-messages'];if (typeof r.wireProtocol !== 'string' || !allowed.includes(r.wireProtocol)) {return invalid(`runtime '${agent}' wireProtocol invalid`);}@@@ -206,6 -219,16 +219,14 @@@return invalid(`runtime '${agent}' modelsUrl is not a valid URL`);}}+ if (- r.piCatalogProviderId !== undefined- && (- agent !== 'pi'- || typeof r.piCatalogProviderId !== 'string'- || !/^[a-z0-9-]+$/.test(r.piCatalogProviderId)- )++ r.piCatalogProviderId !== undefined &&++ (agent !== 'pi' ||++ typeof r.piCatalogProviderId !== 'string' ||++ !/^[a-z0-9-]+$/.test(r.piCatalogProviderId))+ ) {+ return invalid(`runtime '${agent}' piCatalogProviderId invalid`);+ }return { ok: true };}@@@ -252,18 -275,18 +273,16 @@@ function validateAuthSection(auth: unknconst unknownField = Object.keys(o).find((field) => !allowedFields.has(field));if (unknownField) return invalid(`auth.oauth.${unknownField} is not allowed`);if (-- flow === 'authorization-code'-- && (o.deviceAuthorizationUrl !== undefined || o.extraDeviceParams !== undefined)++ flow === 'authorization-code' &&++ (o.deviceAuthorizationUrl !== undefined || o.extraDeviceParams !== undefined)) {return invalid('auth.oauth device-code fields not allowed for authorization-code');}if (-- flow === 'device-code'-- && (-- o.authorizeUrl !== undefined-- || o.extraAuthParams !== undefined-- || o.redirectPort !== undefined-- )++ flow === 'device-code' &&++ (o.authorizeUrl !== undefined ||++ o.extraAuthParams !== undefined ||++ o.redirectPort !== undefined)) {return invalid('auth.oauth authorization-code fields not allowed for device-code');}@@@ -292,12 -315,12 +311,11 @@@}if (o.redirectPort !== undefined) {if (-- flow !== 'authorization-code'-- ||-- typeof o.redirectPort !== 'number'-- || !Number.isInteger(o.redirectPort)-- || o.redirectPort <= 0-- || o.redirectPort >= 65536++ flow !== 'authorization-code' ||++ typeof o.redirectPort !== 'number' ||++ !Number.isInteger(o.redirectPort) ||++ o.redirectPort <= 0 ||++ o.redirectPort >= 65536) {return invalid('auth.oauth.redirectPort invalid');}@@@ -308,16 -331,16 +326,11 @@@return invalid(`auth.oauth.${field} invalid`);}if (-- Object.values(o[field] as Record<string, unknown>).some(-- (value) => typeof value !== 'string',-- )++ Object.values(o[field] as Record<string, unknown>).some((value) => typeof value !== 'string')) {return invalid(`auth.oauth.${field} invalid`);}-- const collision = findReservedOAuthExtraParam(-- o[field] as Record<string, unknown>,-- flow,-- );++ const collision = findReservedOAuthExtraParam(o[field] as Record<string, unknown>, flow);if (collision) {return invalid(`auth.oauth.${field} cannot override '${collision}'`);}@@@ -326,10 -349,10 +339,10 @@@try {const url = new URL(String(o.modelsDiscoveryUrl));if (-- typeof o.modelsDiscoveryUrl !== 'string'-- || url.protocol !== 'https:'-- || url.username-- || url.password++ typeof o.modelsDiscoveryUrl !== 'string' ||++ url.protocol !== 'https:' ||++ url.username ||++ url.password) {return invalid('auth.oauth.modelsDiscoveryUrl must be https');}@@@ -451,6 -485,33 +476,35 @@@ function normalizeConfig(config: Customreturn out;}+ /**+ * 官方目录标记只适用于用户尚未改写的预设快照。所有写入口都在 main 再比一次旧值,+ * 避免非当前设置页(移动端、旧 renderer、异步发现)改了路由或模型后仍保留 marker,+ * 继而在 Pi 启动时用官方模型整条覆盖用户显式配置。+ */+ function invalidateEditedPiCatalogMarker(+ previous: CustomProviderConfig,+ next: CustomProviderConfig,+ ): CustomProviderConfig {+ const previousPi = previous.runtimes.pi;+ const nextPi = next.runtimes.pi;+ if (- !previousPi?.piCatalogProviderId- || !nextPi?.piCatalogProviderId- || previousPi.piCatalogProviderId !== nextPi.piCatalogProviderId- ) return next;++ !previousPi?.piCatalogProviderId ||++ !nextPi?.piCatalogProviderId ||++ previousPi.piCatalogProviderId !== nextPi.piCatalogProviderId++ )++ return next;+ const normalizeBaseUrl = (value: string) => value.trim().replace(/\/+$/, '');- const unchanged = normalizeBaseUrl(previousPi.baseUrl) === normalizeBaseUrl(nextPi.baseUrl)- && effectivePiWireProtocol(previousPi.wireProtocol)- === effectivePiWireProtocol(nextPi.wireProtocol)- && preservesPiCatalogModels(previousPi.models, nextPi.models);++ const unchanged =++ normalizeBaseUrl(previousPi.baseUrl) === normalizeBaseUrl(nextPi.baseUrl) &&++ effectivePiWireProtocol(previousPi.wireProtocol) ===++ effectivePiWireProtocol(nextPi.wireProtocol) &&++ preservesPiCatalogModels(previousPi.models, nextPi.models);+ if (unchanged) return next;+ const pi = { ...nextPi };+ delete pi.piCatalogProviderId;+ return { ...next, runtimes: { ...next.runtimes, pi } };+ }+/*** 把授权后自动发现的模型 additions-only 合并进自定义供应商配置的指定 runtime(纯函数)。* 已有 id first-wins(用户手填 / 上次发现的条目不被覆盖);无新增返回 null(调用方免写库)。@@@ -478,7 -539,7 +532,9 @@@ export function mergeDiscoveredModelsIn...fresh.map((m) => ({id: m.id,name: m.name,-- ...(typeof m.contextWindow === 'number' && Number.isFinite(m.contextWindow) && m.contextWindow > 0++ ...(typeof m.contextWindow === 'number' &&++ Number.isFinite(m.contextWindow) &&++ m.contextWindow > 0? { contextWindow: Math.floor(m.contextWindow) }: {}),})),@@@ -521,16 -582,15 +577,17 @@@ function parseRuntimes(raw: string): Paconst r = rt as Record<string, unknown>;const models = Array.isArray(r.models)? r.models-- .filter((m): m is Record<string, unknown> =>-- !!m && typeof m === 'object' && typeof (m as { id?: unknown }).id === 'string',++ .filter(++ (m): m is Record<string, unknown> =>++ !!m && typeof m === 'object' && typeof (m as { id?: unknown }).id === 'string',).map((m) => ({id: String(m.id),name: String(m.name ?? ''),- ...(typeof m.contextWindow === 'number'- && Number.isFinite(m.contextWindow)- && m.contextWindow > 0+ ...(agent === 'pi' && isPiModelApi(m.piApi) ? { piApi: m.piApi } : {}),- ...(typeof m.contextWindow === 'number'- && Number.isFinite(m.contextWindow)- && m.contextWindow > 0++ ...(typeof m.contextWindow === 'number' &&++ Number.isFinite(m.contextWindow) &&++ m.contextWindow > 0? { contextWindow: m.contextWindow }: {}),...(m.defaultEnabled === false ? { defaultEnabled: false } : {}),@@@ -544,7 -604,7 +601,9 @@@};if (typeof r.wireProtocol === 'string' &&-- (r.wireProtocol === 'anthropic-messages' || r.wireProtocol === 'openai-responses' || r.wireProtocol === 'openai-chat')++ (r.wireProtocol === 'anthropic-messages' ||++ r.wireProtocol === 'openai-responses' ||++ r.wireProtocol === 'openai-chat')) {entry.wireProtocol = r.wireProtocol;}@@@ -555,6 -615,13 +614,13 @@@entry.headers = r.headers as Record<string, string>;}if (typeof r.modelsUrl === 'string' && r.modelsUrl.length > 0) entry.modelsUrl = r.modelsUrl;+ if (- agent === 'pi'- && typeof r.piCatalogProviderId === 'string'- && /^[a-z0-9-]+$/.test(r.piCatalogProviderId)++ agent === 'pi' &&++ typeof r.piCatalogProviderId === 'string' &&++ /^[a-z0-9-]+$/.test(r.piCatalogProviderId)+ ) {+ entry.piCatalogProviderId = r.piCatalogProviderId;+ }out[agent] = entry;}return out;@@@ -663,10 -736,10 +735,11 @@@ export async function updateCustomProviconst expectedRuntimes = JSON.stringify(expectedConfig.runtimes);const expectedAuth = expectedConfig.auth ? JSON.stringify(expectedConfig.auth) : null;if (-- existing.name !== expectedConfig.name-- || existing.runtimes !== expectedRuntimes-- || existing.auth !== expectedAuth-- ) return false;++ existing.name !== expectedConfig.name ||++ existing.runtimes !== expectedRuntimes ||++ existing.auth !== expectedAuth++ )++ return false;const result = await db.update(customProviders).set({@@@ -675,10 -748,10 +748,7 @@@auth: nextConfig.auth ? JSON.stringify(nextConfig.auth) : null,updatedAt: Math.max(now, existing.updatedAt + 1),})-- .where(and(-- eq(customProviders.id, id),-- eq(customProviders.updatedAt, existing.updatedAt),-- ));++ .where(and(eq(customProviders.id, id), eq(customProviders.updatedAt, existing.updatedAt)));return result.changes === 1;}diff --cc apps/desktop/src/main/maker-host/pi-host.tsindex 22ce9e617f,5c1c3a47fe..b983923cde--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@@ -32,8 -29,17 +32,18 @@@ import typePiNativeProviderSpec,PiNativeProvidersResult,} from '@cindy/maker-core';- import { PI_REASONING_EFFORTS } from '@cindy/model-providers';- import type { Catalog, PiReasoningEffort, ProviderWireProtocol } from '@cindy/model-providers';+ import {+ PI_REASONING_EFFORTS,+ runtimeCustomProviderId,+ storedCustomProviderId,+ } from '@cindy/model-providers';+ import piModelCatalogJson from '@cindy/model-providers/pi-model-catalog' with { type: 'json' };+ import type {++ Catalog,+ CustomProviderConfig,+ PiReasoningEffort,+ ProviderWireProtocol,+ } from '@cindy/model-providers';import { getReadyBinaryPath } from '../agent-binaries/index.js';import { getPiExtraSpawnConfig } from '../mcp-integrations/piEnvironment.js';@@@ -61,422 -65,20 +72,457 @@@ import { getActiveCatalog, resolveXdPiGconst log = createLogger('pi-host');const PI_API_KEY_ENV = 'CINDY_PI_API_KEY';+ const PI_XAI_PROXY_API_KEY_ENV = 'CINDY_PI_XAI_PROXY_API_KEY';+ const PI_SESSION_ID_ENV = 'CINDY_PI_SESSION_ID';+ const PI_SESSION_TOKEN_ENV = 'CINDY_PI_SESSION_TOKEN';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>;++ samplingParams?: 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');++ 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;++ 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'),++ 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 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'),++ 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,++ 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) } : {}),++ ...(isRecord(value.samplingParams)++ ? { samplingParams: structuredClone(value.samplingParams) }++ : {}),+ };+}++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,- });++ 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'})`));++ 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;++ !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 () => {+ let configDir: string | undefined;+ try {+ configDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-pi-catalog-'));+ // 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(),++ 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',++ },+ },- xai: {- baseUrl: 'http://127.0.0.1:1/v1',- apiKey: 'cindy-pi-catalog-probe',- },- },- }));++ }),++ );+ const childEnv: NodeJS.ProcessEnv = {- ...await readPiCatalogProbeEnv(binaryPath),++ ...(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),++ (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; using daily PI annotations without bundled baseline', {- message: err instanceof Error ? err.message : String(err),- });++ log.warn(++ 'readPiBundledModels: PI catalog probe failed; using daily PI annotations without bundled baseline',++ {++ message: err instanceof Error ? err.message : String(err),++ },++ );+ return null;+ } finally {+ if (configDir) {+ 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 wireId =++ stripPrefix && model.id.startsWith(stripPrefix)++ ? model.id.slice(stripPrefix.length)++ : model.id;+ const bundledModels = bundledModelsByProvider?.get(piProviderId);+ const bundledModel = bundledModels?.get(wireId);+ // A missing/empty/partial PI probe is not evidence that the daily+ // catalog annotation is wrong. Keep annotated rows in the overlay so+ // inheritModels cannot filter out a confirmed addition or correction.+ const isAnnotatedAddition = !!model.piApi && !bundledModel;- const isProtocolCorrection = sourceProviderId !== 'openai'- && !!model.piApi- && !!bundledModel- && bundledModel.api !== model.piApi;++ 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++ ...(sourceProviderId === 'openai' && isAnnotatedAddition+ ? { catalogAddition: true }+ : {}),- ...(sourceProviderId !== 'openai'- && model.piApi- && (isAnnotatedAddition || isProtocolCorrection)++ ...(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,- ]),- ),- }- : {}),++ ? {++ 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 };+}+ /** Dedicated exact remote port for the Desktop-owned xAI compat proxy. */+ export const PI_XAI_COMPAT_FORWARD_PORT = 47989;/*** 订阅 OAuth provider:网关 `cindy` 块经 compat proxy 用安全存储里的 OAuth 服务这些模型,* models.json 的 $CINDY_PI_API_KEY 只需占位(真凭证由 proxy 按 session-id 注入)。- * 自定义 BYOM provider **不在此列** —— 它们走各自原生块 + 独立 key,而网关块仍需真网关 key- * 以便会话中途切回网关模型可用,故 BYOM 会话不能写占位符毒化网关块。+ * xAI/BYOM provider **不在此列** —— 它们走各自原生块 + 独立 key,而网关块仍需真网关 key+ * 以便会话中途切回网关模型可用,故原生 provider 会话不能写占位符毒化网关块。*/- const PI_OAUTH_SUBSCRIPTION_PROVIDERS = new Set(['anthropic', 'openai', 'xai']);+ const PI_OAUTH_SUBSCRIPTION_PROVIDERS = new Set(['anthropic', 'openai']);++const PI_BUNDLED_RESERVED_PROVIDER_IDS = ['anthropic', 'openai-codex', 'xai'] as const;/*** 解析 pi 主执行文件绝对路径;找不到返回 null(pi 为可选实验 agent,不阻塞启动)。@@@ -640,7 -244,7 +688,10 @@@ export interface BuildPiAgentOpts/** 远端 MCP bridge URL 改写器:把本地 loopback URL 改成 remote-forward 地址。* 轮 24 HIGH-2:返回 { url, close } —— close 关闭本次 rewrite 建立的 forward,* pi-host 在会话 dispose 时调用, 防远端端口随会话累积泄漏。 */-- rewriteRemotePiMcpBridgeUrl?: (remoteHostId: string, localUrl: string) => Promise<{ url: string; close: () => void }>;++ rewriteRemotePiMcpBridgeUrl?: (++ remoteHostId: string,++ localUrl: string,++ ) => Promise<{ url: string; close: () => void }>;/** 远端 agent-proxy env(HTTPS_PROXY/HTTP_PROXY/NO_PROXY 经 SSH remote-forward)。 */getRemotePiAgentProxyEnv?: AgentDeps['getRemotePiAgentProxyEnv'];}@@@ -719,6 -269,87 +770,87 @@@ export function piNativeKeyEnvVar(provireturn `CINDY_PI_KEY_${providerId.toUpperCase().replace(/[^A-Z0-9]+/g, '_')}`;}+ interface PiCatalogModel extends PiNativeModelSpec {+ provider: string;+ baseUrl: string;+ }++ const piModelCatalog = piModelCatalogJson as unknown as {+ generatedAt: string;+ providers: Record<string, PiCatalogModel[]>;+ };++ /** Keep Cindy's historical xai/ ids while Pi's official native provider uses bare model ids. */+ export function piNativeModelId(providerId: string, model: string): string {- return providerId === 'xai' && model.startsWith('xai/')- ? model.slice('xai/'.length)- : model;++ return providerId === 'xai' && model.startsWith('xai/') ? model.slice('xai/'.length) : model;+ }++ function officialPiModels(providerId: string): PiNativeModelSpec[] | null {+ const models = piModelCatalog.providers[providerId];+ if (!models) return null;+ return models.map((model) => ({+ id: model.id,+ name: model.name,+ ...(model.headers && Object.keys(model.headers).length > 0 ? { headers: model.headers } : {}),+ api: model.api,+ reasoning: model.reasoning,+ thinkingLevelMap: model.thinkingLevelMap,+ input: model.input,+ cost: model.cost,+ contextWindow: model.contextWindow,+ maxTokens: model.maxTokens,+ compat: model.compat,+ samplingParams: model.samplingParams,+ }));+ }++ function officialPiRouteMatches(+ providerId: string,+ baseUrl: string,+ wireProtocol: ProviderWireProtocol | undefined,+ ): boolean {+ const models = piModelCatalog.providers[providerId];+ if (!models?.length) return false;+ const baseUrls = new Set(models.map((model) => model.baseUrl.replace(/\/+$/, '')));+ const apis = new Set(models.map((model) => model.api));- return baseUrls.size === 1- && baseUrls.has(baseUrl.trim().replace(/\/+$/, ''))- && apis.size === 1- && apis.has(wireProtocolToPiApi(wireProtocol));++ return (++ baseUrls.size === 1 &&++ baseUrls.has(baseUrl.trim().replace(/\/+$/, '')) &&++ apis.size === 1 &&++ apis.has(wireProtocolToPiApi(wireProtocol))++ );+ }++ function configuredPiModel(model: {+ id: string;+ name?: string;+ contextWindow?: number;+ supportsImageInput?: boolean;+ reasoning?: boolean;+ reasoningEfforts?: PiReasoningEffort[];+ }): PiNativeModelSpec {+ const supportedEfforts = new Set(model.reasoningEfforts ?? []);+ return {+ id: model.id,+ name: model.name,+ contextWindow: model.contextWindow,+ ...(model.supportsImageInput === true+ ? { input: ['text', 'image'] as Array<'text' | 'image'> }+ : {}),+ ...(model.reasoning === true+ ? {+ reasoning: true,+ thinkingLevelMap: Object.fromEntries(+ PI_REASONING_EFFORTS.map((effort) => [+ effort,+ supportedEfforts.has(effort) ? effort : null,+ ]),+ ),+ }+ : {}),+ };+ }+/*** 纯映射:自定义 provider 配置(含 pi runtime)→ pi 原生 provider spec + env。* key 读取经 `readKey` 注入(便于单测)。规则:@@@ -783,15 -413,15 +916,16 @@@ export function buildPiNativeProvidersFonSkip?.(cfg.id, 'oauth not supported for pi native');continue;}-- const headers = rt.headers && Object.keys(rt.headers).length > 0-- ? Object.fromEntries(-- Object.entries(rt.headers).map(([name, value]) => {-- const envVar = uniqueEnvVar(`${cfg.id}_HEADER_${name}`);-- env[envVar] = value;-- return [name, `$${envVar}`];-- }),-- )-- : undefined;++ const headers =++ rt.headers && Object.keys(rt.headers).length > 0++ ? Object.fromEntries(++ Object.entries(rt.headers).map(([name, value]) => {++ const envVar = uniqueEnvVar(`${cfg.id}_HEADER_${name}`);++ env[envVar] = value;++ return [name, `$${envVar}`];++ }),++ )++ : undefined;let apiKeyEnvVar: string | undefined;if (authMethod === 'apiKey') {const key = readKey(cfg.id, 'pi');@@@ -804,145 -434,123 +938,246 @@@env[apiKeyEnvVar] = key;}}- const runtimeApi = rt.wireProtocol === undefined- ? undefined- : wireProtocolToPiApi(rt.wireProtocol);++ const runtimeApi =++ rt.wireProtocol === undefined ? undefined : wireProtocolToPiApi(rt.wireProtocol);+ // Protocol authority, in order: per-model daily correction/addition,+ // explicit endpoint protocol, strictly same-origin PI bundled knowledge,+ // then the legacy BYOM default. A same-named model from another provider is+ // not evidence about this user endpoint and must never rewrite its route.+ 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- ?? 'openai-completions');++ : undefined,++ );++ const official =++ rt.piCatalogProviderId &&++ officialPiRouteMatches(rt.piCatalogProviderId, rt.baseUrl, rt.wireProtocol)++ ? officialPiModels(rt.piCatalogProviderId)++ : null;++ const officialById = new Map((official ?? []).map((model) => [model.id, model]));++ const metadataModels = rt.models.map(++ (model, index) => bundledModels[index] ?? officialById.get(model.id),++ );++ const modelApis = rt.models.map(++ (model, index) =>++ model.piApi ?? runtimeApi ?? metadataModels[index]?.api ?? 'openai-completions',++ );+ const providerApi = runtimeApi ?? modelApis[0] ?? 'openai-completions';providers.push({- id: cfg.id,+ id: runtimeCustomProviderId(cfg.id),name: cfg.name,baseUrl: rt.baseUrl,- api: wireProtocolToPiApi(rt.wireProtocol),+ api: providerApi,apiKeyEnvVar,...(headers && Object.keys(headers).length > 0 ? { headers } : {}),- models: (() => {- const official = rt.piCatalogProviderId- && officialPiRouteMatches(rt.piCatalogProviderId, rt.baseUrl, rt.wireProtocol)- ? officialPiModels(rt.piCatalogProviderId)- : null;- const officialById = new Map((official ?? []).map((model) => [model.id, model]));- // The catalog marker proves metadata only for exact matches. Models added by the user,- // returned by modelsUrl, or retained from an older snapshot keep their saved fields.- return rt.models.map((model) => officialById.get(model.id) ?? configuredPiModel(model));- })(),+ models: rt.models.map((m, index) => {+ const supportedEfforts = new Set(m.reasoningEfforts ?? []);+ const modelApi = modelApis[index]!;- const bundledModel = bundledModels[index];++ const bundledModel = metadataModels[index];+ return {+ id: m.id,+ ...(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'> }- : {}),++ ? { input: ['text', 'image'] as Array<'text' | 'image'> }++ : {}),+ ...(bundledModel?.reasoning+ ? {+ reasoning: true,+ ...(bundledModel.thinkingLevelMap+ ? { thinkingLevelMap: { ...bundledModel.thinkingLevelMap } }+ : {}),+ }+ : m.reasoning === true- ? {- reasoning: true,- thinkingLevelMap: Object.fromEntries(- PI_REASONING_EFFORTS.map((effort) => [- effort,- supportedEfforts.has(effort) ? effort : null,- ]),- ),- }- : {}),++ ? {++ reasoning: true,++ thinkingLevelMap: Object.fromEntries(++ PI_REASONING_EFFORTS.map((effort) => [++ effort,++ supportedEfforts.has(effort) ? effort : null,++ ]),++ ),++ }++ : {}),+ ...(bundledModel?.cost ? { cost: { ...bundledModel.cost } } : {}),+ ...(bundledModel?.headers ? { headers: { ...bundledModel.headers } } : {}),+ ...(bundledModel?.compat ? { compat: structuredClone(bundledModel.compat) } : {}),++ ...(bundledModel?.samplingParams++ ? { samplingParams: structuredClone(bundledModel.samplingParams) }++ : {}),+ };+ }),});}return { providers, env };}+/**+ * Combine host subscriptions with user providers without changing persisted+ * custom-provider IDs. PI's bundled provider IDs (notably `openai-codex`) are+ * runtime implementation details and may legally match an existing BYOM ID.+ * In that case only the generated models.json key is namespaced; routing and+ * auth continue to use sourceProviderId, so no DB or safeStorage migration is+ * required.+ */+export function mergePiNativeProviderResults(+ subscriptions: PiNativeProvidersResult,+ custom: PiNativeProvidersResult,+ onNamespace?: (sourceProviderId: string, runtimeProviderId: string) => void,+): PiNativeProvidersResult {+ const occupiedIds = new Set([+ ...subscriptions.providers.map((provider) => provider.id),+ ...custom.providers.map((provider) => provider.id),+ ]);- const runtimeIds = new Set(subscriptions.providers.map((provider) => provider.id));++ const runtimeIds = new Set<string>([++ ...PI_BUNDLED_RESERVED_PROVIDER_IDS,++ ...subscriptions.providers.map((provider) => provider.id),++ ]);+ const customProviders = custom.providers.map((provider) => {+ if (!runtimeIds.has(provider.id)) {+ runtimeIds.add(provider.id);+ return provider;+ }++ const sourceProviderId = provider.sourceProviderId ?? provider.id;+ const baseRuntimeId = `cindy-byom-${sourceProviderId}`;+ let runtimeProviderId = baseRuntimeId;+ for (let suffix = 2; occupiedIds.has(runtimeProviderId); suffix += 1) {+ runtimeProviderId = `${baseRuntimeId}-${suffix}`;+ }+ occupiedIds.add(runtimeProviderId);+ runtimeIds.add(runtimeProviderId);+ onNamespace?.(sourceProviderId, runtimeProviderId);+ return {+ ...provider,+ id: runtimeProviderId,+ sourceProviderId,+ };+ });++ return {+ providers: [...subscriptions.providers, ...customProviders],+ env: { ...subscriptions.env, ...custom.env },+ };+}++ export async function buildXaiPiNativeProvider(+ model?: string,+ allowHistoricalResume = false,+ remote = false,+ ): Promise<PiNativeProvidersResult> {+ const catalogModels =+ getActiveCatalog().providers.find((provider) => provider.id === 'xai')?.models.pi ?? [];- const officialById = new Map((officialPiModels('xai') ?? []).map((candidate) => [candidate.id, candidate]));++ const officialById = new Map(++ (officialPiModels('xai') ?? []).map((candidate) => [candidate.id, candidate]),++ );+ const models = catalogModels.map((catalogModel) => ({- ...(officialById.get(catalogModel.id) ?? configuredPiModel({- id: catalogModel.id,- name: catalogModel.name,- contextWindow: catalogModel.contextWindowVerified ? catalogModel.contextWindow : undefined,- supportsImageInput:- catalogModel.supportsImageInput === true- || catalogModel.modalities?.input.includes('image') === true,- reasoning: catalogModel.efforts.length > 0,- reasoningEfforts: catalogModel.efforts.filter(- (effort): effort is PiReasoningEffort => effort !== 'ultra',- ),- })),++ ...(officialById.get(catalogModel.id) ??++ configuredPiModel({++ id: catalogModel.id,++ name: catalogModel.name,++ supportsImageInput:++ catalogModel.supportsImageInput === true ||++ catalogModel.modalities?.input.includes('image') === true,++ reasoning: catalogModel.efforts.length > 0,++ reasoningEfforts: catalogModel.efforts.filter(++ (effort): effort is PiReasoningEffort => effort !== 'ultra',++ ),++ })),+ id: `xai/${catalogModel.id}`,+ // Keep the xai/ prefix on the wire so the existing compat proxy selects its Responses+ // bridge, which refreshes OAuth per request, recovers 401/403, and injects x_search.+ api: 'anthropic-messages' as const,+ }));+ const aliases = Object.fromEntries(+ catalogModels.flatMap((candidate) => [+ [candidate.id, `xai/${candidate.id}`],+ [`xai/${candidate.id}`, `xai/${candidate.id}`],+ ]),+ );+ if (model) {+ const namespacedModel = model.startsWith('xai/') ? model : `xai/${model}`;+ if (!models.some((candidate) => candidate.id === namespacedModel)) {+ if (!allowHistoricalResume) {+ throw new Error(`Pi official xAI catalog does not contain model '${model}'`);+ }+ // Resume compatibility only: preserve the historical id and route it through the same+ // proxy without asserting unverified vision/reasoning capabilities or publishing it.+ models.push({ id: namespacedModel, name: namespacedModel, api: 'anthropic-messages' });+ aliases[model] = namespacedModel;+ aliases[piNativeModelId('xai', model)] = namespacedModel;+ }+ }+ return {- providers: [{- id: 'xai',- name: 'xAI',- baseUrl: remote- ? (() => {- const endpoint = new URL(getClaudeEndpoint());- endpoint.hostname = '127.0.0.1';- endpoint.port = String(PI_XAI_COMPAT_FORWARD_PORT);- return endpoint.toString().replace(/\/$/, '');- })()- : getClaudeEndpoint(),- api: 'anthropic-messages',- apiKeyEnvVar: PI_XAI_PROXY_API_KEY_ENV,- headers: {- 'x-cindy-pi-session-id': `$${PI_SESSION_ID_ENV}`,- 'x-cindy-pi-session-token': `$${PI_SESSION_TOKEN_ENV}`,++ providers: [++ {++ id: 'xai',++ name: 'xAI',++ baseUrl: remote++ ? (() => {++ const endpoint = new URL(getClaudeEndpoint());++ endpoint.hostname = '127.0.0.1';++ endpoint.port = String(PI_XAI_COMPAT_FORWARD_PORT);++ return endpoint.toString().replace(/\/$/, '');++ })()++ : getClaudeEndpoint(),++ api: 'anthropic-messages',++ apiKeyEnvVar: PI_XAI_PROXY_API_KEY_ENV,++ headers: {++ 'x-cindy-pi-session-id': `$${PI_SESSION_ID_ENV}`,++ 'x-cindy-pi-session-token': `$${PI_SESSION_TOKEN_ENV}`,++ },++ models,++ modelIdAliases: aliases,++ ...(remote++ ? {++ hostProxyForward: {++ localUrl: getClaudeEndpoint(),++ remotePort: PI_XAI_COMPAT_FORWARD_PORT,++ },++ }++ : {}),+ },- models,- modelIdAliases: aliases,- ...(remote- ? {- hostProxyForward: {- localUrl: getClaudeEndpoint(),- remotePort: PI_XAI_COMPAT_FORWARD_PORT,- },- }- : {}),- }],++ ],+ env: { [PI_XAI_PROXY_API_KEY_ENV]: PI_PROVIDER_AUTH_PLACEHOLDER_KEY },+ };+ }+/** BYOM:读 DB 自定义 provider + safeStorage key → pi 原生 provider spec。IO 外壳,逻辑在上面。 */- async function resolvePiNativeProviders(ctx?: {- workingDir?: string;+ export async function resolvePiNativeProviders(ctx: {+ workingDir: string;remoteHostId?: string | null;+ providerId?: string | null;+ model: string;+ resumeSessionId?: string;}): 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;+ let configs: CustomProviderConfig[] = [];try {configs = await listCustomProvidersWithSecureHeaders();} catch (err) {- log.warn('resolvePiNativeProviders: listCustomProviders failed, subscription providers only', {- log.warn('resolvePiNativeProviders: listCustomProviders failed, continuing without custom providers', {-- message: err instanceof Error ? err.message : String(err),-- });- return subscriptions;++ log.warn(++ 'resolvePiNativeProviders: listCustomProviders failed, continuing with subscriptions only',++ {++ message: err instanceof Error ? err.message : String(err),++ },++ );}- const isRemote = Boolean(ctx?.remoteHostId);+ const isRemote = Boolean(ctx.remoteHostId);// 远端会话:本地 loopback 端点(本机 Ollama/vLLM)远端够不到。// 轮 42 P2(codex-connector):**不再 pre-filter 掉** —— 让 PiAgent 的// [REMOTE_LOCAL_ONLY_PROVIDER] guard 显式拒绝, 用户才能拿到带行动指引的@@@ -952,26 -560,33 +1187,47 @@@for (const c of configs) {const baseUrl = c.runtimes.pi?.baseUrl;if (baseUrl && isLoopbackUrl(baseUrl)) {-- log.debug('resolvePiNativeProviders: remote session has loopback BYOM provider (core guard will reject)', {-- id: c.id,-- baseUrl,-- });++ log.debug(++ 'resolvePiNativeProviders: remote session has loopback BYOM provider (core guard will reject)',++ {++ id: c.id,++ baseUrl,++ },++ );}}}const custom = buildPiNativeProvidersFromConfigs(configs,readCustomProviderKey,-- (id, reason) =>-- log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason }),++ (id, reason) => log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason }),+ bundledModels ?? undefined,);- return mergePiNativeProviderResults(subscriptions, custom, (sourceProviderId, runtimeProviderId) => {- log.info('resolvePiNativeProviders: namespaced custom provider runtime id', {- sourceProviderId,- runtimeProviderId,- });- });- // `xai` is exclusively the official SuperGrok identity. Historical custom connections are- // migrated to the runtime-only `custom:xai` id, so resume/login/model overlap must never infer- // provenance or relabel a user endpoint as official (or vice versa).- if (ctx.providerId === 'xai' || hasGrokOAuthLogin()) {- const selectedXaiModel = ctx.providerId === 'xai'- || (!ctx.providerId && ctx.model.startsWith('xai/'))- ? ctx.model- : undefined;++ // Remote PI cannot use the local native overlay. Preserve upstream's exact++ // SuperGrok provenance/forwarding path there; locally the version-matched PI++ // native provider above remains the protocol authority.++ if (++ !subscriptions.providers.some((provider) => provider.id === 'xai') &&++ (ctx.providerId === 'xai' || hasGrokOAuthLogin())++ ) {++ const selectedXaiModel =++ ctx.providerId === 'xai' || (!ctx.providerId && ctx.model.startsWith('xai/'))++ ? ctx.model++ : undefined;+ const xai = await buildXaiPiNativeProvider(selectedXaiModel, !!ctx.resumeSessionId, isRemote);+ custom.providers.push(...xai.providers);+ Object.assign(custom.env, xai.env);+ }- return custom;++ return mergePiNativeProviderResults(++ subscriptions,++ custom,++ (sourceProviderId, runtimeProviderId) => {++ log.info('resolvePiNativeProviders: namespaced custom provider runtime id', {++ sourceProviderId,++ runtimeProviderId,++ });++ },++ );}/** baseUrl 是否指向本机 loopback(与本机 proxy 同判定,远端会话不可达)。@@@ -981,10 -596,10 +1237,12 @@@function isLoopbackUrl(baseUrl: string): boolean {try {const host = new URL(baseUrl).hostname.toLowerCase();-- return host === 'localhost'-- || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host)-- || host === '::1'-- || host === '[::1]';++ return (++ host === 'localhost' ||++ /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host) ||++ host === '::1' ||++ host === '[::1]'++ );} catch {return false;}@@@ -1012,7 -628,7 +1271,7 @@@ export function buildPiAgent(opts: Buil// 与 Claude Code / Codex 同一份第一方 MCP 审批真源。Pi 之前没接,导致 orca 这类// 可信 server 的工具落进 Auto-review 灰区被模型静默 block(详见 pi/index.ts 权限门)。getMcpToolApprovalPolicy: getDesktopMcpToolApprovalPolicy,--getMcpToolApprovalPresentation: getDesktopMcpToolApprovalPresentation,++ getMcpToolApprovalPresentation: getDesktopMcpToolApprovalPresentation,resolvePiAgentHome: (remoteHostId) => {// 轮 40-w4-t3 CRITICAL:远端 agentHome 承载 session 历史(sessions/*.jsonl,// 与 DB sdk_session_id 持久关联)—— 必须落远端持久目录, 不能用本机@@@ -1060,7 -676,7 +1319,11 @@@// 端残留引用泄漏 —— R2 凭证 Bug7)。然后重抛,由 PiAgent 的 catch// 降级为「远端无 MCP」。for (const close of forwardClosers) {-- try { close(); } catch { /* best-effort */ }++ try {++ close();++ } catch {++ /* best-effort */++ }}try {extra.disposeSessionCtx?.();@@@ -1077,7 -693,7 +1340,11 @@@mcpBridge: { ...extra.mcpBridge, servers },disposeSessionCtx: () => {for (const close of forwardClosers) {-- try { close(); } catch { /* best-effort */ }++ try {++ close();++ } catch {++ /* best-effort */++ }}baseDispose?.();},diff --cc apps/desktop/src/main/maker-host/pi-proxy-session-auth.tsindex 8d33141485,bcd55cab03..b420808817--- a/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts+++ b/apps/desktop/src/main/maker-host/pi-proxy-session-auth.ts@@@ -9,22 -9,20 +9,26 @@@import { timingSafeEqual } from 'node:crypto';-interface PiProxySessionRegistration {+interface ActivePiProxySession {token: string;+ resolveProviderId: () => string | null;}-const activeRegistrations = new Map<string, PiProxySessionRegistration>();+const activeSessions = new Map<string, ActivePiProxySession>();-export function registerPiProxySession(sessionId: string, token: string): () => void {- if (!sessionId || !token) throw new Error('Pi proxy session registration requires an id and token');- const registration = { token };- activeRegistrations.set(sessionId, registration);+export function registerPiProxySession(+ sessionId: string,+ token: string,+ resolveProviderId: () => string | null = () => null,+): () => void {- if (!sessionId || !token) throw new Error('Pi proxy session registration requires an id and token');- activeSessions.set(sessionId, { token, resolveProviderId });++ if (!sessionId || !token)++ throw new Error('Pi proxy session registration requires an id and token');++ const registration = { token, resolveProviderId };++ activeSessions.set(sessionId, registration);return () => {- if (activeSessions.get(sessionId)?.token === token) activeSessions.delete(sessionId);- if (activeRegistrations.get(sessionId) === registration) {- activeRegistrations.delete(sessionId);++ if (activeSessions.get(sessionId) === registration) {++ activeSessions.delete(sessionId);+ }};}@@@ -33,16 -31,8 +37,17 @@@ export function authenticatePiProxySessif (!expected || !candidate) return false;const expectedBytes = Buffer.from(expected);const candidateBytes = Buffer.from(candidate);-- return expectedBytes.length === candidateBytes.length-- && timingSafeEqual(expectedBytes, candidateBytes);++ return (++ expectedBytes.length === candidateBytes.length && timingSafeEqual(expectedBytes, candidateBytes)++ );+}++/**+ * Host-resolved provider bound to the authenticated Pi process. Callers must+ * authenticate the same session immediately before reading this value.+ */+export function getPiProxySessionProvider(sessionId: string): string | null {+ return activeSessions.get(sessionId)?.resolveProviderId() ?? null;}/** Test isolation only. */diff --cc apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsxindex 32d42422da,3922b930f7..a85d2f065a--- a/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx+++ b/apps/desktop/src/renderer/__tests__/customProviderDialogPresetLocale.test.tsx@@@ -24,15 -24,16 +24,27 @@@ vi.mock('@/lib/customProviderId', () =}));vi.mock('@/lib/customProviders', () => ({+ clearCustomProviderModelPiApiOverrides: vi.fn((models: Array<Record<string, unknown>>) =>+ models.map((model) => {+ const next = { ...model };+ delete next.piApi;+ return next;- })),++ }),++ ),createCustomProvider: vi.fn(async () => undefined),- customProviderWireProtocolForSave: vi.fn((agent: string, wireProtocol: string, defaultWireProtocol: string) =>- agent === 'pi' || wireProtocol !== defaultWireProtocol ? wireProtocol : undefined),++ customProviderWireProtocolForSave: vi.fn(++ (agent: string, wireProtocol: string, defaultWireProtocol: string) =>++ agent === 'pi' || wireProtocol !== defaultWireProtocol ? wireProtocol : undefined,++ ),+ piCatalogProviderIdAfterRouteEdit: (+ _agent: string,+ previous: { baseUrl: string; wireProtocol: string; piCatalogProviderId?: string },+ next: { baseUrl: string; wireProtocol: string; piCatalogProviderId?: string },+ ) =>- next.piCatalogProviderId === previous.piCatalogProviderId- && (next.baseUrl !== previous.baseUrl || next.wireProtocol !== previous.wireProtocol)++ next.piCatalogProviderId === previous.piCatalogProviderId &&++ (next.baseUrl !== previous.baseUrl || next.wireProtocol !== previous.wireProtocol)+ ? undefined+ : next.piCatalogProviderId,readCustomProviderKey: vi.fn(),replaceCustomProviderModelId: vi.fn(),setCustomProviderModelReasoning: vi.fn(),@@@ -58,24 -59,6 +70,26 @@@ const localizedPreset: ProviderPreset},};+const piProtocolPreset: ProviderPreset = {+ id: 'pi-protocol-preset',+ name: 'PI Protocol Preset',+ nameEn: 'PI Protocol Preset',+ authMethod: 'none',+ runtimes: {+ pi: {+ baseUrl: 'http://127.0.0.1:4001/v1',+ wireProtocol: 'openai-responses',- models: [{- id: 'deepseek-v4-pro',- name: 'DeepSeek V4 Pro',- piApi: 'openai-responses',- }],++ models: [++ {++ id: 'deepseek-v4-pro',++ name: 'DeepSeek V4 Pro',++ piApi: 'openai-responses',++ },++ ],+ },+ },+};+function renderDialog(onClose = vi.fn()) {return {onClose,@@@ -199,33 -217,6 +250,36 @@@ describe('CustomProviderDialog preset lexpect(onClose).toHaveBeenCalledTimes(1);});+ it.each([+ ['settings.providers.custom.wireProtocol.piChat', 'openai-chat'],+ ['settings.providers.custom.wireProtocol.piAnthropic', 'anthropic-messages'],+ ] as const)(+ 'saves an explicit %s PI selection without the preset piApi override',+ async (buttonName, wireProtocol) => {+ i18nState.language = 'en';+ renderDialog();+- fireEvent.click(await screen.findByRole('button', {- name: 'settings.providers.custom.presets.label',- }));++ fireEvent.click(++ await screen.findByRole('button', {++ name: 'settings.providers.custom.presets.label',++ }),++ );+ fireEvent.click(await screen.findByRole('option', { name: 'PI Protocol Preset' }));+ fireEvent.click(screen.getByRole('tab', { name: 'settings.providers.custom.protocol.pi' }));+ fireEvent.click(screen.getByRole('button', { name: buttonName }));+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.custom.save' }));++ await waitFor(() => expect(createCustomProvider).toHaveBeenCalledTimes(1));+ expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.pi).toMatchObject({+ wireProtocol,+ models: [{ id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' }],+ });- expect(vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.pi?.models[0])- .not.toHaveProperty('piApi');++ expect(++ vi.mocked(createCustomProvider).mock.calls[0][0].runtimes.pi?.models[0],++ ).not.toHaveProperty('piApi');+ },+ );+it.each([['isComposing', { isComposing: true }],['keyCode 229', { keyCode: 229 }],diff --cc apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsxindex e509680f29,bf3f37242d..adfce4b4a5--- a/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx+++ b/apps/desktop/src/renderer/components/settings/CustomProviderDialog.tsx@@@ -15,14 -15,14 +15,7 @@@*/import * as Dialog from '@radix-ui/react-dialog';--import {-- useCallback,-- useEffect,-- useLayoutEffect,-- useRef,-- useState,-- type RefObject,--} from 'react';++import { useCallback, useEffect, useLayoutEffect, useRef, useState, type RefObject } from 'react';import { useTranslation } from 'react-i18next';import { Check, ChevronDown, Plug, Plus, RefreshCw, Sparkles, Trash2, X } from 'lucide-react';@@@ -39,9 -39,8 +32,10 @@@ import} from '@/components/settings/CustomProviderRuntimeFillOverlay';import { extractIpcError } from '@/utils/ipcError';import {+ clearCustomProviderModelPiApiOverrides,createCustomProvider,+ customProviderWireProtocolForSave,+ piCatalogProviderIdAfterRouteEdit,readCustomProviderKey,replaceCustomProviderModelId,setCustomProviderModelReasoning,@@@ -117,24 -116,24 +111,26 @@@ const DIALOG_FOCUSABLE_SELECTOR ='[tabindex]:not([tabindex="-1"])',].join(',');--const TAB_META: Record<DialogAgentKind, { Mark: typeof ClaudeMark; labelKey: string; helpKey: string }> =-- {-- 'claude-code': {-- Mark: ClaudeMark,-- labelKey: 'settings.providers.custom.protocol.claude',-- helpKey: 'settings.providers.custom.protocol.claudeDesc',-- },-- codex: {-- Mark: CodexMark,-- labelKey: 'settings.providers.custom.protocol.codex',-- helpKey: 'settings.providers.custom.protocol.codexDesc',-- },-- pi: {-- Mark: PiMark,-- labelKey: 'settings.providers.custom.protocol.pi',-- helpKey: 'settings.providers.custom.protocol.piDesc',-- },-- };++const TAB_META: Record<++ DialogAgentKind,++ { Mark: typeof ClaudeMark; labelKey: string; helpKey: string }++> = {++ 'claude-code': {++ Mark: ClaudeMark,++ labelKey: 'settings.providers.custom.protocol.claude',++ helpKey: 'settings.providers.custom.protocol.claudeDesc',++ },++ codex: {++ Mark: CodexMark,++ labelKey: 'settings.providers.custom.protocol.codex',++ helpKey: 'settings.providers.custom.protocol.codexDesc',++ },++ pi: {++ Mark: PiMark,++ labelKey: 'settings.providers.custom.protocol.pi',++ helpKey: 'settings.providers.custom.protocol.piDesc',++ },++};/** pi 默认 wire protocol:BYOM 本地端点(Ollama/vLLM 的 /v1/chat/completions)最常见。 */const PI_DEFAULT_WIRE: ProviderWireProtocol = 'openai-chat';@@@ -423,9 -426,9 +423,7 @@@ export function CustomProviderDialog(const picker = childLayer?.kind === 'model-picker' ? childLayer.value : null;const presetMenuOpen = childLayer?.kind === 'preset-menu';const [keyHydrationReady, setKeyHydrationReady] = useState(!editing);-- const [keyHydrationFailed, setKeyHydrationFailed] = useState<-- Record<DialogAgentKind, boolean>-- >({++ const [keyHydrationFailed, setKeyHydrationFailed] = useState<Record<DialogAgentKind, boolean>>({'claude-code': false,codex: false,pi: false,@@@ -504,11 -507,15 +502,17 @@@const rtRef = useRef(rt);/** 唯一的 rt 写入口:状态更新的同时同步镜像进 rtRef(updater 幂等,StrictMode 双调无害)。 */const setRtSynced = useCallback(-- (fn: (prev: Record<DialogAgentKind, RuntimeFields>) => Record<DialogAgentKind, RuntimeFields>) => {++ (++ fn: (prev: Record<DialogAgentKind, RuntimeFields>) => Record<DialogAgentKind, RuntimeFields>,++ ) => {setRt((prev) => {- const next = fn(prev);- rtRef.current = next;- return next;+ const updated = fn(prev);+ // Do not consume the catalog marker while the user is still editing.+ // A temporary route/model change can be reverted before Save; marker+ // ownership is decided once below from the persisted baseline and the+ // final serialized values.+ rtRef.current = updated;+ return updated;});},[],@@@ -577,15 -584,15 +581,19 @@@[savedBaselineFor],);-- const changeAuthMode = useCallback((mode: CustomProviderAuthMode) => {-- setAuthMode(mode);-- if (mode !== 'apiKey') return;-- setRtSynced((prev) =>-- Object.fromEntries(-- AGENTS.map((agent) => [agent, restoreHydratedKey(agent, prev[agent])]),-- ) as Record<DialogAgentKind, RuntimeFields>,-- );-- }, [restoreHydratedKey, setRtSynced]);++ const changeAuthMode = useCallback(++ (mode: CustomProviderAuthMode) => {++ setAuthMode(mode);++ if (mode !== 'apiKey') return;++ setRtSynced(++ (prev) =>++ Object.fromEntries(++ AGENTS.map((agent) => [agent, restoreHydratedKey(agent, prev[agent])]),++ ) as Record<DialogAgentKind, RuntimeFields>,++ );++ },++ [restoreHydratedKey, setRtSynced],++ );// 新建态拉取预设模板(本地 IPC 极快返回;失败静默 —— 没有预设也不影响手填,规则 7 不做 loading)。// 按实际构建区域排序,不随 UI 语言变化(只排序不过滤,可达性由测试连接实测裁决)。@@@ -659,7 -667,7 +668,11 @@@setKeyHydrationFailed({ 'claude-code': false, codex: false, pi: false });const revisionAtStart = { ...keyEditRevisionRef.current };void (async () => {-- const nextHas: Record<DialogAgentKind, boolean> = { 'claude-code': false, codex: false, pi: false };++ const nextHas: Record<DialogAgentKind, boolean> = {++ 'claude-code': false,++ codex: false,++ pi: false,++ };const fetched: Partial<Record<DialogAgentKind, string>> = {};const failed: Record<DialogAgentKind, boolean> = {'claude-code': false,@@@ -841,7 -849,7 +854,9 @@@);});if (hasUnreviewedConflict) {-- setRuntimeFill((prev) => (prev ? { ...prev, stage: 'confirm', targets: freshTargets } : prev));++ setRuntimeFill((prev) =>++ prev ? { ...prev, stage: 'confirm', targets: freshTargets } : prev,++ );return;}@@@ -985,8 -987,8 +1000,8 @@@);const useSaved = Boolean(initial?.id &&-- savedBaseline &&-- connectionTestCanUseSaved(probeFields, savedBaseline, authMode),++ savedBaseline &&++ connectionTestCanUseSaved(probeFields, savedBaseline, authMode),);setTest((prev) => ({ ...prev, [agent]: { status: 'testing' } }));try {@@@ -1004,20 -1006,20 +1019,16 @@@...(agent !== 'pi' && rf.requestPath.trim()? { requestPath: rf.requestPath.trim() }: {}),-- apiKey:-- authMode === 'apiKey' && canSendApiKey ? rf.apiKey.trim() || null : null,++ apiKey: authMode === 'apiKey' && canSendApiKey ? rf.apiKey.trim() || null : null,...(Object.keys(requestHeaders).length > 0 ? { headers: requestHeaders } : {}),},},);if (providerConnectionTestRequestSignature(-- agent === 'pi'-- ? { ...rtRef.current[agent], requestPath: '' }-- : rtRef.current[agent],++ agent === 'pi' ? { ...rtRef.current[agent], requestPath: '' } : rtRef.current[agent],authModeRef.current,-- ) !==-- requestSig++ ) !== requestSig)return;setTest((prev) => ({@@@ -1029,12 -1031,12 +1040,9 @@@} catch (e) {if (providerConnectionTestRequestSignature(-- agent === 'pi'-- ? { ...rtRef.current[agent], requestPath: '' }-- : rtRef.current[agent],++ agent === 'pi' ? { ...rtRef.current[agent], requestPath: '' } : rtRef.current[agent],authModeRef.current,-- ) !==-- requestSig++ ) !== requestSig)return;const ipc = extractIpcError(e);@@@ -1058,7 -1060,7 +1066,8 @@@fetchingModels['claude-code'] ||fetchingModels.codex ||fetchingModels.pi-- ) return; // 单飞(按钮已禁用,兜底)++ )++ return; // 单飞(按钮已禁用,兜底)const baseUrl = rf.baseUrl.trim();if (!baseUrl) {toast.error(t('settings.providers.custom.fetch.needBaseUrl'));@@@ -1084,14 -1086,14 +1093,11 @@@const canSendApiKey =authMode !== 'apiKey' ||!savedBaseline ||-- canSendHydratedApiKey(-- rf,-- savedBaseline,-- authMode,-- keyEditRevisionRef.current[agent],-- );++ canSendHydratedApiKey(rf, savedBaseline, authMode, keyEditRevisionRef.current[agent]);const reuseSaved = Boolean(-- initial?.id && savedBaseline && modelFetchCanReuseSavedCredentials(rf, savedBaseline, authMode),++ initial?.id &&++ savedBaseline &&++ modelFetchCanReuseSavedCredentials(rf, savedBaseline, authMode),);modelFetchInFlightRef.current = true;setFetchingModels((prev) => ({ ...prev, [agent]: true }));@@@ -1206,7 -1218,9 +1224,10 @@@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;+ const reasoningDefaultEffort = latest+ ? latest.reasoningDefaultEffort+ : m.reasoningDefaultEffort;return {id: m.id,name: latest?.name.trim() ? latest.name.trim() : m.name,@@@ -1215,7 -1228,13 +1236,11 @@@...(defaultEnabled === false ? { defaultEnabled: false } : {}),...(supportsImageInput === true ? { supportsImageInput: true } : {}),...(reasoning === true && reasoningEfforts?.length- ? { reasoning: true, reasoningEfforts: [...reasoningEfforts] }+ ? {+ reasoning: true,+ reasoningEfforts: [...reasoningEfforts],- ...(reasoningDefaultEffort- ? { reasoningDefaultEffort }- : {}),++ ...(reasoningDefaultEffort ? { reasoningDefaultEffort } : {}),+ }: {}),};});@@@ -1539,12 -1578,12 +1591,7 @@@onPointerDown={(event) => {// pointerdown 时先按当前层级结算,避免 Popover 的 outside-dismiss 在随后// click 前把状态改成 closed,令同一次手势继续误关底层表单。-- if (-- event.button === 0 &&-- event.target === event.currentTarget &&-- !saving &&-- !runtimeFill-- ) {++ if (event.button === 0 && event.target === event.currentTarget && !saving && !runtimeFill) {event.preventDefault();event.stopPropagation();dismissTopmostLayer();@@@ -1812,28 -1851,28 +1859,32 @@@: undefined}>-- {t(activeTab === 'pi'-- ? `settings.providers.custom.wireProtocol.pi${-- option.value === 'anthropic-messages'-- ? 'Anthropic'-- : option.value === 'openai-responses'-- ? 'Responses'-- : 'Chat'-- }`-- : option.labelKey)}++ {t(++ activeTab === 'pi'++ ? `settings.providers.custom.wireProtocol.pi${++ option.value === 'anthropic-messages'++ ? 'Anthropic'++ : option.value === 'openai-responses'++ ? 'Responses'++ : 'Chat'++ }`++ : option.labelKey,++ )}</button>))}</div><span className="text-12 leading-snug text-[var(--text-tertiary)]">-- {t(activeTab === 'pi'-- ? `settings.providers.custom.wireProtocol.pi${-- f.wireProtocol === 'anthropic-messages'-- ? 'AnthropicHelp'-- : f.wireProtocol === 'openai-chat'-- ? 'ChatHelp'-- : 'ResponsesHelp'-- }`-- : customProviderCodexWireProtocolOption(f.wireProtocol).helpKey)}++ {t(++ activeTab === 'pi'++ ? `settings.providers.custom.wireProtocol.pi${++ f.wireProtocol === 'anthropic-messages'++ ? 'AnthropicHelp'++ : f.wireProtocol === 'openai-chat'++ ? 'ChatHelp'++ : 'ResponsesHelp'++ }`++ : customProviderCodexWireProtocolOption(f.wireProtocol).helpKey,++ )}</span></div>)}@@@ -1982,8 -2021,8 +2033,8 @@@<SettingsTextInputsurface="ivory"value={-- windowDrafts[`${activeTab}:${i}`]-- ?? (m.contextWindow != null ? String(m.contextWindow) : '')++ windowDrafts[`${activeTab}:${i}`] ??++ (m.contextWindow != null ? String(m.contextWindow) : '')}onBlur={() =>setWindowDrafts((drafts) => {diff --cc apps/desktop/src/renderer/lib/__tests__/customProviders.test.tsindex 0d37e6fa0a,91c8cc6a62..254e093ce6--- a/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts+++ b/apps/desktop/src/renderer/lib/__tests__/customProviders.test.ts@@@ -1,12 -1,15 +1,17 @@@import { afterEach, describe, expect, it, vi } from 'vitest';+ import { customProviderSecretStorageKey } from '@/../shared/providerSecrets';+import {appendDiscoveredCustomProviderModels,+ clearCustomProviderModelPiApiOverrides,createCustomProvider,customProviderModelConfigFromCatalogModel,+ customProviderWireProtocolForSave,+ deleteCustomProvider,+ piCatalogProviderIdAfterRouteEdit,providerViewToCustomProviderConfig,+ readCustomProviderKey,replaceCustomProviderModelId,setCustomProviderModelReasoning,setCustomProviderModelReasoningEffort,@@@ -22,16 -25,181 +27,207 @@@ afterEach(() =>vi.unstubAllGlobals();});+ describe('piCatalogProviderIdAfterRouteEdit', () => {+ const official = {+ baseUrl: 'https://api.example.com/anthropic',+ wireProtocol: 'anthropic-messages' as const,+ piCatalogProviderId: 'example',+ };++ it('keeps a newly applied marker and an unchanged official route', () => {+ expect(+ piCatalogProviderIdAfterRouteEdit(+ 'pi',+ { ...official, piCatalogProviderId: undefined },+ official,+ ),+ ).toBe('example');+ expect(piCatalogProviderIdAfterRouteEdit('pi', official, official)).toBe('example');+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...official,+ baseUrl: `${official.baseUrl}/`,+ }),+ ).toBe('example');+ });++ it('clears the marker after either endpoint or protocol is edited', () => {+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...official,+ baseUrl: 'https://proxy.example/v1',+ }),+ ).toBeUndefined();+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...official,+ wireProtocol: 'openai-chat',+ }),+ ).toBeUndefined();+ });++ it('keeps the marker when a temporary route edit is reverted before the final save', () => {+ const temporaryEdit = {+ ...official,+ baseUrl: 'https://proxy.example/v1',+ };+ expect(piCatalogProviderIdAfterRouteEdit('pi', official, temporaryEdit)).toBeUndefined();+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...temporaryEdit,+ baseUrl: official.baseUrl,+ }),+ ).toBe('example');+ expect(+ piCatalogProviderIdAfterRouteEdit('pi', official, {+ ...temporaryEdit,+ wireProtocol: official.wireProtocol,+ }),+ ).toBeUndefined();+ });++ it('treats an omitted Pi protocol as the effective openai-chat default', () => {+ const openAiChat = {+ ...official,+ wireProtocol: 'openai-chat' as const,+ };- expect(piCatalogProviderIdAfterRouteEdit('pi', openAiChat, {- ...openAiChat,- wireProtocol: undefined,- })).toBe('example');- expect(piCatalogProviderIdAfterRouteEdit('pi', {- ...openAiChat,- wireProtocol: undefined,- }, openAiChat)).toBe('example');- expect(piCatalogProviderIdAfterRouteEdit('pi', openAiChat, {- ...openAiChat,- wireProtocol: 'anthropic-messages',- })).toBeUndefined();++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', openAiChat, {++ ...openAiChat,++ wireProtocol: undefined,++ }),++ ).toBe('example');++ expect(++ piCatalogProviderIdAfterRouteEdit(++ 'pi',++ {++ ...openAiChat,++ wireProtocol: undefined,++ },++ openAiChat,++ ),++ ).toBe('example');++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', openAiChat, {++ ...openAiChat,++ wireProtocol: 'anthropic-messages',++ }),++ ).toBeUndefined();+ });++ it('clears the marker after any model metadata is edited', () => {+ const withModels: {+ baseUrl: string;+ wireProtocol: 'anthropic-messages';+ piCatalogProviderId: string;+ models: ProviderRuntimeModelConfig[];+ } = {+ ...official,- models: [{- id: 'model-a',- name: 'Model A',- contextWindow: 128_000,- supportsImageInput: true,- reasoning: true,- reasoningEfforts: ['low', 'high'],- reasoningDefaultEffort: 'high',- }],++ models: [++ {++ id: 'model-a',++ name: 'Model A',++ contextWindow: 128_000,++ supportsImageInput: true,++ reasoning: true,++ reasoningEfforts: ['low', 'high'],++ reasoningDefaultEffort: 'high',++ },++ ],+ };+ expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, withModels)).toBe('example');+ const editedModels: ProviderRuntimeModelConfig[] = [+ { ...withModels.models[0], name: 'Renamed' },+ { ...withModels.models[0], contextWindow: 64_000 },+ { ...withModels.models[0], supportsImageInput: false },+ { ...withModels.models[0], reasoningEfforts: ['low'] },+ ];+ for (const model of editedModels) {- expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {- ...withModels,- models: [model],- })).toBeUndefined();++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', withModels, {++ ...withModels,++ models: [model],++ }),++ ).toBeUndefined();+ }- expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {- ...withModels,- models: [- ...withModels.models,- { id: 'models-url-only', name: 'Models URL Only', defaultEnabled: false },- ],- })).toBe('example');- expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {- ...withModels,- models: [{ ...withModels.models[0], defaultEnabled: false }],- })).toBe('example');- expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {- ...withModels,- models: [],- })).toBeUndefined();- expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {- ...withModels,- models: [{- id: 'model-b',- name: 'My Model B',- contextWindow: 64_000,- supportsImageInput: false,- reasoning: true,- reasoningEfforts: ['low'],- reasoningDefaultEffort: 'low',- }],- })).toBeUndefined();- expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {- ...withModels,- models: [- { id: 'new-model', name: 'New model' },- withModels.models[0],- ],- })).toBe('example');++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', withModels, {++ ...withModels,++ models: [++ ...withModels.models,++ { id: 'models-url-only', name: 'Models URL Only', defaultEnabled: false },++ ],++ }),++ ).toBe('example');++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', withModels, {++ ...withModels,++ models: [{ ...withModels.models[0], defaultEnabled: false }],++ }),++ ).toBe('example');++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', withModels, {++ ...withModels,++ models: [],++ }),++ ).toBeUndefined();++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', withModels, {++ ...withModels,++ models: [++ {++ id: 'model-b',++ name: 'My Model B',++ contextWindow: 64_000,++ supportsImageInput: false,++ reasoning: true,++ reasoningEfforts: ['low'],++ reasoningDefaultEffort: 'low',++ },++ ],++ }),++ ).toBeUndefined();++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', withModels, {++ ...withModels,++ models: [{ id: 'new-model', name: 'New model' }, withModels.models[0]],++ }),++ ).toBe('example');+ const twoModels = {+ ...withModels,- models: [- withModels.models[0],- { id: 'model-b', name: 'Model B', contextWindow: 64_000 },- ],++ models: [withModels.models[0], { id: 'model-b', name: 'Model B', contextWindow: 64_000 }],+ };- expect(piCatalogProviderIdAfterRouteEdit('pi', twoModels, {- ...twoModels,- models: [...twoModels.models].reverse(),- })).toBe('example');- expect(piCatalogProviderIdAfterRouteEdit('pi', withModels, {- ...withModels,- models: [- { ...withModels.models[0], name: 'Edited first duplicate' },- withModels.models[0],- ],- })).toBeUndefined();++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', twoModels, {++ ...twoModels,++ models: [...twoModels.models].reverse(),++ }),++ ).toBe('example');++ expect(++ piCatalogProviderIdAfterRouteEdit('pi', withModels, {++ ...withModels,++ models: [{ ...withModels.models[0], name: 'Edited first duplicate' }, withModels.models[0]],++ }),++ ).toBeUndefined();+ });+ });+describe('replaceCustomProviderModelId', () => {it('drops hidden metadata when the model id changes', () => {-- expect(replaceCustomProviderModelId({-- id: 'MiniMax-M3',-- name: 'MiniMax M3',-- contextWindow: 1_000_000,-- supportsImageInput: true,-- reasoning: true,-- reasoningEfforts: ['low', 'high'],- reasoningDefaultEffort: 'high',-- }, 'another-model')).toEqual({++ expect(++ replaceCustomProviderModelId(++ {++ id: 'MiniMax-M3',++ name: 'MiniMax M3',++ contextWindow: 1_000_000,++ supportsImageInput: true,++ reasoning: true,++ reasoningEfforts: ['low', 'high'],++ reasoningDefaultEffort: 'high',++ },++ 'another-model',++ ),++ ).toEqual({id: 'another-model',name: 'MiniMax M3',});@@@ -47,30 -215,6 +243,36 @@@});});+describe('PI custom-provider protocol overrides', () => {+ it('drops preset piApi metadata and persists an explicit Chat selection', () => {- const models: ProviderRuntimeModelConfig[] = [{- id: 'deepseek-v4-pro',- name: 'DeepSeek V4 Pro',- piApi: 'openai-responses',- contextWindow: 1_000_000,- }];++ const models: ProviderRuntimeModelConfig[] = [++ {++ id: 'deepseek-v4-pro',++ name: 'DeepSeek V4 Pro',++ piApi: 'openai-responses',++ contextWindow: 1_000_000,++ },++ ];+- expect(clearCustomProviderModelPiApiOverrides(models)).toEqual([{- id: 'deepseek-v4-pro',- name: 'DeepSeek V4 Pro',- contextWindow: 1_000_000,- }]);- expect(customProviderWireProtocolForSave('pi', 'openai-chat', 'openai-chat'))- .toBe('openai-chat');++ expect(clearCustomProviderModelPiApiOverrides(models)).toEqual([++ {++ id: 'deepseek-v4-pro',++ name: 'DeepSeek V4 Pro',++ contextWindow: 1_000_000,++ },++ ]);++ expect(customProviderWireProtocolForSave('pi', 'openai-chat', 'openai-chat')).toBe(++ 'openai-chat',++ );+ });++ it('keeps non-PI default protocol serialization sparse', () => {- expect(customProviderWireProtocolForSave('codex', 'openai-responses', 'openai-responses'))- .toBeUndefined();++ expect(++ customProviderWireProtocolForSave('codex', 'openai-responses', 'openai-responses'),++ ).toBeUndefined();+ });+});+describe('setCustomProviderModelSupportsImageInput', () => {it('updates only the selected model row', () => {const models = [@@@ -117,22 -261,22 +319,26 @@@ describe('Pi custom-provider reasoningdescribe('customProviderModelConfigFromCatalogModel', () => {it('does not freeze the materialized custom-provider default into user config', () => {-- expect(customProviderModelConfigFromCatalogModel({-- id: 'default-context',-- name: 'Default Context',-- contextWindow: 200_000,-- })).toEqual({++ expect(++ customProviderModelConfigFromCatalogModel({++ id: 'default-context',++ name: 'Default Context',++ contextWindow: 200_000,++ }),++ ).toEqual({id: 'default-context',name: 'Default Context',});});it('preserves a provider-specific non-default context window', () => {-- expect(customProviderModelConfigFromCatalogModel({-- id: 'MiniMax-M3',-- name: 'MiniMax M3',-- contextWindow: 1_000_000,-- })).toEqual({++ expect(++ customProviderModelConfigFromCatalogModel({++ id: 'MiniMax-M3',++ name: 'MiniMax M3',++ contextWindow: 1_000_000,++ }),++ ).toEqual({id: 'MiniMax-M3',name: 'MiniMax M3',contextWindow: 1_000_000,@@@ -142,12 -286,12 +348,14 @@@it('preserves an explicit override equal to the current default (explicit flag wins)', () => {// 用户显式填了 200000:值恰好等于当前默认,但显式覆盖必须在未来默认升级后// 原样保留——不能靠等值推断丢掉字段(PR review P1)。-- expect(customProviderModelConfigFromCatalogModel({-- id: 'pinned-default',-- name: 'Pinned',-- contextWindow: 200_000,-- contextWindowExplicit: true,-- })).toEqual({++ expect(++ customProviderModelConfigFromCatalogModel({++ id: 'pinned-default',++ name: 'Pinned',++ contextWindow: 200_000,++ contextWindowExplicit: true,++ }),++ ).toEqual({id: 'pinned-default',name: 'Pinned',contextWindow: 200_000,@@@ -155,12 -299,12 +363,14 @@@});it('preserves hidden defaults while round-tripping catalog models', () => {-- expect(customProviderModelConfigFromCatalogModel({-- id: 'discovered',-- name: 'Discovered',-- contextWindow: 200_000,-- defaultEnabled: false,-- })).toEqual({++ expect(++ customProviderModelConfigFromCatalogModel({++ id: 'discovered',++ name: 'Discovered',++ contextWindow: 200_000,++ defaultEnabled: false,++ }),++ ).toEqual({id: 'discovered',name: 'Discovered',defaultEnabled: false,@@@ -168,12 -312,12 +378,14 @@@});it('preserves an explicit Pi image-input capability through the edit round trip', () => {-- expect(customProviderModelConfigFromCatalogModel({-- id: 'vision-model',-- name: 'Vision Model',-- contextWindow: 200_000,-- supportsImageInput: true,-- })).toEqual({++ expect(++ customProviderModelConfigFromCatalogModel({++ id: 'vision-model',++ name: 'Vision Model',++ contextWindow: 200_000,++ supportsImageInput: true,++ }),++ ).toEqual({id: 'vision-model',name: 'Vision Model',supportsImageInput: true,@@@ -200,7 -346,68 +414,71 @@@});});+ describe('providerViewToCustomProviderConfig Pi catalog metadata', () => {+ it('preserves the hidden Pi official catalog provider id', () => {+ const provider = {+ id: 'deepseek',+ name: 'DeepSeek',+ source: 'user',+ agents: ['pi'],+ auth: { method: 'apiKey' },+ routing: {+ pi: {+ upstream: 'https://api.deepseek.com',+ authStrategy: 'api-key-header',+ piCatalogProviderId: 'deepseek',+ },+ },+ models: {- pi: [{- id: 'deepseek-v4-pro',- name: 'DeepSeek V4 Pro',- contextWindow: 1_000_000,- efforts: ['high', 'max'],- defaultEffort: 'high',- }],++ pi: [++ {++ id: 'deepseek-v4-pro',++ name: 'DeepSeek V4 Pro',++ contextWindow: 1_000_000,++ efforts: ['high', 'max'],++ defaultEffort: 'high',++ },++ ],+ },+ } as ProviderView;- expect(providerViewToCustomProviderConfig(provider).runtimes.pi?.piCatalogProviderId)- .toBe('deepseek');++ expect(providerViewToCustomProviderConfig(provider).runtimes.pi?.piCatalogProviderId).toBe(++ 'deepseek',++ );+ });+ });+describe('providerViewToCustomProviderConfig', () => {+ it('restores the stored id for a legacy custom xai runtime projection', () => {+ const provider = {+ id: 'custom:xai',+ name: 'Legacy custom xAI',+ source: 'user',+ agents: ['codex'],+ auth: { method: 'apiKey' },+ access: { kind: 'api' },+ routing: {+ codex: {+ upstream: 'https://private-xai.example/v1',+ authStrategy: 'api-key-header',+ },+ },+ models: {+ codex: [+ {+ id: 'private-grok',+ name: 'Private Grok',+ contextWindow: 200_000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ },+ connected: true,+ } satisfies ProviderView;++ expect(providerViewToCustomProviderConfig(provider).id).toBe('xai');+ });+it('preserves no-auth and exact request-path fields through the edit round trip', () => {const provider = {id: 'local-chat',@@@ -219,13 -426,13 +497,15 @@@},},models: {-- codex: [{-- id: 'local-model',-- name: 'Local Model',-- contextWindow: 200_000,-- efforts: [],-- defaultEffort: null,-- }],++ codex: [++ {++ id: 'local-model',++ name: 'Local Model',++ contextWindow: 200_000,++ efforts: [],++ defaultEffort: null,++ },++ ],},connected: true,} satisfies ProviderView;@@@ -300,13 -508,13 +581,15 @@@},},models: {-- codex: [{-- id: 'model',-- name: 'Model',-- contextWindow: 200_000,-- efforts: [],-- defaultEffort: null,-- }],++ codex: [++ {++ id: 'model',++ name: 'Model',++ contextWindow: 200_000,++ efforts: [],++ defaultEffort: null,++ },++ ],},connected: true,} satisfies ProviderView;@@@ -385,9 -626,9 +701,7 @@@ describe('custom provider credential livi.stubGlobal('window', {electronAPI: {maker: {-- createCustomProvider: vi.fn().mockRejectedValue(-- new Error('credential staging failed'),-- ),++ createCustomProvider: vi.fn().mockRejectedValue(new Error('credential staging failed')),},},});@@@ -407,10 -648,10 +721,12 @@@},};-- await expect(createCustomProvider(config, {-- 'claude-code': 'first-key',-- codex: 'second-key',-- })).rejects.toThrow('credential staging failed');++ await expect(++ createCustomProvider(config, {++ 'claude-code': 'first-key',++ codex: 'second-key',++ }),++ ).rejects.toThrow('credential staging failed');});it('submits replacement keys with the config through one main-process mutation', async () => {@@@ -432,10 -673,10 +748,7 @@@},},};-- await updateCustomProvider(-- config,-- { codex: 'replacement-key' },-- );++ await updateCustomProvider(config, { codex: 'replacement-key' });expect(update).toHaveBeenCalledWith(config, { codex: 'replacement-key' });});diff --cc apps/desktop/src/renderer/lib/customProviders.tsindex c3936b61cf,a8ce8c85d6..744d19b527--- a/apps/desktop/src/renderer/lib/customProviders.ts+++ b/apps/desktop/src/renderer/lib/customProviders.ts@@@ -141,9 -149,8 +176,9 @@@ export function customProviderModelConf| 'contextWindowExplicit'| 'defaultEnabled'| 'supportsImageInput'+ | 'piApi'> &- Partial<Pick<CatalogModel, 'efforts'>>,+ Partial<Pick<CatalogModel, 'efforts' | 'defaultEffort'>>,agent?: AgentKind,): ProviderRuntimeModelConfig {const reasoningEfforts =diff --cc packages/maker-core/src/agents/base-agent.tsindex 01b93b783a,68d801c071..2a01174dc2--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@@ -178,41 -178,41 +178,52 @@@ 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'>;+ export type PiNativeThinkingLevel = 'off' | Exclude<Effort, 'ultra'>;++ export interface PiNativeModelCost {+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+ tiers?: Array<{+ inputTokensAbove: number;+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+ }>;+ }/** 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;+ /** Per-model request headers from the authoritative Pi catalog. */+ headers?: Record<string, string>;- /** Per-model API from Pi's official catalog; providers may mix protocols. */- api?: PiNativeApi;reasoning?: boolean;/** Pi models.json 的 provider-specific thinking level 映射;null 明确禁用该档。 */thinkingLevelMap?: Partial<Record<PiNativeThinkingLevel, string | null>>;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;- };+ cost?: PiNativeModelCost;+ /** Preserve model-specific request metadata on a required full-entry replacement. */- headers?: Record<string, string>;compat?: Record<string, unknown>;+ samplingParams?: Record<string, unknown>;}/**@@@ -464,16 -470,17 +486,21 @@@ export interface AgentDeps/*** Pi-only: authenticate a child process to the host's loopback model proxy.* PiAgent creates a high-entropy token per session, registers it before spawn,- * binds the currently resolved native provider, and disposes the exact- * registration when startup fails or the session closes. The provider reader- * follows confirmed set_model changes without trusting a child-supplied header.+ * and disposes the exact registration when startup fails or the session closes.*/- registerPiProxySession?: (sessionId: string, token: string) => (() => void) | void;+ registerPiProxySession?: (+ sessionId: string,+ token: string,+ resolveProviderId: () => string | null,+ ) => (() => void) | void;+ /**+ * Pi-only: host-owned derivation for restart-stable remote proxy tokens.+ * Desktop persists the secret key; maker-core receives only the per-session+ * result. Missing hooks preserve the legacy process-stable fallback.+ */+ derivePiProxySessionToken?: (sessionId: string) => string;+/*** BYOM:host 解析出当前会话可用的 pi **原生 provider**(用户自定义/本地模型)+ 需注入的* env(api keys)。PiAgent 把这些写进 models.json 的独立 provider 块(直连用户端点,不过diff --cc packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.tsindex 9a97be4d74,d9c89aec34..cad11202f9--- 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,204 -203,301 +203,499 @@@ describe('Pi provider-aware model routiawait nativeHandle.close();});+ it('routes host subscriptions through PI native providers and wire model ids', async () => {+ const authProviderIds: Array<string | null | undefined> = [];+ let resolveProxyProviderId: (() => 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',+ registerPiProxySession: (_sessionId, _token, resolveProviderId) => {+ resolveProxyProviderId = resolveProviderId;+ },+ 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',+ effort: 'high',+ });++ expect(authProviderIds).toEqual(['openai']);+ expect(resolveProxyProviderId?.()).toBe('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(resolveProxyProviderId?.()).toBe('xai');+ 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',+ });+ expect(resolveProxyProviderId?.()).toBe('anthropic');+ await handle.close();+ });++ it('routes a persisted BYOM id through its namespaced PI runtime provider', async () => {+ const authProviderIds: Array<string | null | undefined> = [];+ const deps: AgentDeps = {+ auth: {+ getState: async (options) => {+ authProviderIds.push(options?.providerId);+ return { authenticated: true, identity: 'custom', authSource: 'api-key' 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: [{+ id: 'chatgpt/gpt-5.6-sol',+ displayName: 'Same-name Custom Model',+ contextWindow: 128_000,+ efforts: [],+ defaultEffort: null,+ }],+ },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: async () => ({+ providers: [+ {+ id: 'openai-codex',+ sourceProviderId: 'openai',+ name: 'OpenAI (ChatGPT)',+ baseUrl: 'http://127.0.0.1:9988',+ inheritModels: true,+ models: [{ id: 'chatgpt/gpt-5.6-sol', wireId: 'gpt-5.6-sol' }],+ },+ {+ id: 'cindy-byom-openai-codex',+ sourceProviderId: 'openai-codex',+ name: 'User endpoint',+ baseUrl: 'https://user.example/v1',+ api: 'openai-completions',+ models: [{ id: 'chatgpt/gpt-5.6-sol' }],+ },+ ],+ env: {},+ }),+ };++ const handle = await new PiAgent(deps).startSession({+ sessionId: 'namespaced-byom-routing',+ workingDir: cwd,+ model: 'chatgpt/gpt-5.6-sol',+ providerId: 'openai-codex',+ });++ expect(authProviderIds).toEqual(['openai-codex']);+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 4))+ .toEqual(['--provider', 'cindy-byom-openai-codex', '--model', 'chatgpt/gpt-5.6-sol']);+ 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, { baseUrl?: string }>;+ };+ expect(models.providers['openai-codex']?.baseUrl).toBe('http://127.0.0.1:9988');+ expect(models.providers['cindy-byom-openai-codex']?.baseUrl).toBe('https://user.example/v1');+ expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'namespaced-byom-routing'), 'utf8')))+ .toEqual({ model: 'chatgpt/gpt-5.6-sol', provider: 'cindy-byom-openai-codex' });+ await handle.close();+ });++ it('keeps xAI and custom providers in one snapshot and switches both directions', async () => {+ const agent = new PiAgent({+ auth: {+ getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'gateway-key' }),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: {+ availableModels: [+ {+ id: 'xai/grok-4.6',+ displayName: 'Grok 4.6',+ contextWindow: 500_000,+ efforts: ['minimal', 'low', 'medium', 'high'],+ defaultEffort: 'medium',+ },+ {+ id: 'local-model',+ displayName: 'Local Model',+ contextWindow: 128_000,+ efforts: [],+ defaultEffort: null,+ },+ ],+ },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: async () => ({+ providers: [+ {+ id: 'xai',+ name: 'xAI',+ baseUrl: 'http://127.0.0.1:9',+ api: 'anthropic-messages',+ apiKeyEnvVar: 'CINDY_PI_XAI_PROXY_API_KEY',+ headers: {+ 'x-cindy-pi-session-id': '$CINDY_PI_SESSION_ID',+ 'x-cindy-pi-session-token': '$CINDY_PI_SESSION_TOKEN',+ },+ modelIdAliases: {+ 'grok-4.6': 'xai/grok-4.6',+ 'xai/grok-4.6': 'xai/grok-4.6',+ },+ models: [{+ id: 'xai/grok-4.6',+ api: 'anthropic-messages',+ contextWindow: 500_000,+ maxTokens: 500_000,+ input: ['text', 'image'],+ reasoning: true,+ compat: {+ supportsStore: false,+ supportsDeveloperRole: false,+ supportsReasoningEffort: false,+ },+ }],+ },+ {+ id: 'native-a',+ name: 'Native A',+ baseUrl: 'http://a.test',+ api: 'openai-completions',+ models: [{ id: 'local-model' }],+ },+ ],+ env: { CINDY_PI_XAI_PROXY_API_KEY: 'xai-proxy-placeholder' },+ }),+ });++ const handle = await agent.startSession({+ sessionId: 'grok-46-native',+ workingDir: cwd,+ model: 'xai/grok-4.6',+ providerId: 'xai',+ effort: 'medium',+ });+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))+ .toEqual(['--provider', 'xai']);+ expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))+ .toEqual(['--model', 'xai/grok-4.6']);+ expect(captured.env.CINDY_PI_API_KEY).toBe('gateway-key');+ expect(captured.env.CINDY_PI_XAI_PROXY_API_KEY).toBe('xai-proxy-placeholder');++ const models = JSON.parse(+ readFileSync(path.join(captured.env.PI_CODING_AGENT_DIR as string, 'models.json'), 'utf8'),+ ) as { providers: Record<string, { apiKey: string; models: Array<Record<string, unknown>> }> };+ expect(models.providers.cindy?.apiKey).toBe('$CINDY_PI_API_KEY');+ expect(models.providers.xai?.apiKey).toBe('$CINDY_PI_XAI_PROXY_API_KEY');+ expect(models.providers.xai?.models.find((model) => model.id === 'xai/grok-4.6')).toMatchObject({+ api: 'anthropic-messages',+ contextWindow: 500_000,+ maxTokens: 500_000,+ input: ['text', 'image'],+ compat: {+ supportsStore: false,+ supportsDeveloperRole: false,+ supportsReasoningEffort: false,+ },+ });+ expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'grok-46-native'), 'utf8'))).toEqual({+ model: 'xai/grok-4.6',+ provider: 'xai',+ });+ await handle.setModel!('local-model', { providerId: 'native-a' });+ await handle.setModel!('xai/grok-4.6', { providerId: 'xai' });+ expect(captured.requests).toContainEqual({+ type: 'set_model',+ provider: 'native-a',+ modelId: 'local-model',+ });+ expect(captured.requests).toContainEqual({+ type: 'set_model',+ provider: 'xai',+ modelId: 'xai/grok-4.6',+ });+ await handle.close();+ });++ it('applies each native provider alias during provider-less compatibility routing', async () => {+ const provider = (id: string, aliases?: Record<string, string>) => ({+ id,+ name: id,+ baseUrl: `http://${id}.test`,+ api: 'anthropic-messages' as const,+ ...(aliases ? { modelIdAliases: aliases } : {}),+ models: [{ id: id === 'xai' ? 'xai/grok-4.6' : 'other-model' }],+ });+ const agent = new PiAgent({+ auth: {+ getState: async (options) => ({+ authenticated: true,+ identity: options?.providerId === 'xai' ? 'SuperGrok' : 'test',+ authSource: 'oauth' as const,+ }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({}),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: {+ availableModels: [{+ id: 'grok-4.6',+ displayName: 'Grok 4.6',+ contextWindow: 500_000,+ efforts: [],+ defaultEffort: null,+ }],+ },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: async () => ({+ providers: [+ provider('other'),+ provider('xai', {+ 'grok-4.6': 'xai/grok-4.6',+ 'xai/grok-4.6': 'xai/grok-4.6',+ }),+ ],+ env: {},+ }),+ });++ const bare = await agent.startSession({+ sessionId: 'providerless-grok-bare',+ workingDir: cwd,+ model: 'grok-4.6',+ });+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))+ .toEqual(['--provider', 'xai']);+ expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))+ .toEqual(['--model', 'xai/grok-4.6']);+ await bare.close();++ const namespaced = await agent.startSession({+ sessionId: 'providerless-grok-namespaced',+ workingDir: cwd,+ model: 'xai/grok-4.6',+ });+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))+ .toEqual(['--provider', 'xai']);+ await namespaced.close();+ });++ it('fails closed when provider-less aliases are ambiguous', async () => {+ const agent = new PiAgent(byomDeps(async () => ({+ providers: [+ {+ id: 'native-a',+ name: 'Native A',+ baseUrl: 'http://a.test',+ api: 'openai-completions',+ modelIdAliases: { legacy: 'native-a-model' },+ models: [{ id: 'native-a-model' }],+ },+ {+ id: 'native-b',+ name: 'Native B',+ baseUrl: 'http://b.test',+ api: 'openai-completions',+ modelIdAliases: { legacy: 'native-b-model' },+ models: [{ id: 'native-b-model' }],+ },+ ],+ env: {},+ })));+ await expect(agent.startSession({+ sessionId: 'providerless-alias-conflict',+ workingDir: cwd,+ model: 'legacy',+ })).rejects.toThrow(/matches multiple native providers.*refusing to guess an endpoint/);+ expect(captured.args).toEqual([]);+ });++ it('fails closed when an explicit xAI selection cannot build the Pi native provider', async () => {+ const deps: AgentDeps = {+ auth: {+ getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({}),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: {+ availableModels: [{+ id: 'grok-4.6',+ displayName: 'Grok 4.6',+ contextWindow: 500_000,+ efforts: ['minimal', 'low', 'medium', 'high'],+ defaultEffort: 'medium',+ }],+ },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: async () => {+ throw new Error('xAI token unavailable');+ },+ };+ await expect(new PiAgent(deps).startSession({+ sessionId: 'grok-46-native-failed',+ workingDir: cwd,+ model: 'grok-4.6',+ providerId: 'xai',+ })).rejects.toThrow(/BYOM provider 'xai' cannot serve model 'grok-4.6'.*refusing to fall back/);+ expect(captured.args).toEqual([]);+ });++ it('passes resume identity so a historical xAI model can stay private to the restored session', async () => {+ const resolver = vi.fn(async (ctx) => ({+ providers: [{+ id: 'xai',+ name: 'xAI',+ baseUrl: 'http://127.0.0.1:9',+ api: 'anthropic-messages' as const,+ modelIdAliases: { 'grok-retired': 'xai/grok-retired' },+ models: [{ id: 'xai/grok-retired', api: 'anthropic-messages' as const }],+ }],+ env: {},+ }));+ const agent = new PiAgent({+ auth: {+ getState: async () => ({ authenticated: true, identity: 'SuperGrok', authSource: 'oauth' as const }),+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({ CINDY_PI_API_KEY: 'provider-auth-placeholder' }),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: { availableModels: [] },+ resolvePiAgentHome: () => agentHome,+ resolvePiNativeProviders: resolver,+ });++ const handle = await agent.startSession({+ sessionId: 'historical-xai-resume',+ resumeSessionId: 'pi-sdk-session-old',+ workingDir: cwd,+ model: 'grok-retired',+ providerId: 'xai',+ });+ expect(resolver).toHaveBeenCalledWith(expect.objectContaining({+ providerId: 'xai',+ model: 'grok-retired',+ resumeSessionId: 'pi-sdk-session-old',+ }));+ expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))+ .toEqual(['--model', 'xai/grok-retired']);+ 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 --cc packages/maker-core/src/agents/pi/index.tsindex 7cfce5f4ff,5c7a93ff8a..ea5a715126--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@@ -749,25 -780,6 +780,30 @@@ export class PiAgent extends BaseAgentthis.deps.logger.warn('pi: native provider id collides with gateway provider "cindy" — skipped', { id: np.id });continue;}- 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) } : {}),- }));++ 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.baseUrl ? { baseUrl: m.baseUrl } : {}),++ ...(m.headers && Object.keys(m.headers).length > 0 ? { headers: m.headers } : {}),++ ...(m.api ? { api: m.api } : {}),++ 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: structuredClone(m.cost) } : {}),++ ...(m.compat ? { compat: structuredClone(m.compat) } : {}),++ ...(m.samplingParams ? { samplingParams: structuredClone(m.samplingParams) } : {}),++ }));+ 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,@@@ -858,13 -879,8 +897,17 @@@.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 =>++ const nativeProviderForSource = (++ providerId: string,++ ): PiNativeProviderSpec | undefined =>+ nativeProviderBySourceId.get(providerId) ?? nativeProviderById.get(providerId);+ const resolveNativeModelId = (providerId: string, model: string): string =>+ nativeProviderById.get(providerId)?.modelIdAliases?.[model] ?? model;// providerId 是模型来源的主键;同名模型可同时存在于 Cindy 网关和多个 BYOM provider。// 三态语义(与 session-provider-store 对齐):// - 显式 BYOM id → 该 native provider(经上面的 model-combo fail-closed 校验);@@@ -877,29 -893,30 +920,46 @@@providerId?: string | null,): string => {if (providerId) {- const native = nativeProviderById.get(providerId);- const nativeModel = resolveNativeModelId(providerId, model);+ const native = nativeProviderForSource(providerId);- return native?.models.some((candidate) => candidate.id === model)++ const nativeModel = native ? resolveNativeModelId(native.id, model) : model;+ return native?.models.some((candidate) => candidate.id === nativeModel)? native.id: PI_PROVIDER_ID;}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/'))+ // 旧会话/旧客户端没有 providerId 时,只能按启动快照做兼容回退。每个 provider+ // 必须先应用自己的 alias:例如 xAI 的裸 `grok-4.6` 实际对应+ // `xai/grok-4.6`。若多个 native provider 都能解释同一个 id,则来源并不唯一,+ // 直接拒绝恢复,不能靠数组顺序猜一个端点,更不能把提示词改发到默认网关。+ const matches = nativeProviders.filter((provider) => {+ if (provider.id === PI_PROVIDER_ID) return false;++ if (++ provider.sourceProviderId !== undefined &&++ !(++ (provider.sourceProviderId === 'openai' && model.startsWith('chatgpt/')) ||++ (provider.sourceProviderId === 'xai' && model.startsWith('xai/')) ||++ (provider.sourceProviderId === 'anthropic' && model.startsWith('claude-'))+ )- && provider.models.some((candidate) => candidate.id === model),- )?.id ?? PI_PROVIDER_ID;++ ) return false;+ const candidateModel = provider.modelIdAliases?.[model] ?? model;+ return provider.models.some((candidate) => candidate.id === candidateModel);+ });+ if (matches.length > 1) {+ throw new Error(+ `pi: provider-less model '${model}' matches multiple native providers `+ + `(${matches.map((provider) => provider.id).join(', ')}); refusing to guess an endpoint.`,+ );+ }+ return matches[0]?.id ?? PI_PROVIDER_ID;};- const resolveWireModel = (providerId: string, model: string): string =>- nativeProviderById++ const resolveWireModel = (providerId: string, model: string): string => {++ const nativeModel = resolveNativeModelId(providerId, model);++ return nativeProviderById+ .get(providerId)- ?.models.find((candidate) => candidate.id === model)- ?.wireId ?? model;++ ?.models.find((candidate) => candidate.id === nativeModel)?.wireId ?? nativeModel;++ };+ const resolveSourceProvider = (providerId: string): string =>+ nativeProviderById.get(providerId)?.sourceProviderId ?? providerId;// 显式 BYOM 路由必须 fail closed:当调用方钉了一个既非 Cindy 网关(cindy/xd)也非// 订阅直连(openai/anthropic/xai)的自定义/本地 provider 时,该来源必须在本次解析出的// nativeProviders 里。若原生解析失败(配置/safeStorage 暂时读不到)或该 provider 缺席,@@@ -920,8 -937,9 +980,9 @@@): providerId is string => {if (!providerId || NON_BYOM_PROVIDER_IDS.has(providerId)) return false;if (resolveFailed) return true;- const native = nativeProviderById.get(providerId);- const nativeModel = resolveNativeModelId(providerId, model);+ const native = nativeProviderForSource(providerId);- return !native || !native.models.some((candidate) => candidate.id === model);++ const nativeModel = native ? resolveNativeModelId(native.id, model) : model;+ return !native || !native.models.some((candidate) => candidate.id === nativeModel);};if (explicitByomUnresolvable(opts.providerId, opts.model, nativeResolveFailed)) {throw new Error(@@@ -940,22 -959,16 +1001,22 @@@// 同时校验显式 providerId 与 legacy/default 路由 resolve 出的 native provider// (providerId 未持久化时 resolveProviderForModel 也能选出 BYOM)。if (opts.remoteHostId) {- const candidateIds = new Set<string>();- if (opts.providerId && !NON_BYOM_PROVIDER_IDS.has(opts.providerId)) candidateIds.add(opts.providerId);- if (initialProvider !== PI_PROVIDER_ID && !NON_BYOM_PROVIDER_IDS.has(initialProvider)) {- candidateIds.add(initialProvider);+ const candidateRuntimeIds = new Set<string>();+ if (opts.providerId && !NON_BYOM_PROVIDER_IDS.has(opts.providerId)) {+ const explicitNative = nativeProviderForSource(opts.providerId);+ if (explicitNative) candidateRuntimeIds.add(explicitNative.id);}- for (const candidateId of candidateIds) {- const loopbackNative = nativeProviderById.get(candidateId);+ if (- initialProvider !== PI_PROVIDER_ID- && !NON_BYOM_PROVIDER_IDS.has(resolveSourceProvider(initialProvider))++ initialProvider !== PI_PROVIDER_ID &&++ !NON_BYOM_PROVIDER_IDS.has(resolveSourceProvider(initialProvider))+ ) {+ candidateRuntimeIds.add(initialProvider);+ }+ for (const runtimeProviderId of candidateRuntimeIds) {+ const loopbackNative = nativeProviderById.get(runtimeProviderId);- if (loopbackNative && isLoopbackOnlyBaseUrl(loopbackNative.baseUrl)) {+ if (loopbackNative && isLoopbackOnlyBaseUrl(loopbackNative.baseUrl) && !loopbackNative.hostProxyForward) {throw new Error(- `[REMOTE_LOCAL_ONLY_PROVIDER] pi: BYOM provider '${candidateId}' baseUrl ${loopbackNative.baseUrl} is loopback-only — ` ++ `[REMOTE_LOCAL_ONLY_PROVIDER] pi: BYOM provider '${resolveSourceProvider(runtimeProviderId)}' baseUrl ${loopbackNative.baseUrl} is loopback-only — ` +'a remote Pi session runs on the SSH host and cannot reach a service on this machine; ' +'pick the XD gateway or a BYOM endpoint reachable from that host.',);@@@ -2379,8 -2420,12 +2477,11 @@@// 所以这一步落的是**带 pending 标记的**新路由:内容已经就位(证明可写、内容可回滚),但// 扩展见到 `pending: true` 就拒绝派发。等待窗口里一个子进程都起不来,既不会用未确认的新// 路由、也不会用与父不一致的旧路由;确认后再清掉标记放行。- const previousSnapshot = { model: mutableWireModel, provider: mutablePiProviderId };+ const previousSnapshot = {- model: resolveNativeModelId(mutablePiProviderId, mutableModel),++ model: mutableWireModel,+ provider: mutablePiProviderId,+ };- const nativeModel = resolveNativeModelId(provider, model);- if (!(await writeSubagentRuntimeFile({ model: nativeModel, provider, pending: true }))) {+ if (!(await writeSubagentRuntimeFile({ model: wireModel, provider, pending: true }))) {throw new Error('pi: 无法持久化子代理路由快照,已取消本次模型切换(避免父会话切到新 provider 而子代理仍按旧路由派发)。'+ '请检查运行目录是否可写后重试。',@@@ -2388,7 -2433,11 +2489,11 @@@}let resp;try {- resp = await proc.request({ type: 'set_model', provider, modelId: wireModel });+ resp = await proc.request({+ type: 'set_model',+ provider,- modelId: nativeModel,++ modelId: wireModel,+ });} catch (err) {// RPC **reject / 超时 / 写 stdin 失败 / 进程已退出**:与 `success:false` 有本质区别 ——// 那种情况我们**知道**没生效,可以回滚;这里我们**不知道** pi 侧到底切没切。@@@ -2474,7 -2522,7 +2579,7 @@@// 元数据必须跟随实际路由, 否则 reviewAutoAction 用旧 provider 做决策// (AutoReviewRequest.providerId + 缓存键都错)。null/订阅来源已归一为// cindy(PI_PROVIDER_ID), 不在此分支。-- mutableProviderId = provider;++ mutableProviderId = resolveSourceProvider(provider);}autoReviewDecisionCache.clear();// 换模型 / 换路由可能正好修掉了审阅器不可用的原因;换完又不可用值得再提醒一次。diff --cc packages/model-providers/catalog/providers.jsonindex 7d0faea65e,15c22be255..7fc7dfabba--- a/packages/model-providers/catalog/providers.json+++ b/packages/model-providers/catalog/providers.json@@@ -5,7 -5,11 +5,7 @@@"id": "xai","name": "xAI","source": "builtin",- "agents": ["claude-code", "codex"],- "agents": [- "claude-code",- "codex",- "pi"- ],++ "agents": ["claude-code", "codex", "pi"],"auth": {"method": "oauth"},@@@ -35,8 -47,25 +41,23 @@@"modelIdRewrite": {"stripPrefix": "xai/"},- "headerDelete": ["chatgpt-account-id", "openai-beta", "originator", "session_id"],+ "headerDelete": [+ "chatgpt-account-id",+ "openai-beta",+ "originator",+ "session_id"+ ],- "modelPrefixes": [- "xai/"- ]+ "modelPrefixes": ["xai/"]+ },+ "pi": {+ "upstream": "https://api.x.ai/v1",+ "authStrategy": "provider-oauth-header",+ "headerDelete": [+ "chatgpt-account-id",+ "openai-beta",+ "originator",+ "session_id"+ ]}},"models": {@@@ -236,6 -285,84 +252,80 @@@"status": "deprecated","defaultEnabled": false}+ ],+ "pi": [+ {+ "id": "grok-4.3",+ "name": "Grok 4.3",+ "group": "grok",+ "sortOrder": 49,+ "contextWindow": 1000000,+ "maxOutput": 30000,+ "efforts": [],+ "defaultEffort": null,+ "status": "active",+ "supportsImageInput": true,+ "cost": {+ "input": 1.25,+ "output": 2.5,+ "cacheRead": 0.2,+ "cacheWrite": 0+ }+ },+ {+ "id": "grok-4.5",+ "name": "Grok 4.5",+ "group": "grok",+ "sortOrder": 50,+ "contextWindow": 500000,+ "maxOutput": 500000,- "efforts": [- "low",- "medium",- "high"- ],++ "efforts": ["low", "medium", "high"],+ "defaultEffort": "medium",+ "status": "active",+ "supportsImageInput": true,+ "cost": {+ "input": 2,+ "output": 6,+ "cacheRead": 0.3,+ "cacheWrite": 0+ }+ },+ {+ "id": "grok-4.6",+ "name": "Grok 4.6",+ "group": "grok",+ "sortOrder": 51,+ "contextWindow": 500000,+ "maxOutput": 500000,+ "efforts": [],+ "defaultEffort": null,+ "status": "active",+ "supportsImageInput": true,+ "cost": {+ "input": 2,+ "output": 6,+ "cacheRead": 0.5,+ "cacheWrite": 0+ }+ },+ {+ "id": "grok-build-0.1",+ "name": "Grok Build 0.1",+ "group": "grok",+ "sortOrder": 52,+ "contextWindow": 256000,+ "maxOutput": 256000,+ "efforts": [],+ "defaultEffort": null,+ "status": "active",+ "supportsImageInput": true,+ "cost": {+ "input": 1,+ "output": 2,+ "cacheRead": 0.2,+ "cacheWrite": 0+ }+ }]}}@@@ -326,16 -455,26 +418,19 @@@"id": "deepseek-v4-flash","name": "DeepSeek V4 Flash","contextWindow": 1000000,- "piApi": "openai-responses"+ "reasoning": true,- "reasoningEfforts": [- "low",- "high",- "max"- ],++ "reasoningEfforts": ["low", "high", "max"],+ "reasoningDefaultEffort": "high"},{"id": "deepseek-v4-pro","name": "DeepSeek V4 Pro","contextWindow": 1000000,- "piApi": "openai-responses"+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"}- ],- "modelsUrl": "https://api.deepseek.com/models"+ ]}}},@@@ -458,6 -597,76 +553,72 @@@}],"modelsUrl": "https://api.moonshot.cn/v1/models"+ },+ "pi": {+ "baseUrl": "https://api.moonshot.cn/v1",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://api.moonshot.cn/v1/models",+ "piCatalogProviderId": "moonshotai-cn",+ "models": [+ {+ "id": "kimi-k2-0711-preview",+ "name": "Kimi K2 0711",+ "contextWindow": 131072+ },+ {+ "id": "kimi-k2-0905-preview",+ "name": "Kimi K2 0905",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-thinking",+ "name": "Kimi K2 Thinking",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-thinking-turbo",+ "name": "Kimi K2 Thinking Turbo",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-turbo-preview",+ "name": "Kimi K2 Turbo",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code-highspeed",+ "name": "Kimi K2.7 Code HighSpeed",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k3",+ "name": "Kimi K3",+ "contextWindow": 1048576,+ "supportsImageInput": true,+ "reasoning": true,- "reasoningEfforts": [- "low",- "high",- "max"- ],++ "reasoningEfforts": ["low", "high", "max"],+ "reasoningDefaultEffort": "max"+ }+ ]}}},@@@ -506,6 -715,76 +667,72 @@@}],"modelsUrl": "https://api.moonshot.ai/v1/models"+ },+ "pi": {+ "baseUrl": "https://api.moonshot.ai/v1",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://api.moonshot.ai/v1/models",+ "piCatalogProviderId": "moonshotai",+ "models": [+ {+ "id": "kimi-k2-0711-preview",+ "name": "Kimi K2 0711",+ "contextWindow": 131072+ },+ {+ "id": "kimi-k2-0905-preview",+ "name": "Kimi K2 0905",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-thinking",+ "name": "Kimi K2 Thinking",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-thinking-turbo",+ "name": "Kimi K2 Thinking Turbo",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2-turbo-preview",+ "name": "Kimi K2 Turbo",+ "contextWindow": 262144+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code-highspeed",+ "name": "Kimi K2.7 Code HighSpeed",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k3",+ "name": "Kimi K3",+ "contextWindow": 1048576,+ "supportsImageInput": true,+ "reasoning": true,- "reasoningEfforts": [- "low",- "high",- "max"- ],++ "reasoningEfforts": ["low", "high", "max"],+ "reasoningDefaultEffort": "max"+ }+ ]}}},@@@ -556,6 -835,51 +783,43 @@@"contextWindow": 262144}]+ },+ "pi": {+ "baseUrl": "https://api.kimi.com/coding",+ "wireProtocol": "anthropic-messages",+ "piCatalogProviderId": "kimi-coding",+ "models": [+ {+ "id": "k3",+ "name": "Kimi K3",+ "contextWindow": 1048576,+ "supportsImageInput": true,+ "reasoning": true,- "reasoningEfforts": [- "low",- "high",- "max"- ],++ "reasoningEfforts": ["low", "high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "k3-256k",+ "name": "Kimi K3-256K",+ "contextWindow": 262144,+ "supportsImageInput": true,+ "reasoning": true,- "reasoningEfforts": [- "low",- "high",- "max"- ],++ "reasoningEfforts": ["low", "high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "kimi-for-coding",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-for-coding-highspeed",+ "name": "Kimi For Coding HighSpeed",+ "contextWindow": 262144,+ "supportsImageInput": true+ }+ ]}}},@@@ -759,6 -1129,144 +1069,122 @@@"contextWindow": 1048576}]+ },+ "pi": {+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/models",+ "piCatalogProviderId": "qwen-token-plan-cn",+ "models": [+ {+ "id": "MiniMax-M2.5",+ "name": "MiniMax-M2.5",+ "contextWindow": 196608+ },+ {+ "id": "deepseek-v3.2",+ "name": "DeepSeek V3.2",+ "contextWindow": 131072+ },+ {+ "id": "deepseek-v4-flash",+ "name": "DeepSeek V4 Flash",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-flash-0731",+ "name": "DeepSeek V4 Flash 0731",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-pro",+ "name": "DeepSeek V4 Pro",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5",+ "name": "GLM-5",+ "contextWindow": 202752,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5.1",+ "name": "GLM-5.1",+ "contextWindow": 202752,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.6-flash",+ "name": "Qwen3.6 Flash",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.6-plus",+ "name": "Qwen3.6 Plus",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.7-max",+ "name": "Qwen3.7 Max",+ "contextWindow": 1000000+ },+ {+ "id": "qwen3.7-plus",+ "name": "Qwen3.7 Plus",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.8-max",+ "name": "Qwen3.8 Max",+ "contextWindow": 1000000,+ "supportsImageInput": true,+ "reasoning": true,- "reasoningEfforts": [- "low",- "medium",- "xhigh"- ],++ "reasoningEfforts": ["low", "medium", "xhigh"],+ "reasoningDefaultEffort": "medium"+ }+ ]}}},@@@ -932,6 -1440,144 +1358,122 @@@"contextWindow": 196608}]+ },+ "pi": {+ "baseUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",+ "wireProtocol": "openai-chat",+ "modelsUrl": "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/models",+ "piCatalogProviderId": "qwen-token-plan-cn",+ "models": [+ {+ "id": "MiniMax-M2.5",+ "name": "MiniMax-M2.5",+ "contextWindow": 196608+ },+ {+ "id": "deepseek-v3.2",+ "name": "DeepSeek V3.2",+ "contextWindow": 131072+ },+ {+ "id": "deepseek-v4-flash",+ "name": "DeepSeek V4 Flash",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-flash-0731",+ "name": "DeepSeek V4 Flash 0731",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "deepseek-v4-pro",+ "name": "DeepSeek V4 Pro",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5",+ "name": "GLM-5",+ "contextWindow": 202752,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5.1",+ "name": "GLM-5.1",+ "contextWindow": 202752,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "high",- "max"- ],++ "reasoningEfforts": ["high", "max"],+ "reasoningDefaultEffort": "high"+ },+ {+ "id": "kimi-k2.5",+ "name": "Kimi K2.5",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.6",+ "name": "Kimi K2.6",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "kimi-k2.7-code",+ "name": "Kimi K2.7 Code",+ "contextWindow": 262144,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.6-flash",+ "name": "Qwen3.6 Flash",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.6-plus",+ "name": "Qwen3.6 Plus",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.7-max",+ "name": "Qwen3.7 Max",+ "contextWindow": 1000000+ },+ {+ "id": "qwen3.7-plus",+ "name": "Qwen3.7 Plus",+ "contextWindow": 1000000,+ "supportsImageInput": true+ },+ {+ "id": "qwen3.8-max",+ "name": "Qwen3.8 Max",+ "contextWindow": 1000000,+ "supportsImageInput": true,+ "reasoning": true,- "reasoningEfforts": [- "low",- "medium",- "xhigh"- ],++ "reasoningEfforts": ["low", "medium", "xhigh"],+ "reasoningDefaultEffort": "medium"+ }+ ]}}},@@@ -1046,6 -1692,41 +1588,36 @@@"name": "GLM-5.1"}]+ },+ "pi": {+ "baseUrl": "https://open.bigmodel.cn/api/coding/paas/v4",+ "wireProtocol": "openai-chat",+ "piCatalogProviderId": "zai-coding-cn",+ "models": [+ {+ "id": "glm-4.7",+ "name": "GLM-4.7",+ "contextWindow": 204800+ },+ {+ "id": "glm-5-turbo",+ "name": "GLM-5-Turbo",+ "contextWindow": 200000+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "low",- "medium",- "high",- "max"- ],++ "reasoningEfforts": ["low", "medium", "high", "max"],+ "reasoningDefaultEffort": "medium"+ },+ {+ "id": "glm-5.2-highspeed",+ "name": "GLM-5.2 Highspeed",+ "contextWindow": 1000000+ }+ ]}}},@@@ -1086,6 -1767,41 +1658,36 @@@"name": "GLM-5.1"}]+ },+ "pi": {+ "baseUrl": "https://api.z.ai/api/coding/paas/v4",+ "wireProtocol": "openai-chat",+ "piCatalogProviderId": "zai",+ "models": [+ {+ "id": "glm-4.7",+ "name": "GLM-4.7",+ "contextWindow": 204800+ },+ {+ "id": "glm-5-turbo",+ "name": "GLM-5-Turbo",+ "contextWindow": 200000+ },+ {+ "id": "glm-5.2",+ "name": "GLM-5.2",+ "contextWindow": 1000000,+ "reasoning": true,- "reasoningEfforts": [- "low",- "medium",- "high",- "max"- ],++ "reasoningEfforts": ["low", "medium", "high", "max"],+ "reasoningDefaultEffort": "medium"+ },+ {+ "id": "glm-5.2-highspeed",+ "name": "GLM-5.2 Highspeed",+ "contextWindow": 1000000+ }+ ]}}},diff --cc packages/model-providers/src/__tests__/catalog.test.tsindex fe72d18f60,b9f7568495..8e7c15ad8e--- a/packages/model-providers/src/__tests__/catalog.test.ts+++ b/packages/model-providers/src/__tests__/catalog.test.ts@@@ -236,20 -232,9 +251,16 @@@ describe('bundled catalog validity (dynopenrouter?.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',++ wireProtocol: 'openai-chat',+ models: [- { id: 'deepseek-v4-flash', piApi: 'openai-responses' },- { id: 'deepseek-v4-pro', piApi: 'openai-responses' },++ { id: 'deepseek-v4-flash' },++ { id: 'deepseek-v4-pro' },+ ],+ });});- it('Kimi Code(编程计划)预设的每个模型都带 contextWindow(k3 缺失曾回落 200K)', () => {- // k3 此前没带 contextWindow → buildUserProvider 回落 200K 保守默认:选择器- // 显示 200K 且压缩阈值过早触发(用户反馈「动不动就压缩」)。取 262144 与同- // 套餐 kimi-for-coding 口径一致(K3 开放平台规格 1M,但编程计划端点是否限窗- // 无公开文档,保守取值;实测放开后可上调)。+ it('Kimi Code(编程计划)按各 harness 的权威目录保留 contextWindow', () => {const presets = BUNDLED_CATALOG.presets ?? [];const kimiCode = presets.find((p) => p.id === 'moonshot-kimi-code');expect(kimiCode).toBeDefined();diff --cc packages/model-providers/src/__tests__/presets.test.tsindex 3db1c5aa68,fa32bda4eb..fd3b4e7808--- a/packages/model-providers/src/__tests__/presets.test.ts+++ b/packages/model-providers/src/__tests__/presets.test.ts@@@ -45,31 -45,30 +45,63 @@@ 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' }],++ wireProtocol: 'openai-responses' as const,++ models: [++ {++ id: 'deepseek-v4-pro',++ name: 'DeepSeek V4 Pro',++ piApi: 'openai-responses' as const,++ },++ ],+ },+ },+ };+ expect(sanitizePresets([valid])).toEqual([valid]);- expect(sanitizePresets([{- ...valid,- id: 'bad-pi-api',++ expect(sanitizePresets([++ {++ ...valid,++ id: 'bad-pi-api',++ runtimes: {++ pi: {++ ...valid.runtimes.pi,++ models: [{ id: 'x', name: 'X', piApi: 'claude-v1' }],++ },++ },++ },++ ])).toEqual([]);++ });+++ it('accepts Pi official catalog provider ids only on Pi runtimes', () => {+ const valid = {+ ...VALID_PRESET,+ id: 'pi-catalog',runtimes: {pi: {- ...valid.runtimes.pi,- models: [{ id: 'x', name: 'X', piApi: 'claude-v1' }],+ baseUrl: 'https://api.deepseek.com',+ piCatalogProviderId: 'deepseek',+ models: [{ id: 'deepseek-v4-pro', name: 'DeepSeek V4 Pro' }],},},+ };+ expect(sanitizePresets([valid])).toEqual([valid]);+ expect(sanitizePresets([{+ ...valid,+ id: 'wrong-runtime',+ runtimes: { codex: valid.runtimes.pi },+ }])).toEqual([]);+ expect(sanitizePresets([{+ ...valid,+ id: 'bad-id',+ runtimes: { pi: { ...valid.runtimes.pi, piCatalogProviderId: '../xai' } },}])).toEqual([]);});-it('accepts explicit Pi reasoning metadata and rejects ambiguous capability declarations', () => {const piReasoning = {...VALID_PRESET,diff --cc packages/model-providers/src/index.tsindex 0fd54e14d4,4ee7d573bd..c73b06a554--- a/packages/model-providers/src/index.ts+++ b/packages/model-providers/src/index.ts@@@ -34,8 -33,10 +34,10 @@@ export typeOAuthProviderDescriptor,} from './types.js';-export { PI_REASONING_EFFORTS } from './types.js';+export { PI_MODEL_APIS, PI_REASONING_EFFORTS } from './types.js';+ export { effectivePiWireProtocol, preservesPiCatalogModels } from './pi-catalog-marker.js';+export { resolveCodexCompatibilityWireProtocol } from './codexCompatibility.js';export { BUNDLED_CATALOG, BUILTIN_PROVIDERS, parseCatalog, presetDisplayName, sanitizePresets, sortPresetsForRegion } from './catalog.js';