Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(codex): 修复 OpenAI 多账号切换后的历史恢复 (#4333)

Dashbe74a47383a5
diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.ts
index fe395e3695..1e83832671 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codex-browser-companion.test.ts
@@ -190,6 +190,31 @@ afterEach(async () => {
});
describe('prepareCodexBrowserCompanion', () => {
+ it.each([false, true])('uses the history config when account configs differ (history transport: %s)', async (historyHasTransport) => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-browser-companion-'));
+ tempDirs.push(root);
+ const historyHome = path.join(root, 'history-a');
+ const credentialHome = path.join(root, 'credentials-b');
+ const transport = '[mcp_servers.node_repl]\ncommand = "fixture-node-repl"\n';
+ for (const [home, config] of [
+ [historyHome, historyHasTransport ? transport : ''],
+ [credentialHome, historyHasTransport ? '' : transport],
+ ]) {
+ await fs.mkdir(home);
+ await fs.writeFile(path.join(home, 'config.toml'), config);
+ }
+ // Guard the Desktop wiring as well as the filesystem-dependent preflight.
+ const source = await fs.readFile(new URL('../index.ts', import.meta.url), 'utf8');
+ expect(source).toMatch(/prepareCodexBrowserCompanion\(\{\s*codexHome: ctx\.runtimeCodexHome \?\? effectiveCodexHome/);
+ const companion = await prepareCodexBrowserCompanion({ codexHome: historyHome, platform: 'win32' });
+ expect(resolveCodexBrowserCompanionSpawnConfig(companion)).toEqual({
+ codexBrowserUseAvailable: false,
+ extraArgs: historyHasTransport ? ['-c', 'mcp_servers.node_repl.enabled=false'] : [],
+ });
+ expect(await fs.readFile(path.join(historyHome, 'config.toml'), 'utf8')).toBe(historyHasTransport ? transport : '');
+ expect(await fs.readFile(path.join(credentialHome, 'config.toml'), 'utf8')).toBe(historyHasTransport ? '' : transport);
+ });
+
it('anchors macOS verification to the signed OpenAI Codex identity', () => {
const args = buildOfficialMacBundleVerificationArgs('/tmp/ChatGPT.app');
diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-thread-locations.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-thread-locations.test.ts
index 43d81d3011..0353a1d86d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codex-thread-locations.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codex-thread-locations.test.ts
@@ -23,11 +23,11 @@ describe('native thread locations across accounts', () => {
await fs.mkdir(path.dirname(rollout), { recursive: true });
await fs.writeFile(rollout, 'history');
await locations.record('thread-a', rollout);
- expect(await locations.readStorageHome('thread-a')).toBe(home);
+ expect(await locations.readStorage('thread-a')).toEqual({ historyHome: home, sqliteHome: home });
await locations.record('thread-a', rollout, home);
const reopened = new CodexThreadLocations(path.join(root, 'owner', 'locations'));
- expect(await reopened.readStorageHome('thread-a')).toBe(home);
- expect(await reopened.readStorageHome('unknown')).toBeUndefined();
+ expect(await reopened.readStorage('thread-a')).toEqual({ historyHome: home, sqliteHome: home });
+ expect(await reopened.readStorage('unknown')).toBeUndefined();
expect(await fs.readFile(rollout, 'utf8')).toBe('history');
});
it('resolves unindexed legacy history before account host startup and remembers its native home', async () => {
@@ -37,20 +37,20 @@ describe('native thread locations across accounts', () => {
await fs.mkdir(path.dirname(rollout), { recursive: true });
await fs.writeFile(rollout, 'old native history\n');
const prepare = vi.fn().mockResolvedValue(rollout);
- expect(await locations.readStorageHome('old-thread', { home, prepare })).toBe(home);
+ expect(await locations.readStorage('old-thread', { home, prepare })).toEqual({ historyHome: home, sqliteHome: home });
expect(prepare).toHaveBeenCalledWith('old-thread');
expect(await locations.read('old-thread')).toBe(rollout);
- expect(await locations.readStorageHome('old-thread', { home, prepare })).toBe(home);
+ expect(await locations.readStorage('old-thread', { home, prepare })).toEqual({ historyHome: home, sqliteHome: home });
expect(prepare).toHaveBeenCalledTimes(1);
expect(await fs.readFile(rollout, 'utf8')).toBe('old native history\n');
await fs.rm(rollout);
- await expect(locations.readStorageHome('old-thread', { home, prepare })).rejects.toThrow();
+ await expect(locations.readStorage('old-thread', { home, prepare })).rejects.toThrow();
expect(prepare).toHaveBeenCalledTimes(1);
});
it('does not invent a storage home when legacy preparation finds no history', async () => {
const { root, locations } = await fixture();
const prepare = vi.fn().mockResolvedValue(undefined);
- expect(await locations.readStorageHome('missing', { home: root, prepare })).toBeUndefined();
+ expect(await locations.readStorage('missing', { home: root, prepare })).toBeUndefined();
expect(await locations.read('missing')).toBeUndefined();
});
@@ -64,6 +64,16 @@ describe('native thread locations across accounts', () => {
const reopened = new CodexThreadLocations(path.join(root, 'owner', 'locations'));
expect(await fs.readFile((await reopened.read('thread-1'))!, 'utf8')).toBe('turn A\nturn B\n');
});
+ it('distinguishes archived rollout ownership from an independently configured database home', async () => {
+ const { root, locations } = await fixture();
+ const historyHome = path.join(root, 'history-a');
+ const sqliteHome = path.join(root, 'database-a');
+ const rollout = path.join(historyHome, 'archived_sessions', 'rollout.jsonl');
+ await fs.mkdir(path.dirname(rollout), { recursive: true });
+ await fs.writeFile(rollout, JSON.stringify({ type: 'session_meta', payload: { id: 'archived' } }));
+ await locations.record('archived', rollout, sqliteHome);
+ expect(await locations.readStorage('archived')).toEqual({ historyHome, sqliteHome });
+ });
it('never falls back to an older rollout after the canonical path disappears', async () => {
const { root, locations } = await fixture();
const rollout = path.join(root, 'latest.jsonl');
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts
new file mode 100644
index 0000000000..e37bcf9d92
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthTokenReaderBoundary.test.ts
@@ -0,0 +1,35 @@
+import { readFileSync } from 'node:fs';
+import { runInNewContext } from 'node:vm';
+import { describe, expect, it, vi } from 'vitest';
+
+// Execute the actual host callback without bootstrapping Electron or real credentials.
+const source = readFileSync(new URL('../index.ts', import.meta.url), 'utf8');
+const callback = source.slice(source.indexOf('createCodexAuthTokenReader:') + 'createCodexAuthTokenReader:'.length,
+ source.indexOf('recordCodexThreadLocation:', source.indexOf('createCodexAuthTokenReader:'))).trim().replace(/,$/, '');
+
+describe('Codex token reader owner boundary', () => {
+ it.each(['before', 'during', 'stable', 'owner-change'])('handles %s credential reads', async phase => {
+ let pending = phase === 'before';
+ let owner = 'owner-a';
+ const readOneShotCreds = vi.fn(() => ({ accessToken: 'fixture-token', accountId: 'account-b' }));
+ const getState = vi.fn(async () => {
+ if (phase === 'during') pending = true;
+ if (phase === 'owner-change') owner = 'owner-b';
+ return { authenticated: true };
+ });
+ const createReader = runInNewContext(`(${callback})`, {
+ activeOwnerScopeKey: () => owner,
+ isAppSessionBoundaryPending: () => pending,
+ desktopCodexAuthAdapter: { getState, readOneShotCreds },
+ });
+ const reader = createReader('account-b');
+ if (phase === 'stable') {
+ await expect(reader()).resolves.toEqual({ accessToken: 'fixture-token', chatgptAccountId: 'account-b' });
+ expect(readOneShotCreds).toHaveBeenCalledWith('account-b');
+ } else {
+ await expect(reader()).rejects.toThrow('Codex authentication owner changed');
+ expect(readOneShotCreds).not.toHaveBeenCalled();
+ if (phase === 'before') expect(getState).not.toHaveBeenCalled();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/codex-thread-locations.ts b/apps/desktop/src/main/maker-host/codex-thread-locations.ts
index 9808e78951..c3e4e85691 100644
--- a/apps/desktop/src/main/maker-host/codex-thread-locations.ts
+++ b/apps/desktop/src/main/maker-host/codex-thread-locations.ts
@@ -33,10 +33,10 @@ export class CodexThreadLocations {
return value.path;
}
- async readStorageHome(
+ async readStorage(
threadId: string,
legacy?: { home: string; prepare: (threadId: string) => Promise<string | undefined> },
- ): Promise<string | undefined> {
+ ): Promise<{ historyHome: string; sqliteHome: string } | undefined> {
const rollout = await this.read(threadId);
if (!rollout) {
// Pre-multi-account threads have no location record. Resolve their native
@@ -44,18 +44,16 @@ export class CodexThreadLocations {
const legacyRollout = await legacy?.prepare(threadId);
if (!legacy || !legacyRollout) return;
await this.record(threadId, legacyRollout, legacy.home);
- return legacy.home;
+ return { historyHome: historyHomeForRollout(legacyRollout), sqliteHome: legacy.home };
}
const value = JSON.parse(await fs.readFile(this.file(threadId), 'utf8'));
if (value.sqliteHome !== undefined) {
if (typeof value.sqliteHome !== 'string' || !path.isAbsolute(value.sqliteHome)) throw new Error('Invalid Codex history storage');
- return value.sqliteHome;
+ return { historyHome: historyHomeForRollout(rollout), sqliteHome: value.sqliteHome };
}
// Compatibility with locations written before native database ownership was recorded.
- for (let dir = path.dirname(rollout); path.dirname(dir) !== dir; dir = path.dirname(dir)) {
- if (['sessions', 'archived_sessions'].includes(path.basename(dir))) return path.dirname(dir);
- }
- throw new Error('Codex history storage is unavailable');
+ const historyHome = historyHomeForRollout(rollout);
+ return { historyHome, sqliteHome: historyHome };
}
async record(threadId: string, rolloutPath: string, sqliteHome?: string): Promise<void> {
@@ -73,3 +71,10 @@ export class CodexThreadLocations {
}
}
}
+
+function historyHomeForRollout(rollout: string): string {
+ for (let dir = path.dirname(rollout); path.dirname(dir) !== dir; dir = path.dirname(dir)) {
+ if (['sessions', 'archived_sessions'].includes(path.basename(dir))) return path.dirname(dir);
+ }
+ throw new Error('Codex history storage is unavailable');
+}
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index f52b935f64..df932d78fc 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1649,7 +1649,7 @@ export function getMaker(): Maker {
}
const browserCompanion = isControlPlane || isReview
? null
- : await prepareCodexBrowserCompanion({ codexHome: effectiveCodexHome });
+ : await prepareCodexBrowserCompanion({ codexHome: ctx.runtimeCodexHome ?? effectiveCodexHome });
const browserCompanionSpawnConfig =
resolveCodexBrowserCompanionSpawnConfig(browserCompanion);
mcpExtraArgs.push(...browserCompanionSpawnConfig.extraArgs);
@@ -1900,12 +1900,26 @@ export function getMaker(): Maker {
const locations = new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations'));
return await locations.read(threadId) ?? await prepareExternalCodexSessionForResume(threadId);
},
- resolveCodexThreadStorageHome: async (threadId) => {
+ resolveCodexThreadStorage: async (threadId) => {
if (!getActiveAppSession().dataOwnerId) return;
- return new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations')).readStorageHome(threadId, {
+ const ownerScope = activeOwnerScopeKey();
+ const storage = await new CodexThreadLocations(path.join(codexAccountHome('thread-index'), 'locations')).readStorage(threadId, {
home: getCodexHome(),
prepare: prepareExternalCodexSessionForResume,
});
+ if (activeOwnerScopeKey() !== ownerScope) throw new Error('Codex history owner changed during preparation');
+ return storage;
+ },
+ createCodexAuthTokenReader: (providerId) => {
+ const ownerScope = activeOwnerScopeKey();
+ return async () => {
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) throw new Error('Codex authentication owner changed');
+ const state = await desktopCodexAuthAdapter.getState({ credentialMode: 'oauth-bearer', providerId });
+ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) throw new Error('Codex authentication owner changed');
+ const credentials = state.authenticated ? desktopCodexAuthAdapter.readOneShotCreds(providerId) : null;
+ if (!credentials) throw new Error('Codex account credentials are unavailable');
+ return { accessToken: credentials.accessToken, chatgptAccountId: credentials.accountId };
+ };
},
recordCodexThreadLocation: async (threadId, storageHome, rolloutPath) => {
if (!rolloutPath || !getActiveAppSession().dataOwnerId) return;
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 363ff7954f..ac6bdf0e2e 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -71,7 +71,25 @@ Claude Code/Codex/Pi 的强制换窗线
`danger`/`overflow` 的本机会话先走同一套 `context_rebuild` bounded handoff,再落目标
route,不能 resume 旧原生窗口。
Codex 跨凭证时先按目标来源 resume 同一个原生线程,不因 `ordinal` / `history_base` 或来源
-变化而 fork、改写历史或交接。普通加密推理失败继续使用现有 HTTP 透明重试;只有上游明确
+变化而 fork、改写历史或交接。本地恢复与分叉必须同时固定该线程的原生历史根
+(`CODEX_HOME`,含 `sessions` / `archived_sessions`)和数据库根(`sqlite_home`);
+仅固定 SQLite 不足以恢复分页祖先,原生按不可变 rollout ID 在历史根内查找祖先。
+凭证、代理路由和模型目录仍按本轮选中账号准备,不能把历史根写回全局账号配置。
+跨历史根的原生进程从启动参数要求 `cli_auth_credentials_store="ephemeral"`,清除继承的
+原生身份环境变量;OAuth 通过独立的 external-auth adapter 在进程内安装目标账号 token,
+网关与第三方 OAuth 继续使用既有代理认证。所有跨根进程在分发任务前检查生效的临时凭证
+配置;每次重连重新认证,刷新必须匹配冻结的 owner、host 代次及账号,且不能复用刚被
+拒绝的 token。owner 切换 pending 期间,即使 owner key 尚未提交变化,也必须在异步认证
+读取前后拒绝提供 token。刷新有超时,失败走正常错误路径,不切回历史所属账号。
+该 adapter 依赖 Codex 实验性的 `chatgptAuthTokens` 协议,0.145.0 已支持该协议且通过
+真实登录及 401 刷新契约验证,不能把 0.153.4 当作协议最低版本。更换原生运行时前必须
+用目标二进制运行 `CINDY_CODEX_TEST_BINARY=<绝对路径> pnpm --filter @cindy/maker-core exec
+vitest run src/agents/codex/app-server/external-auth.native.test.ts`,覆盖分页祖先、归档、
+分叉、重连、实际请求身份和 401 刷新。测试只用临时历史、假凭证和本地 HTTP 服务。
+管理员 requirements 可能覆盖 CLI 临时凭证设置:客户端可阻止后续任务,但启动后的
+配置检查不能证明原生初始化阶段从未读取历史根中的认证;不得声称具备这一保证,
+也不得自行复制上游策略加载器或改写用户认证文件规避策略。
+普通加密推理失败继续使用现有 HTTP 透明重试;只有上游明确
拒绝且请求里仅剩不可剥除的压缩块密文时,proxy 才标记
`CINDY_ENCRYPTED_COMPACTION_INCOMPATIBLE`,交给既有 compact 失败恢复流程。
裸 `invalid_encrypted_content`、网络错误和切换来源本身都不足以触发该恢复;保留同一用户消息
diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.ts
index da8276d11d..903a4402a0 100644
--- a/packages/maker-core/src/agents/base-agent.ts
+++ b/packages/maker-core/src/agents/base-agent.ts
@@ -987,6 +987,8 @@ export interface AgentDeps {
ctx: {
providerId?: string;
codexHome?: string;
+ /** Actual native config/history root; credential/catalog preparation keeps codexHome above. */
+ runtimeCodexHome?: string;
accountHostKey?: string;
remoteHostId?: string;
credentialMode?: AgentCredentialMode;
@@ -1279,7 +1281,9 @@ export interface AgentDeps {
*/
prepareCodexResumeSession?: (threadId: string, context?: { codexHome: string; providerId?: string }) => Promise<string | void>;
recordCodexThreadLocation?: (threadId: string, codexHome: string, rolloutPath?: string) => Promise<void>;
- resolveCodexThreadStorageHome?: (threadId: string) => Promise<string | undefined>;
+ resolveCodexThreadStorage?: (threadId: string) => Promise<{ historyHome: string; sqliteHome: string } | undefined>;
+ /** Freeze the owner/account scope before async host startup; never expose tokens to the renderer. */
+ createCodexAuthTokenReader?: (providerId?: string) => () => Promise<import('./codex/app-server/external-auth.js').CodexChatgptTokens>;
/**
* Codex 专用:把已拼好的产品级 system prompt 同步登记到 host 的 codex proxy registry。
diff --git a/packages/maker-core/src/agents/codex/app-server/external-auth.native.test.ts b/packages/maker-core/src/agents/codex/app-server/external-auth.native.test.ts
new file mode 100644
index 0000000000..385b7b32f2
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/app-server/external-auth.native.test.ts
@@ -0,0 +1,221 @@
+/** Explicit runtime contract: CINDY_CODEX_TEST_BINARY=<absolute binary> vitest run <this file>. */
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { createServer, type Server } from 'node:http';
+import { afterEach, describe, expect, it } from 'vitest';
+import { AppServerHost } from './host.js';
+import { createStdioTransport } from './stdioTransport.js';
+import { useCodexHistoryHome, type CodexExternalAuth } from './external-auth.js';
+import type { Logger } from '../../../interfaces/logger.js';
+
+const binaryPath = process.env.CINDY_CODEX_TEST_BINARY;
+const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child: () => logger };
+const roots: string[] = [];
+const hosts: AppServerHost[] = [];
+const servers: Server[] = [];
+afterEach(async () => {
+ await Promise.all(hosts.splice(0).map(host => host.retire('native contract test complete')));
+ await Promise.all(servers.splice(0).map(server => new Promise<void>((resolve, reject) => {
+ server.close(error => error ? reject(error) : resolve());
+ server.closeAllConnections();
+ })));
+ await Promise.all(roots.splice(0).map(root => fs.rm(root, { recursive: true, force: true })));
+});
+
+function fakeTokens(account: string, revision = 'initial') {
+ const payload = Buffer.from(JSON.stringify({ email: `${account}@example.invalid`, revision, exp: 4102444800,
+ 'https://api.openai.com/auth': { chatgpt_account_id: account, chatgpt_plan_type: 'pro' } })).toString('base64url');
+ return { accessToken: `test.${payload}.not-a-signature`, chatgptAccountId: account, chatgptPlanType: 'pro' };
+}
+
+async function fixture(archivedParent = false, testRefresh = false) {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-codex-history-contract-'));
+ roots.push(root);
+ const historyHome = path.join(root, 'history-a');
+ const credentialHome = path.join(root, 'account-b');
+ await fs.mkdir(credentialHome);
+ const wireRequests: Array<{ authorization: string | undefined; account: string | string[] | undefined }> = [];
+ const refreshRequests: unknown[] = [];
+ const server = createServer(async (request, response) => {
+ if (request.method === 'POST' && request.url === '/oauth/token') {
+ let body = '';
+ for await (const chunk of request) body += chunk;
+ refreshRequests.push(JSON.parse(body));
+ const token = fakeTokens('account-b', 'refreshed').accessToken;
+ response.writeHead(200, { 'content-type': 'application/json' });
+ response.end(JSON.stringify({ id_token: token, access_token: token, refresh_token: 'fixture-refresh-b2' }));
+ return;
+ }
+ if (request.method === 'POST' && request.url?.endsWith('/responses')) {
+ wireRequests.push({ authorization: request.headers.authorization, account: request.headers['chatgpt-account-id'] });
+ request.resume();
+ if (testRefresh && wireRequests.length === 1) {
+ response.writeHead(401, { 'content-type': 'application/json' });
+ response.end(JSON.stringify({ error: { message: 'expired fixture credential' } }));
+ return;
+ }
+ response.writeHead(200, { 'content-type': 'text/event-stream' });
+ response.end(`event: response.completed\ndata: ${JSON.stringify({ type: 'response.completed', response: {
+ id: 'resp_fixture', object: 'response', created_at: 1, status: 'completed', model: 'gpt-6-astra', output: [],
+ usage: { input_tokens: 10, output_tokens: 1, total_tokens: 11 },
+ } })}\n\n`);
+ return;
+ }
+ response.setHeader('content-type', 'application/json');
+ response.end(JSON.stringify({ models: [] }));
+ });
+ servers.push(server);
+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('missing test listener');
+ const baseUrl = `http://127.0.0.1:${address.port}`;
+ async function rollout(base?: { thread_id: string; end_ordinal_exclusive: number; end_byte_offset: number }, archived = false) {
+ const id = randomUUID();
+ const directory = path.join(historyHome, archived ? 'archived_sessions' : 'sessions/2026/09/12');
+ await fs.mkdir(directory, { recursive: true });
+ const file = path.join(directory, `rollout-2026-09-12T00-00-00-${id}.jsonl`);
+ const ordinal = base?.end_ordinal_exclusive ?? 0;
+ const meta = { session_id: id, id, timestamp: '2026-09-12T00:00:00.000Z', cwd: root,
+ originator: 'cindy-contract-test', cli_version: '0.153.4', source: 'cli',
+ history_mode: 'paginated', model_provider: 'probe',
+ ...(base ? { history_base: base, forked_from_id: base.thread_id } : {}) };
+ const text = [
+ { ordinal, type: 'session_meta', payload: meta },
+ { ordinal: ordinal + 1, type: 'response_item', payload: { type: 'message', role: 'user',
+ content: [{ type: 'input_text', text: `history marker ${id}` }] } },
+ ].map(item => JSON.stringify({ timestamp: '2026-09-12T00:00:00.000Z', ...item })).join('\n') + '\n';
+ await fs.writeFile(file, text);
+ return { id, file, text, base: { thread_id: id, end_ordinal_exclusive: ordinal + 2, end_byte_offset: Buffer.byteLength(text) } };
+ }
+ const parent = await rollout(undefined, archivedParent);
+ const child = await rollout(parent.base);
+ // Deliberately invalid persisted auth proves ephemeral startup never needs it.
+ const oldAuth = 'history owner credential sentinel -- never read or replace';
+ await fs.writeFile(path.join(historyHome, 'auth.json'), oldAuth);
+ const authStat = await fs.stat(path.join(historyHome, 'auth.json'));
+ function host(home: string, account?: string, managed = false, externalAuth?: CodexExternalAuth) {
+ const env = useCodexHistoryHome({ PATH: process.env.PATH ?? '',
+ ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}),
+ HOME: root, USERPROFILE: root, TMPDIR: root,
+ CODEX_REFRESH_TOKEN_URL_OVERRIDE: `${baseUrl}/oauth/token` }, home);
+ const instance = new AppServerHost({
+ logger, clientInfo: { name: 'cindy-contract-test', version: '0.0.0' },
+ ...(!managed && account ? { externalAuth: externalAuth ?? { readTokens: async (refresh: boolean) => fakeTokens(account, refresh ? 'refreshed' : 'initial') } } : {}),
+ createTransport: () => createStdioTransport({ binaryPath: binaryPath!, cwd: root, env,
+ extraArgs: ['--disable', 'plugins', '--disable', 'remote_plugin',
+ '-c', `sqlite_home=${JSON.stringify(historyHome)}`,
+ '-c', `cli_auth_credentials_store="${managed ? 'file' : 'ephemeral'}"`, '-c', 'model_provider="probe"',
+ '-c', 'model_providers.probe.name="Probe"', '-c', `model_providers.probe.base_url=${JSON.stringify(baseUrl)}`,
+ '-c', 'model_providers.probe.wire_api="responses"', '-c', `model_providers.probe.requires_openai_auth=${Boolean(account)}`,
+ '-c', `chatgpt_base_url=${JSON.stringify(baseUrl)}`],
+ }),
+ });
+ hosts.push(instance);
+ return instance;
+ }
+ async function resume(instance: AppServerHost, thread: { id: string; file: string } = child) {
+ return instance.request<{ thread: { id: string; path: string } }>('thread/resume', {
+ threadId: thread.id, path: thread.file, model: 'gpt-6-astra', cwd: root,
+ approvalPolicy: 'never', sandbox: 'read-only',
+ }, { timeoutMs: 15_000 });
+ }
+ async function assertOriginals(managed = false) {
+ expect(await fs.readFile(parent.file, 'utf8')).toBe(parent.text);
+ expect(await fs.readFile(path.join(historyHome, 'auth.json'), 'utf8')).toBe(oldAuth);
+ expect((await fs.stat(path.join(historyHome, 'auth.json'))).mtimeMs).toBe(authStat.mtimeMs);
+ if (!managed) await expect(fs.stat(path.join(credentialHome, 'auth.json'))).rejects.toMatchObject({ code: 'ENOENT' });
+ }
+ return { root, historyHome, credentialHome, parent, child, rollout, host, resume, assertOriginals, wireRequests, refreshRequests };
+}
+
+describe.skipIf(!binaryPath)('real Codex history/account isolation contract', () => {
+ it('reproduces the old split-home defect with a complete source rollout still on disk', async () => {
+ const f = await fixture();
+ const original = f.host(f.historyHome);
+ await expect(f.resume(original)).resolves.toMatchObject({ thread: { id: f.child.id } });
+ await original.retire();
+ await expect(f.resume(f.host(f.credentialHome))).rejects.toThrow('missing source rollout');
+ await f.assertOriginals();
+ }, 30_000);
+
+ it.each([false, true])('preserves full ancestry, account identity and restart (archived ancestor: %s)', async archived => {
+ const f = await fixture(archived);
+ const grandchild = await f.rollout(f.child.base);
+ for (const account of ['account-a', 'account-b', 'account-a']) {
+ const host = f.host(f.historyHome, account);
+ await expect(f.resume(host, grandchild)).resolves.toMatchObject({ thread: { id: grandchild.id } });
+ const status = await host.request('account/read', { refreshToken: false });
+ expect(status).toMatchObject({ account: { type: 'chatgpt', email: `${account}@example.invalid`, planType: 'pro' } });
+ await host.shutdown('simulate transport replacement');
+ await expect(f.resume(host, grandchild)).resolves.toMatchObject({ thread: { id: grandchild.id } });
+ expect(await host.request('account/read', { refreshToken: false })).toMatchObject({
+ account: { email: `${account}@example.invalid` },
+ });
+ await host.retire();
+ }
+ await f.assertOriginals();
+ }, 60_000);
+
+ it('keeps native forks in the original history domain', async () => {
+ const f = await fixture();
+ const host = f.host(f.historyHome, 'account-b');
+ await f.resume(host);
+ const fork = await host.request<{ thread: { id: string; path: string } }>('thread/fork', {
+ threadId: f.child.id, path: f.child.file, cwd: f.root, model: 'gpt-6-astra',
+ }, { timeoutMs: 15_000 });
+ expect((await fs.realpath(fork.thread.path)).startsWith((await fs.realpath(path.join(f.historyHome, 'sessions'))) + path.sep)).toBe(true);
+ await host.retire();
+ await expect(f.resume(f.host(f.historyHome, 'account-a'), {
+ id: fork.thread.id, file: fork.thread.path })).resolves.toMatchObject({ thread: { id: fork.thread.id } });
+ await f.assertOriginals();
+ }, 30_000);
+
+ it('rejects the old cross-home native fork path without changing source history', async () => {
+ const f = await fixture();
+ const original = f.host(f.historyHome, 'account-a');
+ await f.resume(original, f.parent);
+ await original.retire();
+ const oldForkHost = f.host(f.credentialHome, 'account-b');
+ await expect(oldForkHost.request('thread/fork', {
+ threadId: f.parent.id, path: f.parent.file, cwd: f.root, model: 'gpt-6-astra',
+ }, { timeoutMs: 15_000 })).rejects.toThrow('must be in Codex home directory');
+ await f.assertOriginals();
+ }, 30_000);
+
+ it('refreshes managed credentials on disk after a native 401 even before natural expiry', async () => {
+ const f = await fixture(false, true);
+ const authPath = path.join(f.credentialHome, 'auth.json');
+ const initial = fakeTokens('account-b').accessToken;
+ // A freshly written managed login must still force-refresh after a rejected request.
+ await fs.writeFile(authPath, JSON.stringify({ auth_mode: 'chatgpt', OPENAI_API_KEY: null,
+ tokens: { id_token: initial, access_token: initial, refresh_token: 'fixture-refresh-b', account_id: 'account-b' },
+ last_refresh: new Date().toISOString() }));
+ const accountHost = f.host(f.credentialHome, 'account-b', true);
+ const host = f.host(f.historyHome, 'account-b', false, { readTokens: async refresh => {
+ if (refresh) await accountHost.request('account/read', { refreshToken: true }, { timeoutMs: 8_000 });
+ const credentials = JSON.parse(await fs.readFile(authPath, 'utf8'));
+ return { accessToken: credentials.tokens.access_token, chatgptAccountId: credentials.tokens.account_id };
+ } });
+ await f.resume(host);
+ let completed!: (value: unknown) => void;
+ const completion = new Promise(resolve => { completed = resolve; });
+ const subscription = host.subscribeThread(f.child.id, { turnCompleted: completed });
+ try {
+ await host.request('turn/start', { threadId: f.child.id, input: [{ type: 'text', text: 'fixture request' }] }, { timeoutMs: 15_000 });
+ await expect(completion).resolves.toMatchObject({ turn: { status: 'completed' } });
+ expect(f.wireRequests).toEqual([
+ { authorization: `Bearer ${fakeTokens('account-b').accessToken}`, account: 'account-b' },
+ { authorization: `Bearer ${fakeTokens('account-b', 'refreshed').accessToken}`, account: 'account-b' },
+ ]);
+ expect(f.refreshRequests).toEqual([expect.objectContaining({ grant_type: 'refresh_token', refresh_token: 'fixture-refresh-b' })]);
+ expect(JSON.parse(await fs.readFile(authPath, 'utf8')).tokens).toMatchObject({
+ access_token: fakeTokens('account-b', 'refreshed').accessToken, refresh_token: 'fixture-refresh-b2', account_id: 'account-b',
+ });
+ await f.assertOriginals(true);
+ } finally {
+ await subscription.release();
+ }
+ }, 30_000);
+});
diff --git a/packages/maker-core/src/agents/codex/app-server/external-auth.test.ts b/packages/maker-core/src/agents/codex/app-server/external-auth.test.ts
new file mode 100644
index 0000000000..f1067b0a02
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/app-server/external-auth.test.ts
@@ -0,0 +1,92 @@
+import { describe, expect, it, vi } from 'vitest';
+import { CodexExternalAuthSession, assertCodexEphemeralAuth, useCodexHistoryHome } from './external-auth.js';
+
+const initial = { accessToken: 'test-token-old', chatgptAccountId: 'account-b' };
+
+describe('external account authentication', () => {
+ it.each(['win32', 'darwin', 'linux'] as const)('honors %s environment casing without leaking Windows identity aliases', (platform) => {
+ const aliases = { Codex_Home: '/old-home', Codex_Access_Token: 'old-token',
+ codex_api_key: 'old-key', OpenAI_API_Key: 'old-key', OpenAI_Federation_Rule_Id: 'old-rule',
+ OpenAI_Identity_Token_File: '/old-file', OpenAI_Workload_Identity_Context: 'old-context' };
+ const env = { ...aliases, CODEX_HOME: '/account-b', OPENAI_API_KEY: 'old-uppercase',
+ XDT_CODEX_API_KEY: 'selected-gateway', Path: '/bin' };
+ expect(useCodexHistoryHome(env, '/history-a', platform)).toEqual({
+ ...(platform === 'win32' ? {} : aliases),
+ CODEX_HOME: '/history-a', XDT_CODEX_API_KEY: 'selected-gateway', Path: '/bin',
+ });
+ expect(env).toMatchObject({ ...aliases, CODEX_HOME: '/account-b', OPENAI_API_KEY: 'old-uppercase' });
+ });
+
+ it('removes inherited native identities while preserving the selected gateway credentials', () => {
+ const env = { CODEX_HOME: '/account-b', CODEX_ACCESS_TOKEN: 'old', CODEX_API_KEY: 'old',
+ OPENAI_API_KEY: 'old', OPENAI_FEDERATION_RULE_ID: '', OPENAI_IDENTITY_TOKEN_FILE: '/old',
+ OPENAI_WORKLOAD_IDENTITY_CONTEXT: 'old', XDT_CODEX_API_KEY: 'selected-gateway', PATH: '/bin' };
+ expect(useCodexHistoryHome(env, '/history-a')).toEqual({
+ CODEX_HOME: '/history-a', XDT_CODEX_API_KEY: 'selected-gateway', PATH: '/bin',
+ });
+ expect(env.CODEX_HOME).toBe('/account-b');
+ });
+
+ it('refreshes the pinned account and reauthenticates each new client', async () => {
+ const readTokens = vi.fn().mockResolvedValueOnce(initial)
+ .mockResolvedValue({ ...initial, accessToken: 'test-token-new' });
+ const session = new CodexExternalAuthSession({ readTokens });
+ const request = vi.fn(async (method: string) => method === 'config/read'
+ ? { config: { cli_auth_credentials_store: 'ephemeral' } } : { type: 'chatgptAuthTokens' });
+ await session.authenticate(request);
+ expect(request).toHaveBeenCalledWith('account/login/start', { type: 'chatgptAuthTokens', ...initial });
+ await expect(session.tokens(true, 'account-b')).resolves.toMatchObject({ accessToken: 'test-token-new' });
+ expect(readTokens).toHaveBeenLastCalledWith(true, 'test-token-old');
+ await session.authenticate(request);
+ expect(request).toHaveBeenLastCalledWith('account/login/start', {
+ type: 'chatgptAuthTokens', ...initial, accessToken: 'test-token-new',
+ });
+ });
+
+ it('does not treat a successful account read with the same rejected token as a refresh', async () => {
+ const session = new CodexExternalAuthSession({ readTokens: async () => initial });
+ await session.tokens(false);
+ await expect(session.tokens(true, 'account-b')).rejects.toThrow('authentication is unavailable');
+ });
+
+ it('rejects foreign refreshes before reading credentials and rejects account changes on reconnect', async () => {
+ const readTokens = vi.fn().mockResolvedValue(initial);
+ const session = new CodexExternalAuthSession({ readTokens });
+ await session.tokens(false);
+ await expect(session.tokens(true, 'account-a')).rejects.toThrow('authentication is unavailable');
+ expect(readTokens).toHaveBeenCalledTimes(1);
+ readTokens.mockResolvedValue({ ...initial, chatgptAccountId: 'account-c' });
+ await expect(session.tokens(false)).rejects.toThrow('authentication is unavailable');
+ });
+
+ it('redacts source and RPC errors, including echoed credentials', async () => {
+ const source = new CodexExternalAuthSession({ readTokens: async () => { throw new Error('secret-token'); } });
+ await expect(source.tokens(false)).rejects.toThrow('Codex account authentication is unavailable or has changed');
+ const session = new CodexExternalAuthSession({ readTokens: async () => initial });
+ await expect(session.authenticate(async () => { throw new Error('secret-token'); }))
+ .rejects.toThrow('Codex could not initialize isolated account authentication');
+ await expect(session.authenticate(async () => ({ type: 'apiKey' })))
+ .rejects.toThrow('Codex could not initialize isolated account authentication');
+ });
+ it('refuses effective persistent credential policy before sending external tokens', async () => {
+ const request = vi.fn().mockResolvedValue({ config: { cli_auth_credentials_store: 'file' } });
+ await expect(assertCodexEphemeralAuth(request)).rejects.toThrow('isolated account authentication');
+ expect(request).toHaveBeenCalledTimes(1);
+ expect(request).toHaveBeenCalledWith('config/read', { includeLayers: false });
+ });
+ it('bounds credential reads and ignores results arriving after timeout', async () => {
+ vi.useFakeTimers();
+ try {
+ let resolve!: (value: typeof initial) => void;
+ const session = new CodexExternalAuthSession({ readTokens: () => new Promise(done => { resolve = done; }) });
+ const pending = session.tokens(false);
+ const rejected = expect(pending).rejects.toThrow('authentication is unavailable');
+ await vi.advanceTimersByTimeAsync(10_000);
+ await rejected;
+ resolve(initial);
+ await expect(session.tokens(true, initial.chatgptAccountId)).rejects.toThrow('authentication is unavailable');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/app-server/external-auth.ts b/packages/maker-core/src/agents/codex/app-server/external-auth.ts
new file mode 100644
index 0000000000..c5ca5f36a5
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/app-server/external-auth.ts
@@ -0,0 +1,93 @@
+/**
+ * Codex 0.153.4's experimental external ChatGPT authentication contract.
+ * Keep this adapter covered by the real-binary contract test before runtime upgrades.
+ * Credentials stay in the selected account's managed home; this process only holds
+ * access tokens in memory, while CODEX_HOME remains the native history's home.
+ */
+export interface CodexChatgptTokens {
+ accessToken: string;
+ chatgptAccountId: string;
+ chatgptPlanType?: string;
+}
+
+export interface CodexExternalAuth {
+ readTokens: (refresh: boolean, staleAccessToken?: string) => Promise<CodexChatgptTokens>;
+}
+
+export const CODEX_EXTERNAL_AUTH_REFRESH = 'account/chatgptAuthTokens/refresh';
+
+export async function assertCodexEphemeralAuth(
+ request: (method: string, params: unknown) => Promise<unknown>,
+): Promise<void> {
+ try {
+ const config = await request('config/read', { includeLayers: false }) as {
+ config?: { cli_auth_credentials_store?: unknown };
+ } | null;
+ if (config?.config?.cli_auth_credentials_store !== 'ephemeral') throw new Error();
+ } catch {
+ throw new Error('Codex could not initialize isolated account authentication');
+ }
+}
+
+/** Must run before spawn: initialize itself can otherwise load the old auth.json. */
+export function useCodexHistoryHome(
+ env: Record<string, string>,
+ historyHome: string,
+ platform: NodeJS.Platform = process.platform,
+): Record<string, string> {
+ const replacedKeys = new Set(['CODEX_HOME', 'CODEX_ACCESS_TOKEN', 'CODEX_API_KEY', 'OPENAI_API_KEY',
+ 'OPENAI_FEDERATION_RULE_ID', 'OPENAI_IDENTITY_TOKEN_FILE', 'OPENAI_WORKLOAD_IDENTITY_CONTEXT']);
+ const result: Record<string, string> = {};
+ for (const [key, value] of Object.entries(env)) {
+ // Windows child environments are case-insensitive, including CODEX_HOME aliases.
+ if (!replacedKeys.has(platform === 'win32' ? key.toUpperCase() : key)) result[key] = value;
+ }
+ result.CODEX_HOME = historyHome;
+ return result;
+}
+
+/** One identity per host, including reconnects. Never log/echo authentication payloads. */
+export class CodexExternalAuthSession {
+ private accountId: string | undefined;
+ private accessToken: string | undefined;
+
+ constructor(private readonly source: CodexExternalAuth) {}
+
+ async tokens(refresh: boolean, previousAccountId?: unknown): Promise<CodexChatgptTokens> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ if (refresh && (!this.accountId || previousAccountId !== this.accountId)) throw new Error();
+ const staleAccessToken = refresh ? this.accessToken : undefined;
+ const tokens = await Promise.race([
+ this.source.readTokens(refresh, staleAccessToken),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error()), 10_000);
+ timer.unref?.();
+ }),
+ ]);
+ if (!tokens.accessToken || !tokens.chatgptAccountId) throw new Error();
+ if (this.accountId && this.accountId !== tokens.chatgptAccountId) throw new Error();
+ if (refresh && tokens.accessToken === staleAccessToken) throw new Error();
+ this.accountId = tokens.chatgptAccountId;
+ this.accessToken = tokens.accessToken;
+ return tokens;
+ } catch {
+ // A source/JSON-RPC error may include credentials. Do not retain its cause.
+ throw new Error('Codex account authentication is unavailable or has changed');
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ }
+
+ async authenticate(request: (method: string, params: unknown) => Promise<unknown>): Promise<void> {
+ const tokens = await this.tokens(false);
+ try {
+ const result = await request('account/login/start', { type: 'chatgptAuthTokens', ...tokens });
+ if (!result || typeof result !== 'object' || !('type' in result) || result.type !== 'chatgptAuthTokens') {
+ throw new Error();
+ }
+ } catch {
+ throw new Error('Codex could not initialize isolated account authentication');
+ }
+ }
+}
diff --git a/packages/maker-core/src/agents/codex/app-server/host.test.ts b/packages/maker-core/src/agents/codex/app-server/host.test.ts
index 75d62e7aa1..191e802237 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.test.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts
@@ -153,6 +153,41 @@ class NotificationTransport implements Transport {
}
}
+describe('AppServerHost isolated account lifecycle', () => {
+ it.each([false, true])('rejects persistent native policy before task dispatch (OAuth: %s)', async oauth => {
+ const transport = new NotificationTransport(() => ({ config: { cli_auth_credentials_store: 'file' } }));
+ const readTokens = vi.fn(async () => ({ accessToken: 'fixture-token', chatgptAccountId: 'account-b' }));
+ const host = new AppServerHost({ createTransport: () => transport, logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' }, requireEphemeralAuth: true,
+ ...(oauth ? { externalAuth: { readTokens } } : {}),
+ });
+ try {
+ await expect(host.request('thread/resume', { threadId: 'fixture' })).rejects.toThrow('isolated account authentication');
+ const methods = transport.lines.map(line => JSON.parse(line).method);
+ expect(methods).not.toContain('account/login/start');
+ expect(methods).not.toContain('thread/resume');
+ expect(readTokens).not.toHaveBeenCalled();
+ } finally { await host.retire(); }
+ });
+
+ it('never installs a credential read that finishes after retirement', async () => {
+ const transport = new NotificationTransport(() => ({ config: { cli_auth_credentials_store: 'ephemeral' } }));
+ let resolve!: (value: { accessToken: string; chatgptAccountId: string }) => void;
+ const readTokens = vi.fn(() => new Promise<{ accessToken: string; chatgptAccountId: string }>(done => { resolve = done; }));
+ const host = new AppServerHost({ createTransport: () => transport, logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' }, externalAuth: { readTokens },
+ });
+ const pending = host.ensureStarted();
+ const rejected = expect(pending).rejects.toThrow();
+ await vi.waitFor(() => expect(readTokens).toHaveBeenCalledOnce());
+ const retiring = host.retire();
+ resolve({ accessToken: 'late-fixture-secret', chatgptAccountId: 'account-b' });
+ await retiring;
+ await rejected;
+ expect(transport.lines.join('\n')).not.toContain('late-fixture-secret');
+ });
+});
+
describe('AppServerHost assistant text delta routing', () => {
it('subscribes to dedicated agentMessage deltas and routes them to the owning thread', async () => {
const transport = new NotificationTransport();
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index 713199e54b..19c788b9f9 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -28,6 +28,7 @@ import { randomUUID } from 'node:crypto';
import type { Logger } from '../../../interfaces/logger.js';
import type { CodexSessionMcpConfigInput, CodexSubagentRoutingProfile } from '../../base-agent.js';
import { AppServerClient } from './client.js';
+import { CODEX_EXTERNAL_AUTH_REFRESH, CodexExternalAuthSession, assertCodexEphemeralAuth, type CodexExternalAuth } from './external-auth.js';
import type { Transport } from './transport.js';
import {
Method,
@@ -235,6 +236,10 @@ export interface ThreadSubscription {
}
export interface AppServerHostOptions {
+ /** Applied before the host becomes ready, and reapplied after every transport restart. */
+ externalAuth?: CodexExternalAuth;
+ /** Required for every cross-home runtime, including gateway-only routes. */
+ requireEphemeralAuth?: boolean;
/**
* Transport 工厂; host 每次 bootstrap (含 transport-error 后的重连) 都调一次。
* 本地 codex 用 `createStdioTransport({binaryPath, cwd, env, extraArgs})`,
@@ -325,6 +330,7 @@ interface BufferedNotification {
}
export class AppServerHost {
+ private readonly externalAuth: CodexExternalAuthSession | undefined;
private readonly connectionId = randomUUID();
private readonly logger: Logger;
private readonly bufferTtlMs: number;
@@ -367,6 +373,7 @@ export class AppServerHost {
private retirementPromise: Promise<void> | null = null;
constructor(private readonly opts: AppServerHostOptions) {
+ this.externalAuth = opts.externalAuth ? new CodexExternalAuthSession(opts.externalAuth) : undefined;
if (typeof opts.createTransport !== 'function') {
throw new Error('AppServerHost: createTransport factory is required');
}
@@ -640,6 +647,21 @@ export class AppServerHost {
});
this.client = client;
+ if (this.externalAuth) {
+ client.setRequestHandler(CODEX_EXTERNAL_AUTH_REFRESH, async (params) => {
+ if (this.client !== client || this.shuttingDown || this.retired) {
+ throw new Error('Codex account authentication host has retired');
+ }
+ const request = params as { reason?: unknown; previousAccountId?: unknown } | null;
+ if (request?.reason !== 'unauthorized') throw new Error('Unsupported Codex authentication refresh');
+ const tokens = await this.externalAuth!.tokens(true, request.previousAccountId);
+ if (this.client !== client || this.shuttingDown || this.retired) {
+ throw new Error('Codex account authentication host has retired');
+ }
+ return tokens;
+ });
+ }
+
// 注册 notification handlers BEFORE initialize: server 在握手响应前可能就推了
// banner / 启动 notification, 漏接就丢。
for (const method of SUBSCRIBED_METHODS) {
@@ -813,6 +835,17 @@ export class AppServerHost {
...capabilities,
};
const resp = await client.initialize(this.opts.clientInfo, mergedCapabilities);
+ if (this.opts.requireEphemeralAuth || this.externalAuth) {
+ // Requirements can override CLI configuration. Reject before any task RPC
+ // or token installation; initialization has already loaded native config.
+ await assertCodexEphemeralAuth((method, params) => client.request(method, params, { timeoutMs: 10_000 }));
+ }
+ if (this.externalAuth) {
+ await this.externalAuth.authenticate((method, params) => client.request(method, params, { timeoutMs: 10_000 }));
+ if (this.client !== client || this.shuttingDown || this.retired) {
+ throw new Error('Codex account authentication host has retired');
+ }
+ }
this.logger.info('shared app-server up', {
userAgent: resp.userAgent,
codexHome: resp.codexHome,
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index f676c904c9..3501e29fe2 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -258,6 +258,7 @@ const { MockCodexTransport, createdTransports, createdStdioOptions } = vi.hoiste
const createdTransports: MockCodexTransport[] = [];
const createdStdioOptions: Array<{
extraArgs?: string[];
+ env?: Record<string, string>;
onProcessSpawned?: (pid: number) => void | (() => void);
}> = [];
return { MockCodexTransport, createdTransports, createdStdioOptions };
@@ -266,6 +267,7 @@ const { MockCodexTransport, createdTransports, createdStdioOptions } = vi.hoiste
vi.mock('./app-server/stdioTransport.js', () => ({
createStdioTransport: (opts: {
extraArgs?: string[];
+ env?: Record<string, string>;
onProcessSpawned?: (pid: number) => void | (() => void);
}) => {
createdStdioOptions.push(opts);
@@ -358,6 +360,92 @@ function createDeps(
}
describe('CodexAgent spawn configuration', () => {
+ it.each(['oauth-bearer', 'gateway-key'] as const)('separates canonical history from target credentials (%s)', async mode => {
+ const credentialHome = path.resolve(os.tmpdir(), 'target-account-fixture');
+ const historyHome = path.resolve(os.tmpdir(), 'original-history-fixture');
+ const sqliteHome = path.resolve(os.tmpdir(), 'original-database-fixture');
+ const tokens = { accessToken: 'test-target-token', chatgptAccountId: 'target-account' };
+ const readTokens = vi.fn(async () => tokens);
+ const prepare = vi.fn<NonNullable<AgentDeps['prepareCodexExtraSpawnConfig']>>(async () => ({ extraArgs: ['-c', 'model_catalog_json="target-catalog.json"'], extraEnv: {}, codexProxyActive: true }));
+ const deps = createDeps({}, { prepareCodexExtraSpawnConfig: prepare,
+ isCodexAccountProvider: id => id === 'account-b',
+ createCodexAuthTokenReader: () => readTokens,
+ resolveCodexThreadStorage: async () => ({ historyHome, sqliteHome }),
+ });
+ deps.auth.getState = async () => ({ authenticated: true, authSource: mode === 'oauth-bearer' ? 'oauth' : 'api-key' });
+ deps.auth.getAuthEnv = async () => ({ CODEX_HOME: credentialHome, XDT_CODEX_API_KEY: 'selected-gateway' });
+ MockCodexTransport.onCreate = transport => {
+ transport.setMockResponse('initialize', { result: { userAgent: 'mock-codex', codexHome: historyHome } });
+ transport.setMockResponse('config/read', { result: { config: { cli_auth_credentials_store: 'ephemeral' } } });
+ transport.setMockResponse('account/login/start', { result: { type: 'chatgptAuthTokens' } });
+ };
+ const agent = new CodexAgent(deps);
+ try {
+ const handle = await agent.startSession({ sessionId: 'cross-home', resumeSessionId: '0199ae4e-d6b0-7755-a755-66754cd7a847',
+ providerId: mode === 'oauth-bearer' ? 'account-b' : 'xd', model: 'gpt-5.4', workingDir: os.tmpdir() });
+ expect(createdStdioOptions[0].env).toMatchObject({ CODEX_HOME: historyHome, XDT_CODEX_API_KEY: 'selected-gateway' });
+ expect(createdStdioOptions[0].extraArgs).toContain(`sqlite_home=${JSON.stringify(sqliteHome)}`);
+ expect(createdStdioOptions[0].extraArgs).toContain('cli_auth_credentials_store="ephemeral"');
+ expect(prepare.mock.calls[0][1]).toMatchObject({ runtimeCodexHome: historyHome });
+ if (mode === 'oauth-bearer') {
+ expect(prepare.mock.calls[0][1]).toMatchObject({ codexHome: credentialHome, providerId: 'account-b' });
+ expect(readTokens).toHaveBeenCalledTimes(1);
+ const methods = createdTransports[0].lines.map(line => JSON.parse(line).method);
+ expect(methods).toContain('thread/resume');
+ expect(methods.indexOf('thread/resume')).toBeGreaterThan(methods.indexOf('account/login/start'));
+ } else {
+ expect(readTokens).not.toHaveBeenCalled();
+ expect(createdTransports[0].lines.some(line => JSON.parse(line).method === 'account/login/start')).toBe(false);
+ }
+ await handle.close();
+ } finally {
+ await agent.forceDisposeLocalHostForAuthChange('test cleanup');
+ }
+ });
+
+ it('refreshes external credentials through the target managed account host without recursive login', async () => {
+ const credentialHome = path.resolve(os.tmpdir(), 'target-account-fixture');
+ const historyHome = path.resolve(os.tmpdir(), 'original-history-fixture');
+ const initial = { accessToken: 'test-old-token', chatgptAccountId: 'target-account' };
+ const updated = { ...initial, accessToken: 'test-new-token' };
+ const readTokens = vi.fn().mockResolvedValueOnce(initial).mockResolvedValueOnce(initial).mockResolvedValue(updated);
+ const deps = createDeps({}, { isCodexAccountProvider: id => id === 'account-b',
+ createCodexAuthTokenReader: () => readTokens,
+ resolveCodexThreadStorage: async () => ({ historyHome, sqliteHome: historyHome }),
+ });
+ deps.auth.getState = async () => ({ authenticated: true, authSource: 'oauth' });
+ deps.auth.getAuthEnv = async () => ({ CODEX_HOME: credentialHome, CODEX_ACCESS_TOKEN: 'inherited-token',
+ OPENAI_IDENTITY_TOKEN_FILE: '/inherited-identity' });
+ MockCodexTransport.onCreate = transport => {
+ transport.setMockResponse('config/read', { result: { config: { cli_auth_credentials_store: 'ephemeral' } } });
+ transport.setMockResponse('account/login/start', { result: { type: 'chatgptAuthTokens' } });
+ transport.setMockResponse('account/read', { result: {} });
+ };
+ const agent = new CodexAgent(deps);
+ try {
+ const handle = await agent.startSession({ sessionId: 'cross-home-refresh', resumeSessionId: 'source',
+ providerId: 'account-b', model: 'gpt-5.4', workingDir: os.tmpdir() });
+ const taskTransport = createdTransports[0];
+ taskTransport.emitMockLine({ id: 'refresh-account', method: 'account/chatgptAuthTokens/refresh',
+ params: { reason: 'unauthorized', previousAccountId: 'target-account' } });
+ await vi.waitFor(() => expect(taskTransport.lines.map(line => JSON.parse(line)))
+ .toContainEqual({ id: 'refresh-account', result: updated }));
+ expect(createdStdioOptions[1].env?.CODEX_HOME).toBe(credentialHome);
+ for (const options of createdStdioOptions) {
+ expect(options.env).not.toHaveProperty('CODEX_ACCESS_TOKEN');
+ expect(options.env).not.toHaveProperty('OPENAI_IDENTITY_TOKEN_FILE');
+ }
+ expect(createdStdioOptions[1].extraArgs).not.toContain('cli_auth_credentials_store="ephemeral"');
+ expect(createdTransports[1].lines.some(line => JSON.parse(line).method === 'account/login/start')).toBe(false);
+ expect(createdTransports[1].lines.map(line => JSON.parse(line))).toContainEqual(expect.objectContaining({
+ method: 'account/read', params: { refreshToken: true },
+ }));
+ await handle.close();
+ } finally {
+ await agent.forceDisposeLocalHostForAuthChange('test cleanup');
+ }
+ });
+
it('keeps host-enforced plugin disabling when dynamic spawn preparation fails', async () => {
const prepareCodexExtraSpawnConfig = vi.fn(async () => {
throw new Error('bridge unavailable');
@@ -8860,7 +8948,7 @@ describe('CodexAgent MCP thread context hooks', () => {
const prepare = vi.fn(async () => source);
const recordLocation = vi.fn(async () => {});
const agent = new CodexAgent(createDeps({}, { prepareCodexResumeSession: prepare,
- resolveCodexThreadStorageHome: async () => dir, recordCodexThreadLocation: recordLocation }));
+ resolveCodexThreadStorage: async () => ({ historyHome: dir, sqliteHome: dir }), recordCodexThreadLocation: recordLocation }));
const host = installFakeHost(agent, (method, raw) => {
if (method === 'thread/read') throw new Error(`thread not loaded: ${threadId}`);
if (method === Method.ThreadResume) return { thread: { id: threadId, path: source }, model: 'gpt-5.6-luna', modelProvider: (raw as { modelProvider?: string }).modelProvider };
@@ -22809,20 +22897,20 @@ describe('CodexAgent.forkSdkSession', () => {
const recordCodexThreadLocation = vi.fn(async () => {});
const agent = new CodexAgent(createDeps({}, {
isCodexAccountProvider: (id) => id === 'account-b',
- resolveCodexThreadStorageHome: async () => '/account-a',
+ resolveCodexThreadStorage: async () => ({ historyHome: '/account-a', sqliteHome: '/account-a' }),
prepareCodexResumeSession: async () => '/account-a/sessions/source.jsonl',
recordCodexThreadLocation,
}));
const host = installFakeHost(agent, method => {
if (method === Method.ThreadTurnsList) {
expect(host.getHost).toHaveBeenCalledWith(undefined, 'oauth-bearer',
- expect.objectContaining({ providerId: 'account-b', sqliteHome: '/account-a' }));
+ expect.objectContaining({ providerId: 'account-b', sqliteHome: '/account-a', historyHome: '/account-a' }));
return { data: [{ id: 'boundary', status: 'completed', startedAt: 100 }], nextCursor: null };
}
if (method === Method.ThreadFork) return {
- thread: { id: 'child', path: '/account-b/sessions/child.jsonl' },
+ thread: { id: 'child', path: '/account-a/sessions/child.jsonl' },
};
- }, { userAgent: 'mock-codex/0.153.4', codexHome: '/account-b' });
+ }, { userAgent: 'mock-codex/0.153.4', codexHome: '/account-a' });
await expect(agent.forkSdkSession({
sourceSdkSessionId: 'source', upToMessageId: undefined,
providerId: 'account-b', tailTurnsToDrop: 1, forkAtTimestampMs: 110_123,
@@ -22830,7 +22918,7 @@ describe('CodexAgent.forkSdkSession', () => {
expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({
path: '/account-a/sessions/source.jsonl', lastTurnId: 'boundary',
}));
- expect(recordCodexThreadLocation).toHaveBeenCalledWith('child', '/account-a', '/account-b/sessions/child.jsonl');
+ expect(recordCodexThreadLocation).toHaveBeenCalledWith('child', '/account-a', '/account-a/sessions/child.jsonl');
});
it('forks failed paginated history without rollback when no UI anchor was saved', async () => {
@@ -29321,6 +29409,7 @@ describe('CodexAgent reconnect-stall watchdog', () => {
agent: CodexAgent,
interruptHangs = false,
interruptAck?: Promise<unknown>,
+ codexHome?: string,
) {
let turnSeq = 0;
return installFakeHost(agent, (method) => {
@@ -29330,7 +29419,7 @@ describe('CodexAgent reconnect-stall watchdog', () => {
return interruptHangs ? new Promise<never>(() => {}) : {};
}
return undefined;
- });
+ }, { codexHome });
}
async function startReconnectTurn(
@@ -29338,8 +29427,9 @@ describe('CodexAgent reconnect-stall watchdog', () => {
sessionId: string,
interruptAck?: Promise<unknown>,
signal?: AbortSignal,
+ codexHome?: string,
) {
- const host = installReconnectHost(agent, false, interruptAck);
+ const host = installReconnectHost(agent, false, interruptAck, codexHome);
const handle = await agent.startSession({ sessionId, model: 'gpt-5.4', workingDir: '/repo' });
const seen: AgentEvent[] = [];
void (async () => {
@@ -29405,14 +29495,15 @@ describe('CodexAgent reconnect-stall watchdog', () => {
].flatMap((scenario) => [
{ ...scenario, releaseFailure: undefined as boolean | undefined },
...(scenario.rejectAck ? [false, true].map((releaseFailure) => ({ ...scenario, releaseFailure })) : []),
- ]))('settles oversized recovery: %j', async ({ cancelled, completion, rejectAck, releaseFailure }) => {
+ ]))('settles oversized recovery without a global account home: %j', async ({ cancelled, completion, rejectAck, releaseFailure }) => {
vi.useFakeTimers();
const agent = new CodexAgent(createDeps());
const proto = Object.getPrototypeOf(agent) as {
findRolloutPath: (id: string) => Promise<string>;
hasLocalCodexHome: () => boolean;
};
- const localHome = vi.spyOn(proto, 'hasLocalCodexHome').mockReturnValue(true);
+ // Cold resume has a session history home but must not populate the global account cache.
+ const localHome = vi.spyOn(proto, 'hasLocalCodexHome').mockReturnValue(false);
const find = vi.spyOn(proto, 'findRolloutPath').mockResolvedValue('/tmp/mock-oversized.jsonl');
const measure = vi.spyOn(await import('./rollout-sanitize.js'), 'measureRolloutLiveTailStats')
.mockResolvedValue({
@@ -29430,7 +29521,7 @@ describe('CodexAgent reconnect-stall watchdog', () => {
const cancellation = new AbortController();
const retire = vi.spyOn(agent as unknown as { retireHostKey: (...args: unknown[]) => Promise<void> },
'retireHostKey').mockResolvedValue(undefined);
- const { host, handle, handlers, seen } = await startReconnectTurn(agent, 'session-reconnect-oversized', ack, cancellation.signal);
+ const { host, handle, handlers, seen } = await startReconnectTurn(agent, 'session-reconnect-oversized', ack, cancellation.signal, '/tmp/session-history-home');
const releasing = deferred<void>();
const release = host.subscribeThread.mock.results[0]?.value.release;
if (releaseFailure !== undefined) release.mockImplementationOnce(() => releasing.promise);
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 522b0b89e1..2233be6203 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -191,6 +191,7 @@ import { parseReconnectAttemptMessage } from '../shared/network-error.js';
import { extractNonSecretErrorSignals } from '@cindy/maker-shared/error-redaction';
import { AppServerHost, type ThreadEventHandlers, type ThreadSubscription } from './app-server/host.js';
import { AppServerRequestTimeoutError } from './app-server/client.js';
+import { useCodexHistoryHome, type CodexExternalAuth } from './app-server/external-auth.js';
import {
isTerminalRateLimitRetryExhaustion,
TERMINAL_RATE_LIMIT_RETRY_MAX_ATTEMPTS,
@@ -2292,6 +2293,7 @@ export class CodexAgent extends BaseAgent {
customContextModel?: string;
customContextWindow?: number;
sqliteHome?: string;
+ historyHome?: string;
} = {},
): Promise<AppServerHost> {
const key = opts.keyOverride ?? (opts.providerId ? `local-account:${opts.providerId}` : hostKey(remoteHostId));
@@ -2496,6 +2498,7 @@ export class CodexAgent extends BaseAgent {
opts.customContextWindow,
opts.providerId,
opts.sqliteHome,
+ opts.historyHome,
).finally(() => {
// 成功: this.hosts 已赋值, 后续走快路径; 失败: 清掉 promise 让下次调用能重试
const current = this.hostPromises.get(key);
@@ -2534,14 +2537,16 @@ export class CodexAgent extends BaseAgent {
}
/** Start the local OAuth host used by non-model account control-plane RPCs. */
- private async getStartedAccountHost(providerId?: string): Promise<AppServerHost> {
+ private async getStartedAccountHost(providerId?: string, startupTimeoutMs?: number): Promise<AppServerHost> {
const credentialMode = 'oauth-bearer';
const host = await this.getHost(undefined, credentialMode, {
providerId,
keyOverride: providerId ? `local-account:${providerId}:control-plane` : localControlPlaneHostKey(credentialMode),
hostPurpose: 'control-plane',
});
- const init = await host.ensureStarted();
+ const init = startupTimeoutMs
+ ? await host.ensureStartedWithTimeout(startupTimeoutMs, 'account token refresh')
+ : await host.ensureStarted();
if (init.codexHome && !providerId) this.codexHome = init.codexHome;
return host;
}
@@ -2675,6 +2680,7 @@ export class CodexAgent extends BaseAgent {
customContextWindow?: number,
providerId?: string,
sqliteHome?: string,
+ historyHome?: string,
): Promise<AppServerHost> {
const seq = (this.createHostSeqByKey.get(key) ?? 0) + 1;
this.createHostSeqByKey.set(key, seq);
@@ -2748,6 +2754,10 @@ export class CodexAgent extends BaseAgent {
let codexOpenAiWebSocketsEnabled = true;
let codexSubagentRoutingProfile: CodexExtraSpawnConfig['codexSubagentRoutingProfile'] = 'default';
let hostRetirementCleanup: CodexExtraSpawnConfig['onHostRetired'];
+ // Capture the owner/account reader before any asynchronous authentication work.
+ const readAccountTokens = !remoteHostId && historyHome
+ ? this.deps.createCodexAuthTokenReader?.(providerId)
+ : undefined;
for (;;) {
const upgradedToSuperset = spawnCredentialMode !== credentialMode;
onSpawnCredentialModeResolved?.(spawnCredentialMode);
@@ -2790,6 +2800,7 @@ export class CodexAgent extends BaseAgent {
remoteHostId,
...(providerId ? { providerId } : {}),
...(key.startsWith('local-account:') ? { codexHome: env.CODEX_HOME } : {}),
+ ...(!remoteHostId && historyHome ? { runtimeCodexHome: historyHome } : {}),
...(key.startsWith('local-account:') ? { accountHostKey: `${key}:${generation}` } : {}),
credentialMode: spawnCredentialMode,
...(spawnCredentialMode !== credentialMode
@@ -2888,6 +2899,41 @@ export class CodexAgent extends BaseAgent {
break;
}
if (!remoteHostId && sqliteHome) extraArgs.push('-c', `sqlite_home=${JSON.stringify(sqliteHome)}`);
+ let externalAuth: CodexExternalAuth | undefined;
+ const requireEphemeralAuth = !remoteHostId && !!historyHome && path.resolve(historyHome) !== path.resolve(env.CODEX_HOME ?? '');
+ if (!remoteHostId && hostPurpose === 'control-plane' && effectiveMode === 'oauth-bearer' && env.CODEX_HOME) {
+ // Managed refresh must read the selected account's file, not an inherited identity.
+ env = useCodexHistoryHome(env, env.CODEX_HOME);
+ }
+ if (requireEphemeralAuth) {
+ // Extra spawn configuration above intentionally uses the TARGET credential
+ // home (proxy auth, model catalogs and account controls). Only the native
+ // runtime uses the canonical history home, including lineage/writer locks.
+ env = useCodexHistoryHome(env, historyHome!);
+ extraArgs.push('-c', 'cli_auth_credentials_store="ephemeral"');
+ if (effectiveMode === 'oauth-bearer') {
+ if (!readAccountTokens) {
+ await hostRetirementCleanup?.();
+ throw new Error('Codex account authentication bridge is unavailable');
+ }
+ externalAuth = {
+ readTokens: async (refresh, staleAccessToken) => {
+ assertCurrentGeneration('external authentication');
+ // Validate scope before opening a native credential control-plane host.
+ let tokens = await readAccountTokens();
+ assertCurrentGeneration('external authentication scope');
+ if (refresh && tokens.accessToken === staleAccessToken) {
+ const accountHost = await this.getStartedAccountHost(providerId, 8_000);
+ assertCurrentGeneration('account token refresh');
+ await accountHost.request('account/read', { refreshToken: true }, { timeoutMs: 8_000 });
+ tokens = await readAccountTokens();
+ }
+ assertCurrentGeneration('external authentication result');
+ return tokens;
+ },
+ };
+ }
+ }
if (baseExtraArgs.length > 0) {
this.deps.logger.info('Codex plugin runtime disabled for local app-server', {
plugins: false,
@@ -2939,6 +2985,8 @@ export class CodexAgent extends BaseAgent {
const host = new AppServerHost({
createTransport,
+ externalAuth,
+ requireEphemeralAuth,
logger: this.deps.logger,
// 自报名只进 codex app-server 的 userAgent 展示串,无门控消费
// (2026-07-17 随品牌翻转改 cindy;上游 gating 走 originator,与此无关)。
@@ -4495,11 +4543,12 @@ export class CodexAgent extends BaseAgent {
: usesCustomContextHost
? localCustomContextHostKey(sid)
: hostKey(opts.remoteHostId);
- const sessionSqliteHome = !opts.remoteHostId && opts.resumeSessionId
- ? await this.deps.resolveCodexThreadStorageHome?.(opts.resumeSessionId)
+ const sessionStorage = !opts.remoteHostId && opts.resumeSessionId
+ ? await this.deps.resolveCodexThreadStorage?.(opts.resumeSessionId)
: undefined;
+ const sessionSqliteHome = sessionStorage?.sqliteHome;
const currentHostKey = (accountSessionHost ? `local-account:${accountProviderId ?? 'openai'}:session:${sid}` : baseSessionHostKey)
- + (sessionSqliteHome ? `:storage:${sessionSqliteHome}` : '');
+ + (sessionStorage ? `:storage:${sessionSqliteHome}:history:${sessionStorage.historyHome}` : '');
let releaseHostBindingLease: (() => void) | null = null;
const acquireHostBindingLeaseIfNeeded = (): void => {
if (opts.remoteHostId || releaseHostBindingLease) return;
@@ -4519,6 +4568,7 @@ export class CodexAgent extends BaseAgent {
return await this.getHost(opts.remoteHostId, credentialMode, {
...(accountProviderId ? { providerId: accountProviderId } : {}),
...(sessionSqliteHome ? { sqliteHome: sessionSqliteHome } : {}),
+ ...(sessionStorage ? { historyHome: sessionStorage.historyHome } : {}),
...(accountSessionHost || reviewMode || usesCustomContextHost || sessionSqliteHome ? { keyOverride: currentHostKey } : {}),
ignoreBindingLeases: 1,
...(reviewMode
@@ -4601,7 +4651,7 @@ export class CodexAgent extends BaseAgent {
throw error;
}
const sessionCodexHome = initResp.codexHome ?? null;
- if (initResp.codexHome && !accountProviderId) this.codexHome = initResp.codexHome;
+ if (initResp.codexHome && !accountProviderId && !sessionStorage) this.codexHome = initResp.codexHome;
// reviewer 路由的凭证模式判定: 远程 daemon 用的是 auth sync 推过去的
// 同一份订阅凭证, reviewer 调用发生在 daemon 本地 — 订阅下走 daemon →
// chatgpt.com 直连, 与本地订阅同构 (远端出网由用户网络或 agent-proxy
@@ -7641,7 +7691,8 @@ export class CodexAgent extends BaseAgent {
message,
});
};
- if (!stalledThreadId || opts.remoteHostId || !stallAgent.hasLocalCodexHome()) {
+ if (!stalledThreadId || opts.remoteHostId ||
+ (!sessionRolloutPath && !sessionCodexHome && !stallAgent.hasLocalCodexHome())) {
emitStalled('codex_reconnect_stalled', stalledMessage);
return;
}
@@ -13813,12 +13864,14 @@ export class CodexAgent extends BaseAgent {
}
// ID-only turn queries must use the source thread's index even when the
// account supplying credentials has changed. Keep the child in that index.
- const forkSqliteHome = await this.deps.resolveCodexThreadStorageHome?.(opts.sourceSdkSessionId);
+ const forkStorage = await this.deps.resolveCodexThreadStorage?.(opts.sourceSdkSessionId);
+ const forkSqliteHome = forkStorage?.sqliteHome;
stage = 'host-create';
const host = await this.getHost(undefined, forkCredentialMode, {
keyOverride: forkHostKey,
...(forkAccountId ? { providerId: forkAccountId } : {}),
...(forkSqliteHome ? { sqliteHome: forkSqliteHome } : {}),
+ ...(forkStorage ? { historyHome: forkStorage.historyHome } : {}),
hostPurpose: 'control-plane',
}).catch((error) => {
// This is the outgoing source's offline fork host, not a target send.
@@ -13834,7 +13887,7 @@ export class CodexAgent extends BaseAgent {
// Child rollout discovery scans this.codexHome. The fork host may be
// the first host started by this process, so hydrate it here.
const forkCodexHome = initResp.codexHome ?? undefined;
- if (forkCodexHome && !forkAccountId) this.codexHome = forkCodexHome;
+ if (forkCodexHome && !forkAccountId && !forkStorage) this.codexHome = forkCodexHome;
// Imported Codex threads may still live under another CODEX_HOME. Resume
// already asks the desktop host to link/adopt their state and rollout;
// fork must cross the same preparation boundary before thread/fork or the