Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(pi): preserve colliding custom provider routes
Chrisfa5d53d65244
diff --cc apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.tsindex b50d3e9e2d,265fb0028c..c7d4e048e1--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts@@@ -18,16 -14,7 +18,17 @@@ vi.mock('electron', () => (},}));-import { buildPiNativeProvidersFromConfigs, piNativeKeyEnvVar } from '../pi-host.js';+import {+ buildPiNativeProvidersFromConfigs,+ buildPiSubscriptionNativeProviders,++ mergePiNativeProviderResults,+ parsePiListModels,+ piNativeKeyEnvVar,+ readPiBundledModels,+ resolvePiBundledApiByModelId,+ resolvePiBundledModelById,+ type PiBundledModelInfo,+} from '../pi-host.js';type Cfg = Parameters<typeof buildPiNativeProvidersFromConfigs>[0][number];@@@ -37,247 -24,7 +38,302 @@@ 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('reads exact provider/model IDs from PI list output', () => {+ const parsed = parsePiListModels([+ 'provider model context max-out thinking images',+ 'openai-codex gpt-5.6-sol 272K 128K yes yes',+ 'openai-codex gpt-5.6-terra 272K 128K yes yes',+ '',+ ].join('\n'));+ expect([...parsed.get('openai-codex') ?? []]).toEqual(['gpt-5.6-sol', 'gpt-5.6-terra']);+ });++ const bundledPiPath = path.join(process.cwd(), 'apps/pi-bin/darwin-arm64/pi');+ it.skipIf(process.platform !== 'darwin' || process.arch !== 'arm64' || !existsSync(bundledPiPath))(+ 'reads full APIs from the exact bundled PI binary without network access',+ async () => {+ const catalog = await readPiBundledModels(bundledPiPath);+ expect(catalog?.get('openai-codex')?.get('gpt-5.6-sol')?.api)+ .toBe('openai-codex-responses');+ expect(catalog?.get('xai')?.get('grok-4.5')?.api).toBe('openai-responses');+ expect(catalog?.get('xai')?.get('grok-build-0.1')?.api).toBe('openai-completions');+ const anthropicModels = [...catalog?.get('anthropic')?.values() ?? []];+ expect(anthropicModels.length).toBeGreaterThan(0);+ expect(anthropicModels.every((model) => model.api === 'anthropic-messages')).toBe(true);+ expect(resolvePiBundledApiByModelId(catalog ?? undefined, 'glm-5.2'))+ .toBe('openai-completions');+ expect(catalog?.get('zai')?.get('glm-5.2')).toMatchObject({+ api: 'openai-completions',+ baseUrl: 'https://api.z.ai/api/coding/paas/v4',+ });+ },+ );++ it('overlays host subscriptions onto PI native providers and keeps piApi sparse', () => {+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;+ const anthropic = catalog.providers.find((provider) => provider.id === 'anthropic')!;+ const openai = catalog.providers.find((provider) => provider.id === 'openai')!;+ const xai = catalog.providers.find((provider) => provider.id === 'xai')!;+ anthropic.models.pi = [{+ id: 'claude-opus-5', name: 'Claude Opus 5', contextWindow: 1_000_000,+ efforts: ['high'], defaultEffort: 'high', piApi: 'anthropic-messages',+ }];+ openai.models.pi = [+ {+ id: 'chatgpt/gpt-5.6-sol', name: 'GPT-5.6 Sol', contextWindow: 272_000,+ efforts: ['low', 'high'], defaultEffort: 'high', piApi: 'openai-responses',+ },+ {+ id: 'chatgpt/gpt-5.7', name: 'GPT-5.7', contextWindow: 272_000,+ efforts: ['low', 'high'], defaultEffort: 'high', piApi: 'openai-responses',+ },+ ];+ xai.models.pi = [+ {+ id: 'xai/grok-4.5', name: 'Grok 4.5', contextWindow: 1_000_000,+ efforts: ['high'], defaultEffort: 'high', piApi: 'openai-responses',+ },+ {+ id: 'xai/grok-4.20', name: 'Grok 4.20', contextWindow: 1_000_000,+ efforts: ['high'], defaultEffort: 'high', piApi: 'openai-responses',+ },+ ];++ const { providers, env } = buildPiSubscriptionNativeProviders(+ catalog,+ 'http://127.0.0.1:4567/',+ new Map([+ ['anthropic', new Map([+ ['claude-opus-5', piBundledModel('claude-opus-5', 'anthropic-messages')],+ ])],+ ['openai-codex', new Map([+ ['gpt-5.6-sol', piBundledModel('gpt-5.6-sol', 'openai-codex-responses')],+ ])],+ ['xai', new Map([+ ['grok-4.5', piBundledModel('grok-4.5', 'openai-responses')],+ ])],+ ]),+ );++ expect(providers.map((provider) => provider.id)).toEqual([+ 'anthropic',+ 'openai-codex',+ 'xai',+ ]);+ expect(providers[0]).toMatchObject({+ sourceProviderId: 'anthropic',+ baseUrl: 'http://127.0.0.1:4567/',+ inheritModels: true,+ models: [{ id: 'claude-opus-5', wireId: 'claude-opus-5' }],+ });+ expect(providers[1]).toMatchObject({+ sourceProviderId: 'openai',+ baseUrl: 'http://127.0.0.1:4567/',+ inheritModels: true,+ models: [+ {+ id: 'chatgpt/gpt-5.6-sol',+ wireId: 'gpt-5.6-sol',+ },+ {+ id: 'chatgpt/gpt-5.7',+ wireId: 'gpt-5.7',+ catalogAddition: true,+ },+ ],+ });+ expect(providers[1]?.models[0]?.api).toBeUndefined();+ expect(providers[1]?.models[0]?.catalogAddition).toBeUndefined();+ 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' }],++ }],++ 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]),++ );++++ 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('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',+ }];++ 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' });+ }+ });++ 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-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')],+ ])]]),+ ).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',+ }];+ 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',diff --cc apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.tsindex 18e2a9e925,0000000000..bb84623cb9mode 100644,000000..100644--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts@@@ -1,347 -1,0 +1,347 @@@+import { EventEmitter } from 'node:events';+import { describe, expect, it, vi } from 'vitest';++import { createAnthropicCompatProxy } from '@cindy/anthropic-compat-proxy';++vi.mock('electron', () => ({+ app: { getPath: () => '/tmp/cindy-pi-native-forwarding-test' },+}));++vi.mock('../logger-adapter.js', () => ({+ createMakerLogger: () => {+ const make = (): Record<string, unknown> => ({+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),+ child: vi.fn(() => make()),+ });+ return make();+ },+ desktopMakerLogger: {+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),+ child: vi.fn(() => ({+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),+ child: vi.fn(),+ })),+ },+}));++import {+ getPiNativeSubscriptionHandler,+ type PiNativeSubscriptionHandlerDeps,+} from '../anthropic-responses-bridge-host.js';++function responseRecorder() {+ const response = new EventEmitter() as EventEmitter & {+ destroyed: boolean;+ headersSent: boolean;+ status: number;+ headers: Record<string, string>;+ chunks: Buffer[];+ writeHead: (status: number, headers?: Record<string, string>) => void;+ write: (chunk: Uint8Array | string) => boolean;+ end: (chunk?: Uint8Array | string) => void;+ };+ response.destroyed = false;+ response.headersSent = false;+ response.status = 0;+ response.headers = {};+ response.chunks = [];+ response.writeHead = (status, headers = {}) => {+ response.status = status;+ response.headers = headers;+ response.headersSent = true;+ };+ response.write = (chunk) => {+ response.chunks.push(Buffer.from(chunk));+ return true;+ };+ response.end = (chunk) => {+ if (chunk !== undefined) response.chunks.push(Buffer.from(chunk));+ };+ return response;+}++function deps(overrides: Partial<PiNativeSubscriptionHandlerDeps> = {}): PiNativeSubscriptionHandlerDeps {+ return {+ fetch: vi.fn(async () => new Response('ok', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ })) as PiNativeSubscriptionHandlerDeps['fetch'],+ getChatgptAuth: vi.fn(async () => ({ accessToken: 'host-openai-token', accountId: 'account-1' })),+ getGrokToken: vi.fn(async () => 'host-xai-token'),+ invalidateChatgpt: vi.fn(async () => false),+ invalidateXai: vi.fn(async () => 'ignored' as const),+ recordXaiRateLimit: vi.fn(),+ ...overrides,+ };+}++describe('PI native subscription forwarding', () => {+ it('forwards Codex Responses bytes unchanged with host-owned ChatGPT auth', async () => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const injected = deps({ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'] });+ const handler = getPiNativeSubscriptionHandler('openai', 'session-1', injected);+ const rawBody = Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0x00, 0x01]);+ const res = responseRecorder();++ await handler({+ rawBody,+ parsedBody: undefined,+ ctx: {+ reqId: 1,+ method: 'POST',+ url: '/codex/responses',+ headers: {+ 'content-type': 'application/json',+ 'content-encoding': 'zstd',+ authorization: 'Bearer placeholder-that-must-not-leak',+ },+ },+ res,+ } as never);++ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0]!;+ expect(url).toBe('https://chatgpt.com/backend-api/codex/responses');+ expect(init?.headers).toMatchObject({+ authorization: 'Bearer host-openai-token',+ 'chatgpt-account-id': 'account-1',+ 'content-encoding': 'zstd',+ 'content-type': 'application/json',+ });+ expect(Buffer.from(init?.body as Uint8Array)).toEqual(rawBody);+ expect(JSON.stringify(init?.headers)).not.toContain('placeholder-that-must-not-leak');+ expect(res.status).toBe(200);+ expect(Buffer.concat(res.chunks).toString('utf8')).toContain('event: done');+ });++ it('destroys the local bridge response when a native upstream stream fails after headers', async () => {+ const upstreamError = new Error('native upstream disconnected mid-stream');+ let sentFirstChunk = false;+ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ if (!sentFirstChunk) {+ sentFirstChunk = true;+ controller.enqueue(Buffer.from('event: response.output_text.delta\ndata: {"delta":"partial"}\n\n'));+ return;+ }+ controller.error(upstreamError);+ },+ });+ const handler = getPiNativeSubscriptionHandler('openai', 'session-stream-error', deps({+ fetch: vi.fn(async () => new Response(body, {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ })) as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const proxy = await createAnthropicCompatProxy({+ upstream: null,+ transformRequest: [],+ routingTransform: () => ({ localHandler: handler }),+ });++ try {+ await expect((async () => {+ const response = await fetch(`${proxy.url}/codex/responses`, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: '{}',+ });+ await response.text();+ })()).rejects.toThrow();+ } finally {+ await proxy.dispose();+ }+ });++ it('adds model-gated x_search to native general Grok requests after PI function tools', async () => {- const fetchMock = vi.fn(async () => new Response('event: done\n\n', {++ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', 'session-x-search', deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const parsedBody = {+ model: 'grok-4.5',+ tools: [{ type: 'function', name: 'read_file', parameters: { type: 'object' } }],+ tool_choice: 'required',+ };++ await handler({+ rawBody: Buffer.from(JSON.stringify(parsedBody)),+ parsedBody,+ ctx: {+ reqId: 5,+ method: 'POST',+ url: '/v1/responses',+ headers: { 'content-type': 'application/json' },+ },+ res: responseRecorder(),+ } as never);++ const request = JSON.parse(Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array).toString('utf8'));+ expect(request.tools).toEqual([+ { type: 'function', name: 'read_file', parameters: { type: 'object' } },+ { type: 'x_search' },+ ]);+ expect(request.tool_choice).toEqual({ type: 'function', name: 'read_file' });+ });++ it('preserves an existing native x_search declaration without duplicating it', async () => {- const fetchMock = vi.fn(async () => new Response('event: done\n\n', {++ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', 'session-x-search-existing', deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const parsedBody = {+ model: 'grok-4.5',+ tools: [{ type: 'x_search', from_date: '2026-08-01' }],+ };+ const rawBody = Buffer.from(JSON.stringify(parsedBody));++ await handler({+ rawBody,+ parsedBody,+ ctx: {+ reqId: 6,+ method: 'POST',+ url: '/v1/responses',+ headers: { 'content-type': 'application/json' },+ },+ res: responseRecorder(),+ } as never);++ const forwarded = Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array);+ expect(forwarded).toEqual(rawBody);+ expect(JSON.parse(forwarded.toString('utf8')).tools).toEqual([+ { type: 'x_search', from_date: '2026-08-01' },+ ]);+ });++ it.each(['grok-code-fast', 'grok-build-0.1'])(+ 'does not add x_search to native coding model %s',+ async (model) => {- const fetchMock = vi.fn(async () => new Response('event: done\n\n', {++ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('event: done\n\n', {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ }));+ const handler = getPiNativeSubscriptionHandler('xai', `session-${model}`, deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ }));+ const parsedBody = { model };+ const rawBody = Buffer.from(JSON.stringify(parsedBody));++ await handler({+ rawBody,+ parsedBody,+ ctx: {+ reqId: 7,+ method: 'POST',+ url: '/v1/responses',+ headers: { 'content-type': 'application/json' },+ },+ res: responseRecorder(),+ } as never);++ expect(Buffer.from(fetchMock.mock.calls[0]![1]?.body as Uint8Array)).toEqual(rawBody);+ },+ );++ it('forwards xAI Chat Completions natively and invalidates the failed host token', async () => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) => new Response('{"error":"expired"}', {+ status: 401,+ headers: { 'content-type': 'application/json' },+ }));+ const invalidateXai = vi.fn(async () => 'ignored' as const);+ const injected = deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ invalidateXai,+ });+ const handler = getPiNativeSubscriptionHandler('xai', 'session-2', injected);+ const rawBody = Buffer.from('{"model":"grok-build-0.1"}');+ const res = responseRecorder();++ await handler({+ rawBody,+ parsedBody: undefined,+ ctx: {+ reqId: 2,+ method: 'POST',+ url: '/v1/chat/completions',+ headers: { 'content-type': 'application/json' },+ },+ res,+ } as never);++ expect(fetchMock).toHaveBeenCalledWith(+ 'https://api.x.ai/v1/chat/completions',+ expect.objectContaining({+ headers: expect.objectContaining({ authorization: 'Bearer host-xai-token' }),+ }),+ );+ expect(invalidateXai).toHaveBeenCalledWith(expect.objectContaining({+ status: 401,+ failedAccessToken: 'host-xai-token',+ }));+ expect(res.status).toBe(401);+ expect(Buffer.concat(res.chunks).toString('utf8')).toContain('expired');+ });++ it('records only xAI rate-limit headers that are actually present', async () => {+ const fetchMock = vi.fn(async (_input: string | URL | Request, _init?: RequestInit) =>+ new Response('event: done\n\n', {+ status: 200,+ headers: {+ 'content-type': 'text/event-stream',+ 'x-ratelimit-remaining-requests': '9',+ },+ }));+ const recordXaiRateLimit = vi.fn();+ const injected = deps({+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],+ recordXaiRateLimit,+ });+ const handler = getPiNativeSubscriptionHandler('xai', 'session-rate', injected);+ const res = responseRecorder();++ await handler({+ rawBody: Buffer.from('{}'),+ parsedBody: {},+ ctx: {+ reqId: 4,+ method: 'POST',+ url: '/v1/responses',+ headers: { 'content-type': 'application/json' },+ },+ res,+ } as never);++ expect(recordXaiRateLimit).toHaveBeenCalledWith({+ limitRequests: undefined,+ remainingRequests: 9,+ limitTokens: undefined,+ remainingTokens: undefined,+ });+ });++ it('rejects unsupported native paths without contacting an upstream', async () => {+ const injected = deps();+ const handler = getPiNativeSubscriptionHandler('openai', 'session-3', injected);+ const res = responseRecorder();++ await handler({+ rawBody: Buffer.alloc(0),+ parsedBody: undefined,+ ctx: { reqId: 3, method: 'GET', url: '/models', headers: {} },+ res,+ } as never);++ expect(injected.fetch).not.toHaveBeenCalled();+ expect(res.status).toBe(404);+ });+});diff --cc apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.tsindex b86b90d62d,eec7efbaa7..bf08cff7ae--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts@@@ -325,265 -324,3 +325,265 @@@ export function getResponsesBridgeHandl}return _handler;}++type PiNativeSubscriptionProvider = 'openai' | 'xai';++export interface PiNativeSubscriptionHandlerDeps {+ fetch: typeof outboundFetch;+ getChatgptAuth: typeof getChatgptBridgeAuth;+ getGrokToken: typeof getGrokAccessToken;+ invalidateChatgpt: typeof invalidateChatgptBridgeAuth;+ invalidateXai: typeof invalidateXaiBridgeAuth;+ recordXaiRateLimit: typeof recordXaiRateLimitSnapshot;+}++const defaultPiNativeSubscriptionHandlerDeps: PiNativeSubscriptionHandlerDeps = {+ fetch: outboundFetch,+ getChatgptAuth: getChatgptBridgeAuth,+ getGrokToken: getGrokAccessToken,+ invalidateChatgpt: invalidateChatgptBridgeAuth,+ invalidateXai: invalidateXaiBridgeAuth,+ recordXaiRateLimit: recordXaiRateLimitSnapshot,+};++function piNativeUpstreamUrl(+ providerId: PiNativeSubscriptionProvider,+ requestUrl: string,+): string | null {+ let pathname: string;+ try {+ pathname = new URL(requestUrl, 'http://127.0.0.1').pathname;+ } catch {+ return null;+ }+ if (providerId === 'openai') {+ return pathname === '/codex/responses'+ ? 'https://chatgpt.com/backend-api/codex/responses'+ : null;+ }+ const normalized = pathname.startsWith('/v1/') ? pathname : `/v1${pathname}`;+ return normalized === '/v1/responses' || normalized === '/v1/chat/completions'+ ? `https://api.x.ai${normalized}`+ : null;+}++function nativeResponseHeaders(response: Response): Record<string, string> {+ const headers: Record<string, string> = {};+ response.headers.forEach((value, name) => {+ const lower = name.toLowerCase();+ if (+ lower === 'content-type'+ || lower === 'cache-control'+ || lower === 'retry-after'+ || lower === 'x-request-id'+ || lower.startsWith('x-ratelimit-')+ || lower.startsWith('openai-')+ ) {+ headers[lower] = value;+ }+ });+ return headers;+}++function finiteRateLimitHeader(headers: Headers, name: string): number | undefined {+ const raw = headers.get(name);+ if (raw === null || raw.trim().length === 0) return undefined;+ const value = Number(raw);+ return Number.isFinite(value) ? value : undefined;+}++function recordNativeXaiRateLimit(+ headers: Headers,+ record: typeof recordXaiRateLimitSnapshot,+): void {+ const info = {+ limitRequests: finiteRateLimitHeader(headers, 'x-ratelimit-limit-requests'),+ remainingRequests: finiteRateLimitHeader(headers, 'x-ratelimit-remaining-requests'),+ limitTokens: finiteRateLimitHeader(headers, 'x-ratelimit-limit-tokens'),+ remainingTokens: finiteRateLimitHeader(headers, 'x-ratelimit-remaining-tokens'),+ };+ if (Object.values(info).some((value) => value !== undefined)) {+ record(info);+ }+}++function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++/**+ * PI already emits xAI-native payloads, so this path bypasses the Messages →+ * Responses bridge that normally supplies xAI's model-gated server tools.+ * Restore the same stable contract here: append missing tools after PI's own+ * tools, preserve an existing declaration verbatim, and keep a forced single+ * function call from being satisfied by x_search instead.+ */+function withNativeXaiServerSideTools(body: unknown): Record<string, unknown> | null {+ if (!isPlainRecord(body) || typeof body.model !== 'string') return null;+ const model = body.model.startsWith(XAI_MODEL_PREFIX)+ ? body.model.slice(XAI_MODEL_PREFIX.length)+ : body.model;+ const serverTools = xaiServerSideTools(model);+ if (serverTools.length === 0) return null;++ const existing = Array.isArray(body.tools) ? body.tools : [];+ const declaredTypes = new Set(+ existing.map((tool) => (+ isPlainRecord(tool) && typeof tool.type === 'string' ? tool.type : ''+ )),+ );+ const missing = serverTools.filter((tool) => !declaredTypes.has(tool.type));+ const tools = missing.length > 0 ? [...existing, ...missing] : existing;+ let next = missing.length > 0 ? { ...body, tools } : body;++ if (body.tool_choice === 'required') {+ const functionTools = tools.filter(+ (tool) => isPlainRecord(tool) && tool.type === 'function' && typeof tool.name === 'string',+ );+ if (functionTools.length === 1) {+ next = {+ ...next,+ tool_choice: { type: 'function', name: functionTools[0]!.name },+ };+ return next;+ }+ }+ return missing.length > 0 ? next : null;+}++async function pipeNativeResponse(response: Response, res: Parameters<LocalRequestHandler>[0]['res']): Promise<void> {+ res.writeHead(response.status, nativeResponseHeaders(response));+ if (!response.body) {+ res.end();+ return;+ }+ const reader = response.body.getReader();+ try {+ while (!res.destroyed) {+ const chunk = await reader.read();+ if (chunk.done) break;+ if (!res.write(Buffer.from(chunk.value))) {+ await new Promise<void>((resolve) => {+ const done = (): void => {+ res.off('drain', done);+ res.off('close', done);+ resolve();+ };+ res.once('drain', done);+ res.once('close', done);+ });+ }+ }+ } finally {+ await reader.cancel().catch(() => undefined);+ }+ if (!res.destroyed) res.end();+}++/**+ * Forward an already-native PI request. Unlike getResponsesBridgeHandler this+ * performs no Messages/Responses conversion: PI constructs the provider's+ * native payload, while the host swaps placeholder loopback credentials for+ * the connected account credential and restores xAI's model-gated server tools.+ */+export function getPiNativeSubscriptionHandler(+ providerId: PiNativeSubscriptionProvider,+ sessionId: string,+ deps: PiNativeSubscriptionHandlerDeps = defaultPiNativeSubscriptionHandlerDeps,+): LocalRequestHandler {+ return async ({ rawBody, parsedBody, ctx, res }) => {+ const upstreamUrl = piNativeUpstreamUrl(providerId, ctx.url);+ if (ctx.method !== 'POST' || !upstreamUrl) {+ res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });+ res.end(JSON.stringify({ error: { message: 'Unsupported PI subscription endpoint.' } }));+ return;+ }+ const controller = new AbortController();+ const abortOnClose = (): void => controller.abort();+ res.once('close', abortOnClose);+ try {+ let accessToken: string;+ let headers: Record<string, string>;+ if (providerId === 'openai') {+ const auth = await deps.getChatgptAuth();+ accessToken = auth.accessToken;+ headers = buildChatgptBridgeHeaders({+ accessToken,+ accountId: auth.accountId,+ sessionId,+ });+ } else {+ accessToken = await deps.getGrokToken();+ headers = { authorization: `Bearer ${accessToken}` };+ }+ headers['content-type'] = ctx.headers['content-type'] ?? 'application/json';+ headers.accept = ctx.headers.accept ?? 'text/event-stream';+ let outboundBody = rawBody;- let contentEncoding = ctx.headers['content-encoding'];++ let contentEncoding: string | undefined = ctx.headers['content-encoding'];+ if (providerId === 'xai') {+ const withServerTools = withNativeXaiServerSideTools(parsedBody);+ if (withServerTools) {+ outboundBody = Buffer.from(JSON.stringify(withServerTools));+ // The proxy parsed a plain JSON request. After reserializing it the+ // original content encoding, if any, no longer describes the bytes.+ contentEncoding = undefined;+ }+ }+ if (contentEncoding) headers['content-encoding'] = contentEncoding;++ const response = await deps.fetch(upstreamUrl, {+ method: 'POST',+ headers,+ body: new Uint8Array(outboundBody),+ signal: controller.signal,+ });+ if (providerId === 'xai' && response.ok) {+ recordNativeXaiRateLimit(response.headers, deps.recordXaiRateLimit);+ }+ if (!response.ok) {+ const errorBody = Buffer.from(await response.arrayBuffer());+ const errorText = errorBody.toString('utf8');+ if (providerId === 'openai') {+ await deps.invalidateChatgpt({+ status: response.status,+ body: errorText,+ failedAccessToken: accessToken,+ });+ } else {+ await deps.invalidateXai({+ status: response.status,+ body: errorText,+ failedAccessToken: accessToken,+ });+ }+ res.writeHead(response.status, nativeResponseHeaders(response));+ res.end(errorBody);+ return;+ }+ await pipeNativeResponse(response, res);+ } catch (err) {+ if (controller.signal.aborted || res.destroyed) return;+ // Once a 200/SSE response has started, an upstream body failure cannot+ // be converted into a structured 502. Propagate it to runLocalHandler,+ // which destroys the client response so PI observes a transport failure+ // instead of accepting a cleanly-ended truncated stream.+ if (res.headersSent) throw err;+ log.warn('PI native subscription forwarding failed', {+ providerId,+ err: err instanceof Error ? err.message : String(err),+ });+ res.writeHead(502, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',+ });+ res.end(JSON.stringify({+ error: {+ type: 'upstream_error',+ message: err instanceof Error ? err.message : String(err),+ },+ }));+ } finally {+ res.off('close', abortOnClose);+ }+ };+}diff --cc apps/desktop/src/main/maker-host/pi-host.tsindex 2429ec91b2,4293c5ef37..1d04c28544--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@@ -869,6 -368,6 +869,52 @@@ export function buildPiNativeProvidersFreturn { 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 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 },++ };++}++/** BYOM:读 DB 自定义 provider + safeStorage key → pi 原生 provider spec。IO 外壳,逻辑在上面。 */async function resolvePiNativeProviders(ctx?: {workingDir?: string;@@@ -910,27 -399,9 +956,19 @@@}}}- return buildPiNativeProvidersFromConfigs(configs, readCustomProviderKey, (id, reason) => {- log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason });+ const custom = buildPiNativeProvidersFromConfigs(+ configs,+ readCustomProviderKey,+ (id, reason) =>+ log.warn('resolvePiNativeProviders: skipped custom provider', { id, reason }),+ bundledModels ?? undefined,+ );- const reserved = new Set(subscriptions.providers.map((provider) => provider.id));- return {- providers: [- ...subscriptions.providers,- ...custom.providers.filter((provider) => {- if (!reserved.has(provider.id)) return true;- log.warn('resolvePiNativeProviders: custom provider collides with native subscription provider', {- id: provider.id,- });- return false;- }),- ],- env: { ...subscriptions.env, ...custom.env },- };++ return mergePiNativeProviderResults(subscriptions, custom, (sourceProviderId, runtimeProviderId) => {++ log.info('resolvePiNativeProviders: namespaced custom provider runtime id', {++ sourceProviderId,++ runtimeProviderId,++ });+ });}/** baseUrl 是否指向本机 loopback(与本机 proxy 同判定,远端会话不可达)。diff --cc packages/maker-core/src/agents/base-agent.tsindex b6c7488223,5ad841a4db..340d847c13--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@@ -240,16 -219,11 +240,16 @@@ export interface PiRemoteFileOps* 解析产出;PiAgent 写进 models.json 的独立 provider 块,并按 model→provider 路由 set_model。*/export interface PiNativeProviderSpec {- /** PI provider id(slug,禁与网关 provider `cindy` 撞名)。 */- /** provider id(slug,禁与网关 provider `cindy` 撞名)。 */++ /** PI runtime provider id(slug,禁与网关 provider `cindy` 撞名)。 */id: string;- /** Cindy catalog provider id; defaults to id for BYOM providers. */++ /** Cindy catalog / persisted provider id; defaults to the runtime id. */+ sourceProviderId?: string;name: string;baseUrl: string;- api: PiNativeApi;+ /** BYOM provider default. Omitted only when inheriting PI's bundled provider catalog. */+ api?: PiNativeApi;+ /** Keep PI's bundled models and serialize only models carrying an explicit api override. */+ inheritModels?: boolean;/*** 存放该 provider api key 的 env 变量名;models.json 用 `$<envVar>` 插值引用(与网关* CINDY_PI_API_KEY 同机制,密钥只进子进程 env、不落盘)。keyless(本机 Ollama 等)留空 →diff --cc packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.tsindex cca40066a5,495d892550..fd67bd6e6e--- 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,129 -203,6 +203,198 @@@ 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> = [];+ const availableModels: ModelDescriptor[] = [+ {+ id: 'chatgpt/gpt-cindy-daily-test', displayName: 'GPT Daily', contextWindow: 272_000,+ efforts: ['low', 'high'], defaultEffort: 'high',+ },+ {+ id: 'xai/grok-4.5', displayName: 'Grok 4.5', contextWindow: 1_000_000,+ efforts: ['high'], defaultEffort: 'high',+ },+ {+ id: 'xai/grok-4.20', displayName: 'Grok 4.20', contextWindow: 1_000_000,+ efforts: ['high'], defaultEffort: 'high',+ },+ {+ id: 'claude-opus-5', displayName: 'Claude Opus 5', contextWindow: 1_000_000,+ efforts: ['high'], defaultEffort: 'high',+ },+ ];+ const deps: AgentDeps = {+ auth: {+ getState: async (options) => {+ authProviderIds.push(options?.providerId);+ return { authenticated: true, identity: 'test', authSource: 'oauth' as const };+ },+ triggerLogin: async () => ({ authenticated: true }),+ logout: async () => {},+ getAuthEnv: async () => ({}),+ },+ runtimeConfig: { endpoint: 'http://127.0.0.1:9988' },+ binaryPath: path.join(agentHome, 'pi'),+ logger: noopLogger,+ capabilityAdditions: { availableModels },+ resolvePiAgentHome: () => agentHome,+ resolvePiGatewayModelApi: () => 'openai-responses',+ resolvePiNativeProviders: async () => ({+ providers: [+ {+ id: 'anthropic', sourceProviderId: 'anthropic', name: 'Anthropic',+ baseUrl: 'http://127.0.0.1:9988', inheritModels: true,+ models: [{ id: 'claude-opus-5', wireId: 'claude-opus-5' }],+ },+ {+ id: 'openai-codex', sourceProviderId: 'openai', name: 'OpenAI',+ baseUrl: 'http://127.0.0.1:9988', inheritModels: true,+ apiKeyEnvVar: 'CINDY_PI_OPENAI_PROXY_KEY',+ models: [{+ id: 'chatgpt/gpt-cindy-daily-test',+ wireId: 'gpt-cindy-daily-test',+ catalogAddition: true,+ contextWindow: 272_000,+ maxTokens: 32_000,+ }],+ },+ {+ id: 'xai', sourceProviderId: 'xai', name: 'xAI',+ baseUrl: 'http://127.0.0.1:9988/v1', inheritModels: true,+ models: [+ { id: 'xai/grok-4.5', wireId: 'grok-4.5' },+ {+ id: 'xai/grok-4.20', wireId: 'grok-4.20', api: 'openai-responses',+ contextWindow: 1_000_000, maxTokens: 64_000,+ cost: { input: 2, output: 6, cacheRead: 0.3, cacheWrite: 0 },+ compat: { supportsStrictTools: true },+ },+ ],+ },+ ],+ env: { CINDY_PI_OPENAI_PROXY_KEY: 'placeholder-jwt' },+ }),+ };++ const handle = await new PiAgent(deps).startSession({+ sessionId: 'native-subscription-routing',+ workingDir: cwd,+ model: 'chatgpt/gpt-cindy-daily-test',+ providerId: 'openai',+ effort: 'high',+ });++ expect(authProviderIds).toEqual(['openai']);+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 4))+ .toEqual(['--provider', 'openai-codex', '--model', 'gpt-cindy-daily-test']);+ const configHome = captured.env.PI_CODING_AGENT_DIR as string;+ const models = JSON.parse(readFileSync(path.join(configHome, 'models.json'), 'utf8')) as {+ providers: Record<string, { api?: string; models?: Array<{ id: string; api?: string }> }>;+ };+ expect(models.providers.anthropic).not.toHaveProperty('api');+ expect(models.providers.anthropic?.models).toBeUndefined();+ expect(models.providers['openai-codex']).not.toHaveProperty('api');+ expect(models.providers['openai-codex']?.models).toEqual([+ expect.objectContaining({ id: 'gpt-cindy-daily-test' }),+ ]);+ expect(models.providers['openai-codex']?.models?.[0]).not.toHaveProperty('api');+ expect(models.providers.xai).not.toHaveProperty('api');+ expect(models.providers.xai?.models).toEqual([+ expect.objectContaining({+ id: 'grok-4.20',+ api: 'openai-responses',+ cost: { input: 2, output: 6, cacheRead: 0.3, cacheWrite: 0 },+ compat: { supportsStrictTools: true },+ }),+ ]);+ expect(JSON.parse(readFileSync(path.join(configHome, 'settings.json'), 'utf8')))+ .toEqual({ transport: 'sse' });+ expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'native-subscription-routing'), 'utf8')))+ .toEqual({ model: 'gpt-cindy-daily-test', provider: 'openai-codex' });++ await handle.setModel!('xai/grok-4.5', { providerId: 'xai' });+ expect(captured.requests).toContainEqual({+ type: 'set_model', provider: 'xai', modelId: 'grok-4.5',+ });+ expect(JSON.parse(readFileSync(runtimeFileOf('subagent', 'native-subscription-routing'), 'utf8')))+ .toEqual({ model: 'grok-4.5', provider: 'xai' });++ await handle.setModel!('claude-opus-5', { providerId: 'anthropic' });+ expect(captured.requests).toContainEqual({+ type: 'set_model', provider: 'anthropic', modelId: 'claude-opus-5',+ });+ await handle.close();+ });+++ it('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 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 d84969f21e,7bb3554ec1..b12cea73a4--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@@ -940,16 -903,16 +940,22 @@@ export class PiAgent extends BaseAgent// 同时校验显式 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))++ ) {++ candidateRuntimeIds.add(initialProvider);+ }- for (const candidateId of candidateIds) {- const loopbackNative = nativeProviderById.get(candidateId);++ for (const runtimeProviderId of candidateRuntimeIds) {++ const loopbackNative = nativeProviderById.get(runtimeProviderId);if (loopbackNative && isLoopbackOnlyBaseUrl(loopbackNative.baseUrl)) {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.',);