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 bf19e0ded53..f5fb632c1c5 100644 --- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts +++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts @@ -45,6 +45,7 @@ vi.mock('electron', () => ({ import { buildXaiPiNativeProvider, + createPiSubscriptionConnectionReader, buildPiNativeProvidersFromConfigs, buildPiSubscriptionNativeProviders, mergePiNativeProviderResults, @@ -67,6 +68,10 @@ import { deriveAvailableModels } from '../catalog-to-descriptors.js'; type Cfg = Parameters[0][number]; +/** 连接态判定只需要目录里的 provider 身份与 auth 家族标记。 */ +const catalogOf = (providers: unknown[]): Catalog => + ({ providers } as unknown as Catalog); + // #10434, unit: an empty UI intensity ladder must not disable the native switch. it.each(['xiaomi', 'xiaomi-token-plan-cn', 'xiaomi-token-plan-ams', 'xiaomi-token-plan-sgp'])( 'retains the %s native Pi on/off map behind the visible switch', source => { @@ -169,6 +174,106 @@ it('materializes a separate native ChatGPT provider for each independent account expect(account.models.map((model) => model.id)).toEqual(builtin.models.map((model) => model.id)); }); +// #12298: 订阅来源的连接态判定(桌面装配用的纯读判据)。 +describe('Pi subscription connection reader (#12298)', () => { + const build = (options: { + providers?: unknown[]; + grokLogin?: boolean; + codexAuthenticated?: boolean; + codexLogin?: boolean; + poolConnected?: boolean; + onReadFailure?: (providerId: string, error: unknown) => void; + }) => { + const hasGrokOAuthLogin = vi.fn(() => options.grokLogin ?? false); + const codexAccountState = vi.fn(() => ({ authenticated: options.codexAuthenticated ?? false })); + const hasCodexOAuthLoginReadOnly = vi.fn(() => options.codexLogin ?? false); + const hasConnectedSubscriptionPool = vi.fn(() => options.poolConnected ?? false); + const reader = createPiSubscriptionConnectionReader({ + getActiveCatalog: () => catalogOf(options.providers ?? []), + hasGrokOAuthLogin, + codexAccountState, + hasCodexOAuthLoginReadOnly, + hasConnectedSubscriptionPool, + onReadFailure: options.onReadFailure, + }); + return { + reader, + hasGrokOAuthLogin, + codexAccountState, + hasCodexOAuthLoginReadOnly, + hasConnectedSubscriptionPool, + }; + }; + + it('reports the ChatGPT subscription as connected through either credential path', () => { + const viaLogin = build({ codexLogin: true }); + expect(viaLogin.reader('openai')).toBe(true); + expect(viaLogin.hasConnectedSubscriptionPool).not.toHaveBeenCalled(); + + const viaPool = build({ poolConnected: true }); + expect(viaPool.reader('openai')).toBe(true); + expect(viaPool.hasConnectedSubscriptionPool) + .toHaveBeenCalledWith('openai', { includeBoundAccounts: true }); + }); + + it('reports the ChatGPT subscription as disconnected when neither path has a credential', () => { + const { reader } = build({}); + expect(reader('openai')).toBe(false); + }); + + it('reads the xAI family from the Grok OAuth login state', () => { + const connected = build({ + providers: [{ id: 'xai', auth: { method: 'oauth' } }], + grokLogin: true, + }); + expect(connected.reader('xai')).toBe(true); + expect(connected.hasGrokOAuthLogin).toHaveBeenCalledWith('xai'); + + const disconnected = build({ + providers: [{ id: 'xai', auth: { method: 'oauth' } }], + grokLogin: false, + }); + expect(disconnected.reader('xai')).toBe(false); + }); + + it('reads an independent Codex account from its own login state', () => { + const { reader, codexAccountState } = build({ + providers: [{ id: 'openai-a', auth: { method: 'oauth', native: 'codex' } }], + codexAuthenticated: true, + }); + expect(reader('openai-a')).toBe(true); + expect(codexAccountState).toHaveBeenCalledWith('openai-a'); + }); + + it('reads the ChatGPT subscription without a pool to read', () => { + // Node Host 没有账号池可读(它的订阅账号各自判自己的登录态):只有本机登录这一条。 + const reader = createPiSubscriptionConnectionReader({ + getActiveCatalog: () => catalogOf([]), + hasGrokOAuthLogin: () => false, + codexAccountState: () => ({ authenticated: false }), + hasCodexOAuthLoginReadOnly: () => true, + }); + expect(reader('openai')).toBe(true); + }); + + it('keeps a source listed when the connection read fails', () => { + const onReadFailure = vi.fn(); + const reader = createPiSubscriptionConnectionReader({ + getActiveCatalog: () => catalogOf([{ id: 'openai-a', auth: { method: 'oauth', native: 'codex' } }]), + hasGrokOAuthLogin: () => false, + codexAccountState: () => { throw new Error('secret store unavailable'); }, + hasCodexOAuthLoginReadOnly: () => false, + hasConnectedSubscriptionPool: () => false, + onReadFailure, + }); + // 读不到结论时不得剔除来源。 + expect(reader('openai-a')).toBe(true); + expect(onReadFailure).toHaveBeenCalledWith('openai-a', expect.any(Error)); + // 目录里没有的来源也不剔除。 + expect(reader('unknown-provider')).toBe(true); + }); +}); + it.each(['google/gemini-3.8-flash', 'google/gemini-99-pro-preview'])( 'uses the Global Gateway Responses route for %s in local and remote Pi', (id) => { diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.ts index 4a430dd25a1..047ad794b87 100644 --- a/apps/desktop/src/main/maker-host/pi-host.ts +++ b/apps/desktop/src/main/maker-host/pi-host.ts @@ -84,7 +84,8 @@ import { } from './anthropic-compat-proxy-host.js'; import { hostCredentialEndpointAllowed } from './pi-provider-transport.js'; import { hasGrokOAuthLogin } from './grok-oauth-login.desktop.js'; -import { isOpenAiSubscriptionProviderId } from './codex-account-auth.desktop.js'; +import { codexAccountState, isOpenAiSubscriptionProviderId } from './codex-account-auth.desktop.js'; +import { hasConnectedSubscriptionPool } from '../subscription-accounts/runtime.js'; import { withProviderAppAttribution } from './provider-app-attribution.js'; import { createLogger } from '../logger.js'; import { registerPiProxySession } from './pi-proxy-session-auth.js'; @@ -107,11 +108,13 @@ import { import { mutateAuthorizedPiManagedPackage } from './pi-managed-package-mutation.js'; import { createPiNativeProviderResolver, + createPiSubscriptionConnectionReader, resolvePiCindyGatewayModelApi, resolvePiCindyGatewayModelSpec, } from './piNativeProvidersCore.js'; export { buildPiSubscriptionNativeProviders, + createPiSubscriptionConnectionReader, listedPiModelIds, mergePiNativeProviderResults, parsePiListModels, @@ -140,6 +143,28 @@ export function resolvePiBinaryPath(): string | null { return getReadyBinaryPath('pi') ?? null; } +/** + * #12298: 订阅来源的连接态(与「设置 → 模型供应商」列表同口径,纯读、无自愈副作用)。 + * 断开的订阅仍留在会话目录里(重连后父会话可直接切换),但子代理路由不能列它。 + * + * 它接在 AgentDeps.isNativeProviderSourceConnected 上,不进入 provider 清单本身 —— + * 清单是桌面与 Node Host 的逐字节契约(host↔desktop parity),连接态是宿主各自的凭证事实。 + */ +const subscriptionSourceConnected = createPiSubscriptionConnectionReader({ + getActiveCatalog, + hasGrokOAuthLogin, + codexAccountState, + hasCodexOAuthLoginReadOnly: () => desktopCodexAuthAdapter.hasCodexOAuthLoginReadOnly(), + hasConnectedSubscriptionPool, + onReadFailure: (providerId, error) => log.warn( + 'pi: subscription connection read failed; keeping the source listed', + { + providerId, + message: error instanceof Error ? error.message : String(error), + }, + ), +}); + // The desktop's ports for the Pi native providers shared with the Node Host (piNativeProvidersCore.ts). const piNativeProviderResolver = createPiNativeProviderResolver({ getClaudeEndpoint: () => getClaudeEndpoint(), @@ -393,6 +418,8 @@ export function buildPiAgent(opts: BuildPiAgentOpts): PiAgent | null { }, registerPiProxySession, resolvePiNativeProviders: (ctx) => resolvePiNativeProviders(ctx), + // #12298: 子代理路由不列确知断开的订阅来源(连接态是桌面宿主的凭证事实,纯读)。 + isNativeProviderSourceConnected: subscriptionSourceConnected, resolvePiRuntimeModelDescriptor: opts.resolvePiRuntimeModelDescriptor, resolvePiRuntimeModels: opts.resolvePiRuntimeModels, resolvePiGatewayModelDescriptor: opts.resolvePiGatewayModelDescriptor, diff --git a/apps/desktop/src/main/maker-host/piNativeProvidersCore.ts b/apps/desktop/src/main/maker-host/piNativeProvidersCore.ts index 8f43b0aa082..da6b15753d4 100644 --- a/apps/desktop/src/main/maker-host/piNativeProvidersCore.ts +++ b/apps/desktop/src/main/maker-host/piNativeProvidersCore.ts @@ -388,6 +388,72 @@ export async function readPiBundledModels( } +/** + * #12298: 订阅来源的连接态判定(供启动器接到 AgentDeps.isNativeProviderSourceConnected)。 + * + * 断开的订阅仍留在会话目录里(重连后父会话可直接切换),但子代理路由不能列它: + * 按这些名字派发的子任务会在首次上游请求时必败(空 runId + 噪声失败通知)。 + * + * 判定口径与「设置 → 模型供应商」列表一致,且是纯读(不触发绑定自愈、不写凭证文件): + * · xAI 家族(内置 SuperGrok 与独立账号)读 Grok OAuth 登录态; + * · Codex 家族账号读该账号自己的登录态(bridge 对非 'openai' 的 providerId 也用这一条); + * · 'openai'(ChatGPT 订阅)两条凭证路径任一可用即算连接 —— 本机 Codex 登录与账号池, + * bridge 实际按会话绑定的账号取凭证,只判一条会把仍可用的来源误删。 + * + * 读不到结论的来源一律按「连接」处理:只在确知断开时剔除,宁可多列也不误伤可用来源。 + * + * 桌面与 Node Host 各接各的凭证读数(port 注入),但判定规则共用这一份;连接态不进入 + * provider 清单本身 —— 清单是桌面与 Host 的逐字节契约(host↔desktop parity)。 + */ +export interface PiSubscriptionConnectionPorts { + /** 当前生效目录(判断来源属于哪个订阅家族)。 */ + getActiveCatalog: () => Catalog; + /** SuperGrok OAuth 登录态(providerId 缺省即内置 'xai')。 */ + hasGrokOAuthLogin: (providerId?: string) => boolean; + /** 独立 Codex 账号的登录态。 */ + codexAccountState: (providerId: string) => { authenticated: boolean }; + /** 本机 Codex(ChatGPT 订阅)登录态,纯读版。 */ + hasCodexOAuthLoginReadOnly: () => boolean; + /** + * ChatGPT 账号池里是否还有已连接的账号。桌面有这个账号池;Node Host 的订阅账号以 + * 独立来源出现(各自判自己的登录态),没有池可读 → 缺省即不读这一条。 + */ + hasConnectedSubscriptionPool?: ( + providerId: string, + options?: { includeBoundAccounts?: boolean }, + ) => boolean; + /** 读取结论失败时的兜底日志。 */ + onReadFailure?: (providerId: string, error: unknown) => void; +} + +export function createPiSubscriptionConnectionReader( + ports: PiSubscriptionConnectionPorts, +): (providerId: string) => boolean { + const { + getActiveCatalog, + hasGrokOAuthLogin, + codexAccountState, + hasCodexOAuthLoginReadOnly, + hasConnectedSubscriptionPool, + onReadFailure, + } = ports; + return (providerId: string): boolean => { + try { + const account = getActiveCatalog().providers.find((provider) => provider.id === providerId); + const native = account?.auth.native; + if (native === 'xai' || providerId === 'xai') return hasGrokOAuthLogin(providerId); + if (native === 'codex') return codexAccountState(providerId).authenticated; + if (providerId === 'openai') { + return hasCodexOAuthLoginReadOnly() + || Boolean(hasConnectedSubscriptionPool?.('openai', { includeBoundAccounts: true })); + } + } catch (error) { + onReadFailure?.(providerId, error); + } + return true; + }; +} + /** * Overlay Cindy's host-managed subscription endpoints onto PI's bundled * provider catalog. Resolved catalog metadata is authoritative for all subscription diff --git a/apps/host/src/agent/agent-deps-engines.ts b/apps/host/src/agent/agent-deps-engines.ts index 3e35ee7d26f..0bfb752d458 100644 --- a/apps/host/src/agent/agent-deps-engines.ts +++ b/apps/host/src/agent/agent-deps-engines.ts @@ -59,6 +59,9 @@ export const PORTS_ONLY_PI_READS = { getRemotePiAgentProxyEnv: undefined, getRemotePiFileOps: undefined, getRemotePiTransport: undefined, + // #12298: the Pi agent reads the host's subscription connection state; Claude and Codex route + // subagent models from their own catalogs and never consult it. + isNativeProviderSourceConnected: undefined, mutatePiManagedPackage: undefined, onPiManagedPackageMutationSettled: undefined, preparePiExtraSpawnConfig: undefined, diff --git a/apps/host/src/agent/pi-native-providers.ts b/apps/host/src/agent/pi-native-providers.ts index 6c868fa8691..6148152bf18 100644 --- a/apps/host/src/agent/pi-native-providers.ts +++ b/apps/host/src/agent/pi-native-providers.ts @@ -8,12 +8,21 @@ * - The Host has no managed local model runtime (Ollama, llama.cpp). It answers as the desktop's * preflight answers when that runtime is not ready: the same error codes and wording. */ +import path from 'node:path'; import { MANAGED_OLLAMA_PROVIDER_ID } from '../../../desktop/src/shared/localModelRuntime.js'; import { MANAGED_LLAMACPP_PROVIDER_ID } from '../../../desktop/src/shared/llamaCpp.js'; import { createPiNativeProviderResolver, + createPiSubscriptionConnectionReader, type PiNativeProviderPorts, } from '../../../desktop/src/main/maker-host/piNativeProvidersCore.js'; +import { getActiveCatalog } from '../../../desktop/src/main/maker-host/active-catalog.js'; +import { isNativeProviderAuthBound } from '../../../desktop/src/main/maker-host/nativeProviderAuthBinding.js'; +import { shouldSuppressLocalCodexAuth } from '../../../desktop/src/main/maker-host/codex-auth-invalidation.js'; +import { hasCodexOAuthLoginUnbound } from './codex-system-login.js'; +import { createLogger } from '../../../desktop/src/main/logger.js'; + +const log = createLogger('host-pi-native-providers'); /** The desktop preflight's not-ready errors (local-model-runtime/preflight.ts). */ export async function hostManagedLocalModelNotReady(input: { providerId: string; remoteHostId: string | null }): Promise { @@ -37,13 +46,16 @@ export function createHostPiNativeProviders(options: { list: PiNativeProviderPorts['listCustomProvidersWithSecureHeaders']; readKey: PiNativeProviderPorts['readCustomProviderKey']; grok: { hasGrokOAuthLogin(providerId?: string): boolean }; - codexAccounts: { isOpenAiSubscriptionProviderId(providerId?: string | null): boolean }; + codexAccounts: { + isOpenAiSubscriptionProviderId(providerId?: string | null): boolean; + codexAccountState(providerId: string): { authenticated: boolean }; + }; }; /** The desktop's first step before a local Pi (release table row 25); no-op when absent. */ ensureSharedGlobalSkills?: () => Promise; }) { const config = options.providerConfig; - return createPiNativeProviderResolver({ + const resolver = createPiNativeProviderResolver({ getClaudeEndpoint: () => options.endpoint(), isAnthropicCompatProxyHandleReady: () => options.claudeProxy?.isReady() ?? false, ensureAnthropicCompatProxyReady: () => options.claudeProxy?.ready?.() ?? Promise.resolve(), @@ -56,4 +68,28 @@ export function createHostPiNativeProviders(options: { ensureManagedOllamaReadyForSession: input => hostManagedLocalModelNotReady(input), getUserDataDir: () => options.userDataDir, }); + /** + * #12298: the Host's own credential state per subscription source (read-only). The + * desktop reads the desktop's stores; the Host reads the profile's — same rules, + * different facts. The state stays out of the provider list: that list is the + * byte-for-byte contract between the desktop and the Host. + */ + const subscriptionSourceConnected = createPiSubscriptionConnectionReader({ + getActiveCatalog, + hasGrokOAuthLogin: id => config.grok.hasGrokOAuthLogin(id), + codexAccountState: id => config.codexAccounts.codexAccountState(id), + hasCodexOAuthLoginReadOnly: () => hasHostCodexHomeLogin(path.join(options.userDataDir, 'codex-home')), + onReadFailure: (providerId, error) => log.warn( + 'pi: subscription connection read failed; keeping the source listed', + { providerId, message: error instanceof Error ? error.message : String(error) }, + ), + }); + return { ...resolver, subscriptionSourceConnected }; +} + +/** The profile's own Codex (ChatGPT subscription) login, as the desktop's read-only check. */ +function hasHostCodexHomeLogin(codexHome: string): boolean { + if (!isNativeProviderAuthBound('openai')) return false; + if (shouldSuppressLocalCodexAuth(codexHome, path.join(codexHome, 'auth.json'))) return false; + return hasCodexOAuthLoginUnbound(codexHome); } diff --git a/apps/host/src/agent/runtime.ts b/apps/host/src/agent/runtime.ts index 77b4b61c19d..1d036989b51 100644 --- a/apps/host/src/agent/runtime.ts +++ b/apps/host/src/agent/runtime.ts @@ -916,6 +916,9 @@ export function createHostAgentGraph(options: HostAgentGraphOptions) { // As the desktop (pi-host.ts): the shared resolver with the Host's ports (pi-native-providers.ts), // and the Cindy gateway block's API and compat from the same probe state. resolvePiNativeProviders: (ctx) => piNativeProviders.resolvePiNativeProviders(ctx), + // #12298: the Host's own subscription connection state (read-only), so subagent + // routes skip a source the Host knows is disconnected. + isNativeProviderSourceConnected: piNativeProviders.subscriptionSourceConnected, // As the desktop (pi-host.ts): durable Subagent runners, forked as Node child processes (pi-subagent-runner.ts). spawnPiSubagentRunner: (request) => spawnHostPiSubagentRunner(request), resolvePiManagedPackageResources: piPackages.deps.resolvePiManagedPackageResources, diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts index 428b785b346..ec125cf7790 100644 --- a/packages/maker-core/src/agents/base-agent.ts +++ b/packages/maker-core/src/agents/base-agent.ts @@ -907,6 +907,17 @@ export interface AgentDeps { }, ) => Promise; + /** + * Pi-only:宿主已知的订阅来源连接态(纯读,无自愈副作用)。 + * + * 子代理路由不列确知断开的来源:账号断开或被移除后目录里的模型名仍在,按这些名字 + * 派发的子任务会先建 run、随后在首次上游请求时因缺凭证必败(#12298)。 + * + * 入参是 provider 的**来源 id**(spec.sourceProviderId ?? spec.id),不是 Pi 侧的 provider id。 + * 缺省 / 读不到结论 → 视为连接,不过滤(宁可多列也不误伤可用来源)。 + */ + isNativeProviderSourceConnected?: (sourceProviderId: string) => boolean; + /** * Pi-only:按实际 provider/model 路由解析运行时描述符。用于启动前校验已持久化 effort, * 以及恢复已 retired 模型时补齐当前 session 的私有 models.json;结果不得进入公开 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 e5b22df9949..c98748b6d2c 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 @@ -3142,6 +3142,210 @@ describe("Pi provider-aware model routing", () => { await handle.close(); }); + // #12298: 断开的订阅来源不得进子代理路由 —— 按它的名字派发会在首次上游请求时必败。 + it("keeps a disconnected subscription source out of the subagent model routes", async () => { + const deps = byomDeps( + async () => ({ + providers: [ + { + id: "openai-codex", + sourceProviderId: "openai", + name: "OpenAI (ChatGPT)", + baseUrl: "http://openai.test", + api: "openai-codex-responses" as const, + modelIdAliases: { + "chatgpt/gpt-5.5-pro": "chatgpt/gpt-5.5-pro", + "gpt-5.5-pro": "chatgpt/gpt-5.5-pro", + }, + models: [{ id: "chatgpt/gpt-5.5-pro", wireId: "gpt-5.5-pro" }], + }, + { + id: "magpie", + sourceProviderId: "magpie-211d8cf5", + name: "Magpie", + baseUrl: "http://magpie.test", + api: "openai-responses" as const, + models: [{ id: "gpt-5.5-pro", wireId: "gpt-5.5-pro" }], + }, + ], + env: {}, + }), + [ + { + id: "local-model", + displayName: "Local", + contextWindow: 200_000, + efforts: [], + defaultEffort: null, + }, + ], + ); + // 宿主知道自己这条来源已断开(账号断开或被移除)。 + deps.isNativeProviderSourceConnected = sourceProviderId => sourceProviderId !== "openai"; + const handle = await new PiAgent(deps).startSession({ + sessionId: "subagent-disconnected-subscription", + workingDir: cwd, + model: "local-model", + providerId: "xd", + }); + const runtime = JSON.parse( + readFileSync( + runtimeFileOf("subagent", "subagent-disconnected-subscription"), + "utf8", + ), + ) as { + modelRoutes: Record< + string, + Array<{ provider: string; model: string; sourceProviderId?: string }> + >; + }; + // 断开来源的两个名字都不再出现在路由里。 + expect(runtime.modelRoutes["chatgpt/gpt-5.5-pro"]).toBeUndefined(); + // 另一个仍连接的同名来源照常可指定。 + expect(runtime.modelRoutes["gpt-5.5-pro"]).toEqual([ + { + provider: "magpie", + model: "gpt-5.5-pro", + sourceProviderId: "magpie-211d8cf5", + }, + ]); + await handle.close(); + }); + + it("keeps a subscription source the host knows is connected in the subagent model routes", async () => { + const deps = byomDeps( + async () => ({ + providers: [ + { + id: "openai-codex", + sourceProviderId: "openai", + name: "OpenAI (ChatGPT)", + baseUrl: "http://openai.test", + api: "openai-codex-responses" as const, + modelIdAliases: { + "chatgpt/gpt-5.5-pro": "chatgpt/gpt-5.5-pro", + }, + models: [{ id: "chatgpt/gpt-5.5-pro", wireId: "gpt-5.5-pro" }], + }, + { + id: "xai", + sourceProviderId: "xai", + name: "xAI", + baseUrl: "http://xai.test", + api: "openai-responses" as const, + models: [{ id: "xai/grok-4.6", wireId: "grok-4.6" }], + }, + ], + env: {}, + }), + [ + { + id: "local-model", + displayName: "Local", + contextWindow: 200_000, + efforts: [], + defaultEffort: null, + }, + ], + ); + deps.isNativeProviderSourceConnected = () => true; + const handle = await new PiAgent(deps).startSession({ + sessionId: "subagent-connected-subscription", + workingDir: cwd, + model: "local-model", + providerId: "xd", + }); + const runtime = JSON.parse( + readFileSync( + runtimeFileOf("subagent", "subagent-connected-subscription"), + "utf8", + ), + ) as { + modelRoutes: Record< + string, + Array<{ provider: string; model: string; sourceProviderId?: string }> + >; + }; + expect(runtime.modelRoutes["chatgpt/gpt-5.5-pro"]).toEqual([ + { + provider: "openai-codex", + model: "gpt-5.5-pro", + sourceProviderId: "openai", + }, + ]); + expect(runtime.modelRoutes["xai/grok-4.6"]).toEqual([ + { provider: "xai", model: "grok-4.6", sourceProviderId: "xai" }, + ]); + await handle.close(); + }); + + it("keeps subscription sources in the subagent model routes when the host has no connection state", async () => { + // 宿主没给判据(读不到结论)→ 不剔除:宁可多列也不误伤可用来源。 + const deps = byomDeps( + async () => ({ + providers: [ + { + id: "openai-codex", + sourceProviderId: "openai", + name: "OpenAI (ChatGPT)", + baseUrl: "http://openai.test", + api: "openai-codex-responses" as const, + modelIdAliases: { + "chatgpt/gpt-5.5-pro": "chatgpt/gpt-5.5-pro", + }, + models: [{ id: "chatgpt/gpt-5.5-pro", wireId: "gpt-5.5-pro" }], + }, + { + id: "xai", + sourceProviderId: "xai", + name: "xAI", + baseUrl: "http://xai.test", + api: "openai-responses" as const, + models: [{ id: "xai/grok-4.6", wireId: "grok-4.6" }], + }, + ], + env: {}, + }), + [ + { + id: "local-model", + displayName: "Local", + contextWindow: 200_000, + efforts: [], + defaultEffort: null, + }, + ], + ); + const handle = await new PiAgent(deps).startSession({ + sessionId: "subagent-unknown-connection-state", + workingDir: cwd, + model: "local-model", + providerId: "xd", + }); + const runtime = JSON.parse( + readFileSync( + runtimeFileOf("subagent", "subagent-unknown-connection-state"), + "utf8", + ), + ) as { + modelRoutes: Record< + string, + Array<{ provider: string; model: string; sourceProviderId?: string }> + >; + }; + expect(runtime.modelRoutes["chatgpt/gpt-5.5-pro"]).toEqual([ + { + provider: "openai-codex", + model: "gpt-5.5-pro", + sourceProviderId: "openai", + }, + ]); + expect(runtime.modelRoutes["xai/grok-4.6"]).toEqual([ + { provider: "xai", model: "grok-4.6", sourceProviderId: "xai" }, + ]); + await handle.close(); + }); + it("fails closed when provider-less aliases are ambiguous", async () => { const agent = new PiAgent( byomDeps(async () => ({ diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.ts index ff9b46cb526..4cf804c3604 100644 --- a/packages/maker-core/src/agents/pi/index.ts +++ b/packages/maker-core/src/agents/pi/index.ts @@ -3106,9 +3106,15 @@ export class PiAgent extends BaseAgent { }; for (const provider of nativeProviders) { if (provider.id === PI_PROVIDER_ID) continue; + const sourceProviderId = provider.sourceProviderId ?? provider.id; + // #12298: 宿主已知断开的订阅来源不进子代理路由。账号断开/移除后目录里的模型仍在, + // 父会话保留该 provider 块(重连后可直接切换),但子代理按这些名字派发会被接受, + // 然后在首次上游请求时必败(空 runId + 噪声失败通知)。路由不列即让调用方在派发前 + // 撞上现有的「model not available in this session」拒绝,不创建 run、不尝试转发; + // 显式选择不被静默替换成父模型。宿主没给判据 / 读不到结论 → 不过滤。 + if (this.deps.isNativeProviderSourceConnected?.(sourceProviderId) === false) continue; for (const model of provider.models) { const wireModel = model.wireId ?? model.id; - const sourceProviderId = provider.sourceProviderId ?? provider.id; const routeProxySessionToken = proxyTokenForSubagentProvider(provider, sourceProviderId); addSubagentModelRoute( model.id,