Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(models): 缺少推理能力配置时不生成通用档位 (#4860)
Dash62400c80452a
diff --git a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.tsindex a937e54b7a..22b6487eaf 100644--- a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts+++ b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts@@ -657,6 +657,7 @@ describe('model:pick 持久化失败', () => {authStrategy: 'none',},responseRoutingByModel: {},+ responseEffortsByModel: {},credentialRevision: 1,};const routeB: CodexCustomProviderRoute = {diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProviderBridge.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProviderBridge.test.tsindex b1678c0d7f..bf16d0c790 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeProviderBridge.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProviderBridge.test.ts@@ -11,6 +11,7 @@ async function runBridge(upstream: string,onRequest: (url: string, init?: RequestInit) => void,extras: Partial<Parameters<typeof createClaudeProviderBridge>[0]> = {},+ effort = 'high',) {const handler = createClaudeProviderBridge({url: `https://supplier.example/v1/${protocol === 'openai-chat' ? 'chat/completions' : 'responses'}`,@@ -28,7 +29,7 @@ async function runBridge(req.on('end', () => {void handler.handle({ parsedBody: JSON.parse(Buffer.concat(chunks).toString()),ctx: { reqId: 1, method: 'POST', url: req.url!, headers: {} }, res,- prefs: { reasoningEffort: 'high' },+ prefs: { reasoningEffort: effort },}).catch(() => { res.statusCode = 500; res.end(); });});});@@ -50,6 +51,19 @@ const chatStream = [].map(frame => `data: ${JSON.stringify(frame)}\r\n\r\n`).join('') + 'data: [DONE]\r\n\r\n';describe('Claude Code custom provider translation', () => {+ it.each(['openai-chat', 'openai-responses'] as const)(+ 'reconciles saved effort against current capabilities before %s forwarding', async protocol => {+ const sent: unknown[] = [];+ for (const efforts of [['high', 'max'], ['high'], [], ['high', 'max']] as const) {+ await runBridge(protocol, true, chatStream, (_url, init) => {+ const request = JSON.parse(String(init?.body));+ sent.push(protocol === 'openai-chat' ? request.reasoning_effort : request.reasoning?.effort);+ }, { efforts }, 'max');+ }+ expect(sent).toEqual(['max', 'high', undefined, 'max']);+ },+ );+it.each([true, false])('translates chat requests and replies with streaming=%s', async stream => {const result = await runBridge('openai-chat', stream, chatStream, (url, init) => {expect(url).toBe('https://supplier.example/v1/chat/completions');diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.tsindex 2a9bff1274..f02efbf7b2 100644--- a/apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.ts@@ -71,6 +71,27 @@ const baseCatalog = {};describe('Codex smart Subagent catalog', () => {+ it('does not borrow reasoning capabilities from existing records or GPT templates', () => {+ const raw = { models: baseCatalog.models.map(entry => ({+ ...entry, default_reasoning_level: 'medium',+ })) };+ const built = buildCodexSmartModelCatalog(raw, [+ { providerId: 'custom', model: { ...model('gpt-5.6-luna'), efforts: [], defaultEffort: null } },+ { providerId: 'custom', model: { ...model('unknown-model'), efforts: [], defaultEffort: null } },+ { providerId: 'custom', model: { ...model('declared-model'), defaultEffort: null } },+ ]);+ for (const slug of ['gpt-5.6-luna', 'unknown-model']) {+ expect(built?.models.find(entry => entry.slug === slug)).toMatchObject({+ supported_reasoning_levels: [], default_reasoning_level: null,+ });+ }+ expect(built?.models.find(entry => entry.slug === 'declared-model')).toMatchObject({+ supported_reasoning_levels: [expect.objectContaining({ effort: 'low' }), expect.objectContaining({ effort: 'medium' })],+ default_reasoning_level: null,+ });+ expect(raw.models[1].supported_reasoning_levels).toEqual([{ effort: 'medium', description: 'medium' }]);+ });+it('only selects subscription routes belonging to the current account host', () => {const providers = [provider('openai', [model('gpt-account-default')], { authStrategy: 'oauth-passthrough' }),diff --git a/apps/desktop/src/main/maker-host/__tests__/codexCustomProviderRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexCustomProviderRoute.test.tsindex 1b8a4ee608..547fc1b755 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexCustomProviderRoute.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexCustomProviderRoute.test.ts@@ -294,6 +294,13 @@ describe('Codex custom Provider identity', () => {};expect(codexCustomProviderConfigSignature(routeChanged)).not.toBe(baseline);+ const effortChanged = structuredClone(config);+ effortChanged.runtimes.codex!.models![0]!.reasoning = true;+ effortChanged.runtimes.codex!.models![0]!.reasoningEfforts = ['high'];+ expect(codexCustomProviderConfigSignature(effortChanged)).not.toBe(baseline);+ expect(codexCustomProviderRouteSignature(catalog(buildUserProvider(effortChanged))))+ .not.toBe(codexCustomProviderRouteSignature(catalog(buildUserProvider(config))));+const disabled = structuredClone(config);delete disabled.runtimes.codex?.supportsImageGeneration;expect(codexCustomProviderConfigSignature(disabled)).toBe('');diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 8c2db19af9..4bc8e822b1 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -1848,7 +1848,7 @@ describe('chatBridgeCapabilitiesForRoute', () => {modelIdRewrite: { stripPrefix: 'chat/' },},},- models: { codex: [{ id: 'chat/model-a', name: 'Chat Model A' }] },+ models: { codex: [{ id: 'chat/model-a', name: 'Chat Model A', efforts: ['high'] }] },} as never]);setCustomProviderKeyReader(() => 'locked-chat-key');host.registerComposed(@@ -2753,7 +2753,7 @@ describe('codex proxy host', () => {expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function),expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function),expect.any(Function), expect.any(Function), expect.any(Function), expect.any(Function),- expect.any(Function),+ expect.any(Function), expect.any(Function), // frozen custom-provider effort],transformResponse: expect.any(Function),routingTransform: expect.any(Function),@@ -2780,7 +2780,7 @@ describe('codex proxy host', () => {);expect(requestScopedTransforms).toHaveLength(1);expect(requestScopedTransforms[0]?.errorMode).toBe('reject-request');- const strip = mockState.createAnthropicCompatProxy.mock.calls[0][0].transformRequest.at(-1);+ const strip = mockState.createAnthropicCompatProxy.mock.calls[0][0].transformRequest.at(-2);const body = { model: 'gpt-5', input: [] };strip(body, { url: '/responses' });expect(mockState.stripNonAnthropicFields).toHaveBeenCalledWith(body, { url: '/responses' });@@ -3397,6 +3397,107 @@ describe('codex proxy host', () => {expect(host.getCodexProxyEndpoint()).toBe(`${XD_GATEWAY_BASE_URL}/v1`);});+ it('reconciles a saved Responses effort on every catalog refresh without borrowing another route', async () => {+ const host = await freshCodexProxyHost();+ const { buildUserProvider } = await import('@cindy/model-providers');+ const { setCustomProviders } = await import('../active-catalog.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ const provider = (id: string, efforts: readonly ('high' | 'max')[]) => buildUserProvider({+ id, name: 'Fixture', runtimes: {+ codex: { baseUrl: 'https://fixture.example/v1', wireProtocol: 'openai-responses', models: [{+ id: 'same-model', name: 'Same model', reasoning: true, reasoningEfforts: [...efforts],+ }] },+ },+ });+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210', dispose: vi.fn(async () => undefined),+ });+ host.setCodexProxyAuthInjection('env-key');+ host.registerComposed('effort-session', 'effort-thread', '');+ setSessionProvider('effort-session', 'selected-route');+ try {+ await host.ensureCodexProxyReady();+ const original = { model: 'same-model', input: [], reasoning: { effort: 'max', summary: 'auto' } };+ for (const efforts of [['high', 'max'], ['high'], [], ['high', 'max']] as const) {+ setCustomProviders([provider('other-route', ['high', 'max']), provider('selected-route', efforts)]);+ let current: unknown = original;+ for (const transform of mockState.createAnthropicCompatProxy.mock.calls[0][0].transformRequest) {+ const next = transform(current, { method: 'POST', url: '/responses', headers: { 'thread-id': 'effort-thread' } });+ if (next !== null && next !== undefined) current = next;+ }+ expect(current).toHaveProperty('reasoning.summary', 'auto');+ if (!efforts.length) expect(current).not.toHaveProperty('reasoning.effort');+ else expect(current).toHaveProperty('reasoning.effort', efforts[efforts.length - 1]);+ expect(original.reasoning.effort).toBe('max');+ }+ } finally {+ clearSessionProvider('effort-session');+ setCustomProviders([]);+ }+ });++ it.each([+ ['env-key', null, 'xd'],+ ['oauth-bearer', null, 'openai'],+ ['env-key', 'openai', 'xd'],+ ['env-key', null, 'oauth-fixture'],+ ] as const)('uses effective capabilities for %s / session %s / destination %s', async (auth, selected, destination) => {+ const host = await freshCodexProxyHost();+ const { BUNDLED_CATALOG } = await import('@cindy/model-providers');+ const { setActiveCatalog } = await import('../active-catalog.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ const catalog = structuredClone(BUNDLED_CATALOG);+ const oauth = structuredClone(catalog.providers.find(p => p.id === 'xai')!);+ // Exercise explicit legacy rows; the bundled v4 registry otherwise projects over them.+ delete catalog.modelRegistry;+ oauth.id = 'oauth-fixture';+ if (destination === 'oauth-fixture') catalog.providers.unshift(oauth);+ const modelId = destination === 'oauth-fixture' ? 'xai/effort-fixture' : 'gpt-5.6-sol';+ for (const provider of catalog.providers.filter(p => ['xd', 'openai', 'oauth-fixture'].includes(p.id))) {+ const template = provider.models.codex![0];+ const id = destination === 'oauth-fixture' && provider.id !== destination ? 'gpt-5.6-sol' : modelId;+ provider.models.codex = [{ ...template, id, efforts: ['high', 'max'], defaultEffort: 'high' }];+ }+ const target = catalog.providers.find(p => p.id === destination)!.models.codex![0];+ host.setCodexProxyAuthInjection(auth);+ host.registerComposed('implicit-effort-session', 'implicit-effort-thread', '');+ if (selected) setSessionProvider('implicit-effort-session', selected);+ else clearSessionProvider('implicit-effort-session');+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({ url: 'http://127.0.0.1:43210', dispose: vi.fn(async () => undefined) });+ try {+ await host.ensureCodexProxyReady();+ const original = { model: modelId, input: [], reasoning: { effort: 'max', summary: 'auto' } };+ for (const efforts of [['high'], [], null, ['high', 'max']] as const) {+ // An implicit OAuth provider must advertise membership to be selected at all.+ if (efforts === null && destination === 'oauth-fixture') continue;+ target.efforts = [...(efforts ?? [])];+ catalog.providers.find(p => p.id === destination)!.models.codex = efforts === null ? [] : [target];+ setActiveCatalog(structuredClone(catalog));+ const activeCatalog = await import('../active-catalog.js');+ activeCatalog.setDiscoveredCodexModels(catalog.providers.find(p => p.id === 'openai')!.models.codex!);+ activeCatalog.setXdGatewayModels(catalog.providers.find(p => p.id === 'xd')!.models.codex!.map(m => ({+ id: m.id, name: m.name, efforts: m.efforts, agents: ['codex'],+ })));+ const active = activeCatalog.getActiveCatalog();+ expect(active.providers.find(p => p.id === destination)?.models.codex?.find(m => m.id === modelId)?.efforts).toEqual(efforts === null ? undefined : [...efforts]);+ let current: unknown = original;+ for (const transform of mockState.createAnthropicCompatProxy.mock.calls[0][0].transformRequest) {+ current = transform(current, { method: 'POST', url: '/responses', headers: { 'thread-id': 'implicit-effort-thread' } }) ?? current;+ }+ expect(current).toHaveProperty('reasoning.summary', 'auto');+ if (efforts?.length) expect(current).toHaveProperty('reasoning.effort', efforts.at(-1));+ else expect(current).not.toHaveProperty('reasoning.effort');+ expect(original.reasoning.effort).toBe('max');+ }+ } finally {+ clearSessionProvider('implicit-effort-session');+ const activeCatalog = await import('../active-catalog.js');+ activeCatalog.setDiscoveredCodexModels([]);+ activeCatalog.setXdGatewayModels([]);+ setActiveCatalog(BUNDLED_CATALOG);+ }+ });+it('registers and unregisters composed prompt text by session id', async () => {const host = await freshCodexProxyHost();mockState.createAnthropicCompatProxy.mockResolvedValueOnce({@@ -4112,6 +4213,8 @@ describe('codex proxy host', () => {it('applies the inherited Gateway route on the first collab_spawn transform pass', async () => {const host = await freshCodexProxyHost();+ const { setXdGatewayModels } = await import('../active-catalog.js');+ setXdGatewayModels([{ id: 'codex/gpt-5.6-sol', name: 'Fixture', agents: ['codex'], efforts: ['max'] }]);const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');mockState.createAnthropicCompatProxy.mockResolvedValueOnce({url: 'http://127.0.0.1:43210',@@ -4160,6 +4263,7 @@ describe('codex proxy host', () => {host.unregister('session-openai-parent');clearSessionProvider('session-openai-parent');host.setCodexProxyGatewayKeyReader(() => null);+ setXdGatewayModels([]);}});@@ -5716,6 +5820,8 @@ describe('codex proxy host', () => {it('normalizes requests to ByteDance Seed Responses capabilities', async () => {const host = await freshCodexProxyHost();+ const { setXdGatewayModels } = await import('../active-catalog.js');+ setXdGatewayModels([{ id: 'bytedance-seed/seed-2.1-pro', name: 'Fixture', agents: ['codex'], efforts: ['high'] }]);const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');mockState.createAnthropicCompatProxy.mockResolvedValueOnce({url: 'http://127.0.0.1:43210',@@ -5803,6 +5909,7 @@ describe('codex proxy host', () => {expect(summaryOnlyReasoning).toEqual({ model: 'bytedance-seed/seed-2.1-pro' });clearSessionProvider('session-seed');+ setXdGatewayModels([]);});it('normalizes custom Volcengine Ark Responses routes regardless of the model alias', async () => {@@ -5817,7 +5924,7 @@ describe('codex proxy host', () => {runtimes: {codex: {baseUrl: 'https://ark.cn-beijing.volces.com/api/v3',- models: [{ id: 'production-deployment', name: 'Production Deployment' }],+ models: [{ id: 'production-deployment', name: 'Production Deployment', reasoning: true, reasoningEfforts: ['high'] }],},},}),@@ -5887,7 +5994,7 @@ describe('codex proxy host', () => {runtimes: {codex: {baseUrl: 'https://gateway.volces.com/api/v3',- models: [{ id: 'production-deployment', name: 'Production Deployment' }],+ models: [{ id: 'production-deployment', name: 'Production Deployment', reasoning: true, reasoningEfforts: ['high'] }],},},}),@@ -6156,7 +6263,7 @@ describe('codex proxy host', () => {runtimes: {codex: {baseUrl,- models: [{ id: 'MiniMax-M3', name: 'MiniMax M3' }],+ models: [{ id: 'MiniMax-M3', name: 'MiniMax M3', reasoning: true, reasoningEfforts: ['high'] }],},},}),@@ -6221,7 +6328,7 @@ describe('codex proxy host', () => {runtimes: {codex: {baseUrl: 'https://example.com/v1',- models: [{ id: 'custom-model', name: 'Custom Model' }],+ models: [{ id: 'custom-model', name: 'Custom Model', reasoning: true, reasoningEfforts: ['xhigh'] }],},},}),@@ -6395,6 +6502,8 @@ describe('codex proxy host', () => {// xai 会话里非 xai/ 前缀的请求会被路由 scope 门放回默认上游(ChatGPT/网关),// xAI 兼容改写(挪 instructions / 剥 reasoning)必须同步跳过,否则默认上游收到被改坏的 body。const host = await freshCodexProxyHost();+ const { setXdGatewayModels } = await import('../active-catalog.js');+ setXdGatewayModels([{ id: 'gpt-5.5', name: 'Fixture', agents: ['codex'], efforts: ['high'] }]);const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');mockState.createAnthropicCompatProxy.mockResolvedValueOnce({url: 'http://127.0.0.1:43210',@@ -6425,6 +6534,7 @@ describe('codex proxy host', () => {// instructions 未被挪进 input、reasoning 未被剥、model 未被 rewrite。expect(current).toEqual(original);clearSessionProvider('session-xai-foreign');+ setXdGatewayModels([]);});it('restores native search when provider-oauth foreign-model fallback lands on Gateway', async () => {@@ -6490,7 +6600,7 @@ describe('codex proxy host', () => {await host.ensureCodexProxyReady();const transforms = mockState.createAnthropicCompatProxy.mock.calls[0]?.[0]?.transformRequest ?? [];- expect(transforms).toHaveLength(25); // encrypted activeStrip, image generation activeStrip, provider-aware Guardian reviewer, locked Subagent route, instructions 注入, locked Subagent exec guard, Gateway 原生 web_search, 跨来源压缩块兼容, xAI ModelInput activeStrip, responses item id activeStrip(#4738), responses item id length activeStrip(#4227), exec function adapter, strict gateway history 兼容, xAI ModelInput sanitize, DeepSeek V4 custom tool 兼容, xAI Responses 兼容, XD Gateway Grok 兼容, ByteDance Seed tool 兼容, MiniMax effort 兼容, provider model rewrite, provider 参数归一, 视觉桥(短路), 工具 ID 校正, stripNonAnthropicFields, dump+ expect(transforms).toHaveLength(26); // ordinary transforms + dump + frozen custom-provider effortconst ctx = {method: 'POST',url: '/v1/responses',@@ -7779,7 +7889,7 @@ describe('createModelRoutingTransform —— custom Provider native imagegen pre}});- it('repairs namespaced Responses history over HTTP without rewriting native fields or image JSON', async () => {+ it.each([{ efforts: [] }, { efforts: ['high'] }, { efforts: ['high', 'max'] }] as const)('reconciles frozen namespaced Responses capabilities $efforts over HTTP without rewriting native fields or image JSON', async ({ efforts }) => {const received: Array<{ path: string; body: string }> = [];const upstream = createServer((req, res) => {const chunks: Buffer[] = [];@@ -7804,7 +7914,7 @@ describe('createModelRoutingTransform —— custom Provider native imagegen preruntimes: { codex: {baseUrl: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}/v1`,wireProtocol: 'openai-responses', supportsImageGeneration: true,- models: [{ id: 'codex/native-model', name: 'Native model' }],+ models: [{ id: 'codex/native-model', name: 'Native model', reasoning: true, reasoningEfforts: [...efforts] }],} },});const catalog = { ...BUNDLED_CATALOG, providers: [...BUNDLED_CATALOG.providers, provider] };@@ -7813,10 +7923,15 @@ describe('createModelRoutingTransform —— custom Provider native imagegen preconst route = deriveCodexCustomProviderRoutes(catalog)[0]!;host.setCodexAppliedCustomProviderRoutes([route]);try {- await host.ensureCodexProxyReady();- const endpoint = host.getCodexProxyEndpoint();+ await host.ensureCodexCustomContextProxyReady('frozen-effort', 'env-key', [route]);+ const endpoint = host.getCodexCustomContextProxyEndpoint('frozen-effort');+ // A later catalog/global Host must not lend capabilities to this frozen route.+ provider.models.codex![0]!.efforts = efforts.length ? [] : ['max'];+ setActiveCatalog(catalog);+ host.setCodexAppliedCustomProviderRoutes(deriveCodexCustomProviderRoutes(catalog));const body = {model: 'codex/native-model', max_tokens: 123, vendor_field: { retain: true },+ reasoning: { effort: 'max', summary: 'auto' },tools: [{ type: 'custom', name: 'exec', format: { type: 'text' } }],input: [{ type: 'custom_tool_call', id: 'fc_legacy', call_id: 'call_same', name: 'exec', input: '你好' },@@ -7825,7 +7940,7 @@ describe('createModelRoutingTransform —— custom Provider native imagegen pre{ type: 'compaction', encrypted_content: 'opaque' },],};- const repaired = { ...body, input: body.input.map((item, index) => index < 2+ const repaired = { ...body, reasoning: { summary: 'auto', ...(efforts.length ? { effort: efforts.at(-1) } : {}) }, input: body.input.map((item, index) => index < 2? { ...item, id: index === 0 ? 'ctc_legacy' : 'ctco_legacy' } : item) };const post = async (path: string, raw: string) => {const response = await fetch(`${endpoint}/_cindy/custom-provider/${route.routeId}/${path}`, {@@ -7844,7 +7959,9 @@ describe('createModelRoutingTransform —— custom Provider native imagegen preconst imageBody = JSON.stringify({ ...body, model: 'gpt-image-2', prompt: 'draw' }, null, 2);await post('images/generations', imageBody);expect(received[2]?.body).toBe(imageBody);+ expect(body.reasoning.effort).toBe('max');} finally {+ await host.releaseCodexCustomContextProxy('frozen-effort');await host.disposeCodexProxy();host.setCodexAppliedCustomProviderRoutes([]);setCustomProviderKeyReader(() => null);diff --git a/apps/desktop/src/main/maker-host/__tests__/outbound-reasoning-effort.test.ts b/apps/desktop/src/main/maker-host/__tests__/outbound-reasoning-effort.test.tsnew file mode 100644index 0000000000..dfdb09f329--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/outbound-reasoning-effort.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';+import { reconcileOutboundReasoningEffort } from '../outbound-reasoning-effort.js';++describe('outbound reasoning capability boundary', () => {+ it('does not create a preference for missing or unrecognized input', () => {+ for (const requested of [undefined, null, '', 'none', 'invalid', 42]) {+ expect(reconcileOutboundReasoningEffort(requested, ['high'])).toBeUndefined();+ }+ });++ it('uses shared nearest-supported ordering, independently of declaration order', () => {+ expect(reconcileOutboundReasoningEffort('xhigh', ['max', 'low', 'high'])).toBe('high');+ expect(reconcileOutboundReasoningEffort('minimal', ['high', 'low'])).toBe('low');+ expect(reconcileOutboundReasoningEffort('low', ['low', 'high'])).toBe('low');+ expect(reconcileOutboundReasoningEffort('max', [])).toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts b/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.tsindex 5b10cafd5e..599d733d3b 100644--- a/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts@@ -13,6 +13,47 @@ const reply = [].map(value => `data: ${JSON.stringify(value)}\n\n`).join('') + 'data: [DONE]\n\n';describe('Pi-owned transport for Cindy harnesses', () => {+ it('reconciles saved max when capabilities narrow, disappear and return', async () => {+ const request = { model: 'changing-model', input: 'hello', reasoning: { effort: 'max' }, stream: true };+ for (const efforts of [['high', 'max'], ['high'], [], ['high', 'max']] as const) {+ const provider = buildUserProvider({ id: 'changing-provider', name: 'Changing provider', runtimes: {+ codex: { baseUrl: 'https://fixture.example/v1', wireProtocol: 'openai-chat', models: [{+ id: request.model, name: 'Changing model', reasoning: true, reasoningEfforts: [...efforts],+ }] },+ } });+ const row = invocationModelRecord(provider.models.codex![0], 'https://fixture.example/v1', 'openai-completions')!;+ let sent: Record<string, unknown> | undefined;+ const send = createPiProviderFetch({ row, providerId: provider.id, apiKey: 'fixture-key', fetchImpl: async (_url, init) => {+ sent = JSON.parse(String(init?.body));+ return new Response(reply, { headers: { 'content-type': 'text/event-stream' } });+ } });+ expect(await (await send('https://unused.invalid', { body: JSON.stringify(request) })).text()).toContain('response.completed');+ if (!efforts.length) expect(sent).not.toHaveProperty('reasoning_effort');+ else expect(sent).toHaveProperty('reasoning_effort', efforts[efforts.length - 1]);+ expect(request.reasoning.effort).toBe('max');+ }+ });++ it('omits stale reasoning effort for a model without a capability declaration', async () => {+ const provider = buildUserProvider({ id: 'unknown-provider', name: 'Unknown provider', runtimes: {+ codex: { baseUrl: 'https://unknown.example/v1', wireProtocol: 'openai-chat',+ models: [{ id: 'unknown-model', name: 'Unknown model' }] },+ } });+ const row = invocationModelRecord(provider.models.codex![0], 'https://unknown.example/v1', 'openai-completions')!;+ let sent: Record<string, unknown> | undefined;+ const send = createPiProviderFetch({ row, providerId: provider.id, apiKey: 'fixture-key', fetchImpl: async (_url, init) => {+ sent = JSON.parse(String(init?.body));+ return new Response(reply, { headers: { 'content-type': 'text/event-stream' } });+ } });+ const response = await send('https://unused.invalid', { body: JSON.stringify({+ model: row.id, input: 'hello', reasoning: { effort: 'max' }, stream: true,+ }) });+ expect(await response.text()).toContain('response.completed');+ expect(sent).toMatchObject({ model: row.id });+ expect(sent).not.toHaveProperty('reasoning_effort');+ expect(sent).not.toHaveProperty('thinking');+ });+it.each(['ant-ling', 'qwen-token-plan', 'zai', 'together'])('sends the actual %s thinking dialect and model limits', async providerId => {const row = PROVIDER_MODEL_CATALOG.providers[providerId].find(row => row.reasoning && row.execution.pi.api === 'openai-completions')!;const effort = row.efforts.includes('high') ? 'high' : row.efforts[0];diff --git a/apps/desktop/src/main/maker-host/claude-provider-bridge.ts b/apps/desktop/src/main/maker-host/claude-provider-bridge.tsindex 0751e13a4a..b669e66bdc 100644--- a/apps/desktop/src/main/maker-host/claude-provider-bridge.ts+++ b/apps/desktop/src/main/maker-host/claude-provider-bridge.ts@@ -1,6 +1,7 @@import { normalizeProviderRequest } from '@cindy/model-compat';import { createHash } from 'node:crypto';-import type { ProviderModelRecord } from '@cindy/model-providers';+import type { Effort, ProviderModelRecord } from '@cindy/model-providers';+import { reconcileOutboundReasoningEffort } from './outbound-reasoning-effort.js';import { createPiProviderFetch, nativeBridgeApiKey } from './pi-provider-transport.js';import { createResponsesHandler, type ResponsesBridgeHandler } from '@cindy/anthropic-responses-bridge';import { ChatSseTranslator, translateResponsesRequestWithContext, type ChatBridgeCapabilities, type ResponsesRequest } from '@cindy/responses-chat-bridge';@@ -16,7 +17,7 @@ export function createClaudeProviderBridge(options: {url: string;protocol: 'openai-chat' | 'openai-responses';headers: Readonly<Record<string, string>>;- efforts: readonly string[];+ efforts: readonly Effort[];capabilities?: ChatBridgeCapabilities;model?: ProviderModelRecord;providerId?: string;@@ -32,9 +33,15 @@ export function createClaudeProviderBridge(options: {fetchImpl: options.fetchImpl,}) : undefined;const upstreamFetch: typeof fetch = async (_url, init) => {+ const responses = JSON.parse(String(init?.body)) as ResponsesRequest;+ if (responses.reasoning) {+ const effort = reconcileOutboundReasoningEffort(responses.reasoning.effort, options.efforts);+ if (effort) responses.reasoning.effort = effort;+ else delete responses.reasoning.effort;+ init = { ...init, body: JSON.stringify(responses) };+ }if (nativeFetch) return nativeFetch(_url, init);if (options.protocol === 'openai-responses') return options.fetchImpl(options.url, init);- const responses = JSON.parse(String(init?.body)) as ResponsesRequest;const translated = translateResponsesRequestWithContext(responses, { capabilities: options.capabilities });const upstream = await options.fetchImpl(options.url, { ...init, body: JSON.stringify(normalizeProviderRequest(translated.request, { harness: 'claude-code', protocol: 'openai-chat', upstreamBase: options.url, model: responses.model }, { reasoningEffortAlreadyMapped: true })) });if (!upstream.ok || !upstream.body) return upstream;diff --git a/apps/desktop/src/main/maker-host/codex-custom-provider-route.ts b/apps/desktop/src/main/maker-host/codex-custom-provider-route.tsindex 64a1dbfeaa..705c226d87 100644--- a/apps/desktop/src/main/maker-host/codex-custom-provider-route.ts+++ b/apps/desktop/src/main/maker-host/codex-custom-provider-route.ts@@ -3,6 +3,7 @@ import { createHash } from 'node:crypto';import type {Catalog,CustomProviderConfig,+ Effort,Provider,RoutingDescriptor,} from '@cindy/model-providers';@@ -43,6 +44,8 @@ export interface CodexCustomProviderRoute {routing: RoutingDescriptor;/** Per-model Responses routes frozen with the same Host snapshot. */responseRoutingByModel: Readonly<Record<string, RoutingDescriptor>>;+ /** Model capabilities belong to the same Host generation as the upstream routes. */+ responseEffortsByModel: Readonly<Record<string, readonly Effort[]>>;/** Non-sensitive route/capability/credential dispatch generation frozen with this Host snapshot. */credentialRevision: number;}@@ -120,6 +123,9 @@ function routeForProvider(provider: Provider): CodexCustomProviderRoute | null {responseModels: responseModelIds,credentialRevision: getProviderRouteCredentialRevision(provider.id),routing: frozenRouting,+ responseEffortsByModel: Object.fromEntries(+ responseModels.map(model => [model.id, [...model.efforts]]),+ ),responseRoutingByModel: Object.fromEntries(responseModels.map((model) => {if (!model.route) return [model.id, { ...frozenRouting }];@@ -157,6 +163,9 @@ export function codexCustomProviderConfigSignature(config: CustomProviderConfig)),),responseModels: [...route.responseModels].sort(),+ responseEffortsByModel: Object.fromEntries(+ Object.entries(route.responseEffortsByModel).sort(([left], [right]) => left.localeCompare(right)),+ ),routing: route.routing,responseRoutingByModel: Object.fromEntries(Object.entries(route.responseRoutingByModel).sort(([left], [right]) =>@@ -206,6 +215,7 @@ export function codexCustomProviderRoutesSignature(responseModels: [...route.responseModels].sort(),routing: route.routing,responseRoutingByModel: route.responseRoutingByModel,+ responseEffortsByModel: route.responseEffortsByModel,credentialRevision: route.credentialRevision,})).sort((left, right) => left.modelProviderId.localeCompare(right.modelProviderId));diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex bfdeeb44b3..2261a8feee 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -1,7 +1,8 @@import { createAttachmentRecovery } from './oversized-attachment-recovery.js';import { clearCodexTextOnlyPolicies, codexTextOnlyRequestGuard, codexTextOnlyWebSocketTransforms, isCodexTextOnly } from './codex-text-only-policy.js';import { resolveConversationSessionHeaders, withChatBridgeUserAgent, overrideHeadersCaseInsensitive } from '@cindy/responses-chat-bridge';-import { providerModelRecord } from '@cindy/model-providers';+import { providerModelRecord, type Effort } from '@cindy/model-providers';+import { reconcileOutboundReasoningEffort } from './outbound-reasoning-effort.js';import { createPiProviderFetch, handlePiProviderRequest, invocationModelRecord, nativeBridgeApiKey, readBoundedResponseText, requiresNativeProviderAuth } from './pi-provider-transport.js';import { normalizeProviderRequest, normalizeMiniMaxResponsesReasoning } from '@cindy/model-compat';import { createCodexResponsesCompatibilityAdapter, sanitizeXaiTools, hasCacheOnlySearchProhibition, sanitizeByteDanceSeedTools, normalizeByteDanceSeedInput, sanitizeByteDanceSeedReasoning, normalizeStrictGatewayHistory, sanitizeDeepSeekV4CustomTools } from '@cindy/model-compat';@@ -532,6 +533,28 @@ function applyReasoningEffortOverride(return next;}+/** Saved harness preferences are not a capability declaration for this route. */+function reconcileProviderReasoningEffort(+ body: Record<string, unknown>,+ providerId: string,+ modelId: string,+): Record<string, unknown> {+ const model = getActiveCatalog().providers.find(provider => provider.id === providerId)+ ?.models.codex?.find(candidate => candidate.id === modelId);+ // A missing row is unknown capability, including models removed since a task was saved.+ // Never retain a saved effort or borrow another provider's declaration in that case.+ return reconcileResponsesReasoningEffort(body, model?.efforts ?? []);+}++function reconcileResponsesReasoningEffort(+ body: Record<string, unknown>,+ efforts: readonly Effort[],+): Record<string, unknown> {+ if (!isPlainObject(body.reasoning) || !Object.hasOwn(body.reasoning, 'effort')) return body;+ const effort = reconcileOutboundReasoningEffort(body.reasoning.effort, efforts);+ return effort === body.reasoning.effort ? body : applyReasoningEffortOverride(body, effort ?? null);+}+function observedReasoningEffort(body: Record<string, unknown>): string | undefined {if (!isPlainObject(body.reasoning) || typeof body.reasoning.effort !== 'string') {return undefined;@@ -1213,6 +1236,9 @@ function prepareLocalBridgeBody(opts: PrepareLocalBridgeBodyOptions): unknown {}if (isPlainObject(body)) {body = applyReasoningEffortOverride(body, opts.reasoningEffortOverride);+ if (isPlainObject(body) && typeof body.model === 'string') {+ body = reconcileProviderReasoningEffort(body, opts.providerId, body.model);+ }}if (opts.instructions && isPlainObject(body)) {const existing = body.instructions;@@ -1819,7 +1845,7 @@ function createXaiResponsesCompatTransform(): RequestTransform {};}-function responsesCompatibilityRouting(+function responsesCompatibilityRoute(body: Record<string, unknown>,ctx: RequestTransformCtx,frozenAuthInjection?: CodexProxyAuthInjection,@@ -1829,6 +1855,7 @@ function responsesCompatibilityRouting(const authInjection = frozenAuthInjection ?? getCodexProxyAuthInjection();const implicitProviderId = inferProviderIdForModel(requestModel, 'codex');let routing: ReturnType<typeof getProviderRoutingDescriptor> = null;+ let providerId = providerContext.providerId;if (providerContext.subagentRoute) {routing = getProviderRoutingDescriptor(@@ -1847,6 +1874,7 @@ function responsesCompatibilityRouting(undefined,authInjection,);+ providerId = adopted ? providerContext.providerId : 'xd';routing = adopted? getSessionRoutingDescriptor(providerContext.sessionId!, 'codex', requestModel): getProviderRoutingDescriptor('xd', 'codex', requestModel);@@ -1855,6 +1883,7 @@ function responsesCompatibilityRouting(// user/API-key provider merely sharing a model id does not win routing.const inferred = getProviderRoutingDescriptor(implicitProviderId, 'codex', requestModel);routing = inferred?.authStrategy === 'provider-oauth-header' ? inferred : null;+ if (routing) providerId = implicitProviderId;}if (!routing) {@@ -1866,9 +1895,18 @@ function responsesCompatibilityRouting(? 'openai': 'xd';routing = getProviderRoutingDescriptor(defaultProviderId, 'codex', requestModel);+ providerId = defaultProviderId;}- return routing;+ return { routing, providerId, catalogModel: providerContext.catalogModel };+}++function responsesCompatibilityRouting(+ body: Record<string, unknown>,+ ctx: RequestTransformCtx,+ frozenAuthInjection?: CodexProxyAuthInjection,+) {+ return responsesCompatibilityRoute(body, ctx, frozenAuthInjection).routing;}/**@@ -2101,8 +2139,19 @@ function createMiniMaxResponsesCompatTransform(): RequestTransform {};}-function createProviderModelRewriteTransform(): RequestTransform {+function createProviderModelRewriteTransform(+ frozenAuthInjection?: CodexProxyAuthInjection,+): RequestTransform {return (body, ctx) => {+ let normalized = body;+ const original = body;+ if (isPlainObject(body) && typeof body.model === 'string') {+ const route = responsesCompatibilityRoute(body, ctx, frozenAuthInjection);+ if (route.providerId) {+ normalized = reconcileProviderReasoningEffort(body, route.providerId, route.catalogModel);+ }+ }+ body = normalized;if (isPlainObject(body) && typeof body.model === 'string') {const subagentRoute = subagentRouteFromHeaders(ctx.headers);if (subagentRoute) {@@ -2119,8 +2168,10 @@ function createProviderModelRewriteTransform(): RequestTransform {}const sessionId = sessionIdFromTransformCtx(ctx);const explicitProviderId = sessionId ? getSessionProvider(sessionId) : null;- if (sessionId && explicitProviderId) return rewriteSessionModelIdForRoute(sessionId, 'codex', body);- return rewriteImplicitModelIdForRoute('codex', body);+ const rewritten = sessionId && explicitProviderId+ ? rewriteSessionModelIdForRoute(sessionId, 'codex', body)+ : rewriteImplicitModelIdForRoute('codex', body);+ return rewritten ?? (normalized !== original ? normalized : null);};}@@ -2564,6 +2615,26 @@ function createCodexImageGenerationForwardLifecycleObserver(};}+function customProviderRouteSnapshot(routeId: string, frozenRoutes?: readonly CodexCustomProviderRoute[]) {+ return frozenRoutes === undefined+ ? findCodexAppliedCustomProviderRoute(routeId)+ : frozenRoutes.find(candidate => candidate.routeId === routeId);+}++function createCustomProviderReasoningTransform(+ frozenRoutes?: readonly CodexCustomProviderRoute[],+): RequestTransform {+ return (body, ctx) => {+ const path = parseCodexCustomProviderPath(ctx.url);+ if (path.kind !== 'route' || path.pathKind !== 'responses'+ || !isPlainObject(body) || typeof body.model !== 'string') return null;+ const route = customProviderRouteSnapshot(path.routeId, frozenRoutes);+ if (!route?.responseModels.includes(body.model)) return null;+ const next = reconcileResponsesReasoningEffort(body, route.responseEffortsByModel[body.model] ?? []);+ return next === body ? null : next;+ };+}+function resolveCodexCustomProviderRoutingDecision(body: unknown,ctx: RequestTransformCtx,@@ -2575,9 +2646,7 @@ function resolveCodexCustomProviderRoutingDecision(return codexCustomProviderRouteFailure(400, 'invalid_custom_provider_route');}- const route = frozenRoutes === undefined- ? findCodexAppliedCustomProviderRoute(parsed.routeId)- : frozenRoutes.find((candidate) => candidate.routeId === parsed.routeId);+ const route = customProviderRouteSnapshot(parsed.routeId, frozenRoutes);if (!route) return codexCustomProviderRouteFailure(403, 'custom_provider_route_unavailable');if (parsed.pathKind === 'images' && route.capabilities.imageGeneration !== true) {@@ -2951,7 +3020,7 @@ function createTransformRequestChain(createGatewayGrokResponsesCompatTransform(frozenAuthInjection),createByteDanceSeedResponsesCompatTransform(),createMiniMaxResponsesCompatTransform(),- createProviderModelRewriteTransform(),+ createProviderModelRewriteTransform(frozenAuthInjection),providerRequestTransform,// 视觉桥透明替换(层 A,Responses 格式):controller 未注入时短路透传,零干扰;// 注入后把纯文本模型请求 input[] 里的 input_image 转成文字描述。放在 strip 之前与@@ -3071,7 +3140,8 @@ function createCodexProxyHandle(transformRequest: createTransformRequestChain(frozenAuthInjection, execAdapter).map((transform): RequestTransform => {// Namespaced Responses use a frozen Provider route. Preserve its native- // fields and model; only repair known tool ID mismatches on this path.+ // fields and model. The dedicated transform below reconciles effort+ // against that same snapshot; ordinary session/catalog transforms stay out.if (transform === normalizeResponsesToolItemIds) return transform;const scoped: RequestTransform = (body, ctx) =>isCodexCustomProviderNamespacePath(ctx.url) ? null : transform(body, ctx);@@ -3080,7 +3150,7 @@ function createCodexProxyHandle(scoped.onRequestSettled = transform.onRequestSettled;return scoped;},- ),+ ).concat(createCustomProviderReasoningTransform(frozenCustomProviderRoutes)),routeOpaqueRequestBody: (ctx) => isCodexCustomProviderNamespacePath(ctx.url),bypassRequestTransforms: (_body, ctx) => {const path = parseCodexCustomProviderPath(ctx.url);diff --git a/apps/desktop/src/main/maker-host/codex-smart-subagent-routing.ts b/apps/desktop/src/main/maker-host/codex-smart-subagent-routing.tsindex 4658e2a797..a62d4e6308 100644--- a/apps/desktop/src/main/maker-host/codex-smart-subagent-routing.ts+++ b/apps/desktop/src/main/maker-host/codex-smart-subagent-routing.ts@@ -116,8 +116,7 @@ export function codexSmartSubagentRoutingSignature(return `smart:${catalogRevision}:${JSON.stringify(candidates.map(({ providerId, model }) => [providerId, model.id]))}`;}-function reasoningLevels(model: CatalogModel, fallback: unknown): unknown {- if (model.efforts.length === 0) return fallback;+function reasoningLevels(model: CatalogModel): unknown {return model.efforts.map((effort) => ({effort,description: `${model.name} ${effort} reasoning`,@@ -159,11 +158,8 @@ export function buildCodexSmartModelCatalog(description: candidate.model.description ?? record.description,context_window: candidate.model.contextWindow,max_context_window: candidate.model.contextWindow,- default_reasoning_level: candidate.model.defaultEffort ?? record.default_reasoning_level,- supported_reasoning_levels: reasoningLevels(- candidate.model,- record.supported_reasoning_levels,- ),+ default_reasoning_level: candidate.model.defaultEffort,+ supported_reasoning_levels: reasoningLevels(candidate.model),...fullPromptCompatibility(candidate.model.id),multi_agent_version: 'v2',visibility: 'list',@@ -187,11 +183,8 @@ export function buildCodexSmartModelCatalog(priority,context_window: candidate.model.contextWindow,max_context_window: candidate.model.contextWindow,- default_reasoning_level: candidate.model.defaultEffort ?? template.default_reasoning_level,- supported_reasoning_levels: reasoningLevels(- candidate.model,- template.supported_reasoning_levels,- ),+ default_reasoning_level: candidate.model.defaultEffort,+ supported_reasoning_levels: reasoningLevels(candidate.model),...fullPromptCompatibility(candidate.model.id),multi_agent_version: 'v2',visibility: 'list',diff --git a/apps/desktop/src/main/maker-host/outbound-reasoning-effort.ts b/apps/desktop/src/main/maker-host/outbound-reasoning-effort.tsnew file mode 100644index 0000000000..36f8a35afd--- /dev/null+++ b/apps/desktop/src/main/maker-host/outbound-reasoning-effort.ts@@ -0,0 +1,12 @@+import { clampEffortToSupported, EFFORT_VALUES, type Effort } from '@cindy/model-providers';++/** Resolve an outgoing preference against this invocation's declared capabilities. */+export function reconcileOutboundReasoningEffort(+ requested: unknown,+ efforts: readonly Effort[],+): Effort | undefined {+ // Missing input must not create a default; missing capabilities must not forward a preference.+ if (typeof requested !== 'string' || !efforts.length+ || !(EFFORT_VALUES as readonly string[]).includes(requested)) return undefined;+ return clampEffortToSupported(requested as Effort, efforts) as Effort | undefined;+}diff --git a/apps/desktop/src/main/maker-host/pi-provider-transport.ts b/apps/desktop/src/main/maker-host/pi-provider-transport.tsindex f89482d268..3d95ca7951 100644--- a/apps/desktop/src/main/maker-host/pi-provider-transport.ts+++ b/apps/desktop/src/main/maker-host/pi-provider-transport.ts@@ -1,4 +1,5 @@import { randomUUID, createHash } from 'node:crypto';+import { reconcileOutboundReasoningEffort } from './outbound-reasoning-effort.js';import { once } from 'node:events';import type { ServerResponse } from 'node:http';import { ChatSseTranslator, translateResponsesRequestWithContext, type ResponsesRequest } from '@cindy/responses-chat-bridge';@@ -269,8 +270,7 @@ export function createPiProviderFetch(options: PiProviderTransportOptions): type...(!['google-generative-ai', 'google-vertex', 'bedrock-converse-stream'].includes(model.api)? { fetch: diagnosticFetch } : {}),signal, maxRetries: 0,- reasoning: request.reasoning?.effort && request.reasoning.effort !== 'none'- ? request.reasoning.effort as ThinkingLevel : undefined,+ reasoning: reconcileOutboundReasoningEffort(request.reasoning?.effort, options.row.efforts) as ThinkingLevel | undefined,maxTokens: typeof request.max_output_tokens === 'number' ? Math.min(request.max_output_tokens, model.maxTokens) : model.maxTokens,});const iterator = events[Symbol.asyncIterator]();diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.tsindex 18f92bcd69..e90d54ff95 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts@@ -71,6 +71,7 @@ const imageGenerationRoutes: readonly CodexCustomProviderRoute[] = [authStrategy: 'none',},responseRoutingByModel: {},+ responseEffortsByModel: {},credentialRevision: 1,},{@@ -85,6 +86,7 @@ const imageGenerationRoutes: readonly CodexCustomProviderRoute[] = [authStrategy: 'none',},responseRoutingByModel: {},+ responseEffortsByModel: {},credentialRevision: 1,},];diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.tsindex 12ea5d253b..e7fe1e2195 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerModelSelection.test.ts@@ -202,6 +202,7 @@ const schedulerImageGenerationRoutes: readonly CodexCustomProviderRoute[] = [authStrategy: 'none',},responseRoutingByModel: {},+ responseEffortsByModel: {},credentialRevision: 1,},{@@ -216,6 +217,7 @@ const schedulerImageGenerationRoutes: readonly CodexCustomProviderRoute[] = [authStrategy: 'none',},responseRoutingByModel: {},+ responseEffortsByModel: {},credentialRevision: 1,},];diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.tsindex 17b76c2a26..8c56782e61 100644--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts@@ -116,6 +116,7 @@ const queuedImageGenerationRoutes: readonly CodexCustomProviderRoute[] = [authStrategy: 'none',},responseRoutingByModel: {},+ responseEffortsByModel: {},credentialRevision: 1,},{@@ -130,6 +131,7 @@ const queuedImageGenerationRoutes: readonly CodexCustomProviderRoute[] = [authStrategy: 'none',},responseRoutingByModel: {},+ responseEffortsByModel: {},credentialRevision: 1,},];diff --git a/docs/product-rules/model-metadata-precedence.md b/docs/product-rules/model-metadata-precedence.mdindex e2b095b655..49c3c58fd9 100644--- a/docs/product-rules/model-metadata-precedence.md+++ b/docs/product-rules/model-metadata-precedence.md@@ -40,6 +40,46 @@ Pi 明确声明的 `reasoningDefaultEffort` 属于 Harness 默认例外,高于显式空数组不补回。媒体资料不授予账号成员资格,也不能解锁尚未实现的请求协议。详见 [V4 全类型规范](../model-registry-v4-media.md)。+## 推理能力缺失时的统一规则++裁决日期:2026-09-22。**能力有依据才声明,资料缺失交给供应商默认,不把猜测变成配置。**+本节适用于 Claude Code、Codex、Pi 的模型目录、选择器和实际调用,不因入口或引擎不同另设通用档位。++1. **未知不等于不支持。** 资料层保留以下区别;最终可选条目的兜底值不作为能力事实写回资料层。++ | 原始声明 | 含义 | 继承后的行为 |+ | --- | --- | --- |+ | 缺少推理能力字段 | 能力未知,允许继续继承 | 仍未知则不指定强度,不主动发送关闭思考的参数 |+ | 明确 `efforts: []` 或用户配置 `reasoning: false` | 明确无可调档位 | 保留明确声明,不用低优先级资料补回档位 |+ | 非空 `efforts` | 已声明支持的档位 | 仅提供和发送该范围内的强度 |++2. **不提供通用档位套餐。** 缺少资料时不得补 `low / medium / high / xhigh / max`,+ 也不得统一指定 `medium` 或 `high`。兼容 OpenAI 等接口协议只证明请求格式可用,+ 不证明模型支持该协议的全部可选参数或档位。+3. **按字段继承并保留来源。** 沿用本文的公共资料 → 接入默认 → 接口实报 → 有依据的强制修正+ → 用户显式配置顺序。缺字段继续继承;明确的 `false`、空数组和 `null` 保留各自语义,+ 不被低优先级资料补回。客户端回退值不得冒充供应商实报或用户配置。+4. **默认值不能创造能力。** 非空默认档必须属于有效支持列表;列表已知而默认字段缺失时,+ 只按共享默认选择规则从已声明档位中选取。`defaultEffort: null` 保持不指定默认档。+ 列表仍未知时最终使用 `efforts: []`、`defaultEffort: null`,请求省略推理强度参数。+5. **展示与请求遵守同一有效能力。** 普通任务、子 Agent、自动任务和辅助调用均按实际目标的+ 连接、模型与引擎校验档位。旧任务保存的选择不是能力声明,不能凭旧 `max` 绕过当前校验;+ 选择器占位值、父任务档位和 GPT 模板也不能补回未经确认的能力。支持列表为空时不发送强度,+ 非空时沿用共享协调规则处理不再受支持的选择;不借此覆盖已保存的用户偏好。+6. **新资料自动生效,用户设置不被覆盖。** 新型号先按未知能力处理;目录或接口补齐资料后,+ 沿用现有刷新和继承链恢复已声明能力。不得按型号前缀或名称相似度猜测能力;精确型号、明确+ alias 和既有协议 ID 归一仍按本文身份规则处理。临时回退不落成用户 override,刷新不覆盖+ 用户显式设置,也不因缺少推理资料删除模型。++回归验证必须覆盖:缺资料时的三个引擎、无目录与旧版/当前目录、明确空值、接口实报与用户覆盖、+后续资料补齐、旧任务档位的出站参数,以及子 Agent 已有条目/新增模板两条路径。+当前回归入口:+[自定义模型资料继承](../../packages/model-providers/src/__tests__/user-provider.test.ts)、+[原生适配器出站参数](../../apps/desktop/src/main/maker-host/__tests__/piProviderTransport.test.ts)、+[Responses 转发与供应商隔离](../../apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts)、+[Codex 子 Agent 目录](../../apps/desktop/src/main/maker-host/__tests__/codex-smart-subagent-routing.test.ts)。+这些测试各自证明对应路径,不以目录或 UI 测试通过代替实际请求参数验证。+## 字段归属与默认值| 位置 | 允许表达的内容 | 易混淆的边界 |diff --git a/packages/model-providers/src/__tests__/user-provider.test.ts b/packages/model-providers/src/__tests__/user-provider.test.tsindex 0faab98654..3b25593f39 100644--- a/packages/model-providers/src/__tests__/user-provider.test.ts+++ b/packages/model-providers/src/__tests__/user-provider.test.ts@@ -289,14 +289,92 @@ describe("buildUserProvider (per-runtime)", () => {id: "meta/llama-4-405b",name: "Llama 4 405B",contextWindow: DEFAULT_CUSTOM_CONTEXT_WINDOW,- // codex runtime:参考内置默认 effort 档位(low/medium/high/xhigh/max,默认 medium)。- efforts: ["low", "medium", "high", "xhigh", "max"],- defaultEffort: "medium",+ // 未声明能力时不指定推理档位,让供应商使用默认行为。+ efforts: [],+ defaultEffort: null,group: "custom:openrouter",defaultEnabled: false,});});+ it.each(["claude-code", "codex", "pi"] as const)(+ "%s leaves unknown reasoning unspecified and preserves declared capabilities",+ (agent) => {+ for (const modelRegistry of [+ undefined,+ LEGACY_REGISTRY,+ BUNDLED_CATALOG.modelRegistry,+ ]) {+ const models = [+ { id: "unknown-model", name: "Unknown" },+ {+ id: "discovered-model",+ name: "Discovered",+ discoveredMetadata: {+ efforts: ["low", "high"] as const,+ defaultEffort: "high" as const,+ },+ },+ {+ id: "configured-model",+ name: "Configured",+ reasoning: true,+ reasoningEfforts: ["high", "max"] as const,+ reasoningDefaultEffort: "max" as const,+ discoveredMetadata: {+ efforts: ["low"] as const,+ defaultEffort: "low" as const,+ },+ },+ {+ id: "disabled-model",+ name: "Disabled",+ reasoning: false,+ discoveredMetadata: {+ efforts: ["high"] as const,+ defaultEffort: "high" as const,+ },+ },+ ];+ const config: CustomProviderConfig = {+ id: "unknown-provider",+ name: "Unknown provider",+ runtimes: {+ [agent]: { baseUrl: "https://unknown.example/v1", models },+ },+ };+ const before = structuredClone(config);+ const provider = buildUserProvider(config, { modelRegistry });+ expect(provider.models[agent]).toEqual([+ expect.objectContaining({+ id: "unknown-model",+ efforts: [],+ defaultEffort: null,+ }),+ expect.objectContaining({+ id: "discovered-model",+ efforts: ["low", "high"],+ defaultEffort: "high",+ }),+ expect.objectContaining({+ id: "configured-model",+ efforts: ["high", "max"],+ defaultEffort: "max",+ }),+ expect.objectContaining({+ id: "disabled-model",+ efforts: [],+ defaultEffort: null,+ }),+ ]);+ expect(config).toEqual(before);+ expect(provider.models[agent]?.[0].userModelConfig).not.toHaveProperty(+ "reasoning",+ );+ }+ },+ );+it("projects a model-specific protocol route into the provider catalog", () => {const provider = buildUserProvider({...codexOnly,@@ -363,14 +441,14 @@ describe("buildUserProvider (per-runtime)", () => {}),expect.objectContaining({id: "unregistered-model",- efforts: ["low", "medium", "high", "xhigh", "max"],- defaultEffort: "medium",+ efforts: [],+ defaultEffort: null,}),]);expect(provider.models["claude-code"]?.[0]).toMatchObject({id: "gpt-5.6-sol",- efforts: ["low", "medium", "high", "xhigh", "max"],- defaultEffort: "medium",+ efforts: [],+ defaultEffort: null,});});@@ -478,7 +556,7 @@ describe("buildUserProvider (per-runtime)", () => {});});- it("unregistered prefix falls back to CUSTOM_EFFORTS", () => {+ it("unregistered prefix does not invent reasoning efforts", () => {const p = buildUserProvider({id: "unknown-relay",@@ -492,11 +570,11 @@ describe("buildUserProvider (per-runtime)", () => {},{ modelRegistry: LEGACY_REGISTRY },);- // custom/my-model → no registry match → CUSTOM_EFFORTS for codex+ // custom/my-model has no matching capability declaration.expect(p.models.codex?.[0]).toMatchObject({id: "custom/my-model",- efforts: ["low", "medium", "high", "xhigh", "max"],- defaultEffort: "medium",+ efforts: [],+ defaultEffort: null,});});@@ -609,8 +687,8 @@ describe("buildUserProvider (per-runtime)", () => {);expect(provider.models.codex?.[0]).toMatchObject({- efforts: ["low", "medium", "high", "xhigh", "max"],- defaultEffort: "medium",+ efforts: [],+ defaultEffort: null,});});@@ -649,8 +727,8 @@ describe("buildUserProvider (per-runtime)", () => {{ modelRegistry: registry },);expect(ambiguous.models.codex?.[0]).toMatchObject({- efforts: ["low", "medium", "high", "xhigh", "max"],- defaultEffort: "medium",+ efforts: [],+ defaultEffort: null,});registry.models.pop();@@ -688,8 +766,8 @@ describe("buildUserProvider (per-runtime)", () => {{ modelRegistry: LEGACY_REGISTRY },);expect(noTargetRoute.models.codex?.[0]).toMatchObject({- efforts: ["low", "medium", "high", "xhigh", "max"],- defaultEffort: "medium",+ efforts: [],+ defaultEffort: null,});});@@ -1042,7 +1120,7 @@ describe("buildUserProvider (per-runtime)", () => {);// xd/codex/gpt-5.6-sol → strips xd/ → codex/gpt-5.6-sol → matches route for claude-code// without prefix-stripping, the model ID wouldn't match any registry entry- // and efforts would fall back to CUSTOM_EFFORTS (no 'xhigh' from registry).+ // and efforts would remain empty.const model = p.models["claude-code"]?.[0];expect(model?.efforts?.length).toBeGreaterThan(0);expect(model?.efforts).toContain("xhigh");@@ -1139,7 +1217,7 @@ describe("buildUserProvider (per-runtime)", () => {);expect(pChatgpt.models["claude-code"]?.[0]?.efforts).toContain("ultra");- // unknown prefix: should NOT match registry, gets default CUSTOM_EFFORTS (no 'ultra')+ // Unknown prefix must not borrow capability declarations.const pUnknown = buildUserProvider({id: "relay",@@ -1256,7 +1334,7 @@ describe("buildUserProvider (per-runtime)", () => {expect(p.models["claude-code"]?.[0]?.defaultEffort).toBe("max");});- it("Case C: no exact match → prefix fallback yields ambiguity → CUSTOM_EFFORTS", () => {+ it("Case C: no exact match → prefix fallback yields ambiguity → no declared efforts", () => {// Two entries both have route.modelId='baz' after stripping openai/const reg: ModelRegistry = {updatedAt: "2026-01-01T00:00:00Z",@@ -1289,7 +1367,7 @@ describe("buildUserProvider (per-runtime)", () => {},{ modelRegistry: reg },);- // Ambiguous → falls back to CUSTOM_EFFORTS (no 'ultra')+ // Ambiguous declarations must not invent capabilities.expect(p.models.codex?.[0]?.efforts).not.toContain("ultra");});diff --git a/packages/model-providers/src/user-provider.ts b/packages/model-providers/src/user-provider.tsindex 961b1c2d2d..02aa64c25f 100644--- a/packages/model-providers/src/user-provider.ts+++ b/packages/model-providers/src/user-provider.ts@@ -145,22 +145,6 @@ export function xaiApiOfficialRuntimeAgents();}-/**- * 自定义模型的默认 effort 档位(「参考默认设置」)——与内置当代旗舰模型对齐:- * - claude-code:low/medium/high/xhigh/max(同 opus / fable);- * - codex:low/medium/high/xhigh/max(gpt-5.x 同款五档,ultra 仍仅限已登记模型)。- * 让自定义模型像内置模型一样能在选择器里切 reasoning/thinking 强度(默认 medium)。- * 端点是否真支持由其后端决定:cc 经 `thinking`、codex 经 reasoning effort 透传,- * anthropic-compat-proxy 仅对个别内置 model id strip 字段、对自定义 id 一律字节透传。- * 未登记模型(Registry 无法确认能力)也放开到 max:第三方 Responses 兼容端点普遍- * 接受与否只有端点方/用户知道,选到不支持的档位会被上游拒绝,用户改选即可;- * 默认中档;用户显式配置仍优先。- */-const CUSTOM_EFFORTS: Partial<Record<AgentKind, Effort[]>> = {- "claude-code": ["low", "medium", "high", "xhigh", "max"],- codex: ["low", "medium", "high", "xhigh", "max"],-};-interface RegistryEffortMetadata {efforts: Effort[];defaultEffort: Effort | null;@@ -291,7 +275,7 @@ function registrySupportsFastMode(/** 固定 agent 顺序:保证派生出的 provider.agents / routing / models 顺序稳定。 */const AGENT_ORDER: readonly AgentKind[] = ["claude-code", "codex", "pi"];-/** 单个用户填写的模型 → CatalogModel(补默认元数据;effort 按所属 agent 参考内置默认)。 */+/** 单个用户填写的模型 → CatalogModel(只从已声明的能力补推理档位)。 */function toCatalogModel(m: ProviderRuntimeModelConfig,providerId: string,@@ -301,15 +285,12 @@ function toCatalogModel(metadataProviderId = providerId,): CatalogModel {// 显式 runtime 能力优先:reasoning:true 才导出 efforts;false = 明确无思考档。- // 字段缺省才走历史 fallback(Pi 空档 / 其它自定义 Provider 的 CUSTOM_EFFORTS)。+ // 未知能力不借用其它模型的档位;后续仍按目录、预设、实报和用户配置逐层继承。+ // 空档位只表示不指定推理强度,不代表要求供应商关闭思考。const efforts: Effort[] =m.reasoning === true? [...(m.reasoningEfforts ?? [])]- : m.reasoning === false- ? []- : agent === "pi"- ? []- : (CUSTOM_EFFORTS[agent] ?? []);+ : [];const registryEfforts =m.reasoning !== undefined || (modelRegistry?.schemaVersion ?? 0) >= 4? undefined