Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 未绑定会话的 claude-code 请求先按模型路由,再落默认网关 (#3211)
murphy shen5d6fc9d4e8cf
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyImplicitRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyImplicitRoute.test.tsnew file mode 100644index 0000000000..67427b8455--- /dev/null+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyImplicitRoute.test.ts@@ -0,0 +1,214 @@+/**+ * claudeProxyImplicitRoute.test.ts+ * ---------------------------------------------------------------------------+ * 回归:cc routingTransform ①.5 段 —— 未绑定/未反解出供应商的请求按模型隐式路由。+ *+ * 现场(智谱 GLM-5.3 事故):会话模型选了用户智谱来源的裸 catalog id(glm-5.3),+ * 会话启动/切模的首批请求抢在 session↔provider 绑定(session header 反解 / set-model+ * 落库)之前到达 proxy —— ① 段因 getSessionProvider 为 null 放空,② 段把请求透传给+ * 默认网关(LiteLLM)。网关只注册命名空间 id(z-ai/glm-5.3),裸 id 在模型校验层被拒:+ * 400 {'error': 'anthropic_messages: Invalid model name passed in model=glm-5.3. ...'}+ * Claude Code 把它 surface 成 API Error 400,靠重试恢复,用户侧表现为偶发报错。+ *+ * 本测试用真实 provider-route + active-catalog fixture,只 mock 触电模块,验证+ * 决策级行为(codex 侧同语义见 codexProxyHost ①.5;cc 侧为本次补齐):+ * - 无会话 + 裸 glm-5.3 → ①.5 路由到用户智谱上游,鉴权头换成用户 key;+ * - 会话已反解但未绑定供应商 + 裸 glm-5.3 → 同上(启动竞态的真实形态);+ * - 网关命名空间 id(z-ai/glm-5.3)/ anthropic wire 模型(claude-*)/ 目录外模型+ * → 不受 ①.5 影响,保持 ② 段默认路径(passthrough),#886 语义不回归。+ */++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('../../appCapabilities.js', () => ({+ getAppCapabilities: () => ({ canUseCindyGateway: true }),+}));++vi.mock('../logger-adapter', () => ({+ createMakerLogger: () => ({+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),+ child: vi.fn(function self() { return { trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(), child: self }; }),+ }),+ desktopMakerLogger: {+ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn(),+ child: vi.fn(() => ({ trace: vi.fn(), debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() })),+ },+}));+vi.mock('../runtime-configs', () => ({+ claudeUpstreamEndpoint: () => 'https://gateway.example.com',+}));+vi.mock('../silent-encrypted-retry-store', () => ({+ readSilentEncryptedRetrySettings: () => ({ enabled: false }),+}));+vi.mock('../claude-fast-mode-log', () => ({+ createClaudeFastModeRequestTransform: () => () => null,+ createClaudeFastModeResponseObserver: () => () => undefined,+}));++import {+ createModelRoutingTransform,+ setClaudeProxyGatewayKeyReader,+ setClaudeProxySessionIdResolver,+} from '../anthropic-compat-proxy-host';+import {+ setCustomProviderKeyReader,+ setPendingCredentialSwitchReader,+ setProviderOAuthTokenReader,+ setProviderViewsReader,+} from '../provider-route';+import { getActiveCatalog, setCustomProviders } from '../active-catalog';+import { buildRegistry, buildUserProvider } from '@cindy/model-providers';+import { clearSessionProvider } from '../session-provider-store';+import {+ readClaudeSessionRoute,+ resetClaudeSessionRouteRegistryForTest,+} from '../claude-session-route-registry';++const ZHIPU_UPSTREAM = 'https://open.bigmodel.example/api/anthropic';++function ctxWith(headers: Record<string, string>) {+ return { reqId: 1, method: 'POST', url: '/v1/messages', headers } as never;+}++function installZhipuProvider(): void {+ setCustomProviders([+ buildUserProvider({+ id: 'zhipu-plan',+ name: 'Zhipu Plan',+ runtimes: {+ 'claude-code': {+ baseUrl: ZHIPU_UPSTREAM,+ wireProtocol: 'anthropic-messages',+ models: [{ id: 'glm-5.3', name: 'GLM-5.3' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader(() => 'glm-user-key');+ setProviderViewsReader(async () => buildRegistry(getActiveCatalog(), { 'zhipu-plan': true }));+}++describe('cc routingTransform — ①.5 隐式来源路由 (智谱 glm-5.3 裸 id 事故回归)', () => {+ let transform: ReturnType<typeof createModelRoutingTransform>;++ beforeEach(() => {+ resetClaudeSessionRouteRegistryForTest();+ setClaudeProxyGatewayKeyReader(() => 'sk-gw');+ setClaudeProxySessionIdResolver(() => null);+ setPendingCredentialSwitchReader(() => undefined);+ setProviderOAuthTokenReader(() => null);+ clearSessionProvider('sess-race');+ installZhipuProvider();+ transform = createModelRoutingTransform();+ });++ afterEach(() => {+ setCustomProviders([]);+ setCustomProviderKeyReader(() => null);+ setProviderViewsReader(async () => []);+ clearSessionProvider('sess-race');+ resetClaudeSessionRouteRegistryForTest();+ });++ it('无会话头的裸 glm-5.3 → 路由到用户智谱上游并换用户 key,不再透传默认网关', async () => {+ const decision = await Promise.resolve(+ transform({ model: 'glm-5.3' }, ctxWith({ 'x-api-key': 'sk-gw' })),+ );+ // 修复前:① 段放空 → ② 段 passthrough → LiteLLM 对裸 id 400。+ expect(decision).toMatchObject({+ upstreamOverride: ZHIPU_UPSTREAM,+ headerOverride: {+ 'x-api-key': 'glm-user-key',+ authorization: 'Bearer glm-user-key',+ },+ });+ });++ it('会话已反解但 provider 绑定未落(启动竞态)→ 同样走 ①.5 用户上游', async () => {+ setClaudeProxySessionIdResolver((sdkId) => (sdkId === 'sdk-race' ? 'sess-race' : null));+ const decision = await Promise.resolve(+ transform(+ { model: 'glm-5.3' },+ ctxWith({ 'x-claude-code-session-id': 'sdk-race', 'x-api-key': 'sk-gw' }),+ ),+ );+ expect(decision).toMatchObject({+ upstreamOverride: ZHIPU_UPSTREAM,+ headerOverride: { 'x-api-key': 'glm-user-key' },+ });+ });++ it('同一裸 model 有多个已连接来源时拒绝请求,不外发默认网关或写计费路由', async () => {+ const provider = (id: string, baseUrl: string) => buildUserProvider({+ id,+ name: id,+ runtimes: {+ 'claude-code': {+ baseUrl,+ wireProtocol: 'anthropic-messages',+ models: [{ id: 'shared-model', name: 'Shared Model' }],+ },+ },+ });+ setCustomProviders([+ provider('provider-a', 'https://a.example/v1'),+ provider('provider-b', 'https://b.example/v1'),+ ]);+ setCustomProviderKeyReader((id) => `${id}-key`);+ setProviderViewsReader(async () => buildRegistry(getActiveCatalog(), {+ 'provider-a': true,+ 'provider-b': true,+ }));+ setClaudeProxySessionIdResolver((sdkId) => (sdkId === 'sdk-race' ? 'sess-race' : null));++ const decision = await Promise.resolve(+ transform(+ { model: 'shared-model' },+ ctxWith({ 'x-claude-code-session-id': 'sdk-race', 'x-api-key': 'sk-gw' }),+ ),+ );++ const writeHead = vi.fn();+ const end = vi.fn();+ await decision?.localHandler?.({ res: { writeHead, end } } as never);+ expect(writeHead).toHaveBeenCalledWith(503, expect.objectContaining({+ 'retry-after': '1',+ }));+ expect(JSON.parse(end.mock.calls[0][0])).toMatchObject({+ error: { code: 'provider_route_ambiguous' },+ });+ expect(readClaudeSessionRoute('sess-race')).toBeNull();+ });++ it('网关命名空间 id(z-ai/glm-5.3)不受 ①.5 影响,保持默认 passthrough', async () => {+ const decision = await Promise.resolve(+ transform({ model: 'z-ai/glm-5.3' }, ctxWith({ 'x-api-key': 'sk-gw' })),+ );+ expect(decision).toBeNull();+ });++ it('anthropic wire 模型(claude-*)保持 ② 段默认路径 (#886 语义)', async () => {+ const decision = await Promise.resolve(+ transform({ model: 'claude-haiku-4-5' }, ctxWith({ 'x-api-key': 'sk-gw' })),+ );+ expect(decision).toBeNull();+ });++ it('目录外未知模型 → ①.5 解析落空,回落 ② 段默认(与修复前一致)', async () => {+ const decision = await Promise.resolve(+ transform({ model: 'who-knows-9' }, ctxWith({ 'x-api-key': 'sk-gw' })),+ );+ expect(decision).toBeNull();+ });++ it('未绑定会话的默认 passthrough 仍记 gateway 计费路由(② 段行为保留)', async () => {+ setClaudeProxySessionIdResolver((sdkId) => (sdkId === 'sdk-race' ? 'sess-race' : null));+ await Promise.resolve(+ transform(+ { model: 'z-ai/glm-5.3' },+ ctxWith({ 'x-claude-code-session-id': 'sdk-race', 'x-api-key': 'sk-gw' }),+ ),+ );+ expect(readClaudeSessionRoute('sess-race')).toBe('gateway');+ });+});diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.tsindex 96d5fd94ec..1c161a3a63 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeProxyScopeGate.test.ts@@ -249,12 +249,16 @@ describe('cc routingTransform — xAI 会话的辅助请求回落默认路由 (iexpect(parsedBody.model.startsWith('xai/')).toBe(false);});- it('网关风格 x-ai/grok-4.6 仍走默认路由(不是 SuperGrok 独占户口)', () => {+ it('网关风格 x-ai/grok-4.6 仍走默认路由(不是 SuperGrok 独占户口)', async () => {clearSessionProvider('sess-grok');const transform = createModelRoutingTransform();- const decision = transform(- { model: 'x-ai/grok-4.6' },- ctxWith({ ...SESSION_HEADER, authorization: 'Bearer sk-ant-oat01' }),+ // ①.5 隐式来源解析经 providerViewsReader 为异步;决策内容与同步时代逐字段一致,+ // 这里 await 后锁定的仍是「默认路由 + 网关换 key」这层语义。+ const decision = await Promise.resolve(+ transform(+ { model: 'x-ai/grok-4.6' },+ ctxWith({ ...SESSION_HEADER, authorization: 'Bearer sk-ant-oat01' }),+ ),);expect(decision).toEqual({headerOverride: { 'x-api-key': 'sk-gw', authorization: 'Bearer sk-gw' },diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteObservation.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteObservation.test.tsindex b44f29a552..34e20e69bf 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteObservation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeSessionRouteObservation.test.ts@@ -43,6 +43,9 @@ vi.mock('../provider-route', () => ({resolveSessionRouteDecision: routeMocks.resolveSessionRouteDecision,gatewayDefaultRouteDecision: vi.fn((_agent: string, gatewayKey: string | null) =>gatewayKey ? { headerOverride: { 'x-api-key': gatewayKey } } : null),+ // ①.5 隐式来源解析恒落空 → 回落 ② 段默认,与本套件锁定的记账语义一致。+ resolveImplicitLocalBridgeRouteResolution: vi.fn(async () => ({ kind: 'none' })),+ resolveImplicitProviderOAuthRouteDecision: vi.fn(() => null),}));import {@@ -148,11 +151,14 @@ describe('claude session route observation (routing transform ② 段)', () => {expect(takeClaudeRequestRoute(23)).toEqual({ sessionId: 'sess-1', route: 'gateway' });});- it('does not record ambiguous no-key non-anthropic passthroughs', () => {+ it('does not record ambiguous no-key non-anthropic passthroughs', async () => {const transform = createModelRoutingTransform();- const decision = transform(- { model: 'gpt-5.5[1m]' },- ctxWith({ ...SESSION_HEADER, authorization: 'Bearer sk-ant-oat01' }),+ // ①.5 隐式来源解析是异步路径(本套件 mock 恒落空 → 回落 ② 段),决策内容不变。+ const decision = await Promise.resolve(+ transform(+ { model: 'gpt-5.5[1m]' },+ ctxWith({ ...SESSION_HEADER, authorization: 'Bearer sk-ant-oat01' }),+ ),);expect(decision).toBeNull();expect(readClaudeSessionRoute('sess-1')).toBeNull();diff --git a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.tsindex 84ac9c79ef..9a0e933b76 100644--- a/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/anthropic-compat-proxy-host.ts@@ -69,8 +69,11 @@ import { createClaudeGatewayErrorObserver } from './claude-gateway-error-observeimport { shouldApplyExclusiveProviderReroute } from './model-route-guard.js';import { getSessionProvider } from './session-provider-store.js';import {+ buildRouteDecision,gatewayDefaultRouteDecision,getUserProviderIdForSession,+ resolveImplicitLocalBridgeRouteResolution,+ resolveImplicitProviderOAuthRouteDecision,resolvePendingSessionRouteDecision,resolveProviderRouteDecision,resolveSessionRouteDecision,@@ -172,6 +175,28 @@ function refuseExclusiveXaiDefaultGateway(wireModel: string): RoutingDecision {};}+function refuseAmbiguousImplicitProviderRoute(wireModel: string): RoutingDecision {+ return {+ localHandler: async ({ res }) => {+ const payload = JSON.stringify({+ type: 'error',+ error: {+ type: 'provider_route_ambiguous',+ code: 'provider_route_ambiguous',+ message:+ `model '${wireModel}' matches multiple connected Providers; retry after the session Provider is bound`,+ },+ });+ res.writeHead(503, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',+ 'retry-after': '1',+ });+ res.end(payload);+ },+ };+}+function bridgedSubscriptionModel(wireModel: string): string {if (wireModel.startsWith(XAI_MODEL_PREFIX) || !isExclusiveXaiModelId(wireModel)) {return wireModel;@@ -437,68 +462,126 @@ export function createModelRoutingTransform(): RoutingTransform {if (perSession) return recordSelectedRoute(perSession);}- // ② 未显式选供应商 → 据请求凭证判定 spawn 形态(见上方注释)。- // 计费路由旁路只记「未显式选供应商」的会话(registry 声明的语义,消费方也只在- // providerId=null 时读)——显式选了供应商但被 scope 门放下来的辅助请求(如 xai 会话- // 的 claude-* 分类器调用)不该往表里写死记录。- const recordDefaultRoute =- requestAgent === 'claude-code'- && sessionId !== null- && getSessionProvider(sessionId) == null;- const recordResolvedDefaultRoute = (route: ClaudeSessionBillingRoute): void => {- if (!recordDefaultRoute) return;- recordClaudeSessionRoute(sessionId, route);- recordClaudeRequestRoute(ctx.reqId, sessionId, route);- };- // provider-oauth spawn 的占位 key **不是可用凭证**:scope 门放下来的辅助请求- // (如 openai / xai 来源 cc 会话里 CLI 自发的 claude-* 权限分类器调用)带着它- // passthrough 会在网关吃确定性 401 → 误触发 auto→ask 降级(#831)。与 codex- // ①.5 段 #890 修复同语义:占位 key 按「无可用凭证」处理,走下方换网关 key 的- // 默认路由;真实 key(gateway-spawn)照旧 passthrough。- if (isExclusiveXaiModelId(wireModel)) {- log.warn('exclusive xAI model escaped subscription routing; refusing default gateway', {- wireModel,- selectedProviderId,+ // ①.5 隐式来源(sessionId 未反解出/未绑定供应商,或 ① 段 scope 门放行下来):按模型+ // 推断路由,必须先于 ② 默认网关 —— 裸 catalog id(如用户智谱来源的 glm-5.3)不是+ // 网关注册的命名空间 id(z-ai/glm-5.3),直接落默认网关会被 LiteLLM 模型校验层拒:+ // 400 'anthropic_messages: Invalid model name passed in model=glm-5.3 ...'+ // 会话启动/切模的首批请求若抢在 session↔provider 绑定之前到达即触发,表现为+ // 偶发 API Error 400、重试后恢复。与 codex-proxy-host ①.5 段同语义:+ // - anthropic-messages wire 来源(智谱/自定义 Anthropic 兼容上游)透明转发;+ // - 唯一 provider-oauth 来源(xai/grok-*)注入对应供应商 OAuth。+ // 刻意排除:显式自定义供应商会话(① 段已裁决,镜像 codex 的 !explicitProviderId+ // 闸门)、anthropic wire 模型(claude-* 辅助调用保持 #886 的默认路径语义)、xd+ // 来源(网关即默认上游,② 段处理且带计费路由记账,这里接管会漏记)、PI 会话+ // (PI 有自己的 per-model 路由解析 resolvePiModelRoute,不受隐式推断接管)。+ // 解析复用+ // resolveImplicitLocalBridgeRouteResolution —— 与模型选择器共用连接态(providerViewsReader),+ // 目录无 bridge 候选的模型同步短路,热路径零额外开销。+ const implicitRouteEligible =+ !piSessionId+ && !explicitCustomProvider+ && wireModel+ && !isAnthropicWireModel(wireModel, anthropicCatalogModelIds(getActiveCatalog()));+ if (implicitRouteEligible) {+ return resolveImplicitLocalBridgeRouteResolution(wireModel, 'claude-code').then((resolution) => {+ if (resolution.kind === 'ambiguous') {+ return refuseAmbiguousImplicitProviderRoute(wireModel);+ }+ const bridgeRoute = resolution.kind === 'route' ? resolution.route : null;+ // wire 缺省推断与 provider-route 的 implicitBridgeWire 同口径:claude-code 的+ // 用户 Anthropic 兼容上游在目录里省略 wireProtocol(buildUserProvider 约定)。+ const bridgeWire = bridgeRoute?.routing.wireProtocol ?? 'anthropic-messages';+ if (bridgeRoute && bridgeRoute.providerId !== 'xd' && bridgeWire === 'anthropic-messages') {+ const bridged = buildRouteDecision(+ bridgeRoute.routing,+ gatewayKey,+ 'claude-code',+ bridgeRoute.apiKey,+ bridgeRoute.oauthToken,+ );+ const withRequestPath =+ bridged && bridgeRoute.routing.requestPath+ ? { ...bridged, pathOverride: bridgeRoute.routing.requestPath }+ : bridged;+ if (withRequestPath) return withRequestPath;+ }+ const implicitOAuth = resolveImplicitProviderOAuthRouteDecision(+ wireModel,+ 'claude-code',+ gatewayKey,+ );+ return implicitOAuth instanceof Promise+ ? implicitOAuth.then((decision) => decision ?? decideDefaultRoute())+ : (implicitOAuth ?? decideDefaultRoute());});- return refuseExclusiveXaiDefaultGateway(wireModel);}- const apiKeyHeader = headerValue(ctx.headers, 'x-api-key');- const hasUsableApiKey =- apiKeyHeader !== null && apiKeyHeader !== CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY;- if (hasUsableApiKey) {- // gateway-spawn:自带网关 key,passthrough。- if (requestAgent === 'claude-code' && sessionId && selectedProviderId === 'xd') {- // 显式 XD 会话在 live gateway key 被清除后,仍可能携带 spawn 时冻结的 x-api-key。- // resolveSessionRouteDecision 会因缺 key 返回 null,但这条 passthrough 仍实际进入 XD Gateway。- recordClaudeRequestRoute(ctx.reqId, sessionId, 'gateway');- } else {+ return decideDefaultRoute();++ // ② 未显式选供应商 → 据请求凭证判定 spawn 形态(见上方注释)。+ // 函数声明提升:①.5 的回落分支在自身解析落空时复用本段,行为与引入 ①.5 前一致。+ function decideDefaultRoute(): RoutingDecision | null {+ // 计费路由旁路只记「未显式选供应商」的会话(registry 声明的语义,消费方也只在+ // providerId=null 时读)——显式选了供应商但被 scope 门放下来的辅助请求(如 xai 会话+ // 的 claude-* 分类器调用)不该往表里写死记录。+ const recordDefaultRoute =+ requestAgent === 'claude-code'+ && sessionId !== null+ && getSessionProvider(sessionId) == null;+ const recordResolvedDefaultRoute = (route: ClaudeSessionBillingRoute): void => {+ if (!recordDefaultRoute) return;+ recordClaudeSessionRoute(sessionId, route);+ recordClaudeRequestRoute(ctx.reqId, sessionId, route);+ };+ // provider-oauth spawn 的占位 key **不是可用凭证**:scope 门放下来的辅助请求+ // (如 openai / xai 来源 cc 会话里 CLI 自发的 claude-* 权限分类器调用)带着它+ // passthrough 会在网关吃确定性 401 → 误触发 auto→ask 降级(#831)。与 codex+ // ①.5 段 #890 修复同语义:占位 key 按「无可用凭证」处理,走下方换网关 key 的+ // 默认路由;真实 key(gateway-spawn)照旧 passthrough。+ if (isExclusiveXaiModelId(wireModel)) {+ log.warn('exclusive xAI model escaped subscription routing; refusing default gateway', {+ wireModel,+ selectedProviderId,+ });+ return refuseExclusiveXaiDefaultGateway(wireModel);+ }+ const apiKeyHeader = headerValue(ctx.headers, 'x-api-key');+ const hasUsableApiKey =+ apiKeyHeader !== null && apiKeyHeader !== CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY;+ if (hasUsableApiKey) {+ // gateway-spawn:自带网关 key,passthrough。+ if (requestAgent === 'claude-code' && sessionId && selectedProviderId === 'xd') {+ // 显式 XD 会话在 live gateway key 被清除后,仍可能携带 spawn 时冻结的 x-api-key。+ // resolveSessionRouteDecision 会因缺 key 返回 null,但这条 passthrough 仍实际进入 XD Gateway。+ recordClaudeRequestRoute(ctx.reqId, sessionId, 'gateway');+ } else {+ recordResolvedDefaultRoute('gateway');+ }+ return null;+ }+ const decision = gatewayDefaultRouteDecision(requestAgent, gatewayKey);+ if (decision) {+ // oauth-spawn 默认:全量换网关 key(防订阅 token 泄漏到网关)。recordResolvedDefaultRoute('gateway');+ return decision;+ }+ if (apiKeyHeader !== null) {+ // 占位 key 且无网关 key:保持改动前行为(passthrough,上游 401)——下方的+ // Anthropic 直连支路是给 oauth-spawn 订阅 token 准备的,占位 key 不适用。+ log.warn('provider-oauth cc spawn 占位 key 且无网关 key; passthrough (预期 401)', { wireModel });+ return null;+ }+ // 没网关 key:Anthropic 模型只能直连(唯一出路),其余 passthrough + 记一条诊断。+ // 判据 = 前缀地板 ∪ 目录 anthropic 供应商模型集合(新家族改 OSS 目录即可,无需发版)。+ if (isAnthropicWireModel(wireModel, anthropicCatalogModelIds(getActiveCatalog()))) {+ recordResolvedDefaultRoute('subscription');+ return { upstreamOverride: ANTHROPIC_DIRECT_UPSTREAM };+ }+ if (wireModel) {+ // 无 key 的非 Anthropic 模型 passthrough 大概率 401 —— 路由归属不明确, 不记录。+ log.warn('claude oauth-spawn but no gateway key; non-anthropic passthrough (可能 401)', { wireModel });}return null;}- const decision = gatewayDefaultRouteDecision(requestAgent, gatewayKey);- if (decision) {- // oauth-spawn 默认:全量换网关 key(防订阅 token 泄漏到网关)。- recordResolvedDefaultRoute('gateway');- return decision;- }- if (apiKeyHeader !== null) {- // 占位 key 且无网关 key:保持改动前行为(passthrough,上游 401)——下方的- // Anthropic 直连支路是给 oauth-spawn 订阅 token 准备的,占位 key 不适用。- log.warn('provider-oauth cc spawn 占位 key 且无网关 key; passthrough (预期 401)', { wireModel });- return null;- }- // 没网关 key:Anthropic 模型只能直连(唯一出路),其余 passthrough + 记一条诊断。- // 判据 = 前缀地板 ∪ 目录 anthropic 供应商模型集合(新家族改 OSS 目录即可,无需发版)。- if (isAnthropicWireModel(wireModel, anthropicCatalogModelIds(getActiveCatalog()))) {- recordResolvedDefaultRoute('subscription');- return { upstreamOverride: ANTHROPIC_DIRECT_UPSTREAM };- }- if (wireModel) {- // 无 key 的非 Anthropic 模型 passthrough 大概率 401 —— 路由归属不明确, 不记录。- log.warn('claude oauth-spawn but no gateway key; non-anthropic passthrough (可能 401)', { wireModel });- }- return null;};return (body, ctx) => {const decision = route(body, ctx);diff --git a/apps/desktop/src/main/maker-host/provider-route.ts b/apps/desktop/src/main/maker-host/provider-route.tsindex df53f90936..e8e7865370 100644--- a/apps/desktop/src/main/maker-host/provider-route.ts+++ b/apps/desktop/src/main/maker-host/provider-route.ts@@ -21,6 +21,7 @@import {actualSourceIdForModel,+ chatEligibleSourcesForModel,isExclusiveXaiModelId,resolvePiModelRoute,runtimeCustomProviderId,@@ -789,20 +790,55 @@ function providersForModel(modelId: string, agent: AgentKind) {);}-async function connectedDefaultProviderForModel(modelId: string, agent: AgentKind) {+type ConnectedDefaultProviderResolution =+ | { kind: 'provider'; provider: ProviderView }+ | { kind: 'ambiguous' }+ | { kind: 'none' };++async function connectedDefaultProviderForModel(+ modelId: string,+ agent: AgentKind,+): Promise<ConnectedDefaultProviderResolution> {const providers = await providerViewsReader();+ const eligible = chatEligibleSourcesForModel(providers, modelId, agent, {+ includeDisabled: true,+ });+ // Claude Code can emit its first request before the selected Provider is+ // bound to the session. If more than one connected source exposes the same+ // bare model id, choosing the native default/first source would risk sending+ // that prompt to a Provider the user did not select. Fail closed until the+ // session binding arrives; Codex retains its established native-default+ // semantics because its implicit bridge is also used for explicit prefixes.+ if (agent === 'claude-code' && eligible.length > 1) return { kind: 'ambiguous' };// This runs while dispatching an already-created implicit-source session. Admission for new// sessions/model switches happened earlier; keep its retired/disabled source usable for resume.const defaultId = actualSourceIdForModel(providers, null, modelId, agent);- return providers.find((provider) => provider.id === defaultId) ?? null;+ const provider = eligible.find((candidate) => candidate.id === defaultId);+ return provider ? { kind: 'provider', provider } : { kind: 'none' };+}++/**+ * 隐式 bridge 的 wire 判定口径:目录条目未显式声明 wireProtocol 时按 agent 原生缺省+ * 推断(claude-code=anthropic-messages,codex=openai-responses;与 resolveVisionBackendRoute+ * 的缺省推断同源)。claude-code 的用户 Anthropic 兼容上游(如智谱)在目录里就是该 agent+ * 的缺省 wire,buildUserProvider 按约定省略该字段 —— 不做缺省推断,这些来源会被整体+ * 排除在隐式路由之外,裸 catalog id(如 glm-5.3)只能落默认网关吃 LiteLLM 模型校验层+ * 的 400(Invalid model name)。+ */+function implicitBridgeWire(+ routing: RoutingDescriptor | null,+ agent: AgentKind,+): RoutingDescriptor['wireProtocol'] {+ if (routing?.wireProtocol) return routing.wireProtocol;+ if (agent === 'claude-code') return 'anthropic-messages';+ if (agent === 'codex') return 'openai-responses';+ return undefined;}function hasImplicitLocalBridgeCandidate(modelId: string, agent: AgentKind): boolean {return providersForModel(modelId, agent).some((provider) => {- const routing = providerRoutingForModel(provider, agent, modelId);- return (- routing?.wireProtocol === 'openai-chat' || routing?.wireProtocol === 'anthropic-messages'- );+ const wire = implicitBridgeWire(providerRoutingForModel(provider, agent, modelId), agent);+ return wire === 'openai-chat' || wire === 'anthropic-messages';});}@@ -819,6 +855,35 @@ export function inferProviderIdForModel(modelId: string, agent: AgentKind): strireturn uniqueProviderForModel(modelId, agent)?.id ?? null;}+export type ImplicitLocalBridgeRouteResolution =+ | { kind: 'route'; route: ResolvedSessionRoute }+ | { kind: 'ambiguous' }+ | { kind: 'none' };++/**+ * Resolve an implicit bridge route while preserving the distinction between+ * no connected source and multiple connected sources. Claude Code callers+ * must refuse the latter until the session's explicit Provider binding arrives.+ */+export async function resolveImplicitLocalBridgeRouteResolution(+ modelId: string,+ agent: AgentKind,+): Promise<ImplicitLocalBridgeRouteResolution> {+ const catalogModelId = modelId.replace(/\[1m\]$/, '');+ if (!hasImplicitLocalBridgeCandidate(catalogModelId, agent)) {+ return { kind: 'none' };+ }+ const source = await connectedDefaultProviderForModel(catalogModelId, agent);+ if (source.kind !== 'provider') return source;+ const routing = providerRoutingForModel(source.provider, agent, modelId);+ const wire = implicitBridgeWire(routing, agent);+ if (wire !== 'openai-chat' && wire !== 'anthropic-messages') {+ return { kind: 'none' };+ }+ const route = await resolveProviderRouteById(source.provider.id, agent, modelId);+ return route ? { kind: 'route', route } : { kind: 'none' };+}+/*** 隐式本地 bridge 来源:会话未显式选 Provider 时,按模型选择器相同的原生默认来源* 解析 Provider;只有最终来源明确声明 Chat / Anthropic Messages wire 才接管。@@ -830,21 +895,9 @@ export function resolveImplicitLocalBridgeRoute(modelId: string,agent: AgentKind,): Promise<ResolvedSessionRoute | null> {- const catalogModelId = modelId.replace(/\[1m\]$/, '');- // Most Codex requests are native OpenAI Responses and do not need provider- // connection resolution. Keep credential-store reads off that hot path; only- // bridge-capable catalog models need the live connected-provider snapshot.- if (!hasImplicitLocalBridgeCandidate(catalogModelId, agent)) {- return Promise.resolve(null);- }- return connectedDefaultProviderForModel(catalogModelId, agent).then((provider) => {- if (!provider) return null;- const routing = providerRoutingForModel(provider, agent, modelId);- if (routing?.wireProtocol !== 'openai-chat' && routing?.wireProtocol !== 'anthropic-messages') {- return null;- }- return resolveProviderRouteById(provider.id, agent, modelId);- });+ return resolveImplicitLocalBridgeRouteResolution(modelId, agent).then((resolution) =>+ resolution.kind === 'route' ? resolution.route : null,+ );}/**