Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(providers): 独立订阅账号继承原生启动与辅助调用能力
Dashe5815d200a5e
diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeBehaviorFlags.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeBehaviorFlags.test.tsindex 4723a47e3b..5f116310d1 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeBehaviorFlags.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeBehaviorFlags.test.ts@@ -4,6 +4,14 @@ import { claudeBehaviorFlagsForSpawn, claudeToolSearchMode } from '../claude-behimport { shouldCloseSessionForCredentialSwitch } from '../codex-credential-switch.js';describe('claudeBehaviorFlagsForSpawn', () => {+ it('preserves native subscription flags for independent Claude accounts', () => {+ const flags = claudeBehaviorFlagsForSpawn({ providerId: 'anthropic-work',+ nativeAuth: 'claude', credentialMode: 'provider-oauth', oauthConnected: () => true });+ expect(flags.CLAUDE_CODE_ATTRIBUTION_HEADER).toBe('1');+ expect(flags.ENABLE_TOOL_SEARCH).toBe('auto');+ expect(claudeToolSearchMode('grok-work', 'provider-oauth', 'xai')).toBe('false');+ });+it('disables attribution for gateway-key spawns without touching the keychain', () => {// 显式 XD source / SSH remote 恒为 gateway-key:请求全走网关,无订阅直连路径。// oauthConnected 必须不被调用 —— spawn 热路径不为此分支付出钥匙串读取。diff --git a/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.tsindex a4c5628dcb..ca72c828b0 100644--- a/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/model-context-limit-store.test.ts@@ -11,6 +11,9 @@ vi.mock('electron', () => ({app: { getPath: vi.fn(() => tempRoot) },}));+// Budget reconciliation does not exercise native account credential IO.+vi.mock('../subscription-account-auth.js', () => ({ readClaudeAccountOAuth: () => null }));+vi.mock('../logger-adapter.js', () => ({desktopMakerLogger: {child: () => ({ info: vi.fn(), warn: vi.fn(), debug: vi.fn() }),diff --git a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.tsindex 91c15edc14..367fbf3b93 100644--- a/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/runtimeConfigs.test.ts@@ -124,3 +124,28 @@ describe('runtime-configs', () => {}});});++it('uses only the selected independent Claude credentials for native spawn flags', async () => {+ vi.resetModules();+ const readAccount = vi.fn(() => ({ accessToken: 'work-token' }));+ const readBuiltin = vi.fn(() => false);+ vi.doMock('../active-catalog.js', () => ({ getActiveCatalog: () => ({ providers: [+ { id: 'claude-work', auth: { method: 'oauth', native: 'claude' } },+ ] }) }));+ vi.doMock('../subscription-account-auth.js', () => ({ readClaudeAccountOAuth: readAccount }));+ vi.doMock('../claude-credentials-store.js', () => ({ hasClaudeAiOAuth: readBuiltin }));+ try {+ const { buildDesktopClaudeRuntimeConfig } = await import('../runtime-configs.js');+ const flags = buildDesktopClaudeRuntimeConfig(() => 'http://localhost').behaviorFlags;+ if (typeof flags !== 'function') throw new Error('expected spawn flags');+ expect(flags({ credentialMode: 'provider-oauth', sessionProviderId: 'claude-work' } as never))+ .toMatchObject({ CLAUDE_CODE_ATTRIBUTION_HEADER: '1', ENABLE_TOOL_SEARCH: 'auto' });+ expect(readAccount).toHaveBeenCalledWith('claude-work');+ expect(readBuiltin).not.toHaveBeenCalled();+ } finally {+ vi.doUnmock('../active-catalog.js');+ vi.doUnmock('../subscription-account-auth.js');+ vi.doUnmock('../claude-credentials-store.js');+ vi.resetModules();+ }+});diff --git a/apps/desktop/src/main/maker-host/claude-behavior-flags.ts b/apps/desktop/src/main/maker-host/claude-behavior-flags.tsindex c88bc5ac73..524b86929a 100644--- a/apps/desktop/src/main/maker-host/claude-behavior-flags.ts+++ b/apps/desktop/src/main/maker-host/claude-behavior-flags.ts@@ -35,9 +35,10 @@ const STATIC_CLAUDE_BEHAVIOR_FLAGS: Readonly<Record<string, string>> = {export function claudeToolSearchMode(providerId: string | null | undefined,credentialMode?: string,+ nativeAuth?: string,): 'auto' | 'false' {const provider = providerId?.trim() || null;- if (provider) return provider === 'xd' || provider === 'anthropic' ? 'auto' : 'false';+ if (provider) return provider === 'xd' || provider === 'anthropic' || nativeAuth === 'claude' ? 'auto' : 'false';return credentialMode === 'provider-oauth' ? 'false' : 'auto';}@@ -46,6 +47,7 @@ export interface ClaudeSpawnFlagsContext {credentialMode?: string;/** 本次 spawn 的会话来源。null/undefined = 隐式默认路由。 */providerId?: string | null;+ nativeAuth?: string;/** 是否连了 Claude.ai 订阅。惰性回调:gateway-key 分支不调用、不产生钥匙串读。 */oauthConnected: () => boolean;}@@ -58,7 +60,7 @@ export function claudeBehaviorFlagsForSpawn(ctx: ClaudeSpawnFlagsContext): Recor// '0'/'false'/'no'/'off' 视为禁用,'1' = 保留归因,与未设置同义。return {...STATIC_CLAUDE_BEHAVIOR_FLAGS,- ENABLE_TOOL_SEARCH: claudeToolSearchMode(ctx.providerId, ctx.credentialMode),+ ENABLE_TOOL_SEARCH: claudeToolSearchMode(ctx.providerId, ctx.credentialMode, ctx.nativeAuth),CLAUDE_CODE_ATTRIBUTION_HEADER: keepAttribution ? '1' : '0',};}diff --git a/apps/desktop/src/main/maker-host/codex-credential-switch.ts b/apps/desktop/src/main/maker-host/codex-credential-switch.tsindex 9eec888b5b..70e9a4a83c 100644--- a/apps/desktop/src/main/maker-host/codex-credential-switch.ts+++ b/apps/desktop/src/main/maker-host/codex-credential-switch.ts@@ -308,8 +308,8 @@ export function shouldCloseSessionForCredentialSwitch(// provider-oauth 凭证家族可复用,也必须重建本会话,不能把旧 flag 热切到新来源。if (input.agentKind === 'claude-code' &&- claudeToolSearchMode(currentProviderId, currentMode) !==- claudeToolSearchMode(nextProviderId, nextMode)+ claudeToolSearchMode(currentProviderId, currentMode, getActiveCatalog().providers.find(p => p.id === currentProviderId)?.auth.native) !==+ claudeToolSearchMode(nextProviderId, nextMode, getActiveCatalog().providers.find(p => p.id === nextProviderId)?.auth.native)) {return true;}diff --git a/apps/desktop/src/main/maker-host/runtime-configs.ts b/apps/desktop/src/main/maker-host/runtime-configs.tsindex ba1911eb32..c388a08233 100644--- a/apps/desktop/src/main/maker-host/runtime-configs.ts+++ b/apps/desktop/src/main/maker-host/runtime-configs.ts@@ -19,6 +19,7 @@ import { getActiveCatalog } from './active-catalog.js';import { readModelDisableOverrides } from './model-disable-store.js';import { claudeBehaviorFlagsForSpawn } from './claude-behavior-flags.js';import { hasClaudeAiOAuth } from './claude-credentials-store.js';+import { readClaudeAccountOAuth } from './subscription-account-auth.js';import claudeSystemPrompt from './claude-system-prompt.md?raw';import codexSystemPrompt from './codex-system-prompt.md?raw';import hostSystemPrompt from './host-system-prompt.md?raw';@@ -170,7 +171,9 @@ export function buildDesktopClaudeRuntimeConfig(endpointFn: () => string): Agent...claudeBehaviorFlagsForSpawn({credentialMode: ctx.credentialMode,providerId: ctx.sessionProviderId,- oauthConnected: hasClaudeAiOAuth,+ nativeAuth: getActiveCatalog().providers.find(p => p.id === ctx.sessionProviderId)?.auth.native,+ oauthConnected: () => getActiveCatalog().providers.find(p => p.id === ctx.sessionProviderId)?.auth.native === 'claude'+ ? Boolean(readClaudeAccountOAuth(ctx.sessionProviderId!)?.accessToken) : hasClaudeAiOAuth(),}),// 工具链限核 env(agent 资源占用治理):只对本机 spawn 注入 —— 值按本机// 核数算,远端机器的资源不归本设置管。设置关闭时为空对象,零影响。diff --git a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.tsindex 1b4c159074..925c39fbae 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneShotCandidates.test.ts@@ -1,3 +1,5 @@+import { getValidClaudeAccountOAuth } from '../../maker-host/subscription-account-auth.js';+vi.mock('../../maker-host/subscription-account-auth.js', () => ({ getValidClaudeAccountOAuth: vi.fn() }));import { beforeEach, describe, expect, it, vi } from 'vitest';vi.mock('electron', () => ({@@ -147,6 +149,7 @@ function makerMock(authenticated: boolean): Maker {describe('utility one-shot candidates', () => {beforeEach(() => {+ vi.mocked(getValidClaudeAccountOAuth).mockReset();vi.clearAllMocks();fetchMock.mockReset();chainState.source = 'auto';@@ -2417,6 +2420,48 @@ describe('utility one-shot candidates', () => {expect(fetchMock).not.toHaveBeenCalled();});+ it.each(['claude', 'xai'] as const)('dispatches only the selected independent %s account and rejects changed credentials', async (native) => {+ const providerId = `${native}-work`;+ const agentKind = native === 'claude' ? 'claude-code' : 'codex';+ const model = native === 'claude' ? 'claude-haiku-4-5' : 'xai/grok-4.3';+ activeCatalog.mockReturnValue({ providers: [{ id: providerId, name: 'Work', source: 'user',+ agents: [agentKind], auth: { method: 'oauth', native },+ routing: { [agentKind]: { upstream: 'https://account.example/v1', authStrategy: 'provider-oauth-header' } },+ models: { [agentKind]: [{ id: model, name: model, contextWindow: 200_000 }] },+ }] } as never);+ vi.mocked(getValidClaudeAccountOAuth).mockResolvedValue({ accessToken: 'selected-token' } as never);+ readGrokToken.mockImplementation(async (id) => {+ if (id !== providerId) throw new Error('wrong account');+ return 'selected-token';+ });+ readClaudeOAuth.mockResolvedValue({ accessToken: 'other-token' } as never);+ fetchMock.mockResolvedValue({ ok: true, text: async () => native === 'claude'+ ? JSON.stringify({ content: [{ type: 'text', text: 'answer' }] })+ : JSON.stringify({ output_text: 'answer' }) } as never);+ const result = await requestUtilityText(makerMock(false), 'generate', {+ providerId, agentKind, model, beforeDispatch: async () => true,+ });+ expect(result).toMatchObject({ ok: true, providerId, model });+ expect(fetchMock.mock.calls[0]?.[1]?.headers).toMatchObject({ Authorization: 'Bearer selected-token' });+ if (native === 'claude') {+ expect(getValidClaudeAccountOAuth).toHaveBeenCalledWith(providerId);+ expect(readClaudeOAuth).not.toHaveBeenCalled();+ } else expect(readGrokToken).toHaveBeenCalledWith(providerId);+ fetchMock.mockClear();+ const changed = await requestUtilityText(makerMock(false), 'generate', {+ providerId, agentKind, model, beforeDispatch: async () => {+ vi.mocked(getValidClaudeAccountOAuth).mockResolvedValue(null);+ readGrokToken.mockRejectedValue(new Error('logged out'));+ return true;+ },+ });+ expect(changed.ok).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ const missing = await requestUtilityText(makerMock(false), 'generate', { providerId, agentKind, model });+ expect(missing.ok).toBe(false);+ expect(fetchMock).not.toHaveBeenCalled();+ });+it('uses xAI OAuth and the selected xAI Responses route', async () => {activeCatalog.mockReturnValue({providers: [{diff --git a/apps/desktop/src/main/utility-model/__tests__/oneshotProviderUsability.test.ts b/apps/desktop/src/main/utility-model/__tests__/oneshotProviderUsability.test.tsindex f215539524..c0ec800f5e 100644--- a/apps/desktop/src/main/utility-model/__tests__/oneshotProviderUsability.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/oneshotProviderUsability.test.ts@@ -1,3 +1,7 @@+import { codexAccountState } from '../../maker-host/codex-account-auth.js';+import { readClaudeAccountOAuth } from '../../maker-host/subscription-account-auth.js';+vi.mock('../../maker-host/codex-account-auth.js', () => ({ codexAccountState: vi.fn() }));+vi.mock('../../maker-host/subscription-account-auth.js', () => ({ readClaudeAccountOAuth: vi.fn() }));/*** oneshotProviderUsability.test.ts — 凭证同步探测单测(store 全 mock)。*/@@ -137,3 +141,21 @@ describe('hasOneshotProviderCredential · 自定义供应商', () => {expect(hasOneshotProviderCredential(noRouting, 'codex')).toBe(false);});});++it('probes each native account instead of borrowing the builtin login', () => {+ vi.mocked(readClaudeAccountOAuth).mockReturnValue({ accessToken: 'a' } as never);+ vi.mocked(codexAccountState).mockReturnValue({ authenticated: true });+ vi.mocked(hasGrokOAuthLogin).mockReturnValue(true);+ for (const native of ['claude', 'codex', 'xai'] as const) {+ const p = provider({ id: `${native}-work`, source: 'user', auth: { method: 'oauth', native } });+ expect(hasOneshotProviderCredential(p, 'codex')).toBe(true);+ }+ expect(readClaudeAccountOAuth).toHaveBeenCalledWith('claude-work');+ expect(codexAccountState).toHaveBeenCalledWith('codex-work');+ expect(hasGrokOAuthLogin).toHaveBeenCalledWith('xai-work');+ vi.mocked(readClaudeAccountOAuth).mockReturnValue(null);+ vi.mocked(codexAccountState).mockReturnValue({ authenticated: false });+ vi.mocked(hasGrokOAuthLogin).mockReturnValue(false);+ for (const native of ['claude', 'codex', 'xai'] as const)+ expect(hasOneshotProviderCredential(provider({ id: `${native}-work`, source: 'user', auth: { method: 'oauth', native } }), 'codex')).toBe(false);+});diff --git a/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts b/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.tsindex ce7be9faed..ff2c32ff3b 100644--- a/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts+++ b/apps/desktop/src/main/utility-model/__tests__/textOneshotPinOptions.test.ts@@ -473,3 +473,14 @@ describe('resolveOneshotCatalogModel', () => {expect(resolveOneshotCatalogModel(catalog, undefined, 'gpt-retired')).toBeNull();});});++it.each(['claude', 'xai', 'codex'] as const)('lists an independent %s account using its own pin identity', (native) => {+ const p = provider({ id: `${native}-work`, source: 'user', agents: ['codex'],+ auth: { method: 'oauth', native },+ routing: { codex: { upstream: 'https://account.example/v1', authStrategy: 'provider-oauth-header' } },+ models: { codex: [chat('gpt-5.5', { mode: 'chat' })] } });+ expect(buildTextOneshotPinOptions(catalogOf(p), undefined)).toEqual([+ expect.objectContaining({ providerId: p.id, id: encodeCatalogPin(p.id, 'codex', 'gpt-5.5') }),+ ]);+ expect(buildTextOneshotPinOptions(catalogOf({ ...p, routing: { codex: { ...p.routing.codex!, disabled: true } } }), undefined)).toEqual([]);+});diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.tsindex fb31f20205..680074679a 100644--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts@@ -1,4 +1,4 @@-import { isOpenAiSubscriptionProvider } from '@cindy/model-providers';+import { isOpenAiSubscriptionProvider, providerCatalogId } from '@cindy/model-providers';import { randomUUID } from 'node:crypto';import { type AgentKind, type Maker } from '@cindy/maker-core';@@ -14,6 +14,7 @@ import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionSimport { readClaudeApiKey } from '../maker-host/auth-adapters.js';import { getChatgptBridgeAuth } from '../maker-host/anthropic-responses-bridge-host.js';import { getValidClaudeAiOAuth } from '../maker-host/claude-oauth-refresh.js';+import { getValidClaudeAccountOAuth } from '../maker-host/subscription-account-auth.js';import { getGrokAccessToken } from '../maker-host/grok-oauth-login.js';import { readCachedGenericOAuthAccessToken } from '../maker-host/generic-oauth.js';// undici 的 fetch,但 per-request 现取系统代理(裸 undici 不吃代理设置)。@@ -859,7 +860,7 @@ async function requestExplicitProviderText(opts = { ...opts, maxTokens: Math.min(opts.maxTokens, catalogModel.maxOutput) };}- if (provider.id === 'xd' || provider.id === 'anthropic' || isOpenAiSubscriptionProvider(provider) || provider.id === 'xai') {+ if (provider.id === 'xd' || providerCatalogId(provider) === 'anthropic' || isOpenAiSubscriptionProvider(provider) || providerCatalogId(provider) === 'xai') {return requestBuiltinProviderText(prompt, {provider,agentKind,@@ -1123,8 +1124,10 @@ async function requestBuiltinProviderText(}], prompt, [], input);}- if (input.provider.id === 'anthropic') {- const oauth = await getValidClaudeAiOAuth();+ if (providerCatalogId(input.provider) === 'anthropic') {+ const readOAuth = () => input.provider.id === 'anthropic'+ ? getValidClaudeAiOAuth() : getValidClaudeAccountOAuth(input.provider.id);+ const oauth = await readOAuth();if (input.signal?.aborted) return cancelledUtilityTextResult(profile);if (!oauth?.accessToken) {return { ok: false, reason: 'no_candidate', attempts: [skippedAttempt(profile, 'not_authenticated')] };@@ -1163,7 +1166,7 @@ async function requestBuiltinProviderText(}): undefined,credentialStillCurrent: requestOpts?.beforeDispatch- ? async () => (await getValidClaudeAiOAuth())?.accessToken === oauth.accessToken+ ? async () => (await readOAuth())?.accessToken === oauth.accessToken: undefined,routeStillCurrent: requestOpts?.beforeDispatch ? input.routeStillCurrent : undefined,}),@@ -1233,10 +1236,10 @@ async function requestBuiltinProviderText(}], prompt, [], input);}- if (input.provider.id === 'xai') {+ if (providerCatalogId(input.provider) === 'xai') {let accessToken: string;try {- accessToken = await getGrokAccessToken();+ accessToken = await (input.provider.id === 'xai' ? getGrokAccessToken() : getGrokAccessToken(input.provider.id));} catch {return { ok: false, reason: 'no_candidate', attempts: [skippedAttempt(profile, 'not_authenticated')] };}@@ -1270,7 +1273,7 @@ async function requestBuiltinProviderText(credentialStillCurrent: requestOpts?.beforeDispatch? async () => {try {- return (await getGrokAccessToken()) === accessToken;+ return (await (input.provider.id === 'xai' ? getGrokAccessToken() : getGrokAccessToken(input.provider.id))) === accessToken;} catch {return false;}diff --git a/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts b/apps/desktop/src/main/utility-model/oneshotProviderUsability.tsindex cf28d411c2..7901e8b4ec 100644--- a/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts+++ b/apps/desktop/src/main/utility-model/oneshotProviderUsability.ts@@ -1,3 +1,5 @@+import { codexAccountState } from '../maker-host/codex-account-auth.js';+import { readClaudeAccountOAuth } from '../maker-host/subscription-account-auth.js';/*** oneshotProviderUsability.ts — 快问快答钉档的「已配置凭证」同步探测。*@@ -21,6 +23,11 @@ import { readCustomProviderKey } from '../secrets/providerSecretStore.js';* 自定义供应商分支)的凭证判读逐一对应;内置只认执行侧可执行的四家。*/export function hasOneshotProviderCredential(provider: Provider, agentKind: AgentKind): boolean {+ if (provider.source !== 'builtin') {+ if (provider.auth.native === 'claude') return Boolean(readClaudeAccountOAuth(provider.id)?.accessToken);+ if (provider.auth.native === 'xai') return hasGrokOAuthLogin(provider.id);+ if (provider.auth.native === 'codex') return codexAccountState(provider.id).authenticated;+ }if (provider.source === 'builtin') {switch (provider.id) {case 'xd':diff --git a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts b/apps/desktop/src/main/utility-model/textOneshotPinOptions.tsindex d70b8827df..134d8747a9 100644--- a/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts+++ b/apps/desktop/src/main/utility-model/textOneshotPinOptions.ts@@ -80,7 +80,7 @@ function isRoutableForOneshot(provider: Provider, agentKind: AgentKind): booleanif (!provider.agents.includes(agentKind)) return false;const routing = provider.routing[agentKind];if (!routing || routing.disabled) return false;- if (isOpenAiSubscriptionProvider(provider)) return true;+ if (isOpenAiSubscriptionProvider(provider) || provider.auth.native === 'claude' || provider.auth.native === 'xai') return true;if (provider.source === 'builtin') return ONESHOT_EXECUTABLE_BUILTIN_PROVIDERS.has(provider.id);if (agentKind === 'claude-code') {if (routing.wireProtocol !== undefined && routing.wireProtocol !== 'anthropic-messages') return false;