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): 修复 fork 后子任务无法继续发送消息

DavidShen1de0b27f1391
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 7e08666522..8c93a0e024 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -7044,7 +7044,10 @@ describe('CodexAgent MCP thread context hooks', () => {
await agent.dispose();
});
- it('does not retire an explicit credential host for Codex fork utility calls', async () => {
+ it.each([false, true])('keeps the source host alive while retiring the fork host (native=%s)', async (native) => {
+ MockCodexTransport.onCreate = transport => transport.setMockResponse('initialize', {
+ result: { userAgent: 'mock-codex/0.153.4' },
+ });
const prepareCodexExtraSpawnConfig = vi.fn(async () => ({
extraArgs: [],
extraEnv: {},
@@ -7067,6 +7070,7 @@ describe('CodexAgent MCP thread context hooks', () => {
const result = await agent.forkSdkSession({
sourceSdkSessionId: 'thread-1',
upToMessageId: undefined,
+ ...(native ? { lastTurnId: 'source-turn' } : {}),
tailTurnsToDrop: 0,
});
@@ -7078,6 +7082,11 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(createdTransports[0].closed).toBe(false);
expect(createdTransports[1].closed).toBe(true);
expect(prepareCodexLocalCredentialModeSwitch).not.toHaveBeenCalled();
+ expect(result.usedNativeForkAnchor).toBe(native ? true : undefined);
+ expect(createdTransports[0].lines.some(line => {
+ const request = JSON.parse(line);
+ return request.method === Method.ThreadFork || request.method === Method.ThreadUnsubscribe;
+ })).toBe(false);
await handle.close();
await agent.dispose();
@@ -22400,11 +22409,11 @@ describe('CodexAgent.forkSdkSession', () => {
expect(retire).toHaveBeenCalledOnce();
});
- it('reuses the shared host and forks directly at a native turn', async () => {
+ it.each(['0.145.0', '0.153.4'])('isolates a native-turn fork on Codex %s', async (version) => {
const prepareCodexResumeSession = vi.fn(async () => {});
const agent = new CodexAgent(createDeps({}, { prepareCodexResumeSession }));
const host = installFakeHost(agent, undefined, {
- userAgent: 'mock-codex/0.145.0',
+ userAgent: `mock-codex/${version}`,
activeThreadIds: ['source-thread-id'],
});
const retireHostKey = vi.spyOn(
@@ -22421,19 +22430,26 @@ describe('CodexAgent.forkSdkSession', () => {
});
expect(host.getHost).toHaveBeenCalledWith(undefined, undefined, {
- ignoreBindingLeases: 1,
+ keyOverride: expect.stringMatching(/^local-fork:/),
+ hostPurpose: 'control-plane',
});
- expect(prepareCodexResumeSession).not.toHaveBeenCalled();
+ expect(prepareCodexResumeSession).toHaveBeenCalledWith('source-thread-id');
expect(host.request).toHaveBeenCalledTimes(1);
expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {
threadId: 'source-thread-id',
lastTurnId: 'turn-at-boundary',
+ persistExtendedHistory: true,
excludeTurns: true,
cwd: '/repo',
});
expect(host.request).not.toHaveBeenCalledWith(Method.ThreadRollback, expect.anything());
expect(host.unsubscribeThread).toHaveBeenCalledWith('fork-thread-id');
- expect(retireHostKey).not.toHaveBeenCalled();
+ expect(retireHostKey).toHaveBeenCalledExactlyOnceWith(
+ expect.stringMatching(/^local-fork:/),
+ 'Codex fork host is single-use',
+ expect.objectContaining({ expectedHost: host, throwOnShutdownFailure: true }),
+ );
+ expect(host.unsubscribeThread).not.toHaveBeenCalledWith('source-thread-id');
expect(result).toMatchObject({
newSdkSessionId: 'fork-thread-id',
usedNativeForkAnchor: true,
@@ -22460,6 +22476,7 @@ describe('CodexAgent.forkSdkSession', () => {
expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {
threadId: 'imported-source-thread',
lastTurnId: 'turn-at-boundary',
+ persistExtendedHistory: true,
excludeTurns: true,
});
});
@@ -22486,7 +22503,7 @@ describe('CodexAgent.forkSdkSession', () => {
expect(result.usedNativeForkAnchor).toBeUndefined();
});
- it('fails a precise fork without retiring the shared host when child unload fails', async () => {
+ it('retires only the isolated native fork host when child unsubscribe fails', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent, undefined, {
userAgent: 'mock-codex/0.145.0',
@@ -22504,10 +22521,75 @@ describe('CodexAgent.forkSdkSession', () => {
lastTurnId: 'turn-at-boundary',
})).rejects.toThrow('unsubscribe failed');
- expect(retireHostKey).not.toHaveBeenCalled();
+ expect(retireHostKey).toHaveBeenCalledExactlyOnceWith(
+ expect.stringMatching(/^local-fork:/),
+ 'Codex fork host is single-use',
+ expect.objectContaining({ expectedHost: host, throwOnShutdownFailure: true }),
+ );
expect(host.unsubscribeThread).not.toHaveBeenCalledWith('source-thread-id');
});
+ it('waits for the native fork writer to exit before the child can resume', async () => {
+ const childId = '123e4567-e89b-12d3-a456-426614174000';
+ const exit = deferred<void>();
+ const retiring = deferred<void>();
+ let writerActive = false;
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.ThreadFork) {
+ writerActive = true;
+ return { thread: { id: childId } };
+ }
+ if (method === Method.ThreadResume && writerActive) {
+ throw new Error(`thread ${childId} already has an active writer`);
+ }
+ return undefined;
+ }, { userAgent: 'mock-codex/0.153.4' });
+ vi.spyOn(agent as any, 'retireHostKey').mockImplementation(async () => {
+ retiring.resolve();
+ await exit.promise;
+ writerActive = false;
+ });
+ let forkPublished = false;
+ const resumed = agent.forkSdkSession({
+ sourceSdkSessionId: 'source-thread-id',
+ upToMessageId: undefined,
+ lastTurnId: 'turn-at-boundary',
+ }).then((fork) => {
+ forkPublished = true;
+ return agent.startSession({
+ sessionId: 'fork-child', model: 'gpt-5.4', workingDir: '/repo',
+ resumeSessionId: fork.newSdkSessionId,
+ });
+ });
+ try {
+ await retiring.promise;
+ expect(host.unsubscribeThread).toHaveBeenCalledWith(childId);
+ // Codex 0.153 acknowledges unsubscribe but retains the live writer.
+ expect(writerActive).toBe(true);
+ expect(forkPublished).toBe(false);
+ expect(host.request.mock.calls.some(([method]) => method === Method.ThreadResume)).toBe(false);
+ } finally {
+ exit.resolve();
+ }
+ const handle = await resumed;
+ expect(forkPublished).toBe(true);
+ expect(host.request.mock.calls.filter(([method]) => method === Method.ThreadResume)).toHaveLength(1);
+ await handle.close();
+ });
+
+ it.each([undefined, 'turn-at-boundary'])('rejects a fork if writer shutdown fails (anchor=%s)', async (lastTurnId) => {
+ const cause = new Error('process exit was not confirmed');
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, undefined, { userAgent: 'mock-codex/0.153.4' });
+ vi.spyOn(agent as any, 'retireHostKey').mockRejectedValue(cause);
+
+ await expect(agent.forkSdkSession({
+ sourceSdkSessionId: 'source-thread-id', upToMessageId: undefined, lastTurnId,
+ })).rejects.toMatchObject({ stage: 'host-retire', cause });
+ expect(host.unsubscribeThread).toHaveBeenCalledWith('fork-thread-id');
+ });
+
it('prepares an imported source thread before thread/fork', async () => {
const order: string[] = [];
const prepareCodexResumeSession = vi.fn(async () => {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index d1b570946b..93c8b8fb79 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -13485,84 +13485,6 @@ export class CodexAgent extends BaseAgent {
return bestPath;
}
- private async tryForkSdkSessionAtNativeTurn(
- opts: ForkSdkSessionOptions,
- lastTurnId: string,
- credentialMode: AgentCredentialMode | undefined,
- ): Promise<ForkSdkSessionResult | null> {
- const log = this.deps.logger.child('codex/fork');
- const sharedHostKey = hostKey();
- let releaseHostBindingLease: (() => void) | null = null;
- let nativeForkRequestStarted = false;
- const startedAt = Date.now();
- try {
- await this.waitForHostCredentialModeSwitch(sharedHostKey);
- releaseHostBindingLease = this.acquireHostSessionBindingLease(sharedHostKey);
- const hostStartedAt = Date.now();
- const sharedHost = await this.getHost(undefined, credentialMode, {
- ignoreBindingLeases: 1,
- });
- const initResp = await sharedHost.ensureStarted();
- const hostReadyMs = Date.now() - hostStartedAt;
- if (!supportsCodexNativeTurnFork(initResp.userAgent)) {
- log.info('native-turn fork unavailable; using legacy isolated fallback', {
- userAgent: initResp.userAgent ?? null,
- });
- return null;
- }
-
- if (initResp.codexHome) this.codexHome = initResp.codexHome;
- const prepareStartedAt = Date.now();
- if (!sharedHost.hasThreadSubscription(opts.sourceSdkSessionId)) {
- await this.deps.prepareCodexResumeSession?.(opts.sourceSdkSessionId);
- }
- const prepareMs = Date.now() - prepareStartedAt;
- const forkStartedAt = Date.now();
- nativeForkRequestStarted = true;
- const resp = await sharedHost.request<ThreadForkResponse>(Method.ThreadFork, {
- threadId: opts.sourceSdkSessionId,
- lastTurnId,
- excludeTurns: true,
- ...(opts.workingDir ? { cwd: opts.workingDir } : {}),
- } satisfies ThreadForkParams);
- const threadForkMs = Date.now() - forkStartedAt;
- const newSdkSessionId = resp.thread.id;
- const cleanupStartedAt = Date.now();
- try {
- await sharedHost.unsubscribeThread(newSdkSessionId);
- } catch (error) {
- log.warn('precise fork child cleanup failed', {
- threadId: newSdkSessionId,
- error: error instanceof Error ? error.message : String(error),
- });
- throw error;
- }
- const cleanupMs = Date.now() - cleanupStartedAt;
- log.info('forkSdkSession ◀', {
- newSdkSessionId,
- mode: 'native-turn',
- hostReadyMs,
- prepareMs,
- threadForkMs,
- cleanupMs,
- totalMs: Date.now() - startedAt,
- });
- return {
- newSdkSessionId,
- uuidMap: new Map(),
- usedNativeForkAnchor: true,
- };
- } catch (error) {
- if (nativeForkRequestStarted) throw error;
- log.warn('shared host unavailable before precise fork; using legacy isolated fallback', {
- error: error instanceof Error ? error.message : String(error),
- });
- return null;
- } finally {
- releaseHostBindingLease?.();
- }
- }
-
async forkSdkSession(opts: ForkSdkSessionOptions): Promise<ForkSdkSessionResult> {
const log = this.deps.logger.child('codex/fork');
const tailTurnsToDrop = normalizeTailTurnsToDrop(opts.tailTurnsToDrop);
@@ -13573,18 +13495,10 @@ export class CodexAgent extends BaseAgent {
model: opts.model,
});
- // Keep exact native-turn forks on the regular host so an active source
- // thread is already hydrated. The helper holds a binding lease across the
- // control-plane request and returns null only before a fork is attempted.
- if (lastTurnId && !opts.stripEncryptedReasoning) {
- const nativeForkResult = await this.tryForkSdkSessionAtNativeTurn(
- opts,
- lastTurnId,
- forkCredentialMode,
- );
- if (nativeForkResult) return nativeForkResult;
- }
-
+ // Codex 0.153 keeps unsubscribed threads loaded for 30 minutes. Even an
+ // exact native-turn fork must own a one-shot host: returning its child ID
+ // before that process exits leaves a writer that blocks a different host
+ // from resuming the child. Never retire the shared host to release it.
// 故障半径隔离(2026-08-08 实排):thread/fork 的响应体与源 thread 历史成正比、
// 无上界 —— 47MB rollout 实测产出 31MiB 单行 NDJSON,超过 client 16MiB
// maxLineBytes 守卫后整条连接被熔断,当时共享 utility host 上挂着的 5 个活跃
@@ -13601,12 +13515,10 @@ export class CodexAgent extends BaseAgent {
if (!forkHost || createdThreadIds.size === 0) return;
for (const threadId of createdThreadIds) {
try {
- // Codex 0.145 keeps a forked child loaded in the app-server. Unload
- // it before the new Cindy Session resumes with its own MCP instance
- // URL; otherwise thread/resume.config is ignored and the child
- // remains bound to this host's spawn-level URL. The ephemeral host
- // is retired right after, but graceful unload also flushes the
- // child's state before the process dies.
+ // Request graceful cleanup before retiring the one-shot host.
+ // Since 0.153 this only schedules unload, so the process shutdown
+ // below is the barrier that releases the writer and allows the new
+ // session to resume with its own MCP instance configuration.
await forkHost.unsubscribeThread(threadId);
} catch (error) {
log.warn('fork child cleanup failed; ephemeral fork host will be retired', {
@@ -13680,9 +13592,13 @@ export class CodexAgent extends BaseAgent {
// Cindy's handoff recovery, never a file rewrite that invalidates Codex's DB.
await assertCodexRolloutRewriteSupported(preparedSourcePath || await this.findRolloutPath(opts.sourceSdkSessionId));
}
+ const usedNativeForkAnchor = Boolean(
+ lastTurnId && !opts.stripEncryptedReasoning && supportsCodexNativeTurnFork(initResp.userAgent),
+ );
const params: ThreadForkParams = {
threadId: opts.sourceSdkSessionId,
persistExtendedHistory: true,
+ ...(usedNativeForkAnchor ? { lastTurnId } : {}),
// 响应体瘦身:fork 后 Cindy 自己的会话数据负责历史展示,thread.turns 全量
// 回传只会撑爆单行上限。老 daemon 不认识该字段则保持 legacy 行为 —— 此时
// 一次性 host 的隔离仍兜住故障半径。
@@ -13694,7 +13610,7 @@ export class CodexAgent extends BaseAgent {
const resp = await host.request<ThreadForkResponse>(Method.ThreadFork, params);
let newSdkSessionId = resp.thread.id;
createdThreadIds.add(newSdkSessionId);
- if (tailTurnsToDrop > 0) {
+ if (!usedNativeForkAnchor && tailTurnsToDrop > 0) {
const rollbackParams: ThreadRollbackParams = {
threadId: newSdkSessionId,
numTurns: tailTurnsToDrop,
@@ -13729,7 +13645,11 @@ export class CodexAgent extends BaseAgent {
});
}
log.info('forkSdkSession ◀', { newSdkSessionId, tailTurnsToDrop });
- return { newSdkSessionId, uuidMap: new Map() };
+ return {
+ newSdkSessionId,
+ uuidMap: new Map(),
+ ...(usedNativeForkAnchor ? { usedNativeForkAnchor: true } : {}),
+ };
} catch (error) {
operationFailed = true;
// Recovery and authentication are control signals consumed by callers.
@@ -13746,13 +13666,20 @@ export class CodexAgent extends BaseAgent {
await cleanupCreatedThreads();
} catch (error) {
// A cleanup failure must never replace the primary failure.
- if (!operationFailed) throw new CodexForkError('child-cleanup', error);
+ if (!operationFailed) {
+ operationFailed = true;
+ forkFailure = new CodexForkError('child-cleanup', error);
+ throw forkFailure;
+ }
if (forkFailure) forkFailure.cleanupFailed = true;
} finally {
// 一次性 host 用完即收,无论成败。key 唯一、无 session 绑定,
// retire 不会波及任何共享 host 或活跃会话。
if (forkHost && !forkHostRetired) {
- await retireForkHost(forkFailure !== undefined).catch((err) => {
+ // Unsubscribe is not a writer-release barrier. Never publish a
+ // successful fork unless physical shutdown has been confirmed.
+ await retireForkHost(true).catch((err) => {
+ if (!operationFailed) throw new CodexForkError('host-retire', err);
if (forkFailure) forkFailure.cleanupFailed = true;
log.warn('fork host retire failed', {
forkHostKey,