Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): refresh gateway credential hosts during rotation
liugaowei27c8b0a91240
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.tsindex f3561ff79d..dc9b973b0a 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexCredentialSwitch.test.ts@@ -735,6 +735,56 @@ describe('prepareLocalCodexCredentialModeSwitch', () => {describe('Codex host-scoped credential coordination', () => {+ it('soft-closes all selected gateway hosts while preserving busy siblings and history resources', async () => {+ const sideEffect = vi.fn(async () => undefined);+ const closeSession = vi.fn(async (sessionId: string) => {+ await rehydrateCloseSuppression.runOnCloseSideEffects(sessionId, sideEffect);+ });+ const result = await prepareLocalCodexCredentialModeSwitch({+ hostKeys: ['local', 'local-custom-context:gateway:external-auth'],+ maker: {+ listActiveSessions: () => [+ { id: 'shared', agentKind: 'codex', isTurnRunning: () => false },+ { id: 'isolated', agentKind: 'codex', codexHostKey: 'local-custom-context:gateway:external-auth', isTurnRunning: () => false },+ { id: 'oauth', agentKind: 'codex', codexHostKey: 'local-account:openai:oauth', isTurnRunning: () => true },+ { id: 'remote', agentKind: 'codex', remoteHostId: 'ssh', isTurnRunning: () => true },+ ],+ closeSession,+ },+ });+ expect(result.closedSessionIds).toEqual(['shared', 'isolated']);+ expect(closeSession.mock.calls.map(([id]) => id)).toEqual(['shared', 'isolated']);+ expect(sideEffect).not.toHaveBeenCalled();+ });++ it('refuses the entire key refresh before closing any selected busy host', async () => {+ const closeSession = vi.fn(async () => undefined);+ await expect(prepareLocalCodexCredentialModeSwitch({+ hostKeys: ['local', 'local:external-auth'],+ maker: {+ listActiveSessions: () => [+ { id: 'idle', agentKind: 'codex', codexHostKey: 'local', isTurnRunning: () => false },+ { id: 'busy', agentKind: 'codex', codexHostKey: 'local:external-auth', isTurnRunning: () => true },+ ],+ closeSession,+ },+ })).rejects.toThrow(/busy/);+ expect(closeSession).not.toHaveBeenCalled();+ });++ it('does not close sessions when no host uses the rotated key', async () => {+ const closeSession = vi.fn(async () => undefined);+ const result = await prepareLocalCodexCredentialModeSwitch({+ hostKeys: [],+ maker: {+ listActiveSessions: () => [{ id: 'oauth', agentKind: 'codex', isTurnRunning: () => true }],+ closeSession,+ },+ });+ expect(result.closedSessionIds).toEqual([]);+ expect(closeSession).not.toHaveBeenCalled();+ });+it.each(['local', 'local:external-auth'])('does not block or close a busy sibling when replacing %s', async (hostKey) => {const sibling = hostKey === 'local' ? 'local:external-auth' : 'local';const closeSession = vi.fn(async () => undefined);diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.tsindex 0945d76d27..684b09b393 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts@@ -30,7 +30,7 @@ import { buildUserProvider } from '@cindy/model-providers';import type { RoutingDecision } from '@cindy/anthropic-compat-proxy';import { setCustomProviders } from '../active-catalog';-import { createCodexGuestRoutingGuard, registerComposed, setCodexProxyGatewayKeyReader, unregister } from '../codex-proxy-host';+import { createCodexGuestRoutingGuard, registerComposed, unregister } from '../codex-proxy-host';import { CODEX_CUSTOM_PROVIDER_ROUTE_ROOT } from '../codex-custom-provider-route';import { registerGuestProviderRoute, resetGuestProviderRoutesForTest } from '../guest-provider-route-store';import { clearAllSessionProviders, setSessionProvider } from '../session-provider-store';@@ -65,7 +65,6 @@ describe('Codex proxy guard for shared-provider guests', () => {resetGuestProviderRoutesForTest();clearAllSessionProviders();setCustomProviders([]);- setCodexProxyGatewayKeyReader(() => null);});it('lets a guest request for a shared model continue to the session route', () => {@@ -89,17 +88,13 @@ describe('Codex proxy guard for shared-provider guests', () => {expect(await statusOf(guard({ model: 'shared-model' }, ctx('/responses', { 'thread-id': 'owner-thread' })))).toBe(403);});- it('routes an unresolved request with the current gateway key only when that is the shared provider', async () => {+ it('routes an unresolved request straight to the default upstream only when that is the shared provider', () => {const gateway = createCodexGuestRoutingGuard('xd', 'env-key');// 模型核对按 xd 的目录:这里的 fixture 没有 xd 模型,所以推理请求被拒;非推理路径只看默认路由。- setCodexProxyGatewayKeyReader(() => 'test-current-gateway-key');- expect(gateway({ model: 'gpt-image-1' }, ctx('/images/generations'))).toEqual({- headerOverride: { authorization: 'Bearer test-current-gateway-key' },- });- setCodexProxyGatewayKeyReader(() => null);- expect(await statusOf(gateway({ model: 'gpt-image-1' }, ctx('/images/generations')))).toBe(401);+ expect(gateway({ model: 'gpt-image-1' }, ctx('/images/generations'))).toBeNull();const mismatched = createCodexGuestRoutingGuard('xd', 'oauth-bearer');- expect(await statusOf(mismatched({ model: 'gpt-image-1' }, ctx('/images/generations')))).toBe(403);+ return statusOf(mismatched({ model: 'gpt-image-1' }, ctx('/images/generations')))+ .then((status) => expect(status).toBe(403));});it('leaves custom-provider paths and control-plane requests to the frozen routing', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex d7389d2b24..7588350e58 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -189,7 +189,7 @@ beforeAll(async () => {}, process.platform === 'win32' ? 120_000 : 60_000);-/** 本地拒绝的 localHandler:执行它并返回写出的状态码与响应体。 */+/** 本地 403 拒绝的 localHandler:执行它并返回写出的状态码与响应体。 */async function runLocalRefusal(decision: unknown): Promise<{ status: number; body: { error?: { code?: string } } }> {const handler = (decision as { localHandler?: (args: { res: unknown }) => Promise<void> }).localHandler;if (typeof handler !== 'function') throw new Error('expected a local refusal handler');@@ -677,10 +677,10 @@ describe('createCrossProviderCompactionCompatTransform', () => {describe('decideCodexRoute', () => {const CHATGPT = 'https://chatgpt.com/backend-api/codex';- it.each(['gpt-5.5', 'codex/gpt-5.5', ''])('env-key spawn → 用当前 gateway key 覆盖请求头: %s', async (model) => {+ it('env-key spawn → 不 override(codex 已带 gateway key, 走默认上游)', async () => {const { decideCodexRoute } = await import('../codex-proxy-host.js');- expect(decideCodexRoute({ model, authInjection: 'env-key', gatewayKey: 'test-current-gateway-key' }))- .toEqual({ headerOverride: { authorization: 'Bearer test-current-gateway-key' } });+ expect(decideCodexRoute({ model: 'gpt-5.5', authInjection: 'env-key', gatewayKey: 'k' })).toBeNull();+ expect(decideCodexRoute({ model: 'codex/gpt-5.5', authInjection: 'env-key', gatewayKey: 'k' })).toBeNull();});it('oauth-bearer + codex/ 折扣模型 → 换 gateway key', async () => {@@ -1401,7 +1401,7 @@ describe('chatBridgeCapabilitiesForRoute', () => {},));- expect(decision).toEqual({ headerOverride: { authorization: 'Bearer xd-gateway-key' } });+ expect(decision).toBeNull();expect(mockState.createResponsesAnthropicHandler).not.toHaveBeenCalled();host.unregister('session-xd-no-projection');@@ -1449,7 +1449,7 @@ describe('chatBridgeCapabilitiesForRoute', () => {},));- expect(decision).toEqual({ headerOverride: { authorization: 'Bearer xd-gateway-key' } });+ expect(decision).toBeNull();expect(mockState.createResponsesAnthropicHandler).not.toHaveBeenCalled();} finally {host.unregister('session-implicit-xd');@@ -1477,7 +1477,6 @@ describe('chatBridgeCapabilitiesForRoute', () => {);clearSessionProvider('session-native-hot-path');host.setCodexProxyAuthInjection('env-key');- host.setCodexProxyGatewayKeyReader(() => 'test-native-gateway-key');try {const decision = await Promise.resolve(host.createModelRoutingTransform()(@@ -1493,14 +1492,13 @@ describe('chatBridgeCapabilitiesForRoute', () => {},));- expect(decision).toEqual({ headerOverride: { authorization: 'Bearer test-native-gateway-key' } });+ expect(decision).toBeNull();expect(providerViewsReader).not.toHaveBeenCalled();} finally {host.unregister('session-native-hot-path');clearSessionProvider('session-native-hot-path');setProviderViewsReader(async () => []);setXdGatewayModels([]);- host.setCodexProxyGatewayKeyReader(() => null);}});@@ -2356,10 +2354,7 @@ describe('chatBridgeCapabilitiesForRoute', () => {},));- expect(await runLocalRefusal(decision)).toMatchObject({- status: 401,- body: { error: { code: 'cindy_gateway_credentials_unavailable' } },- });+ expect(decision).toBeNull();expect(mockState.createResponsesAnthropicHandler).not.toHaveBeenCalled();clearSessionProvider('session-xd-no-key');@@ -2563,44 +2558,11 @@ describe('createModelRoutingTransform —— session-less 控制面请求(桶③})).toEqual({ upstreamOverride: CHATGPT });});- it.each(['responses', 'models'] as const)('env-key proxy 随凭据轮换更新 /%s,撤销后拒绝旧 key', async (endpoint) => {- const host = await freshCodexProxyHost();- const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');- let gatewayKey: string | null = 'test-old-gateway-key';- const readKey = vi.fn(() => gatewayKey);- host.setCodexProxyGatewayKeyReader(readKey);- host.registerComposed('session-key-rotation', 'thread-key-rotation', 'PRODUCT_PROMPT');- setSessionProvider('session-key-rotation', 'xd');- // 独立 host 冻结 env-key 身份;其它 host 改写全局形态不应改变它的路由。- host.setCodexProxyAuthInjection('oauth-bearer');- const transform = host.createModelRoutingTransform('env-key');- const body = endpoint === 'responses' ? { model: 'gpt-5.5', input: [] } : undefined;- const headers = { authorization: 'Bearer test-old-gateway-key',- ...(endpoint === 'responses' ? { 'thread-id': 'thread-key-rotation' } : {}),- };- const ctx = { reqId: 1, method: endpoint === 'responses' ? 'POST' : 'GET', url: `/${endpoint}`, headers };-- try {- expect(await transform(body, ctx)).toEqual({- headerOverride: { authorization: 'Bearer test-old-gateway-key' },- });- gatewayKey = 'test-new-gateway-key';- expect(await transform(body, { ...ctx, reqId: 2 })).toEqual({- headerOverride: { authorization: 'Bearer test-new-gateway-key' },- });- gatewayKey = null;- const refused = await transform(body, { ...ctx, reqId: 3 });- expect(await runLocalRefusal(refused)).toMatchObject({- status: 401,- body: { error: { code: 'cindy_gateway_credentials_unavailable' } },- });- expect(readKey).toHaveBeenCalledTimes(3);- expect(headers.authorization).toBe('Bearer test-old-gateway-key');- } finally {- host.unregister('session-key-rotation');- clearSessionProvider('session-key-rotation');- host.setCodexProxyGatewayKeyReader(() => null);- }+ it('env-key + 无 session + 无 model(GET /models)→ null(留默认网关, sk- key 本就有效)', async () => {+ const host = await import('../codex-proxy-host.js');+ host.setCodexProxyAuthInjection('env-key');+ const transform = host.createModelRoutingTransform();+ expect(transform(undefined, { reqId: 1, method: 'GET', url: '/models', headers: {} })).toBeNull();});it('provider-oauth + 无 session + 无 model(GET /models)→ 路由到 provider OAuth 上游', async () => {diff --git a/apps/desktop/src/main/maker-host/codex-credential-switch.ts b/apps/desktop/src/main/maker-host/codex-credential-switch.tsindex 1f76884288..c41e5d9787 100644--- a/apps/desktop/src/main/maker-host/codex-credential-switch.ts+++ b/apps/desktop/src/main/maker-host/codex-credential-switch.ts@@ -86,6 +86,8 @@ interface LocalCredentialModeSwitchMaker {export interface PrepareLocalCodexCredentialModeSwitchInput {/** Restrict arbitration to the host being replaced, preserving sibling hosts. */hostKey?: string;+ /** Hosts selected by the credential-change guard, including isolated hosts. */+ hostKeys?: readonly string[];maker: LocalCredentialModeSwitchMaker;isSessionInTurn?: (sessionId: string) => boolean;signal?: AbortSignal;@@ -421,7 +423,8 @@ export async function prepareLocalCodexCredentialModeSwitch(throwIfCredentialSwitchAborted(input.signal);const localCodexSessions = input.maker.listActiveSessions().filter((session) =>isLocalCodexSession(session) &&- (input.hostKey === undefined || (session.codexHostKey ?? 'local') === input.hostKey),+ (input.hostKey === undefined || (session.codexHostKey ?? 'local') === input.hostKey)+ && (input.hostKeys === undefined || input.hostKeys.includes(session.codexHostKey ?? 'local')),);const busySessions = localCodexSessions.filter((session) =>isSessionBusy(session, input.isSessionInTurn),diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 50b7c9641d..26810e4f29 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -2428,7 +2428,7 @@ function createCodexResponseObserver(): ResponseObserver {/*** 纯函数: 按 model(原始, 含 codex/ 前缀)+ spawn 鉴权注入方式决定 **默认** 上游 / 鉴权 override。* (会话显式选了供应商时由 resolveSessionRouteDecision 优先接管,不会走到这里。)- * - env-key spawn: 走默认上游 gateway,用当前 key 覆盖子进程启动时的旧 key;无 key 则本地拒绝。+ * - env-key spawn(codex 已带 gateway key): 全程 null(走默认上游 gateway, 不动 header)。* - oauth-bearer spawn(codex 带 OAuth token):* codex/ 折扣模型 → 换 gateway key, 默认上游(gateway); 无 key 则 null(passthrough, 上游会 401)。* 普通模型 → override 上游到 ChatGPT, 透传 OAuth token(不动 header)= 订阅默认。@@ -2439,27 +2439,7 @@ export function decideCodexRoute(opts: {authInjection: CodexProxyAuthInjection;gatewayKey: string | null;}): RoutingDecision | null {- if (opts.authInjection === 'env-key') {- if (opts.gatewayKey) {- return { headerOverride: { authorization: `Bearer ${opts.gatewayKey}` } };- }- return {- localHandler: async ({ res }) => {- res.writeHead(401, {- 'content-type': 'application/json; charset=utf-8',- 'cache-control': 'no-store',- });- res.end(JSON.stringify({- error: {- type: 'authentication_error',- code: 'cindy_gateway_credentials_unavailable',- message: 'Cindy AI credentials are unavailable.',- },- }));- },- };- }- if (opts.authInjection === 'provider-oauth') return null;+ if (opts.authInjection === 'env-key' || opts.authInjection === 'provider-oauth') return null;if (!opts.model) return null;const toGateway = gatewayProviderIdForRewrittenModel(opts.model) !== null;if (toGateway) {@@ -3036,8 +3016,8 @@ export function createModelRoutingTransform(}// ① 该会话显式选了供应商 → 据 catalog 统一路由。thread-id header → threadToSession 反解 xdt sessionId。- // oauth-bearer 态全量适用;env-key 态默认走网关,由 decideCodexRoute 换成当前网关 key。- // 例外:自定义(user)供应商和 host 注入鉴权的+ // oauth-bearer 态全量适用;env-key 态默认全量走网关、per-session 无意义(与 decideCodexRoute 的+ // env-key 短路一致,内置三家保持旧行为)。例外:自定义(user)供应商和 host 注入鉴权的// 供应商(provider-oauth-header 如 xAI、通用 Runner 的 oauth-token)必须按会话路由,// 因为它们的鉴权由 proxy 覆盖,不依赖 Codex 子进程凭证。if (sessionId && (@@ -3106,17 +3086,17 @@ export function createModelRoutingTransform(// spawn 时那把凭证 —— oauth-bearer 揣的 OAuth token 在网关无效(要 sk-)→ 401。// 故按 spawn 凭证回它的原生后端: oauth-bearer → ChatGPT 订阅后端(只 override 上游、透传 OAuth// token,等价 stock codex 订阅模式轮 /models 的去处); provider-oauth → 唯一 provider-oauth- // 供应商的上游/令牌(当前 xAI),避免把占位 key 打到网关; env-key → 默认网关,同样换成当前 key。+ // 供应商的上游/令牌(当前 xAI),避免把占位 key 打到网关; env-key → null(留默认网关, sk- key 本就有效)。// `!model` 这道闸确保真实 /responses(永远带 model)绝不落进此分支,杜绝注册时序竞争误伤推理请求。if (!sessionId && !model) {if (authInjection === 'oauth-bearer') return { upstreamOverride: CODEX_OAUTH_UPSTREAM };if (authInjection === 'provider-oauth') {return resolveProviderOAuthControlRouteDecision('codex', gatewayKey);}- return decideCodexRoute({ model, authInjection, gatewayKey });+ return null;}- // ② 未显式选供应商 → 回落默认路由(decideCodexRoute)。+ // ② 未显式选供应商 → 回落默认路由(decideCodexRoute,与未升级行为字节级一致)。const decision = decideCodexRoute({ model, authInjection, gatewayKey });// codex/ 折扣模型该走 gateway 换 key 但没配 key → null(passthrough), 上游大概率 401, 记一条诊断。if (decision === null && authInjection === 'oauth-bearer' && modeldiff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex b4456987e1..7d6a76647d 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -47,6 +47,7 @@ import {CodexAgent,configureDefaultImageResizer,type AgentKind,+ type AgentCredentialMode,type InteractionRequest,type AutoReviewDelegate,type McpProvider,@@ -3235,7 +3236,7 @@ export async function waitForInitialCustomMcpRefresh(): Promise<void> {** null-safe: getMaker() 还没构造过 codexAgent 时直接 no-op (此时也没进程要收)。*/-export async function prepareCodexForAuthModeChange(options: { allLocalHosts?: boolean } = {}): Promise<void> {+export async function prepareCodexForAuthModeChange(options: { allLocalHosts?: boolean; credentialMode?: AgentCredentialMode } = {}): Promise<void> {if (_codexCredentialChangeGuard) {throw new Error('Codex credential mode change is already in progress');}@@ -3254,6 +3255,7 @@ export async function prepareCodexForAuthModeChange(options: { allLocalHosts?: bawait prepareLocalCodexCredentialModeSwitch({maker,isSessionInTurn,+ ...(options.credentialMode ? { hostKeys: guard?.affectedHostKeys ?? [] } : {}),});} catch (e) {desktopMakerLogger.warn(@@ -3311,7 +3313,7 @@ export function cancelCodexAuthModeChange(): void {guard?.release();}-export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvironment?: boolean } = {}): Promise<void> {+export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvironment?: boolean; refreshAuthState?: boolean } = {}): Promise<void> {// 只 dispose 本地 app-server, 让下一次本地 send 按新模式重新 spawn。// 远端 Codex host 使用远端 daemon / 远端用户配置,不能被本地 key / OAuth 变化误关。const guard = _codexCredentialChangeGuard;@@ -3338,8 +3340,10 @@ export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvi} else {await agent?.disposeLocalHostForCredentialChange();}- clearCodexProxyAuthInjection();- await broadcastCodexRuntimeRoute();+ if (options.refreshAuthState !== false) {+ clearCodexProxyAuthInjection();+ await broadcastCodexRuntimeRoute();+ }} catch (e) {desktopMakerLogger.warn('restartCodexAfterAuthModeChange: dispose threw', {error: e instanceof Error ? e.message : String(e),@@ -3347,6 +3351,8 @@ export async function finalizeCodexAfterAuthModeChange(options: { prepareMcpEnvithrow e;}}+ // Gateway key rotation leaves OAuth state and unaffected hosts unchanged.+ if (options.refreshAuthState === false) return;// proxy 路线: proxy 始终保活(两种 spawn 形态都依赖它), 仅在 app quit(bootstrap-electron onQuit)dispose。// codex 登录态变化只需上面 dispose codex agent 重 spawn —— 重 spawn 时按最新 OAuth 登录态冻结// authInjection(oauth-bearer / env-key), routingTransform 据此 + per-session 选择出路由。diff --git a/apps/desktop/src/main/model-access/index.ts b/apps/desktop/src/main/model-access/index.tsindex d30b1be075..819ad2740b 100644--- a/apps/desktop/src/main/model-access/index.ts+++ b/apps/desktop/src/main/model-access/index.ts@@ -12,7 +12,6 @@ import { isExternalOrganizationByokUser } from './organizationManaged.js';import { serverApiFetch, ServerApiError } from '../serverApiClient.js';import { getClientEndpoint } from '../clientEndpointsService.js';import { getProviderSecretStore } from '../secrets/providerSecretStore.js';-import { getCodexProxyAuthInjectionState } from '../maker-host/codex-proxy-host.js';import {prepareCodexForAuthModeChange,prepareCodexForCustomProviderHostChange,@@ -102,17 +101,11 @@ function rotateCredentials(): Promise<CredentialsPayload> {* 写 XD key(main 侧自动下发路径),带 codex env-key 重启副作用:* env-key spawn 的 codex app-server 把 gateway key 冻在子进程 env 里,写盘后* 必须重建才生效——与 renderer 手填走的 safe-storage IPC 同一套语义。- * 非 env-key 形态零副作用(Claude 每 session 现读 key,天然跟随)。+ * 按 host 的实际凭据筛选,覆盖不登记共享 proxy 状态的独立 session。*/async function writeXdKeyWithCodexSideEffect(key: string): Promise<boolean> {- const needRestart = getCodexProxyAuthInjectionState() === 'env-key';- if (!needRestart) {- const stored = getProviderSecretStore().set('xd', key);- if (stored) notifyXdProviderKeyChanged();- return stored;- }try {- await prepareCodexForAuthModeChange();+ await prepareCodexForAuthModeChange({ allLocalHosts: true, credentialMode: 'gateway-key' });} catch (err) {log.warn('prepare codex before auto key write failed', {error: err instanceof Error ? err.message : String(err),@@ -126,7 +119,7 @@ async function writeXdKeyWithCodexSideEffect(key: string): Promise<boolean> {}notifyXdProviderKeyChanged();try {- await finalizeCodexAfterAuthModeChange();+ await finalizeCodexAfterAuthModeChange({ refreshAuthState: false });} catch (err) {// key 已写盘(新值有效);codex 重建失败只记日志,下次 spawn 自然用新 key。log.warn('finalize codex after auto key write failed', {diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 6344207a03..4429147232 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -1077,6 +1077,109 @@ describe('Codex official OAuth host isolation', () => {});describe('CodexAgent spawn configuration', () => {+ it.each(['shared', 'isolated', 'custom-context'])('rebuilds a %s gateway host with the rotated key and resumes the same thread', async (scope) => {+ MockCodexTransport.onCreate = transport => transport.setMockResponse(Method.ThreadStart, {+ result: { thread: { id: '11111111-1111-4111-8111-111111111111' }, model: 'gpt-5.4', modelProvider: 'cindy_gateway', cwd: '/repo' },+ });+ let key = 'test-old-gateway-key';+ const deps = createDeps({}, {+ resolveCodexLocalAuthPolicy: () => scope === 'shared' ? 'legacy-shared' : 'isolated',+ ...(scope === 'custom-context' ? { resolveCodexThreadContextWindow: () => 700_000 } : {}),+ prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [], extraEnv: {}, codexProxyActive: true }),+ });+ deps.auth.getState = async () => ({ authenticated: true, authSource: 'api-key' });+ deps.auth.getAuthEnv = async () => ({ XDT_CODEX_API_KEY: key });+ const agent = new CodexAgent(deps);+ try {+ const session = await agent.startSession({ sessionId: 'gateway', providerId: 'xd', model: 'gpt-5.4', workingDir: '/repo' });+ const original = createdTransports[0];+ expect(createdStdioOptions[0].env?.XDT_CODEX_API_KEY).toBe(key);+ const guard = await agent.beginLocalHostCredentialChange('gateway key rotation', {+ allLocalHosts: true, credentialMode: 'gateway-key',+ });+ try {+ expect(guard.affectedHostKeys).toContain(session.codexHostKey);+ expect(() => guard.assertIdle()).toThrow(/active Codex session/);+ await session.close();+ guard.assertIdle();+ await guard.retireActiveHost();+ expect(original.closed).toBe(true);+ key = 'test-new-gateway-key';+ await guard.finalize();+ } finally { guard.release(); }+ const restored = await agent.startSession({ sessionId: 'gateway', providerId: 'xd', model: 'gpt-5.4', workingDir: '/repo', resumeSessionId: session.id });+ expect(createdStdioOptions.at(-1)?.env?.XDT_CODEX_API_KEY).toBe(key);+ const resume = createdTransports.at(-1)!.lines.map(line => JSON.parse(line))+ .find(message => message.method === Method.ThreadResume);+ expect(resume.params.threadId).toBe(session.id);+ await restored.close();+ } finally { await agent.dispose(); }+ });++ it('excludes OAuth, custom provider and remote hosts from gateway key rotation', async () => {+ const deps = createDeps({}, {+ resolveCodexLocalAuthPolicy: provider => provider === 'xd' || provider === 'cprov-test' ? 'isolated' : 'legacy-shared',+ resolveCodexThreadContextWindow: () => 700_000,+ prepareCodexExtraSpawnConfig: async () => ({ extraArgs: [], extraEnv: {}, codexProxyActive: true }),+ getRemoteCodexTransport: () => {+ const transport = new MockCodexTransport();+ createdTransports.push(transport);+ return transport;+ },+ });+ deps.auth.getState = async opts => ({ authenticated: true, authSource: opts?.credentialMode === 'gateway-key' ? 'api-key' : 'oauth' });+ const agent = new CodexAgent(deps);+ try {+ const gateway = await agent.startSession({ sessionId: 'gateway', providerId: 'xd', model: 'gpt-5.4', workingDir: '/repo' });+ const siblings = [];+ for (const providerId of ['openai', 'cprov-test']) {+ siblings.push(await agent.startSession({ sessionId: providerId, providerId, model: 'gpt-5.4', workingDir: '/repo' }));+ }+ siblings.push(await agent.startSession({ sessionId: 'remote', remoteHostId: 'ssh', model: 'gpt-5.4', workingDir: '/repo' }));+ const guard = await agent.beginLocalHostCredentialChange('gateway key rotation', {+ allLocalHosts: true, credentialMode: 'gateway-key',+ });+ try {+ expect(guard.affectedHostKeys).toEqual([gateway.codexHostKey]);+ await gateway.close();+ guard.assertIdle();+ await guard.retireActiveHost();+ expect(createdTransports[0].closed).toBe(true);+ expect(createdTransports.slice(1).every(transport => !transport.closed)).toBe(true);+ await guard.finalize();+ } finally { guard.release(); }+ for (const sibling of siblings) await sibling.close();+ } finally { await agent.dispose(); }+ });++ it('defers gateway key rotation while an isolated host is starting', async () => {+ const started = deferred<void>();+ const finish = deferred<void>();+ const agent = new CodexAgent(createDeps({}, {+ resolveCodexLocalAuthPolicy: () => 'isolated',+ prepareCodexExtraSpawnConfig: async () => {+ started.resolve();+ await finish.promise;+ return { extraArgs: [], extraEnv: {}, codexProxyActive: true };+ },+ }));+ const startup = agent.startSession({ sessionId: 'starting-gateway', providerId: 'xd', model: 'gpt-5.4', workingDir: '/repo' });+ await started.promise;+ const guard = await agent.beginLocalHostCredentialChange('gateway key rotation', {+ allLocalHosts: true, credentialMode: 'gateway-key',+ });+ try {+ expect(() => guard.assertIdle()).toThrow(/active Codex session/);+ await expect(guard.retireActiveHost()).rejects.toThrow(/active Codex session/);+ } finally {+ guard.release();+ finish.resolve();+ }+ const handle = await startup;+ await handle.close();+ await agent.dispose();+ });+it('holds account session recovery until the MCP bridge replacement is ready', async () => {MockCodexTransport.onCreate = transport => transport.setMockResponse(Method.McpServerStatusList, {result: { data: [{ name: 'cindy_scheduler', tools: { list_tools: {}, call_tool: {} } }], nextCursor: null },diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 7225b5113a..516f16895a 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -2329,8 +2329,9 @@ export class CodexAgent extends BaseAgent {async beginLocalHostCredentialChange(reason = 'CodexAgent local credential state changed',- options: { allLocalHosts?: boolean; forceRetire?: boolean; busyError?: () => Error } = {},+ options: { allLocalHosts?: boolean; credentialMode?: AgentCredentialMode; forceRetire?: boolean; busyError?: () => Error } = {},): Promise<{+ affectedHostKeys: readonly string[];assertIdle(): void;retireActiveHost(): Promise<void>;finalize(): Promise<void>;@@ -2370,7 +2371,15 @@ export class CodexAgent extends BaseAgent {? [...new Set([...this.hosts.keys(), ...this.hostPromises.keys(),...this.hostSessionBindingLeases.keys(), ...this.retiringHosts.keys(),- ])].filter((candidate) => !candidate.startsWith('remote:'))+ ])].filter((candidate) => {+ if (candidate.startsWith('remote:')) return false;+ if (!options.credentialMode) return true;+ const mode = this.hostEffectiveCredentialModes.get(candidate)+ ?? this.hostCredentialModes.get(candidate)+ ?? this.hostPromises.get(candidate)?.credentialMode;+ // Unresolved startup may still freeze the credential being replaced.+ return mode === undefined || mode === options.credentialMode;+ }): [key];const activeUseCount = (): number => affectedKeys().reduce((count, candidate) => {const host = this.hosts.get(candidate);@@ -2390,6 +2399,7 @@ export class CodexAgent extends BaseAgent {};return {+ affectedHostKeys: affectedKeys(),assertIdle: () => {const count = activeUseCount();if (count > 0) {