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): repair subscription recovery and paginated forks (#4142)

Chris Zhang79c89d14a9f0
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.ts
index 26dc1345e6..c28392d1ae 100644
--- a/apps/desktop/src/main/__tests__/fork.test.ts
+++ b/apps/desktop/src/main/__tests__/fork.test.ts
@@ -340,6 +340,7 @@ describe('forkSessionAtMessage', () => {
providerId: 'xd',
upToMessageId: undefined,
tailTurnsToDrop: 2,
+ forkAtTimestampMs: 2500,
title: '[Fork] Project A',
workingDir: '/work',
// 轮 26:Pi fork 守卫透传 remoteHostId(本地源 → null)。
@@ -449,7 +450,7 @@ describe('forkSessionAtMessage', () => {
]);
});
- it('codex path: keeps the legacy fork path when the latest copied turn has no native anchor', async () => {
+ it('codex path: supplies event time for native lookup when the latest copied turn has no anchor', async () => {
const target = makeMessageRow({ id: 'target-user', role: 'user', createdAt: 3000 });
const priorUser = makeMessageRow({ id: 'user-1', role: 'user', createdAt: 2000 });
const olderAnchoredAssistant = makeMessageRow({
@@ -479,7 +480,10 @@ describe('forkSessionAtMessage', () => {
makeSourceRow({ agentKind: 'codex', sdkSessionId: 'legacy-codex-thread' }),
]);
selectQueue.push([target]);
- selectQueue.push([priorUser, olderAnchoredAssistant, priorAssistant]);
+ selectQueue.push([priorUser, olderAnchoredAssistant, priorAssistant,
+ // Error rows have a synthetic display timestamp, not native event time.
+ makeMessageRow({ id: 'failed-error', role: 'error', createdAt: 2600 }),
+ ]);
selectQueue.push([
makeSourceRow({
agentKind: 'codex',
@@ -499,6 +503,9 @@ describe('forkSessionAtMessage', () => {
'codex',
expect.not.objectContaining({ lastTurnId: expect.anything() }),
);
+ expect(forkSdkSessionMock).toHaveBeenCalledWith(
+ 'codex', expect.objectContaining({ forkAtTimestampMs: 2500 }),
+ );
const txArgs = txCalls.find((call) => call.name === 'fork.session')!.args as {
nativeForkAnchorSessionMap?: Array<[string, string]>;
};
@@ -2052,6 +2059,7 @@ describe('forkSessionAtMessage', () => {
providerId: 'xd',
upToMessageId: undefined,
tailTurnsToDrop: 1,
+ forkAtTimestampMs: 2500,
title: '[Fork] Project A',
workingDir: '/work',
// 轮 26:Pi fork 守卫透传 remoteHostId(本地源 → null)。
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
index 2eafa66037..55a982df7d 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts
@@ -3057,6 +3057,48 @@ describe('codex proxy host', () => {
}
});
+ it.each(['custom-context', 'control-plane'] as const)(
+ 'recovers encrypted history on a %s proxy while preserving other threads', async (kind) => {
+ const host = await freshCodexProxyHost();
+ const sharedDisconnect = vi.fn(() => 0);
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43210', disconnectWebSocketsForThread: sharedDisconnect,
+ dispose: vi.fn(async () => undefined),
+ });
+ await host.ensureCodexProxyReady();
+ const sockets = new Set(['thread-target', 'thread-sibling']);
+ const disconnect = vi.fn((id: string) => Number(sockets.delete(id)));
+ const forget = vi.fn();
+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({
+ url: 'http://127.0.0.1:43211', disconnectWebSocketsForThread: disconnect,
+ forgetWebSocketStateForThread: forget, dispose: vi.fn(async () => undefined),
+ });
+ if (kind === 'custom-context') {
+ await host.ensureCodexCustomContextProxyReady('context-target', 'oauth-bearer', []);
+ } else {
+ await host.ensureCodexControlPlaneProxyReady('oauth-bearer');
+ }
+ host.registerComposed('session-target', 'thread-target', 'PRODUCT_PROMPT');
+ const proxyOpts = mockState.createAnthropicCompatProxy.mock.calls[1][0];
+ expect(host.armCodexHttpRecovery({
+ sessionId: 'session-target', threadId: 'thread-target', message: 'invalid_encrypted_content',
+ })).toBe('encrypted_content');
+ expect(disconnect).toHaveBeenCalledWith('thread-target');
+ expect(sockets).toEqual(new Set(['thread-sibling']));
+ expect(proxyOpts.resolveWebSocketUpstream({
+ url: '/v1/responses', headers: { 'thread-id': 'thread-target' },
+ })).toBeNull();
+ expect(proxyOpts.resolveWebSocketUpstream({
+ url: '/v1/responses', headers: { 'thread-id': 'thread-sibling' },
+ })).toBe('https://chatgpt.com/backend-api/codex');
+ host.unregister('session-target');
+ expect(forget).toHaveBeenCalledExactlyOnceWith('thread-target');
+ expect(proxyOpts.resolveWebSocketUpstream({
+ url: '/v1/responses', headers: { 'thread-id': 'thread-target' },
+ })).toBe('https://chatgpt.com/backend-api/codex');
+ },
+ );
+
it('keeps native websocket behavior when no scoped socket can be recovered safely', async () => {
const host = await freshCodexProxyHost();
const disconnectWebSocketsForThread = vi.fn(() => 0);
diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.ts
index c468521540..bf2ffcdcaf 100644
--- a/apps/desktop/src/main/maker-orchestration/fork.ts
+++ b/apps/desktop/src/main/maker-orchestration/fork.ts
@@ -555,6 +555,21 @@ function resolveCodexTurnAnchor(
return undefined;
}
+function resolveCodexForkEventTimestamp(rows: ForkTimelineMessage[]): number | undefined {
+ for (let i = rows.length - 1; i >= 0; i -= 1) {
+ const row = rows[i]!;
+ // A new native segment has no event to anchor yet. Never borrow time from
+ // an earlier engine or the host's handoff marker.
+ if (row.role === 'agent_switch' || row.role === 'context_rebuild' || row.role === 'user') return undefined;
+ // Error rows can be backdated to user.createdAt + 1; user persistence may
+ // precede turn/start. Only actual model/tool output proves the turn began.
+ if (['assistant', 'tool_use', 'tool_result', 'thinking'].includes(row.role)) {
+ return row.createdAt;
+ }
+ }
+ return undefined;
+}
+
async function countCodexTailTurns(
sourceSessionId: string,
sourceCurrentSdkSessionId: string | null,
@@ -833,6 +848,7 @@ export async function forkSessionAtMessage(
const usesTailTurnFork = isCodex || forkSource.agentKind === 'pi';
let assistantUuid: string | undefined;
let lastTurnId: string | undefined;
+ let forkAtTimestampMs: number | undefined;
let tailTurnsToDrop: number | undefined;
let claudeAnchorIndex: ClaudeTranscriptAnchorIndex | null = null;
const resetHandoffBoundaryClientId = findFirstUserAfterSwitchBoundary(
@@ -858,6 +874,7 @@ export async function forkSessionAtMessage(
} else if (forkSource.reuseVendorSession && forkSource.sdkSessionId) {
if (isCodex) {
lastTurnId = resolveCodexTurnAnchor(sourceMessages, forkSource.sdkSessionId);
+ if (!lastTurnId) forkAtTimestampMs = resolveCodexForkEventTimestamp(sourceMessages);
}
tailTurnsToDrop = await countCodexTailTurns(
sourceSessionId,
@@ -890,6 +907,7 @@ export async function forkSessionAtMessage(
...(isCodex ? { model: forkSource.model, providerId: forkSource.providerId } : {}),
upToMessageId: assistantUuid,
...(lastTurnId ? { lastTurnId } : {}),
+ ...(forkAtTimestampMs !== undefined ? { forkAtTimestampMs } : {}),
...(tailTurnsToDrop !== undefined ? { tailTurnsToDrop } : {}),
title: newTitle,
workingDir: source.workingDir ?? undefined,
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index b4509f8de1..ce5d7b27bb 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -67,6 +67,13 @@ Codex 跨凭证时先按目标来源 resume 同一个原生线程,不因 `ordi
`CINDY_ENCRYPTED_COMPACTION_INCOMPATIBLE`,交给既有 compact 失败恢复流程。
裸 `invalid_encrypted_content`、网络错误和切换来源本身都不足以触发该恢复;保留同一用户消息
最多一次重放及已有产出/工具副作用禁止重放的边界。
+跨来源恢复必须在共享、独立上下文和控制面代理中按同一 thread 身份查找并关闭连接,
+关闭任务时也清理这些实例里的同 thread 保活状态;不能只查共享代理而漏掉实际承载连接。
+分支优先使用已保存的原生 turn 锚点。Codex 0.153.4 起,旧消息或失败轮没有锚点时,
+先用 `thread/turns/list(itemsView: notLoaded)` 查询终态边界,再 `thread/fork(lastTurnId)`,
+不能对分页线程执行 rollback。界面软删重试不代表原生 turn 消失,有复制事件时间时据此
+定位,不按可见 user 行数猜边界;复制事件时间缺失、原生时间缺失或秒级精度无法确定顺序时明确失败,不截错
+历史。查询与 fork 使用同一隔离控制面 host,关闭其写入进程后才发布子线程身份。
HTTP 回退遇到缺失 `Content-Type` 的成功响应时,只允许从明文 SSE 前缀(可带注释心跳)
确认事件流并补齐响应头;显式非 SSE 类型、HTML/JSON、空响应与只有心跳的正文不能放行。
正在运行的 turn、SSH 远端缺少本地交接能力、或已有恢复动作在途时必须 fail closed,不能
diff --git a/packages/maker-core/src/agents/codex/app-server/protocol.ts b/packages/maker-core/src/agents/codex/app-server/protocol.ts
index 6fb89d8326..52f87460b8 100644
--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts
+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts
@@ -492,6 +492,20 @@ export interface ThreadRollbackParams {
numTurns: number;
}
+/** Codex 0.153.4: bounded turn metadata, including failed/interrupted turns. */
+export interface ThreadTurnsListParams {
+ threadId: string;
+ cursor?: string;
+ limit: number;
+ sortDirection: 'desc';
+ itemsView: 'notLoaded';
+}
+
+export interface ThreadTurnsListResponse {
+ data: Array<{ id: string; status: string; startedAt?: number | null }>;
+ nextCursor: string | null;
+}
+
export interface ThreadRollbackResponse {
thread: { id: string; [k: string]: unknown };
[k: string]: unknown;
@@ -1212,6 +1226,7 @@ export const Method = {
ThreadResume: 'thread/resume',
ThreadFork: 'thread/fork',
ThreadRollback: 'thread/rollback',
+ ThreadTurnsList: 'thread/turns/list',
ThreadUnsubscribe: 'thread/unsubscribe',
ThreadSettingsUpdate: 'thread/settings/update',
TurnStart: 'turn/start',
diff --git a/packages/maker-core/src/agents/codex/fork-turn-anchor.test.ts b/packages/maker-core/src/agents/codex/fork-turn-anchor.test.ts
new file mode 100644
index 0000000000..ddbcc6ee7d
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/fork-turn-anchor.test.ts
@@ -0,0 +1,64 @@
+import { describe, expect, it, vi } from 'vitest';
+import { resolveForkTurnAnchor } from './fork-turn-anchor.js';
+
+describe('resolveForkTurnAnchor', () => {
+ it('rejects a missing event timestamp before querying native history', async () => {
+ const request = vi.fn();
+ await expect(resolveForkTurnAnchor(request, 'source')).rejects.toThrow('unambiguous native anchor');
+ expect(request).not.toHaveBeenCalled();
+ });
+
+ it('uses event time when a hidden failed retry remains in native history', async () => {
+ const request = vi.fn().mockResolvedValue({ data: [
+ { id: 'visible-retry-2', status: 'failed', startedAt: 400 },
+ { id: 'visible-retry-1', status: 'failed', startedAt: 300 },
+ { id: 'hidden-retry', status: 'failed', startedAt: 200 },
+ { id: 'requested-turn', status: 'interrupted', startedAt: 100 },
+ ], nextCursor: null });
+ await expect(resolveForkTurnAnchor(request, 'source', 110_123)).resolves.toBe('requested-turn');
+ });
+
+ it('does not include a hidden later retry even when the UI reports no tail turns', async () => {
+ const request = vi.fn().mockResolvedValue({ data: [
+ { id: 'hidden-retry', status: 'failed', startedAt: 200 },
+ { id: 'requested-turn', status: 'interrupted', startedAt: 100 },
+ ], nextCursor: null });
+ await expect(resolveForkTurnAnchor(request, 'source', 110_123)).resolves.toBe('requested-turn');
+ });
+
+ it.each([undefined, null, 110])('refuses missing or same-second ambiguous native timestamps (%s)', async (startedAt) => {
+ const request = vi.fn().mockResolvedValue({
+ data: [{ id: 'uncertain', status: 'failed', startedAt }], nextCursor: null,
+ });
+ await expect(resolveForkTurnAnchor(request, 'source', 110_123)).rejects.toThrow();
+ });
+
+ it('finds a failed boundary across metadata pages without loading message bodies', async () => {
+ const request = vi.fn()
+ .mockResolvedValueOnce({ data: [{ id: 'retry-2', status: 'failed', startedAt: 300 }], nextCursor: 'page-2' })
+ .mockResolvedValueOnce({ data: [
+ { id: 'retry-1', status: 'failed', startedAt: 200 }, { id: 'boundary', status: 'interrupted', startedAt: 100 },
+ ], nextCursor: null });
+ await expect(resolveForkTurnAnchor(request, 'source', 110_123)).resolves.toBe('boundary');
+ expect(request.mock.calls.map(([, params]) => params)).toEqual([
+ { threadId: 'source', limit: 100, sortDirection: 'desc', itemsView: 'notLoaded' },
+ { threadId: 'source', cursor: 'page-2', limit: 100, sortDirection: 'desc', itemsView: 'notLoaded' },
+ ]);
+ });
+
+ it.each([
+ { data: [], nextCursor: null },
+ { data: [{ id: 'live', status: 'inProgress' }], nextCursor: null },
+ { data: [{ id: 'only-turn', status: 'completed' }], nextCursor: null },
+ ])('rejects a boundary it cannot establish: %j', async (page) => {
+ await expect(resolveForkTurnAnchor(vi.fn().mockResolvedValue(page), 'source', 110_123)).rejects.toThrow();
+ });
+
+ it('rejects repeated pages instead of selecting a duplicate turn or looping', async () => {
+ const request = vi.fn().mockResolvedValue({
+ data: [{ id: 'repeated', status: 'completed', startedAt: 200 }], nextCursor: 'same',
+ });
+ await expect(resolveForkTurnAnchor(request, 'source', 110_123)).rejects.toThrow();
+ expect(request).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/fork-turn-anchor.ts b/packages/maker-core/src/agents/codex/fork-turn-anchor.ts
new file mode 100644
index 0000000000..65bb21a440
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/fork-turn-anchor.ts
@@ -0,0 +1,49 @@
+import { Method, type ThreadTurnsListParams, type ThreadTurnsListResponse } from './app-server/protocol.js';
+
+/** Resolve a timestamp-backed turn boundary without mutating a paginated thread. */
+export async function resolveForkTurnAnchor(
+ request: (method: string, params: ThreadTurnsListParams) => Promise<ThreadTurnsListResponse>,
+ threadId: string,
+ forkAtTimestampMs?: number,
+): Promise<string> {
+ if (forkAtTimestampMs === undefined) {
+ throw new Error('Codex fork requires an unambiguous native anchor or event timestamp');
+ }
+ if (!Number.isFinite(forkAtTimestampMs) || forkAtTimestampMs <= 0) {
+ throw new Error('Codex fork event timestamp is invalid');
+ }
+ let cursor: string | undefined;
+ const seenCursors = new Set<string>();
+ const seenTurns = new Set<string>();
+ // Bound both response size and a broken daemon's pagination loop. No items,
+ // reasoning, or tool output are needed to select a native turn boundary.
+ for (let page = 0; page < 100; page += 1) {
+ const response = await request(Method.ThreadTurnsList, {
+ threadId, ...(cursor ? { cursor } : {}),
+ limit: 100,
+ sortDirection: 'desc', itemsView: 'notLoaded',
+ });
+ if (!Array.isArray(response.data) || response.data.length === 0) break;
+ for (const turn of response.data) {
+ if (!turn.id || seenTurns.has(turn.id) || !['completed', 'failed', 'interrupted'].includes(turn.status)) {
+ throw new Error('Codex fork requires a stable terminal turn history');
+ }
+ seenTurns.add(turn.id);
+ if (typeof turn.startedAt !== 'number' || !Number.isFinite(turn.startedAt)) {
+ throw new Error('Codex fork native turn timestamp is unavailable');
+ }
+ const eventSecond = Math.floor(forkAtTimestampMs / 1000);
+ // Native timestamps have second precision. Do not guess ordering when
+ // another turn could have started later in the same second as the event.
+ if (turn.startedAt === eventSecond) {
+ throw new Error('Codex fork event overlaps an ambiguous native turn boundary');
+ }
+ if (turn.startedAt < eventSecond) return turn.id;
+ }
+ if (!response.nextCursor) break;
+ if (seenCursors.has(response.nextCursor)) break;
+ seenCursors.add(response.nextCursor);
+ cursor = response.nextCursor;
+ }
+ throw new Error('Codex fork turn boundary is unavailable in native history');
+}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index e97ef91598..c5c5b8297e 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -22525,6 +22525,58 @@ describe('CodexAgent native fork anchor events', () => {
});
describe('CodexAgent.forkSdkSession', () => {
+ it('forks failed paginated history without rollback when no UI anchor was saved', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, method => {
+ if (method === Method.ThreadTurnsList) return {
+ data: [
+ { id: 'retry-2', status: 'failed', startedAt: 400 }, { id: 'retry-1', status: 'failed', startedAt: 300 },
+ { id: 'hidden-retry', status: 'failed', startedAt: 200 },
+ { id: 'failed-boundary', status: 'interrupted', startedAt: 100 },
+ ], nextCursor: null,
+ };
+ if (method === Method.ThreadRollback) throw new Error('paginated threads do not support thread/rollback');
+ }, { userAgent: 'mock-codex/0.153.4' });
+ await expect(agent.forkSdkSession({
+ sourceSdkSessionId: 'source', upToMessageId: undefined, tailTurnsToDrop: 2, forkAtTimestampMs: 110_123,
+ })).resolves.toMatchObject({ newSdkSessionId: 'fork-thread-id', usedNativeForkAnchor: true });
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {
+ threadId: 'source', lastTurnId: 'failed-boundary', excludeTurns: true,
+ });
+ expect(host.request).not.toHaveBeenCalledWith(Method.ThreadRollback, expect.anything());
+ expect(host.unsubscribeThread).toHaveBeenCalledWith('fork-thread-id');
+ });
+
+ it('refuses visible counts without an event boundary when excluded native turns were retried', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, method => {
+ if (method === Method.ThreadTurnsList) return {
+ data: [
+ { id: 'excluded-retry', status: 'failed', startedAt: 300 },
+ { id: 'excluded-original', status: 'failed', startedAt: 200 },
+ { id: 'copied-silent-turn', status: 'failed', startedAt: 100 },
+ ], nextCursor: null,
+ };
+ }, { userAgent: 'mock-codex/0.153.4' });
+ await expect(agent.forkSdkSession({
+ sourceSdkSessionId: 'source', upToMessageId: undefined, tailTurnsToDrop: 1,
+ })).rejects.toMatchObject({ stage: 'source-prepare' });
+ expect(host.request).not.toHaveBeenCalled();
+ expect(host.unsubscribeThread).not.toHaveBeenCalled();
+ });
+
+ it('does not allocate a child or fall back to rollback if native boundary lookup fails', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, method => {
+ if (method === Method.ThreadTurnsList) throw new Error('native read failed');
+ }, { userAgent: 'mock-codex/0.153.4' });
+ await expect(agent.forkSdkSession({
+ sourceSdkSessionId: 'source', upToMessageId: undefined, tailTurnsToDrop: 1, forkAtTimestampMs: 110_123,
+ })).rejects.toMatchObject({ stage: 'source-prepare' });
+ expect(host.request).toHaveBeenCalledTimes(1);
+ expect(host.unsubscribeThread).not.toHaveBeenCalled();
+ });
+
it('keeps a startup cause and records a concurrent host retirement failure', async () => {
const cause = new Error('ECONNRESET');
const agent = new CodexAgent(createDeps());
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 2cdfec0669..d1776f7870 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -10,7 +10,7 @@
* - ✅ Approval: setRequestHandler 接 commandExecution / fileChange RequestApproval
* → dispatchInteraction (复用 Claude 那条 PermissionPrompt 通道)
* - ✅ 运行时切: setModel / setEffort / setPermissionMode 都生效, 下一 turn 自动透传
- * - ✅ Fork: thread/fork(lastTurnId);旧历史回退 fork + rollback → 新 thread_id
+ * - ✅ Fork: thread/fork(lastTurnId);分页历史查询原生边界,旧 daemon 回退 rollback
* - ✅ oneShot: 走 host 临时 thread (起标题), Phase 4 删 SDK dep 后唯一通路
*
* 输出契约:
@@ -183,6 +183,7 @@ import {
} from './rollout-sanitize.js';
import { CodexHistoryRecoveryRequiredError, isCodexHistoryRecoveryRequired } from './history-recovery.js';
import { CodexForkError, type CodexForkStage } from './fork-error.js';
+import { resolveForkTurnAnchor } from './fork-turn-anchor.js';
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';
@@ -13537,7 +13538,7 @@ export class CodexAgent extends BaseAgent {
* 与 Claude 不同:
* - Claude fork 可 truncate 到指定 message uuid (sdkForkSession upToMessageId)
* - Codex 新消息保存原生 turn id,直接用 lastTurnId 精确 fork
- * - 老消息没有原生锚点时,仍先 fork latest 再 rollback 尾部 turn
+ * - 老消息没有原生锚点时,分页 daemon 查 turn 元数据;旧 daemon 才用 rollback
*
* opts.upToMessageId 在 Codex 这里被忽略。uuidMap 返回空 — Codex 不使用
* Claude message uuid;原生 turn 锚点由 usedNativeForkAnchor 单独声明可复用。
@@ -13603,7 +13604,7 @@ export class CodexAgent extends BaseAgent {
async forkSdkSession(opts: ForkSdkSessionOptions): Promise<ForkSdkSessionResult> {
const log = this.deps.logger.child('codex/fork');
const tailTurnsToDrop = normalizeTailTurnsToDrop(opts.tailTurnsToDrop);
- const lastTurnId = normalizeNativeForkTurnId(opts.lastTurnId);
+ let lastTurnId = normalizeNativeForkTurnId(opts.lastTurnId);
const forkCredentialMode = resolveAgentCredentialMode({
agentKind: 'codex',
providerId: opts.providerId,
@@ -13707,6 +13708,19 @@ 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));
}
+ if (
+ !lastTurnId && (tailTurnsToDrop > 0 || opts.forkAtTimestampMs !== undefined) && !opts.stripEncryptedReasoning
+ && codexUserAgentAtLeast(initResp.userAgent, [0, 153, 4])
+ ) {
+ // Older/failed messages have no persisted UI anchor. Paginated threads
+ // reject rollback, so resolve the requested boundary with metadata only
+ // before allocating a child. Never rewrite indexed rollout files.
+ lastTurnId = await resolveForkTurnAnchor(
+ (method, params) => host.request(method, params),
+ opts.sourceSdkSessionId,
+ opts.forkAtTimestampMs,
+ );
+ }
const usedNativeForkAnchor = Boolean(
lastTurnId && !opts.stripEncryptedReasoning && supportsCodexNativeTurnFork(initResp.userAgent),
);
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index ad3320929e..1f20b9062e 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -445,14 +445,20 @@ export interface ForkSdkSessionOptions {
upToMessageId: string | undefined;
/**
* Fork 后从新 session 尾部移除多少个完整 turn。
- * Codex 精确 fork 使用 thread/rollback 实现;Claude 路径不消费此字段。
+ * Codex 旧 daemon 使用 thread/rollback;分页 daemon 先查询原生边界。
+ * Claude 路径不消费此字段。
*/
tailTurnsToDrop?: number;
/**
* Codex only: provider-native turn boundary for a direct thread/fork.
- * Old messages omit it and keep using tailTurnsToDrop + rollback.
+ * Old/failed messages can resolve it through native turn metadata instead.
*/
lastTurnId?: string;
+ /**
+ * Codex only: timestamp of the last copied event in the requested native turn.
+ * Used to resolve old/failed history without counting soft-deleted UI retries.
+ */
+ forkAtTimestampMs?: number;
/** 新 session title (可选, 仅给 SDK 写入 jsonl 头)。 */
title?: string;
/** workingDir — 用于定位 Claude SDK project JSONL 并修复 fork 后的 uuid 引用。 */