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): 分页线程回退改走原生 turn 边界 fork

ficowang674c678b8e53
diff --git a/apps/desktop/src/main/__tests__/rewind.test.ts b/apps/desktop/src/main/__tests__/rewind.test.ts
index c6d6721c63..eb98e535f0 100644
--- a/apps/desktop/src/main/__tests__/rewind.test.ts
+++ b/apps/desktop/src/main/__tests__/rewind.test.ts
@@ -909,7 +909,8 @@ describe('commitRewindAtMessage', () => {
makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 }),
makeUserMessageRow({ clientId: 'later-user', createdAt: 5000 }),
]); // Codex tail turns
- selectQueue.push([makeSessionRow({ agentKind: 'codex' })]); // post-update select
+ selectQueue.push([], // Codex 原生边界行(#4421):无锚点
+ [makeSessionRow({ agentKind: 'codex' })]); // post-update select
const result = await commitRewindAtMessage('sess-1', 'client-id');
@@ -925,6 +926,65 @@ describe('commitRewindAtMessage', () => {
expect(result.id).toBe('sess-1');
});
+ it('Codex: passes the persisted native turn anchor before target for paginated-thread rewind (#4421)', async () => {
+ useFakeSession('codex');
+ commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'fork-thread-id' });
+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]); // target user
+ selectQueue.push([]); // agent_switch 边界守卫:无边界
+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]); // Codex tail turns
+ selectQueue.push([
+ // desc 顺序:最近的在前。上一轮 assistant 带已完成 turn 的原生锚点。
+ makeAssistantMessageRow({
+ createdAt: 2500,
+ agentMeta: JSON.stringify({
+ turnCompleted: true,
+ nativeForkAnchor: { agentKind: 'codex', kind: 'turn', sdkSessionId: 'codex-thread-old', id: 'turn-9' },
+ }),
+ }),
+ makeUserMessageRow({ rowid: 8, clientId: 'earlier-user', createdAt: 2000 }),
+ ]); // Codex 原生边界行
+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]); // post-update select
+
+ await commitRewindAtMessage('sess-1', 'client-id');
+
+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, lastTurnId: 'turn-9' });
+ const txCall = txCalls.find((c) => c.name === 'rewind.commit');
+ expect(txCall?.args).toMatchObject({ sdkSessionId: 'fork-thread-id' });
+ });
+
+ it('Codex: falls back to the last model-output timestamp when no native anchor is persisted (#4421)', async () => {
+ useFakeSession('codex');
+ commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'rollback-thread-id' });
+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);
+ selectQueue.push([]);
+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);
+ selectQueue.push([
+ // 旧数据:assistant 无 nativeForkAnchor;error 行不算真实输出。
+ { role: 'error', content: '"boom"', agentMeta: null, createdAt: 2600 },
+ makeAssistantMessageRow({ createdAt: 2500, agentMeta: null }),
+ makeUserMessageRow({ rowid: 8, clientId: 'earlier-user', createdAt: 2000 }),
+ ]);
+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);
+
+ await commitRewindAtMessage('sess-1', 'client-id');
+
+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1, forkAtTimestampMs: 2500 });
+ });
+
+ it('Codex: omits boundary fields when target is the first turn of the native thread (#4421)', async () => {
+ useFakeSession('codex');
+ commitRewindFilesMock.mockResolvedValueOnce({ sdkSessionId: 'rollback-thread-id' });
+ selectQueue.push([makeUserMessageRow({ agentMeta: null })]);
+ selectQueue.push([]);
+ selectQueue.push([makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })]);
+ selectQueue.push([]); // target 之前没有任何行
+ selectQueue.push([makeSessionRow({ agentKind: 'codex' })]);
+
+ await commitRewindAtMessage('sess-1', 'client-id');
+
+ expect(commitRewindFilesMock).toHaveBeenCalledWith('', '', { tailTurnsToDrop: 1 });
+ });
+
it('Pi: executes rewind after lazy activation establishes a live session', async () => {
fakeSession = undefined;
await expect(
@@ -1051,7 +1111,8 @@ describe('commitRewindAtMessage', () => {
detectCwdMock.mockResolvedValueOnce({ gitInstalled: true, isGitRepo: true, repoRoot: '/repo', isInsideWorktree: false });
listSnapshotsMock.mockResolvedValueOnce([]);
getHeadMock.mockRejectedValueOnce(new Error('unborn HEAD'));
- selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })], [makeSessionRow({ agentKind: 'codex' })]);
+ selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })], [], // Codex 原生边界行(#4421):无锚点
+ [makeSessionRow({ agentKind: 'codex' })]);
await commitRewindAtMessage('sess-1', 'client-id');
@@ -1087,7 +1148,8 @@ describe('commitRewindAtMessage', () => {
],
truncated: true,
});
- selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })], [makeSessionRow({ agentKind: 'codex' })]);
+ selectQueue.push([makeUserMessageRow({ agentMeta: null })], [], [makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })], [], // Codex 原生边界行(#4421):无锚点
+ [makeSessionRow({ agentKind: 'codex' })]);
await commitRewindAtMessage('sess-1', 'client-id');
@@ -1185,6 +1247,7 @@ describe('commitRewindAtMessage', () => {
[makeUserMessageRow({ agentMeta: null })],
[], // agent_switch 边界守卫:无边界
[makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })],
+ [], // Codex 原生边界行(#4421):无锚点
[makeSessionRow({ agentKind: 'codex' })],
);
@@ -1221,6 +1284,7 @@ describe('commitRewindAtMessage', () => {
[makeUserMessageRow({ agentMeta: null })],
[], // agent_switch 边界守卫:无边界
[makeUserMessageRow({ clientId: 'client-id', createdAt: 3000 })],
+ [], // Codex 原生边界行(#4421):无锚点
[makeSessionRow({ agentKind: 'codex' })],
);
diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.ts
index 0dcdb5a98f..8dccf62159 100644
--- a/apps/desktop/src/main/maker-orchestration/fork.ts
+++ b/apps/desktop/src/main/maker-orchestration/fork.ts
@@ -527,8 +527,11 @@ function resolveClaudeAssistantAnchor(
return undefined;
}
-function resolveCodexTurnAnchor(
- rows: ForkTimelineMessage[],
+/** resolveCodexTurnAnchor / resolveCodexForkEventTimestamp 只读这几列;rewind 复用同一套边界判定(#4421)。 */
+export type CodexNativeBoundaryRow = Pick<ForkTimelineMessage, 'role' | 'content' | 'agentMeta' | 'createdAt'>;
+
+export function resolveCodexTurnAnchor(
+ rows: CodexNativeBoundaryRow[],
sourceSdkSessionId: string,
): string | undefined {
let timelineSdkSessionId: string | null = sourceSdkSessionId;
@@ -555,7 +558,7 @@ function resolveCodexTurnAnchor(
return undefined;
}
-function resolveCodexForkEventTimestamp(rows: ForkTimelineMessage[]): number | undefined {
+export function resolveCodexForkEventTimestamp(rows: CodexNativeBoundaryRow[]): 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
diff --git a/apps/desktop/src/main/maker-orchestration/rewind.ts b/apps/desktop/src/main/maker-orchestration/rewind.ts
index c4753303b8..551e9ca3a0 100644
--- a/apps/desktop/src/main/maker-orchestration/rewind.ts
+++ b/apps/desktop/src/main/maker-orchestration/rewind.ts
@@ -21,7 +21,7 @@
* tailTurnsToDrop 调 thread/rollback。
*/
-import { and, asc, eq, gt, gte, isNull, or, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, gt, gte, isNull, lt, or, sql } from 'drizzle-orm';
import { getDbClient } from '../localDb/client/current';
import { sessions, messages } from '../localDb/schema';
@@ -33,6 +33,7 @@ import type { RewindFilesResult } from '@cindy/maker-core';
import { createLogger } from '../logger';
import { setLastAssistantTranscriptUuid } from '../messagePersistBroadcaster.js';
import { recomputePrRefsForSession } from '../git-context/prRefsStore.js';
+import { resolveCodexForkEventTimestamp, resolveCodexTurnAnchor } from './fork';
import {
buildCodexFileRewindPlan,
CodexFileRewindPlanError,
@@ -149,6 +150,8 @@ interface RewindContext {
/** 不可为 null:前置校验通过后必有 LiveSession entry。 */
// 业务函数自己读 isRunning / 拿 query;这里只暴露 sessionId 之类的元数据
targetCreatedAt: number;
+ /** target 行的 rowid(同 createdAt 时的次序键);Codex 原生边界查询用。 */
+ targetRowid?: number;
targetMessageId: string;
targetClientId: string;
/** 当前 agent kind;Claude checkpoint 与 conversation-tree rollback 机制不同。 */
@@ -276,6 +279,7 @@ async function loadRewindContext(
);
return {
targetCreatedAt: target.createdAt,
+ targetRowid: target.rowid,
targetMessageId: target.id,
targetClientId: target.clientId,
agentKind,
@@ -557,6 +561,50 @@ async function loadCodexFileRewindRepoContext(makerSession: { workDir: string; r
* → 标记丢失, 下次启动 resume 走老 jsonl 模型仍能看到被 hide 的消息。建议用户
* commit 后立即发一条消息把 rewind 应用掉。后续可持久化到 sessions 表新列。
*/
+/**
+ * Codex 原地回退的原生边界(#4421):target 之前的时间线里,最近一个已完成 turn 的
+ * 持久化 nativeForkAnchor(lastTurnId);没有锚点(旧数据/上一轮失败)时退到最近一条
+ * 真实模型/工具输出的时间戳,由 maker-core 经 thread/turns/list 解析。两者都没有
+ * 就什么都不传——只有分页线程才会用到,普通线程仍走 thread/rollback。判定逻辑与
+ * fork 共用,原生 turn 计数含失败/重试轮次,不能拿可见 user 消息数去数。
+ */
+async function loadCodexRewindNativeBoundary(
+ sessionId: string,
+ ctx: Pick<RewindContext, 'targetCreatedAt' | 'targetRowid'>,
+ liveSdkSessionId: string | undefined,
+): Promise<{ lastTurnId?: string; forkAtTimestampMs?: number }> {
+ const currentSessionMeta = await getMaker().getSessionMeta(sessionId);
+ const sdkSessionId =
+ activeSdkSessionId(liveSdkSessionId) ??
+ activeSdkSessionId(currentSessionMeta?.sdkSessionId ?? undefined);
+ if (!sdkSessionId) return {};
+ const db = getDbClient().drizzle;
+ const beforeTarget =
+ ctx.targetRowid === undefined
+ ? lt(messages.createdAt, ctx.targetCreatedAt)
+ : or(
+ lt(messages.createdAt, ctx.targetCreatedAt),
+ and(eq(messages.createdAt, ctx.targetCreatedAt), lt(messageRowid, ctx.targetRowid)),
+ );
+ // 只需回看到上一条 user / 引擎切换边界;取最近 200 行足够覆盖一轮的工具输出。
+ const recent = await db
+ .select({
+ role: messages.role,
+ content: messages.content,
+ agentMeta: messages.agentMeta,
+ createdAt: messages.createdAt,
+ })
+ .from(messages)
+ .where(and(eq(messages.sessionId, sessionId), isNull(messages.rewindAt), beforeTarget))
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(200);
+ const rows = [...recent].reverse();
+ const lastTurnId = resolveCodexTurnAnchor(rows, sdkSessionId);
+ if (lastTurnId) return { lastTurnId };
+ const forkAtTimestampMs = resolveCodexForkEventTimestamp(rows);
+ return forkAtTimestampMs !== undefined ? { forkAtTimestampMs } : {};
+}
+
export async function commitRewindAtMessage(
sessionId: string,
clientId: string,
@@ -576,8 +624,14 @@ export async function commitRewindAtMessage(
let rewindResult: Awaited<ReturnType<typeof makerSession.commitRewindFiles>> | undefined;
if (ctx.agentKind === 'codex' || ctx.agentKind === 'pi') {
const filePlan = await buildCodexFilePlanForSession(sessionId, clientId, ctx.codexUserMessages ?? [], makerSession);
+ // Codex 分页线程拒绝 thread/rollback(#4421):把 target 之前的原生 turn 边界
+ // (持久化锚点或事件时间戳)一并交给 maker-core,遇拒绝时改走 thread/fork。
+ const nativeBoundary =
+ ctx.agentKind === 'codex'
+ ? await loadCodexRewindNativeBoundary(sessionId, ctx, makerSession.sdkSessionId)
+ : {};
const commitThreadRollback = () =>
- makerSession.commitRewindFiles('', '', { tailTurnsToDrop: ctx.tailTurnsToDrop });
+ makerSession.commitRewindFiles('', '', { tailTurnsToDrop: ctx.tailTurnsToDrop, ...nativeBoundary });
const logCompensationError = (compErr: unknown, rollbackCommit: string | null) => {
log.error(`[rewind commit] ${ctx.agentKind} file rewind compensation failed`, {
sessionId,
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 747ab0bb5b..fcc55f83d7 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -23775,6 +23775,119 @@ describe('CodexAgent rewind', () => {
await handle.close();
});
+ // #4421: 0.153+ 的分页线程拒绝 thread/rollback(-32600)。原地回退要改走与
+ // forkSdkSession 相同的原生边界 fork,并把活动线程切到 fork 结果。
+ it('falls back to a native turn fork when the paginated thread rejects thread/rollback', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.ThreadRollback) {
+ throw Object.assign(
+ new Error('codex app-server thread/rollback error -32600: paginated threads do not support thread/rollback'),
+ { code: -32600 },
+ );
+ }
+ if (method === Method.ThreadTurnsList) return {
+ data: [
+ { id: 'dropped-turn', status: 'completed', startedAt: 200 },
+ { id: 'boundary-turn', status: 'completed', startedAt: 100 },
+ ], nextCursor: null,
+ };
+ }, { userAgent: 'mock-codex/0.153.4' });
+ const handle = await agent.startSession({
+ sessionId: 'session-rewind-paginated',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const iterator = handle.events()[Symbol.asyncIterator]();
+ const commitRewindFiles = handle.commitRewindFiles;
+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');
+
+ const commitResult = await commitRewindFiles('', '', { tailTurnsToDrop: 1, forkAtTimestampMs: 150_500 });
+
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadRollback, {
+ threadId: 'start-thread-id',
+ numTurns: 1,
+ });
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, {
+ threadId: 'start-thread-id',
+ lastTurnId: 'boundary-turn',
+ excludeTurns: true,
+ cwd: '/repo',
+ });
+ expect(commitResult).toEqual({ sdkSessionId: 'fork-thread-id' });
+ expect(host.subscribeThread).toHaveBeenCalledTimes(2);
+ expect(host.subscribeThread).toHaveBeenLastCalledWith('fork-thread-id', expect.any(Object));
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'session_id',
+ data: 'fork-thread-id',
+ source: 'codex',
+ });
+ await handle.close();
+ });
+
+ it('uses the persisted native anchor for the paginated rewind fork without listing turns', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.ThreadRollback) throw new Error('paginated threads do not support thread/rollback');
+ }, { userAgent: 'mock-codex/0.153.4' });
+ const handle = await agent.startSession({
+ sessionId: 'session-rewind-paginated-anchor',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const commitRewindFiles = handle.commitRewindFiles;
+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');
+
+ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 2, lastTurnId: 'persisted-boundary' }))
+ .resolves.toEqual({ sdkSessionId: 'fork-thread-id' });
+ expect(host.request).not.toHaveBeenCalledWith(Method.ThreadTurnsList, expect.anything());
+ expect(host.request).toHaveBeenCalledWith(Method.ThreadFork, expect.objectContaining({
+ threadId: 'start-thread-id', lastTurnId: 'persisted-boundary',
+ }));
+ await handle.close();
+ });
+
+ it('surfaces a clear error instead of forking when the paginated rewind has no native boundary', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.ThreadRollback) throw new Error('paginated threads do not support thread/rollback');
+ }, { userAgent: 'mock-codex/0.153.4' });
+ const handle = await agent.startSession({
+ sessionId: 'session-rewind-paginated-no-anchor',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const commitRewindFiles = handle.commitRewindFiles;
+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');
+
+ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1 }))
+ .rejects.toThrow(/unambiguous native anchor or event timestamp/);
+ expect(host.request).not.toHaveBeenCalledWith(Method.ThreadFork, expect.anything());
+ // 活动线程未被替换,后续仍订阅原线程。
+ expect(host.subscribeThread).toHaveBeenCalledTimes(1);
+ await handle.close();
+ });
+
+ it('does not fork for non-paginated rollback failures', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.ThreadRollback) throw new Error('codex app-server thread/rollback error -32000: thread not found');
+ }, { userAgent: 'mock-codex/0.153.4' });
+ const handle = await agent.startSession({
+ sessionId: 'session-rewind-other-failure',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const commitRewindFiles = handle.commitRewindFiles;
+ if (!commitRewindFiles) throw new Error('expected commitRewindFiles');
+
+ await expect(commitRewindFiles('', '', { tailTurnsToDrop: 1, forkAtTimestampMs: 150_500 }))
+ .rejects.toThrow(/thread not found/);
+ expect(host.request).not.toHaveBeenCalledWith(Method.ThreadFork, expect.anything());
+ expect(host.request).not.toHaveBeenCalledWith(Method.ThreadTurnsList, expect.anything());
+ await handle.close();
+ });
+
it('re-registers proxy developer instructions for the replacement rollback thread', async () => {
const registerCodexSystemPromptForThread = vi.fn();
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 29cbe71faa..6b2d21e1e8 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -248,6 +248,8 @@ import {
type ThreadForkResponse,
type ThreadRollbackParams,
type ThreadRollbackResponse,
+ type ThreadTurnsListParams,
+ type ThreadTurnsListResponse,
type ThreadResumeParams,
type ThreadResumeResponse,
type ThreadSettingsUpdateParams,
@@ -381,6 +383,16 @@ function normalizeTailTurnsToDrop(value: number | undefined): number {
return Math.max(0, Math.floor(value));
}
+/**
+ * Codex app-server 对分页线程(0.153+ 的 SQLite 索引历史)拒绝 thread/rollback:
+ * JSON-RPC -32600 "paginated threads do not support thread/rollback"。原地回退
+ * 遇到它要改走 thread/fork(lastTurnId) 绕行(#4421),其它错误照常上抛。
+ */
+export function isCodexPaginatedRollbackUnsupportedError(error: unknown): boolean {
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
+ return /paginated threads? do(?:es)? not support thread\/rollback/i.test(message);
+}
+
function normalizeNativeForkTurnId(value: string | undefined): string | undefined {
const normalized = value?.trim();
return normalized ? normalized : undefined;
@@ -13819,13 +13831,56 @@ export class CodexAgent extends BaseAgent {
tailTurnsToDrop,
});
assertCurrentHost('thread/rollback');
- const rollbackResp = await host.request<ThreadRollbackResponse>(
- Method.ThreadRollback,
- { threadId, numTurns: tailTurnsToDrop } as ThreadRollbackParams,
- );
const previousThreadId = threadId;
- const nextThreadId = rollbackResp.thread.id || previousThreadId;
- await recordNativeThreadLocation(rollbackResp.thread);
+ let replacementThread: ThreadRollbackResponse['thread'];
+ try {
+ const rollbackResp = await host.request<ThreadRollbackResponse>(
+ Method.ThreadRollback,
+ { threadId, numTurns: tailTurnsToDrop } as ThreadRollbackParams,
+ );
+ replacementThread = rollbackResp.thread;
+ } catch (error) {
+ if (!isCodexPaginatedRollbackUnsupportedError(error)) throw error;
+ // 分页线程(#4421):app-server 不支持按 turn 数裁剪,改用与 forkSdkSession
+ // 相同的原生边界 fork —— 目标之前最后一个已完成 turn 作 lastTurnId,
+ // thread/fork 出一条截断后的新线程并把活动线程切过去。native turn 计数
+ // 含失败/重试轮次,与可见 user 消息数不一一对应,所以边界只认宿主传来的
+ // 持久化锚点或按事件时间戳经 thread/turns/list 解析,绝不按 numTurns 数。
+ if (!supportsCodexNativeTurnFork(initResp.userAgent)) {
+ throw new Error(
+ `Codex app-server ${initResp.userAgent ?? 'unknown'} rejects thread/rollback for paginated threads and predates native turn fork (0.145.0); rewind is unavailable for this thread`,
+ );
+ }
+ let lastTurnId = normalizeNativeForkTurnId(rewindOpts?.lastTurnId);
+ if (!lastTurnId) {
+ if (!codexUserAgentAtLeast(initResp.userAgent, [0, 153, 4])) {
+ throw new Error(
+ `Codex app-server ${initResp.userAgent ?? 'unknown'} rejects thread/rollback for paginated threads and cannot list native turns (0.153.4); rewind is unavailable for this thread`,
+ );
+ }
+ lastTurnId = await resolveForkTurnAnchor(
+ (method, params) => host.request<ThreadTurnsListResponse>(method, params as ThreadTurnsListParams),
+ threadId,
+ rewindOpts?.forkAtTimestampMs,
+ );
+ }
+ log.info('commitRewindFiles ▶ thread/rollback unsupported for paginated thread; forking at native turn boundary', {
+ threadId,
+ tailTurnsToDrop,
+ lastTurnId,
+ });
+ assertCurrentHost('thread/fork (paginated rewind)');
+ const forkParams: ThreadForkParams = {
+ threadId,
+ lastTurnId,
+ ...(supportsCodexForkExcludeTurns(initResp.userAgent) ? { excludeTurns: true } : {}),
+ ...(opts.workingDir ? { cwd: opts.workingDir } : {}),
+ };
+ const forkResp = await host.request<ThreadForkResponse>(Method.ThreadFork, forkParams);
+ replacementThread = forkResp.thread;
+ }
+ const nextThreadId = replacementThread.id || previousThreadId;
+ await recordNativeThreadLocation(replacementThread);
if (nextThreadId !== previousThreadId) {
const released = await releaseCurrentThreadSubscription('thread/rollback subscription release');
if (!released) {
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index a3ef096aa2..01c756829b 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -457,6 +457,18 @@ export interface RewindCommitOptions {
* Claude 路径不消费此字段。
*/
tailTurnsToDrop?: number;
+ /**
+ * Codex 分页线程拒绝 thread/rollback(-32600 "paginated threads do not support
+ * thread/rollback")时的原生边界:回退目标之前最后一个已完成 turn 的原生
+ * turn id(持久化的 nativeForkAnchor)。有它就直接 thread/fork(lastTurnId)。
+ */
+ lastTurnId?: string;
+ /**
+ * 没有持久化锚点时的兜底:回退目标之前最后一条真实模型/工具输出的时间戳
+ * (ms),由 thread/turns/list 解析出对应原生 turn 边界。与 ForkSdkSessionOptions
+ * 的 forkAtTimestampMs 语义一致。
+ */
+ forkAtTimestampMs?: number;
}
export interface RewindCommitResult {