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): 避免恢复长会话时返回完整历史 (#660)

Chenerc0342302fa3a
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 4cba0fa042..711d5c745b 100644
--- a/packages/maker-core/src/agents/codex/app-server/protocol.ts
+++ b/packages/maker-core/src/agents/codex/app-server/protocol.ts
@@ -395,6 +395,11 @@ export interface ThreadResumeParams {
* 用于重启后恢复 host 产品级 prompt。
*/
developerInstructions?: string;
+ /**
+ * 只恢复 thread 元数据与 live state,不把完整历史塞进单条 NDJSON response。
+ * 历史展示由 Cindy 自己的会话数据负责。
+ */
+ excludeTurns?: boolean;
[k: string]: unknown;
}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 6720ed3790..60d9beba86 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -882,8 +882,30 @@ describe('CodexAgent.startSession developerInstructions', () => {
});
const params = host.request.mock.calls.find(([method]) => method === Method.ThreadResume)?.[1] as {
modelProvider?: string;
+ excludeTurns?: boolean;
+ initialTurnsPage?: unknown;
};
expect(params.modelProvider).toBe('cindy_openai');
+ expect(params.excludeTurns).toBe(true);
+ expect(params.initialTurnsPage).toBeUndefined();
+ await handle.close();
+ });
+
+ it('omits metadata-only resume for remote Codex versions older than 0.125.0', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, undefined, { userAgent: 'mock-codex/0.124.0' });
+
+ const handle = await agent.startSession({
+ sessionId: 'session-legacy-remote-resume',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ remoteHostId: 'legacy-remote',
+ resumeSessionId: '123e4567-e89b-12d3-a456-426614174000',
+ });
+ const params = host.request.mock.calls.find(([method]) => method === Method.ThreadResume)?.[1] as {
+ excludeTurns?: boolean;
+ };
+ expect(params.excludeTurns).toBeUndefined();
await handle.close();
});
@@ -6625,7 +6647,7 @@ describe('CodexAgent plan mode', () => {
await normalHandle.close();
});
- it('does not request a default marker for resumed native plan items without a collaboration marker', async () => {
+ it('conservatively requests a default marker for resumed native plan items', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent, (method) => {
if (method === Method.ThreadResume) {
@@ -6658,7 +6680,7 @@ describe('CodexAgent plan mode', () => {
const [, params] = turnStartCalls(host)[0] as [string, Record<string, unknown>];
expect(params.collaborationMode).toEqual({
mode: 'default',
- settings: { ...PLAN_SETTINGS, developer_instructions: '' },
+ settings: PLAN_SETTINGS,
});
await handle.close();
});
@@ -6701,7 +6723,7 @@ describe('CodexAgent plan mode', () => {
await handle.close();
});
- it('does not request another default marker when resumed history already ended in Default Mode', async () => {
+ it('conservatively requests a default marker when legacy resumed history ended in Default Mode', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent, (method) => {
if (method === Method.ThreadResume) {
@@ -6741,16 +6763,16 @@ describe('CodexAgent plan mode', () => {
const [, params] = turnStartCalls(host)[0] as [string, Record<string, unknown>];
expect(params.collaborationMode).toEqual({
mode: 'default',
- settings: { ...PLAN_SETTINGS, developer_instructions: '' },
+ settings: PLAN_SETTINGS,
});
await handle.close();
});
- it('does not request a default marker for resumed threads without plan history', async () => {
+ it('conservatively resets sticky collaboration mode after metadata-only resume', async () => {
const agent = new CodexAgent(createDeps());
const host = installTurnHost(agent);
const handle = await agent.startSession({
- sessionId: 'session-normal-resume-reset',
+ sessionId: 'session-metadata-only-resume-reset',
model: 'gpt-5.4',
workingDir: '/repo',
resumeSessionId: '123e4567-e89b-12d3-a456-426614174000',
@@ -6761,8 +6783,28 @@ describe('CodexAgent plan mode', () => {
const [, params] = turnStartCalls(host)[0] as [string, Record<string, unknown>];
expect(params.collaborationMode).toEqual({
mode: 'default',
- settings: { ...PLAN_SETTINGS, developer_instructions: '' },
+ settings: PLAN_SETTINGS,
+ });
+ await handle.close();
+ });
+
+ it('uses the resolved resume model for the default collaboration marker', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installTurnHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-default-model-resume',
+ model: 'gpt-5',
+ workingDir: '/repo',
+ resumeSessionId: '123e4567-e89b-12d3-a456-426614174000',
});
+
+ await handle.send({ type: 'user', content: 'continue normally' });
+
+ const [, params] = turnStartCalls(host)[0] as [string, {
+ collaborationMode?: { mode: string; settings: { model: string } };
+ }];
+ expect(params.collaborationMode?.settings.model).toBe('gpt-5.4');
+ expect(handle.model).toBe('gpt-5.4');
await handle.close();
});
@@ -6823,15 +6865,7 @@ describe('CodexAgent plan mode', () => {
}
if (method === Method.ThreadResume) {
return {
- thread: {
- id: 'start-thread-id',
- turns: [
- {
- id: 'turn-1',
- items: [collaborationModeItem('Plan')],
- },
- ],
- },
+ thread: { id: 'start-thread-id' },
model: 'gpt-5.4',
modelProvider: 'openai',
cwd: '/repo',
@@ -6848,6 +6882,11 @@ describe('CodexAgent plan mode', () => {
await vi.waitFor(() => {
expect(turnStartCalls(host)).toHaveLength(3);
});
+ const [, resumeParams] = host.request.mock.calls.find(
+ ([method]) => method === Method.ThreadResume,
+ ) as [string, { excludeTurns?: boolean; initialTurnsPage?: unknown }];
+ expect(resumeParams.excludeTurns).toBe(true);
+ expect(resumeParams.initialTurnsPage).toBeUndefined();
const [, failedImplParams] = turnStartCalls(host)[1] as [string, {
collaborationMode?: { mode: string; settings: { developer_instructions: string | null } };
}];
@@ -6859,6 +6898,59 @@ describe('CodexAgent plan mode', () => {
await handle.close();
});
+ it('uses the resolved resume model when a default turn retries after a daemon restart', async () => {
+ const agent = new CodexAgent(createDeps());
+ let turnStartCount = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.ThreadStart) {
+ return {
+ thread: { id: 'start-thread-id' },
+ model: 'gpt-5',
+ modelProvider: 'openai',
+ cwd: '/repo',
+ };
+ }
+ if (method === Method.TurnStart) {
+ turnStartCount += 1;
+ if (turnStartCount === 1) return { turn: { id: 'turn-1' } };
+ if (turnStartCount === 2) throw new Error('thread not found');
+ return { turn: { id: `turn-${turnStartCount}` } };
+ }
+ if (method === Method.ThreadResume) {
+ return {
+ thread: { id: 'start-thread-id' },
+ model: 'gpt-5.4',
+ modelProvider: 'openai',
+ cwd: '/repo',
+ };
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-plan-exit-retry-default-model',
+ model: 'gpt-5',
+ workingDir: '/repo',
+ planMode: true,
+ });
+ handle.setInteractionResolver(async () => ({ kind: 'plan_review', behavior: 'allow' }));
+
+ await handle.send({ type: 'user', content: 'make a plan' });
+ runPlanTurn(host, 'turn-1', '1. do X\n2. do Y');
+
+ await vi.waitFor(() => {
+ expect(turnStartCalls(host)).toHaveLength(3);
+ });
+ const [, retryParams] = turnStartCalls(host)[2] as [string, {
+ collaborationMode?: { mode: string; settings: { model: string; reasoning_effort: string } };
+ }];
+ expect(retryParams.collaborationMode?.settings).toMatchObject({
+ model: 'gpt-5.4',
+ reasoning_effort: 'high',
+ });
+ expect(handle.model).toBe('gpt-5.4');
+ await handle.close();
+ });
+
it('emits a terminal event when the approved plan implementation turn cannot start', async () => {
const agent = new CodexAgent(createDeps());
let turnSeq = 0;
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 9f5f727419..5daa8cf98c 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -310,16 +310,13 @@ function mapPermissionToCodex(
}
}
-/**
- * `approvalsReviewer` is verified against the app-server bundled with Codex 0.144.6.
- * Remote hosts may keep an older standalone binary across desktop upgrades, so parse the
- * initialize userAgent and conservatively omit the field unless that verified floor is met.
- */
-function supportsCodexApprovalsReviewerProtocol(userAgent: string | undefined): boolean {
+function codexUserAgentAtLeast(
+ userAgent: string | undefined,
+ minimum: readonly [number, number, number],
+): boolean {
const match = /\/(\d+)\.(\d+)\.(\d+)(?:[-+ )]|$)/.exec(userAgent ?? '');
if (!match) return false;
const version = [Number(match[1]), Number(match[2]), Number(match[3])] as const;
- const minimum = [0, 144, 6] as const;
for (let i = 0; i < minimum.length; i += 1) {
if (version[i]! > minimum[i]!) return true;
if (version[i]! < minimum[i]!) return false;
@@ -327,6 +324,15 @@ function supportsCodexApprovalsReviewerProtocol(userAgent: string | undefined):
return true;
}
+/**
+ * `approvalsReviewer` is verified against the app-server bundled with Codex 0.144.6.
+ * Remote hosts may keep an older standalone binary across desktop upgrades, so parse the
+ * initialize userAgent and conservatively omit the field unless that verified floor is met.
+ */
+function supportsCodexApprovalsReviewerProtocol(userAgent: string | undefined): boolean {
+ return codexUserAgentAtLeast(userAgent, [0, 144, 6]);
+}
+
/**
* Runtime workspace roots and named permission profiles were verified against
* the app-server bundled with Codex 0.144.6. Keep older remote daemons
@@ -337,6 +343,15 @@ function supportsCodexReadonlyReferenceDirs(userAgent: string | undefined): bool
return supportsCodexApprovalsReviewerProtocol(userAgent);
}
+/**
+ * `excludeTurns` was introduced in Codex 0.125.0 and later marked experimental.
+ * Older remote daemons can outlive desktop upgrades, so omit the unknown field
+ * and preserve their legacy full-history resume behavior.
+ */
+function supportsCodexResumeExcludeTurns(userAgent: string | undefined): boolean {
+ return codexUserAgentAtLeast(userAgent, [0, 125, 0]);
+}
+
const READONLY_REFERENCES_PERMISSION_PROFILE = 'cindy-readonly-references';
/**
@@ -2099,6 +2114,7 @@ export class CodexAgent extends BaseAgent {
const approvalsReviewerSupported =
approvalsReviewerProtocolSupported && approvalsReviewerRouteSupported;
const readonlyReferenceDirsSupported = supportsCodexReadonlyReferenceDirs(initResp.userAgent);
+ const resumeExcludeTurnsSupported = supportsCodexResumeExcludeTurns(initResp.userAgent);
if (mutableExtraDirs.length > 0 && !readonlyReferenceDirsSupported) {
releaseHostBindingLeaseIfNeeded();
throw new Error(
@@ -2376,44 +2392,6 @@ export class CodexAgent extends BaseAgent {
let threadId: string;
let codexProductPromptDelivery: AgentSessionHandle['codexProductPromptDelivery'];
- const collaborationModeFromText = (text: string): 'plan' | 'default' | null => {
- const match = /<collaboration_mode>\s*#\s*(Plan|Default)\s+Mode/i.exec(text);
- if (!match) return null;
- return match[1]?.toLowerCase() === 'plan' ? 'plan' : 'default';
- };
-
- const textFromResponsesItem = (value: unknown): string[] => {
- if (!value || typeof value !== 'object') return [];
- if (Array.isArray(value)) return value.flatMap(textFromResponsesItem);
- const record = value as Record<string, unknown>;
- const texts: string[] = [];
- if (typeof record.text === 'string') texts.push(record.text);
- if (Array.isArray(record.content)) texts.push(...record.content.flatMap(textFromResponsesItem));
- return texts;
- };
-
- const threadHistoryNeedsDefaultModeMarker = (thread: unknown): boolean => {
- if (!thread || typeof thread !== 'object') return false;
- const turns = (thread as { turns?: unknown }).turns;
- if (!Array.isArray(turns)) return false;
- // Codex 0.142.5 thread/resume includes turns[].items. Only collaboration
- // markers are authoritative here: ordinary non-Plan-Mode Codex turns can
- // also persist native `type:'plan'` items.
- let latestCollaborationMode: 'plan' | 'default' | null = null;
- for (const turn of turns) {
- if (!turn || typeof turn !== 'object') continue;
- const items = (turn as { items?: unknown }).items;
- if (!Array.isArray(items)) continue;
- for (const item of items) {
- if (!item || typeof item !== 'object') continue;
- for (const text of textFromResponsesItem(item)) {
- latestCollaborationMode = collaborationModeFromText(text) ?? latestCollaborationMode;
- }
- }
- }
- return latestCollaborationMode === 'plan';
- };
-
/**
* 会话中途把单个设置 (serviceTier / model / effort) 立即推给 app-server,
* 写入后续 turn 的 sticky context — 不必等下一个 turn/start 携带 (与官方
@@ -2475,6 +2453,7 @@ export class CodexAgent extends BaseAgent {
const useProxyChannel = isCodexProxyChannelReady();
const params: ThreadResumeParams = {
threadId: opts.resumeSessionId,
+ ...(resumeExcludeTurnsSupported ? { excludeTurns: true } : {}),
cwd: opts.workingDir,
...currentThreadWorkspaceConfig(),
...(threadModelProvider ? { modelProvider: threadModelProvider } : {}),
@@ -2492,6 +2471,9 @@ export class CodexAgent extends BaseAgent {
if (Object.hasOwn(resp, 'serviceTier')) {
mutableServiceTier = normalizeServiceTier(resp.serviceTier) ?? null;
}
+ if (mutableModel === 'gpt-5' && resp.model) {
+ mutableModel = resp.model;
+ }
threadId = resp.thread.id;
if (useProxyChannel) {
registerCodexDeveloperInstructions(threadId, developerInstructions);
@@ -2505,7 +2487,10 @@ export class CodexAgent extends BaseAgent {
// that sticky state lives server-side, conservatively send mode:'default'
// on future normal turns after any successful resume.
threadTouchedPlanMode = true;
- planModeDefaultMarkerNeeded = threadHistoryNeedsDefaultModeMarker(resp.thread);
+ // excludeTurns intentionally loads no history, so we cannot prove whether
+ // the persisted thread last used Plan Mode. Inject the official Default
+ // marker once; markCollaborationModeAccepted() suppresses repeats.
+ planModeDefaultMarkerNeeded = true;
log.info('thread/resume ok', { threadId, model: resp.model, serviceTier: mutableServiceTier ?? null });
} catch (e) {
releaseHostBindingLeaseIfNeeded();
@@ -4177,16 +4162,26 @@ export class CodexAgent extends BaseAgent {
host.subscribeThread(threadId, handlers);
const resumeParams: ThreadResumeParams = {
threadId,
+ ...(resumeExcludeTurnsSupported ? { excludeTurns: true } : {}),
cwd: opts.workingDir,
...currentThreadWorkspaceConfig(),
...(mutableModel && mutableModel !== 'gpt-5' ? { model: mutableModel } : {}),
...(mutableServiceTier !== undefined ? { serviceTier: mutableServiceTier } : {}),
};
const resumeResp = await host.request<ThreadResumeResponse>(Method.ThreadResume, resumeParams);
+ if (mutableModel === 'gpt-5' && resumeResp.model) {
+ mutableModel = resumeResp.model;
+ turnParams.effort = clampEffortForCodex(mutableModel, mutableEffort);
+ if (turnParams.collaborationMode) {
+ turnParams.collaborationMode.settings.model = mutableModel;
+ turnParams.collaborationMode.settings.reasoning_effort =
+ clampEffortForCodex(mutableModel, mutableEffort);
+ }
+ }
if (collaborationMode?.mode === 'default') {
- planModeDefaultMarkerNeeded = threadHistoryNeedsDefaultModeMarker(resumeResp.thread);
+ planModeDefaultMarkerNeeded = true;
if (turnParams.collaborationMode?.mode === 'default') {
- turnParams.collaborationMode.settings.developer_instructions = planModeDefaultMarkerNeeded ? null : '';
+ turnParams.collaborationMode.settings.developer_instructions = null;
}
}
log.info('thread/resume after stale daemon ok, retrying turn/start', { threadId });