Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(model-catalog): 让 Pi 使用服务端目录基线 (#2900)

Chris Zhang5ca891b2c20e
diff --git a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
index 54af402e60..d926fba856 100644
--- a/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/catalogDerivedModels.test.ts
@@ -23,6 +23,7 @@ import {
resolvePiRuntimeModelDescriptor,
resolveVerifiedContextWindow,
} from '../catalog-to-descriptors.js';
+import { sanitizeModelCatalogOverrides } from '../model-plane/localCatalogOverrides.js';
function model(id: string, extra: Partial<CatalogModel> = {}): CatalogModel {
return { id, name: id, contextWindow: 200_000, efforts: [], defaultEffort: null, ...extra };
@@ -408,22 +409,133 @@ describe('deriveAvailableModels — dynamic-first catalog contract', () => {
maxOutputTokens: 96_000,
efforts: ['low', 'max'],
defaultEffort: 'max',
+ perAgent: {
+ codex: {
+ contextWindow: 272_000,
+ efforts: ['low'],
+ defaultEffort: 'low',
+ },
+ },
routes: [{ providerId: 'openai', modelId: 'gpt-retired', agents: ['codex'] }],
}],
};
expect(deriveAvailableModels(catalog, 'pi').some((m) => m.id === 'chatgpt/gpt-retired')).toBe(false);
- expect(resolvePiRuntimeModelDescriptor(catalog, 'openai', 'chatgpt/gpt-retired')).toMatchObject({
+ const localOverrides = sanitizeModelCatalogOverrides({
+ patches: {
+ 'openai:gpt-retired': {
+ base: {
+ contextWindow: 444_000,
+ efforts: ['medium', 'high'],
+ defaultEffort: 'high',
+ },
+ },
+ },
+ }).overrides;
+ expect(resolvePiRuntimeModelDescriptor(
+ catalog,
+ 'openai',
+ 'chatgpt/gpt-retired',
+ { localOverrides },
+ )).toMatchObject({
id: 'chatgpt/gpt-retired',
displayName: 'GPT Retired',
- contextWindow: 300_000,
+ contextWindow: 444_000,
maxOutputTokens: 96_000,
- efforts: ['minimal', 'low'],
- defaultEffort: 'low',
+ efforts: ['minimal', 'medium', 'high'],
+ defaultEffort: 'high',
});
expect(resolvePiRuntimeModelDescriptor(catalog, 'anthropic', 'chatgpt/gpt-retired')).toBeNull();
});
+ it('retired Pi fallback 按 addition 后 patch 的最终层顺序重建 root', () => {
+ const catalog = structuredClone(BUNDLED_CATALOG);
+ catalog.modelRegistry = {
+ schemaVersion: 1,
+ updatedAt: '2026-08-17T00:00:00.000Z',
+ models: [{
+ id: 'openai/gpt-local-revival',
+ name: 'Registry baseline',
+ status: 'retired',
+ contextWindow: 300_000,
+ efforts: ['low'],
+ defaultEffort: 'low',
+ routes: [{ providerId: 'openai', modelId: 'gpt-local-revival', agents: ['codex'] }],
+ }],
+ };
+ const localOverrides = sanitizeModelCatalogOverrides({
+ additions: {
+ 'openai:gpt-local-revival': {
+ agents: ['codex'],
+ base: {
+ name: 'Local addition',
+ contextWindow: 500_000,
+ efforts: ['medium', 'high'],
+ defaultEffort: 'medium',
+ status: 'active',
+ },
+ },
+ },
+ patches: {
+ 'openai:gpt-local-revival': {
+ base: { contextWindow: 600_000, defaultEffort: 'high' },
+ },
+ },
+ }).overrides;
+
+ expect(resolvePiRuntimeModelDescriptor(
+ catalog,
+ 'openai',
+ 'chatgpt/gpt-local-revival',
+ { localOverrides },
+ )).toMatchObject({
+ displayName: 'Local addition',
+ contextWindow: 600_000,
+ efforts: ['minimal', 'medium', 'high'],
+ defaultEffort: 'high',
+ });
+ });
+
+ it('retired OpenAI context profile 按 alias id 与 entry baseline 重建 Pi 私有描述符', () => {
+ const catalog = structuredClone(BUNDLED_CATALOG);
+ catalog.modelRegistry = {
+ schemaVersion: 1,
+ updatedAt: '2026-08-17T00:00:00.000Z',
+ models: [
+ {
+ id: 'openai/gpt-5.6-sol',
+ name: 'GPT-5.6-Sol',
+ status: 'active',
+ contextWindow: 272_000,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'medium',
+ routes: [{ providerId: 'openai', modelId: 'gpt-5.6-sol', agents: ['codex'] }],
+ },
+ {
+ id: 'openai/gpt-5.6-sol[1m]',
+ name: 'GPT-5.6-Sol (1M · Higher usage)',
+ status: 'retired',
+ contextWindow: 1_000_000,
+ maxOutputTokens: 128_000,
+ efforts: ['low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'medium',
+ routes: [{ providerId: 'openai', modelId: 'gpt-5.6-sol', agents: ['claude-code'] }],
+ },
+ ],
+ };
+
+ expect(
+ resolvePiRuntimeModelDescriptor(catalog, 'openai', 'chatgpt/gpt-5.6-sol[1m]'),
+ ).toMatchObject({
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ displayName: 'GPT-5.6-Sol (1M · Higher usage)',
+ contextWindow: 1_000_000,
+ maxOutputTokens: 128_000,
+ efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'medium',
+ });
+ });
+
it('runtime refresh replaces both agent model lists in place so existing sessions keep the live reference', () => {
const claudeModels: ModelDescriptor[] = [{ id: 'stale-claude', displayName: 'Stale', contextWindow: 1, efforts: [], defaultEffort: null }];
const codexModels: ModelDescriptor[] = [{ id: 'stale-codex', displayName: 'Stale', contextWindow: 1, efforts: [], defaultEffort: null }];
diff --git a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
index 3e1c270bc8..acd616e349 100644
--- a/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/modelPlane.test.ts
@@ -129,12 +129,7 @@ describe('registry presence 实体化', () => {
});
it('公共 Registry 的 newSessionDefault 不进入 CatalogModel;默认只信区域门控后的 /models', () => {
- setActiveCatalog(
- baseCatalog(
- [gpt6Entry({ newSessionDefault: ['claude-code', 'codex'] })],
- 2,
- ),
- );
+ setActiveCatalog(baseCatalog([gpt6Entry({ newSessionDefault: ['claude-code', 'codex'] })], 2));
const codex = models('openai', 'codex').find((m) => m.id === 'gpt-6');
const claude = models('openai', 'claude-code').find((m) => m.id === 'chatgpt/gpt-6');
@@ -151,26 +146,102 @@ describe('registry presence 实体化', () => {
setActiveCatalog(
baseCatalog([
gpt6Entry({
+ contextWindow: 1_000_000,
efforts: ['low', 'medium', 'high', 'xhigh', 'max'],
defaultEffort: 'xhigh',
perAgent: {
- codex: { efforts: ['low', 'medium', 'high'], defaultEffort: 'high' },
+ codex: {
+ contextWindow: 272_000,
+ efforts: ['low', 'medium', 'high'],
+ defaultEffort: 'high',
+ },
'claude-code': { efforts: ['low', 'medium'], defaultEffort: 'medium' },
},
}),
]),
);
expect(models('openai', 'codex').find((m) => m.id === 'gpt-6')).toMatchObject({
+ contextWindow: 272_000,
efforts: ['low', 'medium', 'high'],
defaultEffort: 'high',
});
expect(models('openai', 'claude-code').find((m) => m.id === 'chatgpt/gpt-6')).toMatchObject({
+ contextWindow: 1_000_000,
efforts: ['low', 'medium'],
defaultEffort: 'medium',
});
- // Pi 没有 wire perAgent,恒定从 codex root 派生。
+ // Pi 没有 wire perAgent,但仍是独立消费端:使用 entry 基线,再执行 bridge 硬约束。
expect(models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-6')).toMatchObject({
- efforts: ['low', 'medium', 'high'],
+ contextWindow: 1_000_000,
+ efforts: ['low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'xhigh',
+ });
+
+ setLocalCatalogOverrides(
+ overridesOf({ patches: { 'openai:gpt-6': { base: { contextWindow: 123_000 } } } }),
+ );
+ expect(models('openai', 'codex').find((m) => m.id === 'gpt-6')?.contextWindow).toBe(123_000);
+ expect(models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-6')?.contextWindow).toBe(
+ 123_000,
+ );
+ });
+
+ it('同一 OpenAI modelId 的长上下文 entry 只生成 Claude/Pi 独立选择', () => {
+ setActiveCatalog(
+ baseCatalog([
+ gpt6Entry({ contextWindow: 272_000 }),
+ gpt6Entry({
+ id: 'openai/gpt-6[1m]',
+ name: 'GPT-6 (1M · 高消耗)',
+ contextWindow: 1_000_000,
+ routes: [{ providerId: 'openai', modelId: 'gpt-6', agents: ['claude-code'] }],
+ }),
+ ]),
+ );
+
+ expect(models('openai', 'codex').filter((m) => m.id.startsWith('gpt-6'))).toMatchObject([
+ { id: 'gpt-6', contextWindow: 272_000 },
+ ]);
+ for (const agent of ['claude-code', 'pi'] as const) {
+ expect(
+ models('openai', agent)
+ .filter((m) => m.id.startsWith('chatgpt/gpt-6'))
+ .map((m) => ({ id: m.id, name: m.name, contextWindow: m.contextWindow })),
+ ).toEqual([
+ { id: 'chatgpt/gpt-6', name: 'GPT-6', contextWindow: 272_000 },
+ {
+ id: 'chatgpt/gpt-6[1m]',
+ name: 'GPT-6 (1M · 高消耗)',
+ contextWindow: 1_000_000,
+ },
+ ]);
+ }
+ setLocalCatalogOverrides(
+ overridesOf({
+ patches: { 'openai:gpt-6[1m]': { base: { contextWindow: 900_000 } } },
+ }),
+ );
+ expect(
+ models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-6[1m]')?.contextWindow,
+ ).toBe(900_000);
+ expect(getModelPlaneWarnings()).toEqual([]);
+ });
+
+ it('没有 Registry entry 时 Pi 保留 Codex discovery 的既有字段', () => {
+ setActiveCatalog(baseCatalog());
+ setDiscoveredCodexModels([
+ {
+ id: 'gpt-discovered',
+ name: 'Discovered GPT',
+ contextWindow: 272_000,
+ efforts: ['high'],
+ defaultEffort: 'high',
+ },
+ ]);
+
+ expect(models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-discovered')).toMatchObject({
+ contextWindow: 272_000,
+ efforts: ['high'],
defaultEffort: 'high',
});
});
@@ -402,8 +473,7 @@ describe('registry presence 实体化', () => {
?.newSessionDefault,
).toEqual(['claude-code', 'codex', 'pi']);
expect(
- models('xd', 'codex').find((m) => m.id === 'deepseek/deepseek-v4-pro')
- ?.newSessionDefault,
+ models('xd', 'codex').find((m) => m.id === 'deepseek/deepseek-v4-pro')?.newSessionDefault,
).toEqual(['claude-code', 'codex', 'pi']);
expect(
models('xd', 'pi').find((m) => m.id === 'deepseek/deepseek-v4-pro')?.newSessionDefault,
@@ -417,6 +487,8 @@ describe('retired tombstone 与 discovery 回补', () => {
gpt6Entry({
id: 'openai/gpt-dead',
status: 'retired',
+ contextWindow: 300_000,
+ perAgent: { codex: { contextWindow: 272_000 } },
routes: [{ providerId: 'openai', modelId: 'gpt-dead', agents: ['codex'] }],
}),
]);
@@ -437,6 +509,30 @@ describe('retired tombstone 与 discovery 回补', () => {
isRegistryTombstoneForConsumer(registry, 'openai', 'chatgpt/gpt-dead', 'claude-code'),
).toBe(false);
expect(isRegistryTombstoneForConsumer(registry, 'xd', 'gpt-dead', 'claude-code')).toBe(false);
+
+ const withAlias = baseCatalog([
+ gpt6Entry(),
+ gpt6Entry({
+ id: 'openai/gpt-6[1m]',
+ status: 'retired',
+ routes: [{ providerId: 'openai', modelId: 'gpt-6', agents: ['claude-code'] }],
+ }),
+ ]).modelRegistry;
+ expect(
+ isRegistryTombstoneForConsumer(withAlias, 'openai', 'chatgpt/gpt-6[1m]', 'pi'),
+ ).toBe(true);
+ expect(
+ isRegistryTombstoneForConsumer(
+ withAlias,
+ 'openai',
+ 'chatgpt/gpt-6[1m]',
+ 'claude-code',
+ ),
+ ).toBe(true);
+ expect(isRegistryTombstoneForConsumer(withAlias, 'openai', 'chatgpt/gpt-6', 'pi')).toBe(false);
+ expect(
+ isRegistryTombstoneForConsumer(withAlias, 'openai', 'chatgpt/gpt-6', 'claude-code'),
+ ).toBe(false);
});
it('discovery 回补的 retired 条目被标记,标准派生禁止新选择,keepSelected 豁免', () => {
@@ -444,6 +540,17 @@ describe('retired tombstone 与 discovery 回补', () => {
setDiscoveredCodexModels([discoveredDead]);
const entry = models('openai', 'codex').find((m) => m.id === 'gpt-dead');
expect(entry?.status).toBe('retired');
+ expect(models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-dead')).toMatchObject({
+ contextWindow: 300_000,
+ status: 'retired',
+ });
+
+ setLocalCatalogOverrides(
+ overridesOf({ patches: { 'openai:gpt-dead': { base: { contextWindow: 123_000 } } } }),
+ );
+ expect(
+ models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-dead')?.contextWindow,
+ ).toBe(123_000);
const views = buildRegistry(getActiveCatalog(), { openai: true });
const withoutSelection = deriveModelList({ providers: views, agent: 'codex' });
@@ -485,6 +592,11 @@ describe('retired tombstone 与 discovery 回补', () => {
name: 'Dead Model Revived',
status: 'active',
});
+ expect(models('openai', 'pi').find((m) => m.id === 'chatgpt/gpt-dead')).toMatchObject({
+ name: 'Dead Model Revived',
+ status: 'active',
+ contextWindow: 100_000,
+ });
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
index f284a49258..d15786ac39 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -426,6 +426,7 @@ describe('buildPiNativeProvidersFromConfigs', () => {
{
id: 'chatgpt/gpt-5.6-sol',
wireId: 'gpt-5.6-sol',
+ api: 'openai-codex-responses',
},
{
id: 'chatgpt/gpt-5.7',
@@ -434,8 +435,11 @@ describe('buildPiNativeProvidersFromConfigs', () => {
},
],
});
- expect(providers[1]?.models[0]?.api).toBeUndefined();
expect(providers[1]?.models[0]?.catalogAddition).toBeUndefined();
+ expect(providers[1]?.models[0]).toMatchObject({
+ api: 'openai-codex-responses',
+ contextWindow: 272_000,
+ });
expect(providers[2]).toMatchObject({
sourceProviderId: 'xai',
baseUrl: 'http://127.0.0.1:4567/v1',
@@ -458,6 +462,129 @@ describe('buildPiNativeProvidersFromConfigs', () => {
}
});
+ it('publishes a distinct Pi 1M profile while inheriting the bundled ChatGPT adapter', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ const openai = catalog.providers.find((provider) => provider.id === 'openai')!;
+ openai.models.pi = [
+ {
+ id: 'chatgpt/gpt-5.6-sol',
+ name: 'GPT-5.6-Sol',
+ contextWindow: 272_000,
+ maxOutput: 128_000,
+ efforts: ['low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'medium',
+ },
+ {
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ name: 'GPT-5.6-Sol (1M · 高消耗)',
+ contextWindow: 1_000_000,
+ maxOutput: 128_000,
+ efforts: ['low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'medium',
+ },
+ ];
+ const bundled = piBundledModel('gpt-5.6-sol', 'openai-codex-responses', {
+ // readPiBundledModels probes with this deliberately unreachable endpoint.
+ // It must never override the provider-level runtime compat proxy.
+ baseUrl: 'http://127.0.0.1:1',
+ contextWindow: 272_000,
+ maxTokens: 128_000,
+ cost: {
+ input: 5,
+ output: 30,
+ cacheRead: 0.5,
+ cacheWrite: 6.25,
+ tiers: [{
+ inputTokensAbove: 272_000,
+ input: 10,
+ output: 45,
+ cacheRead: 1,
+ cacheWrite: 12.5,
+ }],
+ },
+ compat: { supportsStrictTools: true },
+ });
+
+ const provider = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ new Map([['openai-codex', new Map([[bundled.id, bundled]])]]),
+ ).providers.find((candidate) => candidate.id === 'openai-codex');
+
+ expect(provider?.models).toEqual([
+ expect.objectContaining({
+ id: 'chatgpt/gpt-5.6-sol',
+ wireId: 'gpt-5.6-sol',
+ api: 'openai-codex-responses',
+ contextWindow: 272_000,
+ maxTokens: 128_000,
+ compat: bundled.compat,
+ }),
+ expect.objectContaining({
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ wireId: 'gpt-5.6-sol[1m]',
+ catalogAddition: true,
+ name: 'GPT-5.6-Sol (1M · 高消耗)',
+ contextWindow: 1_000_000,
+ cost: bundled.cost,
+ compat: bundled.compat,
+ }),
+ ]);
+ expect(provider?.models[0]?.catalogAddition).toBeUndefined();
+ expect(provider?.models[0]).not.toHaveProperty('baseUrl');
+ expect(provider?.baseUrl).toBe('http://127.0.0.1:4567/');
+
+ const withoutProbe = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ ).providers.find((candidate) => candidate.id === 'openai-codex');
+ expect(withoutProbe?.models[1]).toMatchObject({
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ wireId: 'gpt-5.6-sol[1m]',
+ catalogAddition: true,
+ contextWindow: 1_000_000,
+ });
+ });
+
+ it('keeps a retired OpenAI profile private to its native subscription resume', () => {
+ const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
+ const openai = catalog.providers.find((provider) => provider.id === 'openai')!;
+ openai.models.pi = openai.models.pi?.filter(
+ (model) => model.id !== 'chatgpt/gpt-5.6-sol[1m]',
+ );
+ const bundled = piBundledModel('gpt-5.6-sol', 'openai-codex-responses', {
+ contextWindow: 272_000,
+ maxTokens: 128_000,
+ compat: { supportsStrictTools: true },
+ });
+
+ const provider = buildPiSubscriptionNativeProviders(
+ catalog,
+ 'http://127.0.0.1:4567/',
+ new Map([['openai-codex', new Map([[bundled.id, bundled]])]]),
+ undefined,
+ {
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ displayName: 'GPT-5.6-Sol (1M · Higher usage)',
+ contextWindow: 1_000_000,
+ maxOutputTokens: 128_000,
+ efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'medium',
+ },
+ ).providers.find((candidate) => candidate.id === 'openai-codex');
+
+ expect(provider?.models).toEqual(expect.arrayContaining([
+ expect.objectContaining({
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ wireId: 'gpt-5.6-sol[1m]',
+ catalogAddition: true,
+ contextWindow: 1_000_000,
+ compat: bundled.compat,
+ }),
+ ]));
+ expect(openai.models.pi?.some((model) => model.id.endsWith('[1m]'))).toBe(false);
+ });
+
it('publishes SuperGrok catalog models missing from this PI binary as catalog additions', () => {
const catalog = JSON.parse(JSON.stringify(BUNDLED_CATALOG)) as Catalog;
const xai = catalog.providers.find((provider) => provider.id === 'xai');
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
index bb84623cb9..9ef83e4a85 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeSubscriptionForwarding.test.ts
@@ -1,4 +1,5 @@
import { EventEmitter } from 'node:events';
+import { zstdCompressSync, zstdDecompressSync } from 'node:zlib';
import { describe, expect, it, vi } from 'vitest';
import { createAnthropicCompatProxy } from '@cindy/anthropic-compat-proxy';
@@ -117,6 +118,73 @@ describe('PI native subscription forwarding', () => {
expect(Buffer.concat(res.chunks).toString('utf8')).toContain('event: done');
});
+ it('keeps Pi 1M as a distinct local model but sends the official bare id upstream', 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 handler = getPiNativeSubscriptionHandler('openai', 'session-1m', deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ }));
+ const parsedBody = { model: 'gpt-5.6-sol[1m]', input: 'hello' };
+
+ await handler({
+ rawBody: Buffer.from(JSON.stringify(parsedBody)),
+ parsedBody,
+ ctx: {
+ reqId: 2,
+ method: 'POST',
+ url: '/codex/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).toEqual({ model: 'gpt-5.6-sol', input: 'hello' });
+ expect(fetchMock.mock.calls[0]![1]?.headers).not.toHaveProperty('content-encoding');
+ });
+
+ it('rewrites the profile suffix after the real proxy zstd parse boundary', 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 handler = getPiNativeSubscriptionHandler('openai', 'session-1m-zstd', deps({
+ fetch: fetchMock as PiNativeSubscriptionHandlerDeps['fetch'],
+ }));
+ const proxy = await createAnthropicCompatProxy({
+ upstream: null,
+ transformRequest: [],
+ routingTransform: () => ({ localHandler: handler }),
+ });
+ const compressed = zstdCompressSync(Buffer.from(JSON.stringify({
+ model: 'gpt-5.6-sol[1m]',
+ input: 'hello',
+ })));
+
+ try {
+ const response = await fetch(`${proxy.url}/codex/responses`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', 'content-encoding': 'zstd' },
+ body: compressed,
+ });
+ expect(response.status).toBe(200);
+ await response.text();
+ } finally {
+ await proxy.dispose();
+ }
+
+ const init = fetchMock.mock.calls[0]![1];
+ expect(init?.headers).toMatchObject({ 'content-encoding': 'zstd' });
+ const request = JSON.parse(
+ zstdDecompressSync(Buffer.from(init?.body as Uint8Array)).toString('utf8'),
+ );
+ expect(request).toEqual({ model: 'gpt-5.6-sol', input: 'hello' });
+ });
+
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;
diff --git a/apps/desktop/src/main/maker-host/active-catalog.ts b/apps/desktop/src/main/maker-host/active-catalog.ts
index aa08974988..637bef104c 100644
--- a/apps/desktop/src/main/maker-host/active-catalog.ts
+++ b/apps/desktop/src/main/maker-host/active-catalog.ts
@@ -46,6 +46,7 @@ import { projectUnverifiedCatalogFallbackForBuildRegion } from './provider-acces
import {
applyLocalConsumerOverrides,
applyLocalOverridesToRoot,
+ applyLocalOverridesToRootModel,
hasLocalAddition,
EMPTY_MODEL_CATALOG_OVERRIDES,
resolveLocalBridgeExclusions,
@@ -54,6 +55,7 @@ import {
import {
applyRegistryConsumerOverlay,
applyRootRegistryPlan,
+ consumerPlanKey,
planRegistryRoots,
toChatgptBridgeModel,
rootPlanKey,
@@ -375,6 +377,7 @@ function projectCodexModelsToBridges(
p: Provider,
claudeExcluded: ReadonlySet<string> = new Set(),
prepareClaudeModel: (model: CatalogModel) => CatalogModel = (model) => model,
+ preparePiModel: (model: CatalogModel) => CatalogModel = (model) => model,
): Provider {
const codex = p.models.codex ?? [];
const canonical = new Map(codex.map((model) => [model.id, model]));
@@ -398,7 +401,12 @@ function projectCodexModelsToBridges(
claudeSource.map((model) => toChatgptBridgeModel(prepareClaudeModel(model))),
true,
);
- return augmentModels(withClaude, 'pi', codex.map(toChatgptBridgeModel), true);
+ return augmentModels(
+ withClaude,
+ 'pi',
+ codex.map((model) => toChatgptBridgeModel(preparePiModel(model))),
+ true,
+ );
}
/** 静态段被淘汰的供应商:先清空 providers.models,再由 discovery + Registry/local root 装配。 */
@@ -746,8 +754,7 @@ function computeMerged(): Catalog {
)
: projectUnverifiedCatalogFallbackForBuildRegion(BUNDLED_CATALOG, CURRENT_CINDY_REGION);
const catalogXd = b.providers.find((provider) => provider.id === 'xd');
- const xdShell =
- catalogXd ?? fallbackXdCatalog.providers.find((provider) => provider.id === 'xd');
+ const xdShell = catalogXd ?? fallbackXdCatalog.providers.find((provider) => provider.id === 'xd');
const bundledXai = BUNDLED_CATALOG.providers.find((provider) => provider.id === 'xai');
const remoteXdIndex = b.providers.findIndex((provider) => provider.id === 'xd');
const providerSources = b.providers.filter((provider) => provider.id !== 'xd');
@@ -828,12 +835,61 @@ function computeMerged(): Catalog {
localOverrides,
plan.warnings,
);
- const projected = projectCodexModelsToBridges(withRoot, excluded, prepareClaudeModel);
+ const preparePiModel = (model: CatalogModel): CatalogModel =>
+ applyLocalOverridesToRootModel(
+ 'openai',
+ 'codex',
+ applyRegistryConsumerOverlay(model, 'openai', 'pi', model.id, plan),
+ localOverrides,
+ plan.warnings,
+ );
+ const projected = projectCodexModelsToBridges(
+ withRoot,
+ excluded,
+ prepareClaudeModel,
+ preparePiModel,
+ );
+ const appendConsumerAdditions = (
+ agent: 'claude-code' | 'pi',
+ models: CatalogModel[],
+ ): CatalogModel[] => {
+ const additions = (plan.consumerAdditions.get(consumerPlanKey('openai', agent)) ?? []).map(
+ (model) =>
+ toChatgptBridgeModel(
+ agent === 'pi'
+ ? applyLocalOverridesToRootModel(
+ 'openai',
+ 'codex',
+ model,
+ localOverrides,
+ plan.warnings,
+ )
+ : applyLocalConsumerOverrides(
+ 'openai',
+ 'claude-code',
+ model.id,
+ model,
+ localOverrides,
+ plan.warnings,
+ ),
+ ),
+ );
+ if (additions.length === 0) return models;
+ const seen = new Set(models.map((model) => model.id));
+ return [...models, ...additions.filter((model) => !seen.has(model.id))];
+ };
return {
...projected,
models: {
...projected.models,
- pi: applyPiApiAnnotations('openai', projected.models.pi ?? []),
+ 'claude-code': appendConsumerAdditions(
+ 'claude-code',
+ projected.models['claude-code'] ?? [],
+ ),
+ pi: applyPiApiAnnotations(
+ 'openai',
+ appendConsumerAdditions('pi', projected.models.pi ?? []),
+ ),
},
};
}
@@ -1160,6 +1216,11 @@ export function setLocalCatalogOverrides(overrides: ModelCatalogOverrides): void
markChanged();
}
+/** 当前 active-catalog 使用的已清洗本地最终层快照。 */
+export function getLocalCatalogOverridesSnapshot(): ModelCatalogOverrides {
+ return localOverrides;
+}
+
/** 最近一次合并的 registry 实体化告警(单 route 隔离;刷新路径读走打日志/计数)。 */
export function getModelPlaneWarnings(): readonly ModelPlaneWarning[] {
return lastPlanWarnings;
diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index 630b472173..2b7d51faa6 100644
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@ -21,6 +21,8 @@
import { app } from 'electron';
import fsp from 'node:fs/promises';
import path from 'node:path';
+import { promisify } from 'node:util';
+import { zstdCompress, zstdDecompress } from 'node:zlib';
import type { LocalRequestHandler } from '@cindy/anthropic-compat-proxy';
import { createResponsesHandler, type BridgeProviderConfig, type ResponsesBridgeHandler } from '@cindy/anthropic-responses-bridge';
@@ -39,6 +41,9 @@ import { recordXaiRateLimitSnapshot } from '../usageBroadcaster.js';
import { xaiServerSideTools } from './xai-server-side-tools.js';
import { CHATGPT_MODEL_PREFIX, XAI_MODEL_PREFIX } from '../../shared/subscriptionModels.js';
+const zstdCompressAsync = promisify(zstdCompress);
+const zstdDecompressAsync = promisify(zstdDecompress);
+
const log = createMakerLogger('cc-bridge');
/** Codex CLI 的 OAuth client_id(codex 登录用的同一个;refresh 走它)。取自 codex CLI prod 配置。 */
@@ -411,6 +416,40 @@ function isPlainRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+/** Pi 用独立 `[1m]` 模型项承载上下文/压缩策略;ChatGPT 上游仍只接受官方裸 model id。 */
+function withOpenaiContextProfileModel(body: unknown): Record<string, unknown> | null {
+ if (!isPlainRecord(body) || typeof body.model !== 'string' || !body.model.endsWith('[1m]')) {
+ return null;
+ }
+ return { ...body, model: body.model.slice(0, -'[1m]'.length) };
+}
+
+async function rewriteOpenaiContextProfileRequest(
+ rawBody: Buffer,
+ parsedBody: unknown,
+ contentEncoding: string | undefined,
+): Promise<{ body: Buffer; contentEncoding: string | undefined } | null> {
+ const parsedProfile = withOpenaiContextProfileModel(parsedBody);
+ if (parsedProfile) {
+ return { body: Buffer.from(JSON.stringify(parsedProfile)), contentEncoding: undefined };
+ }
+ if (parsedBody !== undefined || contentEncoding?.toLowerCase() !== 'zstd') return null;
+ try {
+ // Near-1M-token payloads are large enough to stall Electron main. Node's async
+ // zstd APIs move compression work to the libuv worker pool.
+ const decodedBody = await zstdDecompressAsync(rawBody);
+ const decoded = JSON.parse(decodedBody.toString('utf8')) as unknown;
+ const compressedProfile = withOpenaiContextProfileModel(decoded);
+ if (!compressedProfile) return null;
+ return {
+ body: await zstdCompressAsync(Buffer.from(JSON.stringify(compressedProfile))),
+ contentEncoding,
+ };
+ } catch {
+ return null;
+ }
+}
+
/**
* PI already emits xAI-native payloads, so this path bypasses the Messages →
* Responses bridge that normally supplies xAI's model-gated server tools.
@@ -520,7 +559,17 @@ export function getPiNativeSubscriptionHandler(
headers.accept = ctx.headers.accept ?? 'text/event-stream';
let outboundBody = rawBody;
let contentEncoding: string | undefined = ctx.headers['content-encoding'];
- if (providerId === 'xai') {
+ if (providerId === 'openai') {
+ const rewritten = await rewriteOpenaiContextProfileRequest(
+ rawBody,
+ parsedBody,
+ contentEncoding,
+ );
+ if (rewritten) {
+ outboundBody = rewritten.body;
+ contentEncoding = rewritten.contentEncoding;
+ }
+ } else if (providerId === 'xai') {
const withServerTools = withNativeXaiServerSideTools(parsedBody);
if (withServerTools) {
outboundBody = Buffer.from(JSON.stringify(withServerTools));
diff --git a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
index 7cc191cf56..6d781ceec6 100644
--- a/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
+++ b/apps/desktop/src/main/maker-host/catalog-to-descriptors.ts
@@ -29,6 +29,11 @@ import {
} from '@cindy/model-providers';
import type { ModelDescriptor } from '@cindy/maker-core';
import { resolveRetiredRegistryModelForPi } from './model-plane/modelPlanePolicy.js';
+import {
+ applyLocalOverridesToRetiredRootModel,
+ EMPTY_MODEL_CATALOG_OVERRIDES,
+ type ModelCatalogOverrides,
+} from './model-plane/localCatalogOverrides.js';
/** Maker 能力读取面的最小形状;保留数组引用以让已创建 Session 同步看到新目录。 */
interface ModelCapabilitiesTarget {
@@ -180,6 +185,7 @@ export function resolvePiRuntimeModelDescriptor(
catalog: Catalog,
providerId: string | null | undefined,
modelId: string,
+ options: { localOverrides?: ModelCatalogOverrides } = {},
): ModelDescriptor | null {
const providers = providerId === 'cindy'
? catalog.providers.filter((provider) => provider.source !== 'user')
@@ -196,7 +202,15 @@ export function resolvePiRuntimeModelDescriptor(
}
for (const provider of providers) {
- const retired = resolveRetiredRegistryModelForPi(catalog.modelRegistry, provider.id, modelId);
+ const retired = resolveRetiredRegistryModelForPi(catalog.modelRegistry, provider.id, modelId, {
+ prepareRootModel: ({ providerId: matchedProviderId, rootAgent, model }) =>
+ applyLocalOverridesToRetiredRootModel(
+ matchedProviderId,
+ rootAgent,
+ model,
+ options.localOverrides ?? EMPTY_MODEL_CATALOG_OVERRIDES,
+ ),
+ });
if (retired) return toDescriptor(retired, 'pi');
}
return null;
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index c97737d035..fa14b67e29 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -20,6 +20,7 @@ import {
} from '@cindy/maker-core';
import {
getActiveCatalog,
+ getLocalCatalogOverridesSnapshot,
setActiveCatalogChangedListener,
setDiscoveredCodexModels,
} from './active-catalog.js';
@@ -1708,7 +1709,9 @@ export function getMaker(): Maker {
availableModels: deriveAvailableModels(getDesktopSelectableCatalog(), 'pi'),
},
resolvePiRuntimeModelDescriptor: (providerId, modelId) =>
- resolvePiRuntimeModelDescriptor(getDesktopSelectableCatalog(), providerId, modelId),
+ resolvePiRuntimeModelDescriptor(getDesktopSelectableCatalog(), providerId, modelId, {
+ localOverrides: getLocalCatalogOverridesSnapshot(),
+ }),
resolvePiGatewayModelDescriptor: (providerId, modelId) => {
// `cindy` / null 是 Pi 的默认 gateway 路由;其 wire 由 v3 XD runtime plan
// 决定,因此描述符也必须锁定 XD,不能让复合 `cindy` 按目录顺序命中同 id 订阅模型。
@@ -1716,6 +1719,7 @@ export function getMaker(): Maker {
getDesktopSelectableCatalog(),
resolvePiGatewayDescriptorProviderId(providerId),
modelId,
+ { localOverrides: getLocalCatalogOverridesSnapshot() },
);
},
mcpProviders: piMcpProviders,
diff --git a/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts b/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
index 532245b182..61e9ec2b50 100644
--- a/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
+++ b/apps/desktop/src/main/maker-host/model-plane/localCatalogOverrides.ts
@@ -416,6 +416,54 @@ export function applyLocalOverridesToRoot(
return out;
}
+/**
+ * 对单个已存在 root 模型重放本地最终层。完整 addition 整条替换,patch 随后逐字段覆盖;
+ * Pi 在切换到 Registry entry baseline 后用它恢复与最终 root 相同的 local > remote 优先级。
+ */
+export function applyLocalOverridesToRootModel(
+ providerId: string,
+ agent: RootAgentKind,
+ model: CatalogModel,
+ overrides: ModelCatalogOverrides,
+ warnings: ModelPlaneWarning[] = [],
+): CatalogModel {
+ const key = `${providerId}:${model.id}`;
+ let out = model;
+ const addition = overrides.additions[key];
+ if (addition && entryRootAgents(addition, providerId).includes(agent)) {
+ out = additionModelFor(model.id, addition, agent) ?? out;
+ }
+ const patch = overrides.patches[key];
+ if (!patch || !entryRootAgents(patch, providerId).includes(agent)) return out;
+ const patched = overlayFields(out, effectiveFields(patch, agent));
+ if (typeof patched !== 'string') return patched;
+ warnings.push({
+ source: 'local',
+ providerId,
+ agent,
+ modelId: model.id,
+ reason: patched,
+ });
+ return out;
+}
+
+/**
+ * 对 Registry retired root 重放与 active-catalog 相同的最终层顺序。
+ * 完整 addition 可显式复活;仅有 patch 时无论其 status 写什么都重新压回 tombstone。
+ */
+export function applyLocalOverridesToRetiredRootModel(
+ providerId: string,
+ agent: RootAgentKind,
+ model: CatalogModel,
+ overrides: ModelCatalogOverrides,
+ warnings: ModelPlaneWarning[] = [],
+): CatalogModel {
+ const overlaid = applyLocalOverridesToRootModel(providerId, agent, model, overrides, warnings);
+ return hasLocalAddition(overrides, providerId, model.id, agent)
+ ? overlaid
+ : { ...overlaid, status: 'retired' };
+}
+
/**
* root 投影到 bridge 后,应用目标消费端的本地 perAgent/base patch。顺序仍是
* addition → patch;bridge 的 ID/effort/fast 硬约束由 active-catalog 最后收口。
diff --git a/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts b/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
index c38f33248b..3be4b9747e 100644
--- a/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
+++ b/apps/desktop/src/main/maker-host/model-plane/modelPlanePolicy.ts
@@ -49,11 +49,51 @@ export interface BuiltinModelPlanePolicy {
/** 实体化 allowlist:只有这三家允许由 registry presence 长出可选实体。 */
export const MODEL_PLANE_POLICIES: ReadonlyMap<string, BuiltinModelPlanePolicy> = new Map([
['openai', { roots: ['codex'], piRoot: 'codex', membershipGatedBridges: ['claude-code'] }],
- ['anthropic', { roots: ['claude-code'], piRoot: 'claude-code', membershipGatedBridges: ['codex'] }],
+ [
+ 'anthropic',
+ { roots: ['claude-code'], piRoot: 'claude-code', membershipGatedBridges: ['codex'] },
+ ],
['xai', { roots: ['claude-code', 'codex'], piRoot: 'claude-code', membershipGatedBridges: [] }],
// xd 有意不在表内:Gateway 独占存在性(见文件头)。
]);
+function piRegistryMatch(
+ registry: ModelRegistry,
+ providerId: string,
+ piModelId: string,
+): { entry: ModelRegistryEntry; rootModelId: string } | null {
+ const policy = MODEL_PLANE_POLICIES.get(providerId);
+ if (!policy) return null;
+ const rootModelId = canonicalRegistryEntryModelId(providerId, piModelId);
+ if (!rootModelId) return null;
+
+ const exactEntry = registry.models.find((entry) => entry.id === `${providerId}/${rootModelId}`);
+ if (exactEntry) {
+ const exactRoute = exactEntry.routes.find((route) => route.providerId === providerId);
+ if (exactRoute) {
+ const isConsumerAlias = exactRoute.modelId !== rootModelId;
+ const piReachable =
+ exactRoute.agents.includes(policy.piRoot) ||
+ (providerId === 'openai' &&
+ isConsumerAlias &&
+ exactRoute.agents.includes('claude-code'));
+ if (piReachable) return { entry: exactEntry, rootModelId };
+ }
+ }
+
+ const matched = findModelRegistryRoute(registry, providerId, rootModelId, policy.piRoot);
+ return matched ? { entry: matched.entry, rootModelId } : null;
+}
+
+function canonicalRegistryEntryModelId(providerId: string, consumerModelId: string): string | null {
+ const modelId = consumerModelId.trim();
+ if (!modelId) return null;
+ if (providerId !== 'openai') return modelId;
+ if (!modelId.startsWith(CHATGPT_MODEL_PREFIX)) return null;
+ const rootModelId = modelId.slice(CHATGPT_MODEL_PREFIX.length);
+ return rootModelId || null;
+}
+
/**
* Registry tombstone lookup for a concrete client consumer. This mirrors the same root/bridge
* graph used by materialization without requiring a CatalogModel entity: retired routes are
@@ -70,16 +110,28 @@ export function isRegistryTombstoneForConsumer(
const policy = MODEL_PLANE_POLICIES.get(providerId);
if (!registry || !policy) return false;
- let registryAgent: RootAgentKind | null;
if (agent === 'pi') {
- registryAgent = providerId === 'openai' ? 'codex' : 'claude-code';
- } else if (policy.roots.includes(agent) || policy.membershipGatedBridges.includes(agent)) {
- registryAgent = agent;
- } else {
- registryAgent = null;
+ return piRegistryMatch(registry, providerId, modelId)?.entry.status === 'retired';
}
+ const registryAgent =
+ policy.roots.includes(agent) || policy.membershipGatedBridges.includes(agent) ? agent : null;
if (!registryAgent) return false;
+ // Lifecycle identity is the Registry entry id, not merely route.modelId. Context profiles may
+ // deliberately share one official route, so check the canonical alias first; price lookup keeps
+ // its separate bare-route fallback in modelRegistry.ts.
+ const canonicalModelId = canonicalRegistryEntryModelId(providerId, modelId);
+ if (canonicalModelId) {
+ const exactEntry = registry.models.find(
+ (entry) => entry.id === `${providerId}/${canonicalModelId}`,
+ );
+ const exactRoute = exactEntry?.routes.find(
+ (route) =>
+ route.providerId === providerId && route.agents.includes(registryAgent),
+ );
+ if (exactEntry && exactRoute) return exactEntry.status === 'retired';
+ }
+
return (
findModelRegistryRoute(registry, providerId, modelId, registryAgent)?.entry.status === 'retired'
);
@@ -104,7 +156,9 @@ const CLAUDE_BRIDGE_UNSUPPORTED_EFFORTS: ReadonlySet<Effort> = new Set(['max', '
/** OpenAI Codex root → Claude/Pi bridge;目录装配与 retired 续跑共同复用。 */
export function toChatgptBridgeModel(model: CatalogModel): CatalogModel {
- const bridgeEfforts = model.efforts.filter((effort) => !CLAUDE_BRIDGE_UNSUPPORTED_EFFORTS.has(effort));
+ const bridgeEfforts = model.efforts.filter(
+ (effort) => !CLAUDE_BRIDGE_UNSUPPORTED_EFFORTS.has(effort),
+ );
const cappedDefault: Effort | null =
model.defaultEffort && CLAUDE_BRIDGE_UNSUPPORTED_EFFORTS.has(model.defaultEffort)
? bridgeEfforts.includes('xhigh')
@@ -155,8 +209,16 @@ export interface ModelPlaneWarning {
export interface ModelPlaneRegistryPlan {
/** key = `${providerId}:${rootAgent}`。 */
roots: Map<string, RootRegistryPlan>;
- /** key = `${providerId}:${bridgeAgent}`;目标消费端的 perAgent overlay。 */
+ /** key = `${providerId}:${consumer}`;wire bridge 用 perAgent,Pi 用 entry 基线。 */
consumers: Map<string, Map<string, Partial<CatalogModel>>>;
+ /**
+ * key = `${providerId}:${consumer}`;同一上游 modelId 的显式消费端变体。
+ *
+ * 这类条目用不同 canonical entry id 表达独立选择,但 route.modelId 仍保持厂商官方
+ * model id。旧客户端会因没有 canonical root 而安全忽略;理解该语义的新客户端只在
+ * route 明确授权的 bridge 与 Pi 投影中物化,不污染 canonical root(尤其不改 Codex)。
+ */
+ consumerAdditions: Map<string, CatalogModel[]>;
warnings: ModelPlaneWarning[];
}
@@ -164,7 +226,7 @@ export function rootPlanKey(providerId: string, agent: RootAgentKind): string {
return `${providerId}:${agent}`;
}
-export function consumerPlanKey(providerId: string, agent: RootAgentKind): string {
+export function consumerPlanKey(providerId: string, agent: AgentKind): string {
return `${providerId}:${agent}`;
}
@@ -206,9 +268,9 @@ interface EffectiveRouteFields {
/** entry 基线 + perAgent[agent] 覆盖后的有效字段(仅 wire enum agent 有 perAgent)。 */
function effectiveRouteFields(
entry: ModelRegistryEntry,
- agent: RootAgentKind,
+ agent?: RootAgentKind,
): EffectiveRouteFields {
- const override = entry.perAgent?.[agent];
+ const override = agent ? entry.perAgent?.[agent] : undefined;
const efforts = override?.efforts ?? entry.efforts;
const candidateDefaultEffort = override?.defaultEffort ?? entry.defaultEffort;
const hasInvalidEffort =
@@ -263,7 +325,12 @@ function effectiveRouteFields(
* status 缺失的 metadata-only 条目);deprecated 实体化强制 defaultEnabled=false。
*/
export function planRegistryRoots(registry: ModelRegistry | undefined): ModelPlaneRegistryPlan {
- const plan: ModelPlaneRegistryPlan = { roots: new Map(), consumers: new Map(), warnings: [] };
+ const plan: ModelPlaneRegistryPlan = {
+ roots: new Map(),
+ consumers: new Map(),
+ consumerAdditions: new Map(),
+ warnings: [],
+ };
if (!registry) return plan;
const claimedRootRoutes = new Set<string>();
for (const entry of registry.models) {
@@ -273,6 +340,58 @@ export function planRegistryRoots(registry: ModelRegistry | undefined): ModelPla
if (!policy) continue;
const routeAgents = route.agents as readonly RootAgentKind[];
const memberRoots = policy.roots.filter((agent) => routeAgents.includes(agent));
+ const canonicalPrefix = `${route.providerId}/`;
+ const consumerAliasId = entry.id.startsWith(canonicalPrefix)
+ ? entry.id.slice(canonicalPrefix.length)
+ : null;
+ const isConsumerAlias =
+ consumerAliasId !== null &&
+ consumerAliasId.length > 0 &&
+ consumerAliasId !== route.modelId;
+
+ // OpenAI 的包月长上下文是同一官方 modelId 的显式 opt-in。Registry 用不同 entry id
+ // 建立独立选择,route.modelId 仍写官方裸 id;route 只点名 claude-code,因此不能为了
+ // 物化它而把 Codex root 一起抬高。Pi 继续按产品约定从同一 entry 基线投影。
+ if (
+ route.providerId === 'openai' &&
+ memberRoots.length === 0 &&
+ isConsumerAlias &&
+ routeAgents.includes('claude-code')
+ ) {
+ if (status === null) continue;
+ for (const consumer of ['claude-code', 'pi'] as const) {
+ const fields = effectiveRouteFields(
+ entry,
+ consumer === 'claude-code' ? 'claude-code' : undefined,
+ );
+ if (fields.validationError) {
+ plan.warnings.push({
+ source: 'registry',
+ providerId: route.providerId,
+ agent: policy.piRoot,
+ modelId: consumerAliasId,
+ reason: `${consumer} consumer alias ${fields.validationError}`,
+ });
+ continue;
+ }
+ const materialized = toMaterializedModel(consumerAliasId, fields, status);
+ if (typeof materialized === 'string') {
+ plan.warnings.push({
+ source: 'registry',
+ providerId: route.providerId,
+ agent: policy.piRoot,
+ modelId: consumerAliasId,
+ reason: `${consumer} consumer alias ${materialized}`,
+ });
+ continue;
+ }
+ const key = consumerPlanKey(route.providerId, consumer);
+ const additions = plan.consumerAdditions.get(key) ?? [];
+ additions.push(materialized);
+ plan.consumerAdditions.set(key, additions);
+ }
+ continue;
+ }
// 有 lifecycle presence、却没有 canonical root 的 route 无法产生任何实体或
// 投影源。把它当作者错误隔离,而不是留下一个看似授权 bridge、实际永远不生效
// 的幽灵配置。metadata-only 旧条目不升级为 presence,因此保持静默兼容。
@@ -339,6 +458,28 @@ export function planRegistryRoots(registry: ModelRegistry | undefined): ModelPla
rootPlan.additions.push(materialized);
}
if (!acceptedRoot) continue;
+ // Pi 不在 wire perAgent enum 中,但它仍是 Registry 的独立消费端。它必须从
+ // entry 基线投影,不能继承 piRoot 上的 Codex/Claude 专属覆盖。
+ if (memberRoots.includes(policy.piRoot)) {
+ const fields = effectiveRouteFields(entry);
+ if (fields.validationError) {
+ plan.warnings.push({
+ source: 'registry',
+ providerId: route.providerId,
+ agent: policy.piRoot,
+ modelId: route.modelId,
+ reason: `pi baseline ${fields.validationError}`,
+ });
+ } else {
+ const key = consumerPlanKey(route.providerId, 'pi');
+ let overlays = plan.consumers.get(key);
+ if (!overlays) {
+ overlays = new Map();
+ plan.consumers.set(key, overlays);
+ }
+ overlays.set(route.modelId, toOverlay(fields, status));
+ }
+ }
// 目标 bridge 的 effective fields = entry base + perAgent[bridge]。metadata-only
// 仍可 overlay 已存在的 discovery bridge,但不能在下面改变投影拓扑。
for (const bridgeAgent of policy.membershipGatedBridges) {
@@ -402,7 +543,7 @@ export function planRegistryRoots(registry: ModelRegistry | undefined): ModelPla
export function applyRegistryConsumerOverlay(
model: CatalogModel,
providerId: string,
- consumer: RootAgentKind,
+ consumer: AgentKind,
rootModelId: string,
plan: ModelPlaneRegistryPlan,
): CatalogModel {
@@ -491,24 +632,29 @@ export function resolveRetiredRegistryModelForPi(
registry: ModelRegistry | null | undefined,
providerId: string,
piModelId: string,
+ options: {
+ prepareRootModel?: (params: {
+ providerId: string;
+ rootAgent: RootAgentKind;
+ model: CatalogModel;
+ }) => CatalogModel;
+ } = {},
): CatalogModel | null {
const policy = MODEL_PLANE_POLICIES.get(providerId);
if (!registry || !policy) return null;
- const rootAgent = policy.piRoot;
- const rootModelId = providerId === 'openai'
- ? piModelId.startsWith(CHATGPT_MODEL_PREFIX)
- ? piModelId.slice(CHATGPT_MODEL_PREFIX.length)
- : null
- : piModelId;
- if (!rootModelId) return null;
-
- const matched = findModelRegistryRoute(registry, providerId, rootModelId, rootAgent);
+ const matched = piRegistryMatch(registry, providerId, piModelId);
if (!matched || matched.entry.status !== 'retired') return null;
- const fields = effectiveRouteFields(matched.entry, rootAgent);
+ const fields = effectiveRouteFields(matched.entry);
if (fields.validationError) return null;
- const root = toMaterializedModel(rootModelId, fields, 'active');
+ const root = toMaterializedModel(matched.rootModelId, fields, 'active');
if (typeof root === 'string') return null;
- return projectRootModelToPi(providerId, rootAgent, { ...root, status: 'retired' });
+ const retiredRoot = { ...root, status: 'retired' as const };
+ const preparedRoot = options.prepareRootModel?.({
+ providerId,
+ rootAgent: policy.piRoot,
+ model: retiredRoot,
+ }) ?? retiredRoot;
+ return projectRootModelToPi(providerId, policy.piRoot, preparedRoot);
}
/**
diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts
index ae4a1b59df..223c1a1757 100644
--- a/apps/desktop/src/main/maker-host/pi-host.ts
+++ b/apps/desktop/src/main/maker-host/pi-host.ts
@@ -22,7 +22,13 @@ import os from 'node:os';
import path from 'node:path';
import { app } from 'electron';
-import { PiAgent, type AgentDeps, type AuthAdapter, type AuthState } from '@cindy/maker-core';
+import {
+ PiAgent,
+ type AgentDeps,
+ type AuthAdapter,
+ type AuthState,
+ type ModelDescriptor,
+} from '@cindy/maker-core';
import type {
AgentRuntimeConfig,
AuthAdapterOptions,
@@ -67,7 +73,12 @@ import {
getDesktopMcpToolApprovalPresentation,
} from './mcp-tool-approval-policy.js';
import { getRipgrepBinaryPath, claudeUpstreamEndpoint } from './runtime-configs.js';
-import { getActiveCatalog, resolveXdPiGatewayWireProtocol } from './active-catalog.js';
+import {
+ getActiveCatalog,
+ getLocalCatalogOverridesSnapshot,
+ resolveXdPiGatewayWireProtocol,
+} from './active-catalog.js';
+import { resolvePiRuntimeModelDescriptor } from './catalog-to-descriptors.js';
const log = createLogger('pi-host');
@@ -445,15 +456,16 @@ function catalogCostForPiNative(cost: {
/**
* 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.
+ * provider catalog. Registry metadata is authoritative for OpenAI subscription
+ * models; the version-matched PI binary remains authoritative for native API and
+ * compat details that Cindy must preserve when materializing the overlay.
*/
export function buildPiSubscriptionNativeProviders(
catalog: Catalog,
endpoint: string,
bundledModelsByProvider?: PiBundledModelCatalog,
listedModelIdsByProvider?: PiListedModelIds,
+ retainedOpenAiModel?: ModelDescriptor | null,
): PiNativeProvidersResult {
const providers: PiNativeProviderSpec[] = [];
const env: Record<string, string> = {
@@ -467,7 +479,32 @@ export function buildPiSubscriptionNativeProviders(
stripPrefix?: string,
): void => {
const source = catalog.providers.find((provider) => provider.id === sourceProviderId);
- const models = source?.models.pi ?? [];
+ const models = [...(source?.models.pi ?? [])];
+ if (
+ sourceProviderId === 'openai' &&
+ retainedOpenAiModel?.id.startsWith('chatgpt/') &&
+ !models.some((model) => model.id === retainedOpenAiModel.id)
+ ) {
+ // A retired context profile is intentionally absent from the public Pi catalog, but a
+ // persisted session still needs the exact alias in the ChatGPT native provider. Keeping the
+ // alias here preserves both its canonical identity and its subscription endpoint; it remains
+ // private to this one resume and never re-enters availableModels.
+ models.push({
+ id: retainedOpenAiModel.id,
+ name: retainedOpenAiModel.displayName,
+ contextWindow: retainedOpenAiModel.contextWindow,
+ ...(retainedOpenAiModel.maxOutputTokens !== undefined
+ ? { maxOutput: retainedOpenAiModel.maxOutputTokens }
+ : {}),
+ efforts: [...retainedOpenAiModel.efforts],
+ defaultEffort: retainedOpenAiModel.defaultEffort,
+ ...(retainedOpenAiModel.supportsFastMode !== undefined
+ ? { supportsFastMode: retainedOpenAiModel.supportsFastMode }
+ : {}),
+ status: 'retired',
+ defaultEnabled: false,
+ });
+ }
if (models.length === 0) return;
providers.push({
id: piProviderId,
@@ -484,17 +521,57 @@ export function buildPiSubscriptionNativeProviders(
: model.id;
const bundledModels = bundledModelsByProvider?.get(piProviderId);
const bundledModel = bundledModels?.get(wireId);
+ const contextProfileTemplate =
+ sourceProviderId === 'openai' && wireId.endsWith('[1m]')
+ ? bundledModels?.get(wireId.slice(0, -'[1m]'.length))
+ : undefined;
// 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 isContextProfileAddition =
+ sourceProviderId === 'openai' && wireId.endsWith('[1m]') && !bundledModel;
const isProtocolCorrection =
sourceProviderId !== 'openai' &&
!!model.piApi &&
!!bundledModel &&
bundledModel.api !== model.piApi;
- const preserved = isProtocolCorrection ? bundledModel : undefined;
+ const isRegistryBaselineOverlay = sourceProviderId === 'openai' && !!bundledModel;
const catalogCost = catalogCostForPiNative(model.cost);
+ if (isRegistryBaselineOverlay) {
+ const input = model.supportsImageInput === undefined
+ ? [...bundledModel.input]
+ : model.supportsImageInput
+ ? ['text', 'image'] as Array<'text' | 'image'>
+ : ['text'] as Array<'text' | 'image'>;
+ const cost = catalogCost ?? bundledModel.cost;
+ return {
+ id: model.id,
+ wireId,
+ // Materialize Registry metadata for same-id OpenAI models. `api`
+ // makes inheritModels emit the overlay into models.json, while PI's
+ // bundled provider remains authoritative for native transport quirks.
+ api: bundledModel.api,
+ name: model.name,
+ contextWindow: model.contextWindow,
+ maxTokens: model.maxOutput ?? bundledModel.maxTokens,
+ reasoning: model.efforts.length > 0,
+ input,
+ thinkingLevelMap: Object.fromEntries(
+ PI_REASONING_EFFORTS.map((effort) => [
+ effort,
+ model.efforts.includes(effort) ? effort : null,
+ ]),
+ ),
+ ...(cost ? { cost: { ...cost } } : {}),
+ ...(bundledModel.headers ? { headers: { ...bundledModel.headers } } : {}),
+ ...(bundledModel.compat ? { compat: structuredClone(bundledModel.compat) } : {}),
+ ...(bundledModel.samplingParams
+ ? { samplingParams: structuredClone(bundledModel.samplingParams) }
+ : {}),
+ };
+ }
+ const preserved = isProtocolCorrection ? bundledModel : contextProfileTemplate;
return {
id: model.id,
wireId,
@@ -502,7 +579,7 @@ export function buildPiSubscriptionNativeProviders(
// 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 || isContextProfileAddition)
? { catalogAddition: true }
: {}),
// SuperGrok 没有官方列模型通道,Cindy 目录是成员唯一来源。
@@ -522,8 +599,10 @@ export function buildPiSubscriptionNativeProviders(
(isAnnotatedAddition || isProtocolCorrection)
? { api: model.piApi }
: {}),
- name: preserved?.name ?? model.name,
- contextWindow: preserved?.contextWindow ?? model.contextWindow,
+ name: isContextProfileAddition ? model.name : (preserved?.name ?? model.name),
+ contextWindow: isContextProfileAddition
+ ? model.contextWindow
+ : (preserved?.contextWindow ?? model.contextWindow),
...(preserved?.maxTokens
? { maxTokens: preserved.maxTokens }
: model.maxOutput
@@ -1212,10 +1291,18 @@ export async function resolvePiNativeProviders(ctx: {
const bundledModels = piBinaryPath ? await readPiBundledModels(piBinaryPath) : null;
let subscriptions: PiNativeProvidersResult = { providers: [], env: {} };
if (!ctx?.remoteHostId && isAnthropicCompatProxyHandleReady()) {
+ const retainedOpenAiModel =
+ ctx.resumeSessionId && ctx.providerId === 'openai'
+ ? resolvePiRuntimeModelDescriptor(getActiveCatalog(), 'openai', ctx.model, {
+ localOverrides: getLocalCatalogOverridesSnapshot(),
+ })
+ : null;
subscriptions = buildPiSubscriptionNativeProviders(
getActiveCatalog(),
getClaudeEndpoint(),
bundledModels ?? undefined,
+ undefined,
+ retainedOpenAiModel,
);
}
let configs: CustomProviderConfig[] = [];
diff --git a/apps/desktop/src/renderer/__tests__/selectVisibleModels.test.ts b/apps/desktop/src/renderer/__tests__/selectVisibleModels.test.ts
index 69167c09da..43cefb032d 100644
--- a/apps/desktop/src/renderer/__tests__/selectVisibleModels.test.ts
+++ b/apps/desktop/src/renderer/__tests__/selectVisibleModels.test.ts
@@ -217,6 +217,33 @@ describe('selectVisibleModels — excludeSubscriptionDirect(SSH 远程保留但
});
expect(ids(out)).toEqual(['chatgpt/gpt-5.5', 'claude-opus-4-8', 'xai/grok-4.3', 'gpt-5.5']);
});
+
+ it('SSH Pi 隐藏仅本地可改写的 OpenAI [1m] profile,普通订阅模型仍保留', () => {
+ const out = selectVisibleModels({
+ agentKind: 'pi',
+ deviceId: undefined,
+ providers: [provider('openai', 'pi', [
+ 'chatgpt/gpt-5.6-sol',
+ 'chatgpt/gpt-5.6-sol[1m]',
+ 'gateway-model',
+ ])],
+ deviceCcModels: [],
+ deviceCodexModels: [],
+ excludeSubscriptionDirect: true,
+ });
+ expect(ids(out)).toEqual(['chatgpt/gpt-5.6-sol', 'gateway-model']);
+ });
+
+ it('本地 Pi 保留 OpenAI [1m] profile', () => {
+ const out = selectVisibleModels({
+ agentKind: 'pi',
+ deviceId: undefined,
+ providers: [provider('openai', 'pi', ['chatgpt/gpt-5.6-sol[1m]'])],
+ deviceCcModels: [],
+ deviceCodexModels: [],
+ });
+ expect(ids(out)).toEqual(['chatgpt/gpt-5.6-sol[1m]']);
+ });
});
describe('selectVisibleModels — excludeChatBridgedCodex(SSH 远程隐藏 Chat 桥接的 Codex 供应商)', () => {
diff --git a/apps/desktop/src/renderer/lib/providerModels.ts b/apps/desktop/src/renderer/lib/providerModels.ts
index e264480edb..37132639ca 100644
--- a/apps/desktop/src/renderer/lib/providerModels.ts
+++ b/apps/desktop/src/renderer/lib/providerModels.ts
@@ -217,7 +217,9 @@ export function selectVisibleModels(params: {
* 而是保留在清单中由调用方按 isSubscriptionDirectModel 标记禁用(置灰 + 原因提示)。
* 远端 cc 不经本地 compat-proxy 的 responses-bridge,选了必失败;静默消失会让用户
* 误以为订阅掉了。device-link 远程不受影响(被控端跑完整 app,其本地 proxy 上
- * bridge 可用,模型清单本就来自被控端)。
+ * bridge 可用,模型清单本就来自被控端)。唯一例外是 Pi 的 OpenAI `[1m]` context
+ * profile:它依赖 Desktop 本地 subscription adapter 剥离 profile 后缀,SSH 没有等价
+ * 改写链,所以不向远程 Pi picker 发布。
*/
excludeSubscriptionDirect?: boolean;
/**
@@ -238,15 +240,21 @@ export function selectVisibleModels(params: {
excludeSubscriptionDirect,
excludeChatBridgedCodex,
} = params;
- // excludeSubscriptionDirect 不再过滤(见参数文档):行保留,准入由调用方按
- // isSubscriptionDirectModel 打 disabled。保留参数是为了不破坏既有调用签名。
+ // 普通 subscription-direct 行继续保留,准入由调用方按 isSubscriptionDirectModel
+ // 打 disabled。Pi 的 `[1m]` profile 是仅本地可改写的 catalog identity,SSH 侧必须隐藏。
const pass = (list: ModelDescriptor[]): ModelDescriptor[] => list;
const codexDeriveOpts = excludeChatBridgedCodex
? { excludeProvider: isChatBridgedCodexProvider }
: undefined;
const cc = pass(deviceId ? deviceCcModels : deriveModelsFromProviders(providers, 'claude-code'));
const codex = pass(deviceId ? deviceCodexModels : deriveModelsFromProviders(providers, 'codex', codexDeriveOpts));
- const pi = pass(deviceId ? devicePiModels : deriveModelsFromProviders(providers, 'pi'));
+ const pi = pass(deviceId ? devicePiModels : deriveModelsFromProviders(providers, 'pi'))
+ .filter((model) => !(
+ excludeSubscriptionDirect === true &&
+ agentKind === 'pi' &&
+ model.id.startsWith('chatgpt/') &&
+ model.id.endsWith('[1m]')
+ ));
if (agentKind === 'claude-code') return cc;
if (agentKind === 'codex') return codex;
if (agentKind === 'pi') return pi;
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
index 4af09bc990..fa440c1c67 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-provider-routing.test.ts
@@ -289,13 +289,22 @@ describe('Pi provider-aware model routing', () => {
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,
- }],
+ models: [
+ {
+ id: 'chatgpt/gpt-5.6-sol',
+ wireId: 'gpt-5.6-sol',
+ api: 'openai-codex-responses',
+ contextWindow: 1_000_000,
+ maxTokens: 128_000,
+ },
+ {
+ 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',
@@ -338,9 +347,15 @@ describe('Pi provider-aware model routing', () => {
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-5.6-sol',
+ api: 'openai-codex-responses',
+ contextWindow: 1_000_000,
+ maxTokens: 128_000,
+ }),
expect.objectContaining({ id: 'gpt-cindy-daily-test' }),
]);
- expect(models.providers['openai-codex']?.models?.[0]).not.toHaveProperty('api');
+ expect(models.providers['openai-codex']?.models?.[1]).not.toHaveProperty('api');
expect(models.providers.xai).not.toHaveProperty('api');
expect(models.providers.xai?.models).toEqual([
expect.objectContaining({
@@ -937,6 +952,64 @@ describe('Pi provider-aware model routing', () => {
await handle.close();
});
+ it('restores a retired OpenAI context profile through its native subscription provider', async () => {
+ const resolver = vi.fn(async () => ({
+ providers: [{
+ id: 'openai-codex',
+ sourceProviderId: 'openai',
+ name: 'OpenAI (ChatGPT)',
+ baseUrl: 'http://127.0.0.1:9',
+ inheritModels: true,
+ models: [{
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ wireId: 'gpt-5.6-sol[1m]',
+ catalogAddition: true,
+ }],
+ }],
+ env: {},
+ }));
+ const agent = new PiAgent({
+ auth: {
+ getState: async () => ({ authenticated: true, identity: 'ChatGPT', 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: [] },
+ resolvePiAgentHome: () => agentHome,
+ resolvePiNativeProviders: resolver,
+ resolvePiRuntimeModelDescriptor: () => ({
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ displayName: 'GPT-5.6-Sol (1M · Higher usage)',
+ contextWindow: 1_000_000,
+ efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'],
+ defaultEffort: 'medium',
+ }),
+ });
+
+ const handle = await agent.startSession({
+ sessionId: 'historical-openai-profile-resume',
+ resumeSessionId: 'pi-sdk-session-openai-profile',
+ workingDir: cwd,
+ model: 'chatgpt/gpt-5.6-sol[1m]',
+ providerId: 'openai',
+ });
+
+ expect(resolver).toHaveBeenCalledWith(expect.objectContaining({
+ providerId: 'openai',
+ model: 'chatgpt/gpt-5.6-sol[1m]',
+ resumeSessionId: 'pi-sdk-session-openai-profile',
+ }));
+ expect(captured.args.slice(captured.args.indexOf('--provider'), captured.args.indexOf('--provider') + 2))
+ .toEqual(['--provider', 'openai-codex']);
+ expect(captured.args.slice(captured.args.indexOf('--model'), captured.args.indexOf('--model') + 2))
+ .toEqual(['--model', 'gpt-5.6-sol[1m]']);
+ 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;
@@ -2157,6 +2230,93 @@ describe('Pi provider-aware model routing', () => {
expect(captured.args).toEqual([]);
});
+ it('rejects a local-only OpenAI context profile before resolving or spawning remote Pi', async () => {
+ const resolver = vi.fn(async () => ({ providers: [], env: {} }));
+ const transport = vi.fn(async () => {
+ throw new Error('remote transport must not be created');
+ });
+ const agent = new PiAgent({
+ ...byomDeps(resolver, [
+ {
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ displayName: 'GPT-5.6-Sol 1M',
+ contextWindow: 1_000_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ]),
+ getRemotePiTransport: transport,
+ });
+
+ await expect(agent.startSession({
+ sessionId: 'remote-openai-context-profile',
+ workingDir: cwd,
+ model: 'chatgpt/gpt-5.6-sol[1m]',
+ providerId: 'openai',
+ remoteHostId: 'remote-host',
+ })).rejects.toThrow(/\[REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE\]/);
+ expect(resolver).not.toHaveBeenCalled();
+ expect(transport).not.toHaveBeenCalled();
+ expect(captured.args).toEqual([]);
+ });
+
+ it('rejects switching a running remote Pi session to a local-only OpenAI context profile', async () => {
+ const remoteStub: import('../transport.js').PiTransport = {
+ writeLine: async () => {},
+ onLine: () => () => {},
+ onStderr: () => () => {},
+ onClose: () => () => {},
+ close: async () => {},
+ pid: 4321,
+ isClosed: () => false,
+ remoteBinaryPath: '/remote/pi',
+ killRemoteSession: async () => {},
+ };
+ const base = byomDeps(async () => ({ providers: [], env: {} }), [
+ {
+ id: 'gateway-model',
+ displayName: 'Gateway model',
+ contextWindow: 200_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ {
+ id: 'chatgpt/gpt-5.6-sol[1m]',
+ displayName: 'GPT-5.6-Sol 1M',
+ contextWindow: 1_000_000,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ]);
+ const agent = new PiAgent({
+ ...base,
+ runtimeConfig: { ...base.runtimeConfig, remoteEndpoint: 'https://gateway.example.test' },
+ resolveRemotePiBinaryPath: async () => '/remote/pi',
+ getRemotePiTransport: async () => remoteStub,
+ getRemotePiFileOps: () => ({
+ mkdirp: async () => {},
+ writeFile: async () => {},
+ stat: async () => ({ isFile: true }),
+ rm: async () => {},
+ listDir: async () => [],
+ }),
+ });
+ const handle = await agent.startSession({
+ sessionId: 'remote-gateway-context-profile-switch',
+ workingDir: cwd,
+ model: 'gateway-model',
+ providerId: 'xd',
+ remoteHostId: 'remote-host',
+ });
+
+ captured.requests.length = 0;
+ await expect(handle.setModel!('chatgpt/gpt-5.6-sol[1m]', { providerId: 'openai' }))
+ .rejects.toThrow(/\[REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE\]/);
+ expect(handle.model).toBe('gateway-model');
+ expect(captured.requests).not.toContainEqual(expect.objectContaining({ type: 'set_model' }));
+ await handle.close();
+ });
+
it('allows an explicitly forwarded remote xAI provider and keeps proxy auth in the remote env', async () => {
const remoteStub: import('../transport.js').PiTransport = {
writeLine: async () => {},
diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts
index 39340a95f8..916247729f 100644
--- a/packages/maker-core/src/agents/pi/index.ts
+++ b/packages/maker-core/src/agents/pi/index.ts
@@ -192,6 +192,34 @@ function isLoopbackOnlyBaseUrl(baseUrl: string): boolean {
return false; // 非法 URL 不判 loopback(其它校验兜底)
}
}
+
+/**
+ * OpenAI subscription context profiles are catalog identities whose wire model id must be
+ * rewritten by Desktop's local compat handler. SSH Pi sessions do not traverse that handler,
+ * so publishing one remotely would leak the `[1m]` suffix to the gateway/upstream model id.
+ *
+ * An explicitly selected BYOM provider remains allowed: its owner controls the model id and
+ * endpoint, and must not be mistaken for Cindy's OpenAI subscription projection merely because
+ * it uses the same display namespace.
+ */
+function isLocalOnlyOpenAiPiContextProfile(
+ model: string,
+ providerId?: string | null,
+): boolean {
+ if (!model.startsWith('chatgpt/') || !model.endsWith('[1m]')) return false;
+ return providerId === undefined || providerId === null || providerId === 'openai';
+}
+
+function assertRemotePiContextProfileAvailable(
+ remoteHostId: string | null | undefined,
+ model: string,
+ providerId?: string | null,
+): void {
+ if (!remoteHostId || !isLocalOnlyOpenAiPiContextProfile(model, providerId)) return;
+ throw new Error(
+ '[REMOTE_PI_CONTEXT_PROFILE_UNAVAILABLE] remote Pi sessions cannot use this OpenAI context profile because its model-id rewrite is available only in the Desktop local subscription adapter; pick the XD gateway or a BYOM provider reachable from the SSH host',
+ );
+}
const PI_IMAGE_INPUT_UNSUPPORTED_CODE = 'PI_IMAGE_INPUT_UNSUPPORTED';
/** 手动压缩 = 一次完整 LLM 摘要调用(大上下文 + 网关排队),远超默认 30s RPC 超时。 */
const PI_COMPACT_TIMEOUT_MS = 600_000;
@@ -955,6 +983,7 @@ export class PiAgent extends BaseAgent {
message: 'pi remote sessions require a host-provided getRemotePiTransport hook',
});
}
+ assertRemotePiContextProfileAvailable(opts.remoteHostId, opts.model, opts.providerId);
const reviewMode = opts.reviewMode === true;
// BYOM:host 解析当前会话可用的原生 provider(用户自定义/本地模型)+ 需注入的 env(keys)。
@@ -2523,6 +2552,7 @@ export class PiAgent extends BaseAgent {
const requestedProviderId = setOpts && Object.hasOwn(setOpts, 'providerId')
? setOpts.providerId
: undefined;
+ assertRemotePiContextProfileAvailable(opts.remoteHostId, model, requestedProviderId);
// 心跳复用活进程会把当前 (provider, model) 再下发一次。
// spawn 能靠 custom model id 跑在 Pi 自带目录没有的 SuperGrok
// 路由上(grok-4.6);重复 set_model 反而 fail-closed。
diff --git a/packages/model-providers/src/__tests__/modelRegistry.test.ts b/packages/model-providers/src/__tests__/modelRegistry.test.ts
index 9cf3d67ec4..e4204291d8 100644
--- a/packages/model-providers/src/__tests__/modelRegistry.test.ts
+++ b/packages/model-providers/src/__tests__/modelRegistry.test.ts
@@ -87,6 +87,12 @@ describe("model registry", () => {
inputTokens: 272_000,
})?.price,
).toMatchObject({ inputPerMtok: 5, outputPerMtok: 30 });
+ expect(
+ resolveModelReferencePrice(registry, "openai", "chatgpt/gpt-5.6-sol[1m]", {
+ agent: "claude-code",
+ inputTokens: 272_001,
+ })?.price,
+ ).toMatchObject({ inputPerMtok: 10, outputPerMtok: 45 });
expect(
resolveModelReferencePrice(registry, "openai", "gpt-5.6-sol", {
agent: "codex",
diff --git a/packages/model-providers/src/modelRegistry.ts b/packages/model-providers/src/modelRegistry.ts
index b7af874c83..838db662d0 100644
--- a/packages/model-providers/src/modelRegistry.ts
+++ b/packages/model-providers/src/modelRegistry.ts
@@ -84,8 +84,13 @@ function calendarDate(value: string | Date | undefined): string {
function routeModelCandidates(providerId: string, modelId: string): string[] {
const ids = [modelId];
+ const withoutContextProfile = modelId.replace(/\[1m\]$/, "");
+ if (withoutContextProfile !== modelId) ids.push(withoutContextProfile);
if (providerId === "openai" && modelId.startsWith("chatgpt/")) {
- ids.push(modelId.slice("chatgpt/".length));
+ const stripped = modelId.slice("chatgpt/".length);
+ ids.push(stripped);
+ const strippedWithoutContextProfile = stripped.replace(/\[1m\]$/, "");
+ if (strippedWithoutContextProfile !== stripped) ids.push(strippedWithoutContextProfile);
}
if (providerId === "anthropic") {
const undatedModel = modelId.replace(/-\d{8}$/, "");