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。

feat(desktop): Codex 超大历史在同一任务里保底压缩 (#3510)

Dashed816d1ed279
diff --git a/apps/desktop/src/main/__tests__/fork.test.ts b/apps/desktop/src/main/__tests__/fork.test.ts
index 0fa0837817..e4b5394402 100644
--- a/apps/desktop/src/main/__tests__/fork.test.ts
+++ b/apps/desktop/src/main/__tests__/fork.test.ts
@@ -470,6 +470,7 @@ describe('forkSessionAtMessage', () => {
const second = makeMessageRow({ id: 'asst-1', role: 'assistant', createdAt: 2000 });
selectQueue.push([source]); // source session
+ selectQueue.push([]); // no existing strip-fork child
selectQueue.push([first, second]); // source messages for max + ids
selectQueue.push([
makeSourceRow({
@@ -517,6 +518,112 @@ describe('forkSessionAtMessage', () => {
expect(result.parentSessionId).toBe('src-session');
});
+ it('reuses an existing strip-fork child instead of forking twice', async () => {
+ const source = makeSourceRow({
+ agentKind: 'codex',
+ model: 'gpt-5.5',
+ sdkSessionId: 'codex-thread-source',
+ });
+ const existing = makeSourceRow({
+ id: 'already-stripped',
+ agentKind: 'codex',
+ title: '[Fork·已剥离] Project A',
+ sdkSessionId: 'codex-thread-stripped',
+ parentSessionId: 'src-session',
+ forkedAtMessageId: null,
+ status: 'active',
+ });
+ selectQueue.push([source]);
+ selectQueue.push([existing]);
+ selectQueue.push([]); // source has not advanced
+ selectQueue.push([]); // child copied boundary still covers source
+
+ const result = await forkSessionStripEncrypted('src-session');
+
+ expect(forkSdkSessionMock).not.toHaveBeenCalled();
+ expect(txCalls).toHaveLength(0);
+ expect(result.id).toBe('already-stripped');
+ expect(result.parentSessionId).toBe('src-session');
+ });
+
+ it('does not reuse a strip-fork child after the source history has advanced', async () => {
+ const source = makeSourceRow({
+ agentKind: 'codex',
+ model: 'gpt-5.5',
+ sdkSessionId: 'codex-thread-source',
+ });
+ const existing = makeSourceRow({
+ id: 'already-stripped',
+ agentKind: 'codex',
+ title: '[Fork·已剥离] Project A',
+ sdkSessionId: 'codex-thread-stripped',
+ parentSessionId: 'src-session',
+ forkedAtMessageId: null,
+ status: 'active',
+ createdAt: 1500,
+ });
+ const later = makeMessageRow({ id: 'user-2', role: 'user', createdAt: 3000 });
+ selectQueue.push([source]);
+ selectQueue.push([existing]);
+ selectQueue.push([later]);
+ selectQueue.push([makeMessageRow({ id: 'copied-old', role: 'user', createdAt: 1000 })]);
+ selectQueue.push([
+ makeSourceRow({
+ agentKind: 'codex',
+ title: '[Fork·已剥离] Project A',
+ sdkSessionId: 'codex-thread-new',
+ parentSessionId: 'src-session',
+ forkedAtMessageId: null,
+ }),
+ ]);
+ forkSdkSessionMock.mockResolvedValue({
+ newSdkSessionId: 'codex-thread-new',
+ uuidMap: new Map<string, string>(),
+ });
+
+ const result = await forkSessionStripEncrypted('src-session');
+
+ expect(forkSdkSessionMock).toHaveBeenCalled();
+ expect(result.parentSessionId).toBe('src-session');
+ });
+
+ it('reuses the newest strip-fork child that still covers source history', async () => {
+ const source = makeSourceRow({
+ agentKind: 'codex',
+ model: 'gpt-5.5',
+ sdkSessionId: 'codex-thread-source',
+ });
+ const older = makeSourceRow({
+ id: 'strip-old',
+ agentKind: 'codex',
+ title: '[Fork·已剥离] Project A',
+ sdkSessionId: 'codex-thread-old',
+ parentSessionId: 'src-session',
+ forkedAtMessageId: null,
+ status: 'active',
+ createdAt: 1000,
+ });
+ const newer = makeSourceRow({
+ id: 'strip-new',
+ agentKind: 'codex',
+ title: '[Fork·已剥离] Project A',
+ sdkSessionId: 'codex-thread-new',
+ parentSessionId: 'src-session',
+ forkedAtMessageId: null,
+ status: 'active',
+ createdAt: 4000,
+ });
+ selectQueue.push([source]);
+ selectQueue.push([older, newer]);
+ selectQueue.push([makeMessageRow({ id: 'user-2', role: 'user', createdAt: 3000 })]);
+ selectQueue.push([makeMessageRow({ id: 'copied', role: 'user', createdAt: 3000 })]);
+
+ const result = await forkSessionStripEncrypted('src-session');
+
+ expect(forkSdkSessionMock).not.toHaveBeenCalled();
+ expect(result.id).toBe('strip-new');
+ });
+
it('remaps agentMeta uuid via maker uuidMap so chained fork (B → C) keeps valid uuids', async () => {
// 场景: A → fork → B 时, SDK 把 jsonl 里 uuid 全部 remap。源 DB 里的 agentMeta
// 携带的是 A 的旧 uuid; 写入 B 时必须替换成 B jsonl 里的新 uuid (从 uuidMap),
diff --git a/apps/desktop/src/main/localDb/__tests__/codexHistoryOversizedUpgrade.test.ts b/apps/desktop/src/main/localDb/__tests__/codexHistoryOversizedUpgrade.test.ts
new file mode 100644
index 0000000000..cadb6680fe
--- /dev/null
+++ b/apps/desktop/src/main/localDb/__tests__/codexHistoryOversizedUpgrade.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+
+import { CODEX_HISTORY_OVERSIZED_REASON } from '@cindy/maker-core';
+
+import {
+ canUpgradeStalledErrorContent,
+ mergeOversizedHistoryReason,
+ parsePersistedErrorContent,
+} from '../codexHistoryOversizedUpgrade';
+
+describe('codexHistoryOversizedUpgrade', () => {
+ it('only upgrades persisted reconnect-stalled errors', () => {
+ expect(canUpgradeStalledErrorContent({ reason: 'codex_reconnect_stalled' })).toBe(true);
+ expect(canUpgradeStalledErrorContent({ reason: 'context-overflow' })).toBe(false);
+ expect(canUpgradeStalledErrorContent({ reason: 'turn-failed' })).toBe(false);
+ expect(canUpgradeStalledErrorContent(null)).toBe(false);
+ });
+
+ it('keeps original error fields when merging the oversized reason', () => {
+ const next = mergeOversizedHistoryReason({
+ reason: 'codex_reconnect_stalled',
+ message: 'old',
+ sdkError: 'raw',
+ provider: 'openai',
+ });
+ expect(next.reason).toBe(CODEX_HISTORY_OVERSIZED_REASON);
+ expect(next.sdkError).toBe('raw');
+ expect(next.provider).toBe('openai');
+ expect(String(next.message)).toContain('oversized');
+ });
+
+ it('parses object error content and rejects scalars', () => {
+ expect(parsePersistedErrorContent(JSON.stringify({ reason: 'codex_reconnect_stalled' }))).toEqual({
+ reason: 'codex_reconnect_stalled',
+ });
+ expect(parsePersistedErrorContent('"plain"')).toBeNull();
+ expect(parsePersistedErrorContent('not-json')).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/localDb/codexHistoryOversizedUpgrade.ts b/apps/desktop/src/main/localDb/codexHistoryOversizedUpgrade.ts
new file mode 100644
index 0000000000..54eb86e33c
--- /dev/null
+++ b/apps/desktop/src/main/localDb/codexHistoryOversizedUpgrade.ts
@@ -0,0 +1,161 @@
+/**
+ * 打开本地 Codex 会话时,把旧的 `codex_reconnect_stalled` 错误行单向升格为
+ * `codex_history_oversized`。不新增 IPC:messages:list 返回后 fire-and-forget,
+ * 命中后再用既有 messages:created 广播刷新已打开的横幅。
+ */
+import { and, desc, eq, isNull, sql } from 'drizzle-orm';
+
+import {
+ CODEX_HISTORY_OVERSIZED_REASON,
+} from '@cindy/maker-core';
+
+import { createLogger } from '../logger';
+import {
+ classifyCodexHistoryOversized,
+ type CodexHistoryOversizedClass,
+} from '../maker-host/codex-local-sessions';
+import { getDbClient } from './client/current';
+import { messageToCamel, safeStringify } from './mapper';
+import { messages, sessions } from './schema';
+import type { Message } from '../../renderer/lib/ccAgent.types';
+
+const log = createLogger('localDb/codexHistoryOversizedUpgrade');
+const CODEX_RECONNECT_STALLED_REASON = 'codex_reconnect_stalled';
+const inFlight = new Set<string>();
+
+export function parsePersistedErrorContent(raw: string): Record<string, unknown> | null {
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ return parsed as Record<string, unknown>;
+ }
+ } catch {
+ /* fall through */
+ }
+ return null;
+}
+
+export function canUpgradeStalledErrorContent(content: Record<string, unknown> | null): boolean {
+ return content?.reason === CODEX_RECONNECT_STALLED_REASON;
+}
+
+export function mergeOversizedHistoryReason(
+ content: Record<string, unknown>,
+): Record<string, unknown> {
+ return {
+ ...content,
+ reason: CODEX_HISTORY_OVERSIZED_REASON,
+ message:
+ 'Codex remote compaction cannot finish because this thread\'s live history is oversized. ' +
+ 'Fork and strip oversized inline images to continue.',
+ };
+}
+
+export type HistoryOversizedUpgradeResult =
+ | 'upgraded'
+ | 'skipped'
+ | 'in-flight';
+
+export interface HistoryOversizedUpgradeDeps {
+ classify?: (threadId: string) => Promise<CodexHistoryOversizedClass>;
+}
+
+export async function maybeUpgradeCodexHistoryOversizedError(
+ sessionId: string,
+ deps: HistoryOversizedUpgradeDeps = {},
+): Promise<{ result: HistoryOversizedUpgradeResult; message?: Message }> {
+ if (!sessionId || inFlight.has(sessionId)) return { result: 'in-flight' };
+ inFlight.add(sessionId);
+ try {
+ const db = getDbClient().drizzle;
+ const [session] = await db
+ .select({
+ agentKind: sessions.agentKind,
+ remoteHostId: sessions.remoteHostId,
+ sdkSessionId: sessions.sdkSessionId,
+ clearedAt: sessions.clearedAt,
+ })
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ if (!session || session.agentKind !== 'codex' || session.remoteHostId || !session.sdkSessionId) {
+ return { result: 'skipped' };
+ }
+
+ const conds = [
+ eq(messages.sessionId, sessionId),
+ eq(messages.role, 'error'),
+ isNull(messages.rewindAt),
+ ];
+ if (session.clearedAt != null) conds.push(sql`${messages.createdAt} > ${session.clearedAt}`);
+ const [row] = await db
+ .select({
+ clientId: messages.clientId,
+ content: messages.content,
+ })
+ .from(messages)
+ .where(and(...conds))
+ .orderBy(desc(messages.createdAt), desc(sql<number>`rowid`))
+ .limit(1);
+ if (!row) return { result: 'skipped' };
+
+ const parsed = parsePersistedErrorContent(row.content);
+ if (!canUpgradeStalledErrorContent(parsed) || !parsed) return { result: 'skipped' };
+
+ const classify = deps.classify ?? classifyCodexHistoryOversized;
+ const classified = await classify(session.sdkSessionId);
+ if (classified !== 'oversized') return { result: 'skipped' };
+
+ const nextContent = mergeOversizedHistoryReason(parsed);
+ const nextSerialized = safeStringify(nextContent);
+ const write = await db
+ .update(messages)
+ .set({ content: nextSerialized })
+ .where(
+ and(
+ eq(messages.sessionId, sessionId),
+ eq(messages.clientId, row.clientId),
+ eq(messages.role, 'error'),
+ isNull(messages.rewindAt),
+ eq(messages.content, row.content),
+ ),
+ )
+ .run();
+ if (write.changes === 0) return { result: 'skipped' };
+
+ const [narrow] = await db
+ .select({
+ id: messages.id,
+ clientId: messages.clientId,
+ sessionId: messages.sessionId,
+ role: messages.role,
+ toolUseId: messages.toolUseId,
+ agentMeta: messages.agentMeta,
+ agentKind: messages.agentKind,
+ createdAt: messages.createdAt,
+ rewindAt: messages.rewindAt,
+ })
+ .from(messages)
+ .where(and(eq(messages.sessionId, sessionId), eq(messages.clientId, row.clientId)))
+ .limit(1);
+ log.info('upgraded stalled Codex error to oversized history', {
+ sessionId,
+ clientId: row.clientId,
+ threadId: session.sdkSessionId,
+ });
+ return {
+ result: 'upgraded',
+ ...(narrow
+ ? { message: messageToCamel({ ...narrow, content: nextSerialized }) }
+ : {}),
+ };
+ } catch (error) {
+ log.warn('codex oversized history upgrade skipped', {
+ sessionId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return { result: 'skipped' };
+ } finally {
+ inFlight.delete(sessionId);
+ }
+}
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
index 73211b5bf8..b03649b5d6 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListCursor.test.ts
@@ -41,6 +41,10 @@ const h = vi.hoisted(() => ({
),
}));
+vi.mock('../../codexHistoryOversizedUpgrade', () => ({
+ maybeUpgradeCodexHistoryOversizedError: vi.fn(async () => ({ result: 'skipped' })),
+}));
+
vi.mock('electron', () => ({
ipcMain: {
handle: vi.fn((channel: string, handler: (...args: unknown[]) => unknown) => {
@@ -78,6 +82,7 @@ vi.mock('../../client/current', () => ({
getDbClient: () => ({ drizzle: h.db, query: h.query, tx: h.tx }),
}));
+import { maybeUpgradeCodexHistoryOversizedError } from '../../codexHistoryOversizedUpgrade';
import {
findParkedEngineSession,
findPendingAgentHandoff,
@@ -571,6 +576,20 @@ describe('local-db:messages:list cursor', () => {
expect(hydrateSql).toEqual(expect.stringContaining('CASE WHEN json_valid'));
expect(hydrateSql).not.toMatch(/json_valid\([^)]*\) = 0 OR json_extract/);
});
+
+ it('only scans oversized-history upgrade on the first page', async () => {
+ const sqlite = createDb();
+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, NULL)').run('s1');
+ insertMessage(sqlite, { id: 'row-new', createdAt: 1_000, content: 'new' });
+ insertMessage(sqlite, { id: 'row-old', createdAt: 999, content: 'old' });
+ registerMessageIpc();
+ const listHandler = h.handlers.get('local-db:messages:list');
+ await listHandler?.({}, 's1', { limit: 1 });
+ await listHandler?.({}, 's1', { limit: 1, before: 'row-new' });
+ await listHandler?.({}, 's1', { limit: 1, after: 'row-old' });
+ expect(maybeUpgradeCodexHistoryOversizedError).toHaveBeenCalledTimes(1);
+ expect(maybeUpgradeCodexHistoryOversizedError).toHaveBeenCalledWith('s1');
+ });
});
describe('findPendingForkOrigin 来源标记重建', () => {
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListImportSideEffects.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListImportSideEffects.test.ts
index a2e7c5c774..d773730c49 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/messagesListImportSideEffects.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/messagesListImportSideEffects.test.ts
@@ -37,6 +37,10 @@ vi.mock('../../../logger.js', () => ({
}));
vi.mock('../../../maker-host/codex-local-sessions', () => ({
importExternalCodexMessagesForSession: vi.fn(async () => undefined),
+ classifyCodexHistoryOversized: vi.fn(async () => false),
+}));
+vi.mock('../../codexHistoryOversizedUpgrade', () => ({
+ maybeUpgradeCodexHistoryOversizedError: vi.fn(async () => ({ result: 'skipped' })),
}));
vi.mock('../../../maker-host/claude-local-sessions', () => ({
importExternalClaudeCodeMessagesForSession: vi.fn(async () => undefined),
diff --git a/apps/desktop/src/main/localDb/ipc/messages.ts b/apps/desktop/src/main/localDb/ipc/messages.ts
index 8c1e36d1d6..d8e1033336 100644
--- a/apps/desktop/src/main/localDb/ipc/messages.ts
+++ b/apps/desktop/src/main/localDb/ipc/messages.ts
@@ -48,6 +48,7 @@ import {
type RegionalMoney,
} from '../../../shared/regionalMoney.js';
import { capReferenceMessageRows } from './history.js';
+import { maybeUpgradeCodexHistoryOversizedError } from '../codexHistoryOversizedUpgrade';
import type { Message, MessageRole, AgentMeta } from '../../../renderer/lib/ccAgent.types';
const log = createLogger('localDb/messages');
@@ -313,7 +314,24 @@ export function registerMessageIpc(): void {
)
.limit(limit);
const orderedRows = afterCursor ? rows.slice().reverse() : rows;
- return hydrateLegacyUserTurnCosts(orderedRows.map(messageToCamelWithRowid));
+ const listed = hydrateLegacyUserTurnCosts(orderedRows.map(messageToCamelWithRowid));
+ // 不阻塞首屏。旧 reconnect-stalled 横幅只在首页扫描一次,分页不再读 rollout。
+ if (!before && beforeTs == null && !after) {
+ const ownerScope = captureOwnerBroadcastScope();
+ void maybeUpgradeCodexHistoryOversizedError(sid)
+ .then((upgrade) => {
+ if (upgrade.result !== 'upgraded' || !upgrade.message) return;
+ if (!isOwnerBroadcastScopeCurrent(ownerScope)) return;
+ broadcastMessageRow(sid, upgrade.message, ownerScope);
+ })
+ .catch((error) => {
+ log.warn('codex oversized history upgrade rejected', {
+ sessionId: sid,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+ return listed;
});
ipcMain.handle(
diff --git a/apps/desktop/src/main/maker-host/codex-local-sessions.ts b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
index 274236708c..eef63dcde0 100644
--- a/apps/desktop/src/main/maker-host/codex-local-sessions.ts
+++ b/apps/desktop/src/main/maker-host/codex-local-sessions.ts
@@ -25,6 +25,8 @@ import { CURRENT_CINDY_REGION } from '../../shared/brandRegion.js';
import {
CodexResumePreparationBlockedError,
finalizeCodexCitationText,
+ isOversizedLiveTailStats,
+ measureRolloutLiveTailStats,
} from '@cindy/maker-core';
import { getCurrentDbClientUserId, getDbClient } from '../localDb/client/current.js';
@@ -3520,6 +3522,23 @@ function dropUndefined<T extends Record<string, unknown>>(obj: T): Partial<T> {
return out;
}
+export type CodexHistoryOversizedClass = 'oversized' | 'healthy' | 'unknown';
+
+/** 只读测量本地 Codex rollout 活尾巴。找不到文件或读失败归 unknown,不得当成健康。 */
+export async function classifyCodexHistoryOversized(
+ threadId: string,
+): Promise<CodexHistoryOversizedClass> {
+ if (!threadId) return 'unknown';
+ const rolloutPath = resolveRolloutPath(threadId);
+ if (!rolloutPath) return 'unknown';
+ try {
+ const stats = await measureRolloutLiveTailStats(rolloutPath);
+ return isOversizedLiveTailStats(stats) ? 'oversized' : 'healthy';
+ } catch {
+ return 'unknown';
+ }
+}
+
/**
* 为外部 Codex thread 创建的本地会话按需导入可读消息。
* 源 rollout 文件未变化时直接短路;文件变化后按行号 upsert,刷新已导入行并追加新行。
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/cindyContextCompression.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/cindyContextCompression.test.ts
new file mode 100644
index 0000000000..6dfc2ed8b8
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/cindyContextCompression.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest';
+
+import { afterStripAttempt, decideCindyCompression } from '../cindyContextCompression';
+
+describe('decideCindyCompression', () => {
+ it('does nothing remotely', () => {
+ expect(
+ decideCindyCompression({ local: false, bytes: 'violated', tokens: 'violated' }),
+ ).toBe('none');
+ });
+
+ it('strips when the byte budget is violated, even if tokens are also over', () => {
+ expect(
+ decideCindyCompression({ local: true, bytes: 'violated', tokens: 'violated' }),
+ ).toBe('strip');
+ });
+
+ it('rebuilds when only the token budget is violated', () => {
+ expect(
+ decideCindyCompression({ local: true, bytes: 'ok', tokens: 'violated' }),
+ ).toBe('rebuild');
+ });
+
+ it('does nothing when both budgets are ok or unknown', () => {
+ expect(decideCindyCompression({ local: true, bytes: 'ok', tokens: 'ok' })).toBe('none');
+ expect(
+ decideCindyCompression({ local: true, bytes: 'unknown', tokens: 'unknown' }),
+ ).toBe('none');
+ expect(decideCindyCompression({ local: true, bytes: 'unknown', tokens: 'ok' })).toBe(
+ 'none',
+ );
+ expect(decideCindyCompression({ local: true, bytes: 'ok', tokens: 'unknown' })).toBe(
+ 'none',
+ );
+ });
+
+ it('rebuilds when tokens are violated and bytes are unknown', () => {
+ expect(
+ decideCindyCompression({ local: true, bytes: 'unknown', tokens: 'violated' }),
+ ).toBe('rebuild');
+ });
+});
+
+describe('afterStripAttempt', () => {
+ it('finishes after a successful strip', () => {
+ expect(afterStripAttempt('recovered', { local: true, tokens: 'violated' })).toBe('done');
+ });
+
+ it('rebuilds when strip fails', () => {
+ expect(afterStripAttempt('failed', { local: true, tokens: 'ok' })).toBe('rebuild');
+ });
+
+ it('re-evaluates after a healthy measurement, so token overflow still rebuilds', () => {
+ expect(afterStripAttempt('not-needed', { local: true, tokens: 'violated' })).toBe(
+ 'rebuild',
+ );
+ expect(afterStripAttempt('not-needed', { local: true, tokens: 'ok' })).toBe('none');
+ });
+
+ it('does not rebuild when the turn is still running', () => {
+ expect(afterStripAttempt('busy', { local: true, tokens: 'violated' })).toBe('none');
+ });
+
+ it('does not rebuild when the owner snapshot is stale', () => {
+ expect(afterStripAttempt('stale', { local: true, tokens: 'violated' })).toBe('none');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
index 4c8fe0fff3..614d5ca352 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/contextOverflowRollover.test.ts
@@ -6,6 +6,7 @@ import {
findLatestRebuildableError,
lookupVerifiedContextWindow,
isContextOverflowErrorData,
+ isOversizedHistoryErrorData,
isPiPromptRpcTimeoutError,
persistedUserContentToWireMessage,
planContextOverflowRollover,
@@ -126,6 +127,13 @@ describe('shouldRebuildPiNativeSession', () => {
false,
),
).toBeNull();
+ expect(
+ findLatestRebuildableError([
+ msg('user', '继续', 'u1'),
+ msg('error', { reason: 'codex_history_oversized', message: 'oversized' }, 'e1'),
+ ]),
+ ).toEqual({ reason: 'codex_history_oversized', message: 'oversized' });
+ expect(isOversizedHistoryErrorData({ reason: 'codex_history_oversized' })).toBe(true);
});
});
@@ -182,17 +190,30 @@ describe('planContextOverflowRollover', () => {
describe('createContextOverflowRollover', () => {
function makeDeps(source: OverflowSourceMessage[]) {
return {
- getSessionRow: vi.fn(async () => ({
- status: 'active',
- agentKind: 'pi',
- remoteHostId: null as string | null,
- clearedAt: null,
- sdkSessionId: '/tmp/dead.jsonl',
- contextTokens: 0,
- contextWindow: 200_000,
- model: 'x-ai/grok-4.6',
- providerId: 'xai',
- })),
+ getSessionRow: vi.fn(
+ async (): Promise<{
+ status: string;
+ agentKind: string;
+ remoteHostId: string | null;
+ clearedAt: number | null;
+ sdkSessionId: string;
+ contextTokens: number;
+ contextWindow: number;
+ model: string;
+ providerId: string;
+ workingDir?: string | null;
+ }> => ({
+ status: 'active',
+ agentKind: 'pi',
+ remoteHostId: null,
+ clearedAt: null,
+ sdkSessionId: '/tmp/dead.jsonl',
+ contextTokens: 0,
+ contextWindow: 200_000,
+ model: 'x-ai/grok-4.6',
+ providerId: 'xai',
+ }),
+ ),
listMessages: vi.fn(async () => source),
findLatestUser: vi.fn(async (): Promise<OverflowSourceMessage | null> => null),
findLatestRebuildMeta: vi.fn(async () => null),
@@ -668,7 +689,7 @@ describe('createContextOverflowRollover', () => {
expect(deps.closeSession).toHaveBeenCalledWith('s1');
});
- it('keeps remote sessions out of automatic rollover', async () => {
+ it('keeps SSH remote sessions out of automatic rollover', async () => {
const deps = makeDeps([msg('user', '继续', 'u1')]);
deps.getSessionRow.mockResolvedValue({
status: 'active',
@@ -691,6 +712,154 @@ describe('createContextOverflowRollover', () => {
await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(false);
expect(deps.commitRebuild).not.toHaveBeenCalled();
});
+
+ it('strips oversized Codex history in place instead of forking a Cindy session', async () => {
+ const deps = makeDeps([
+ msg('user', '继续', 'u1'),
+ msg('error', { reason: 'codex_history_oversized', message: 'oversized' }, 'e1'),
+ ]);
+ deps.getSessionRow.mockResolvedValue({
+ status: 'active',
+ agentKind: 'codex',
+ remoteHostId: null,
+ clearedAt: null,
+ sdkSessionId: 'thread-fat',
+ contextTokens: 20_000,
+ contextWindow: 200_000,
+ model: 'gpt-5.6',
+ providerId: 'openai',
+ workingDir: '/work',
+ });
+ const tryStrip = vi.fn(async () => 'recovered' as const);
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ tryStripOversizedCodexHistory: tryStrip,
+ });
+ rollover.claim('s1');
+
+ await expect(
+ rollover.tryRecover('s1', { reason: 'codex_history_oversized', message: 'oversized' }),
+ ).resolves.toBe(true);
+ expect(tryStrip).toHaveBeenCalledWith({
+ sessionId: 's1',
+ threadId: 'thread-fat',
+ model: 'gpt-5.6',
+ providerId: 'openai',
+ workingDir: '/work',
+ });
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ expect(deps.onRebuilt).toHaveBeenCalledWith('s1');
+ });
+
+ it('falls back to rollover when oversized strip fails', async () => {
+ const deps = makeDeps([msg('user', '继续', 'u1')]);
+ deps.getSessionRow.mockResolvedValue({
+ status: 'active',
+ agentKind: 'codex',
+ remoteHostId: null,
+ clearedAt: null,
+ sdkSessionId: 'thread-fat',
+ contextTokens: 20_000,
+ contextWindow: 200_000,
+ model: 'gpt-5.6',
+ providerId: 'openai',
+ workingDir: '/work',
+ });
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ tryStripOversizedCodexHistory: vi.fn(async () => 'failed' as const),
+ });
+ rollover.claim('s1');
+
+ await expect(
+ rollover.tryRecover('s1', { reason: 'codex_history_oversized', message: 'oversized' }),
+ ).resolves.toBe(true);
+ expect(deps.commitRebuild).toHaveBeenCalled();
+ });
+
+ it('does not rebuild when strip reports the turn is still running', async () => {
+ const deps = makeDeps([
+ msg('user', '继续', 'u1'),
+ msg('error', { reason: 'codex_history_oversized', message: 'oversized' }, 'e1'),
+ ]);
+ deps.getSessionRow.mockResolvedValue({
+ status: 'active',
+ agentKind: 'codex',
+ remoteHostId: null,
+ clearedAt: null,
+ sdkSessionId: 'thread-fat',
+ contextTokens: 20_000,
+ contextWindow: 200_000,
+ model: 'gpt-5.6',
+ providerId: 'openai',
+ workingDir: '/work',
+ });
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ tryStripOversizedCodexHistory: vi.fn(async () => 'busy' as const),
+ });
+ rollover.claim('s1');
+ await expect(
+ rollover.tryRecover('s1', { reason: 'codex_history_oversized', message: 'oversized' }),
+ ).resolves.toBe(false);
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ expect(deps.onRebuilt).not.toHaveBeenCalled();
+ });
+
+ it('does not rebuild when oversized strip finds a stale owner', async () => {
+ const deps = makeDeps([
+ msg('user', '继续', 'u1'),
+ msg('error', { reason: 'codex_history_oversized', message: 'oversized' }, 'e1'),
+ ]);
+ deps.getSessionRow.mockResolvedValue({
+ status: 'active',
+ agentKind: 'codex',
+ remoteHostId: null,
+ clearedAt: null,
+ sdkSessionId: 'thread-fat',
+ contextTokens: 20_000,
+ contextWindow: 200_000,
+ model: 'gpt-5.6',
+ providerId: 'openai',
+ workingDir: '/work',
+ });
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ tryStripOversizedCodexHistory: vi.fn(async () => 'stale' as const),
+ });
+ rollover.claim('s1');
+ await expect(
+ rollover.tryRecover('s1', { reason: 'codex_history_oversized', message: 'oversized' }),
+ ).resolves.toBe(false);
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ });
+
+ it('does not rollover before send when current Codex thread is already slim', async () => {
+ const deps = makeDeps([
+ msg('user', '继续', 'u1'),
+ msg('error', { reason: 'codex_history_oversized', message: 'oversized' }, 'e1'),
+ ]);
+ deps.getSessionRow.mockResolvedValue({
+ status: 'active',
+ agentKind: 'codex',
+ remoteHostId: null,
+ clearedAt: null,
+ sdkSessionId: 'thread-slim',
+ contextTokens: 20_000,
+ contextWindow: 200_000,
+ model: 'gpt-5.6',
+ providerId: 'openai',
+ workingDir: '/work',
+ });
+ const rollover = createContextOverflowRollover({
+ ...deps,
+ tryStripOversizedCodexHistory: vi.fn(async () => 'not-needed' as const),
+ });
+
+ await expect(rollover.prepareUnhealthySession('s1')).resolves.toBe(false);
+ expect(deps.commitRebuild).not.toHaveBeenCalled();
+ expect(deps.closeSession).not.toHaveBeenCalled();
+ });
});
describe('persistedUserContentToWireMessage', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
index 883e6e1d53..58793ece1e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts
@@ -66,6 +66,15 @@ describe('isInterruptedTurnError', () => {
).toBe(true);
});
+ it('rejects oversized-history classification so auto-resume cannot loop', () => {
+ expect(
+ isInterruptedTurnError({
+ reason: 'codex_history_oversized',
+ message: 'Codex remote compaction cannot finish because this thread\'s live history is oversized.',
+ }),
+ ).toBe(false);
+ });
+
it('accepts the classified empty-response reason (#2320)', () => {
// translator 只在「发起过 API 调用、零文本、零工具、零 usage 增量」的严格
// 形态下盖这个 key —— 上游/网关返回退化空响应,与流被切断同属连接层故障,
diff --git a/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts b/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts
new file mode 100644
index 0000000000..c0be814aaa
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/cindyContextCompression.ts
@@ -0,0 +1,56 @@
+/**
+ * Cindy 保底压缩:一套流程,不是剥图 / 换窗两套功能。
+ *
+ * 问的只有一件事——当前任务还装不装得进约束。装得进就不动。
+ * 字节预算破了(可剥的超大内联图)→ 剥图。
+ * token 预算破了 → 交接重建。
+ * 剥图失败或剥完仍装不进 → 交接重建。
+ * 不确定 → 不动。
+ *
+ * 字节预算目前只有 Codex 能测量(本地 rollout)。Claude / Pi 没有生产者,
+ * bytes 对它们只会是 unknown,决定结果只可能是 rebuild 或 none。
+ * 工具输出不作为独立一档:官方 compact 会先清旧工具结果;官方失败后
+ * 交接正文本来就不带 tool_result。纯文本把字节顶破时 token 一定早已破。
+ * 混合型大尾巴(可剥图不足一半)有意不救,等证据再动比例阈值,不加新档。
+ *
+ * 切模型预检的数学仍在 assessModelSwitchContext。确认切小窗后,动作端
+ * 应以 tokens='violated' 调用本决定走 rebuild,不再走独立 handoff(本版尚未并入)。
+ */
+
+export type CompressionBudgetState = 'ok' | 'violated' | 'unknown';
+
+/**
+ * tokens='violated' 只允许这些证据(普通 timeout / 网络 / 鉴权不算):
+ * - 终态 context-overflow(含 PI prompt RPC 超时)
+ * - 本机占用 ≥ 100%
+ * - 官方 compact 确定性失败(needsRollover:空摘要、compact 路径 invalid-request)
+ *
+ * bytes='violated':Codex 活尾巴可剥超大内联图(>8MB 且可剥 ≥ 一半且剥完 ≤8MB)。
+ * unknown = 没测到,不是「预算没破」。
+ */
+export type CindyCompressionAction = 'strip' | 'rebuild' | 'none';
+
+export function decideCindyCompression(input: {
+ /** false = SSH 等无法读本地历史 */
+ local: boolean;
+ bytes: CompressionBudgetState;
+ tokens: CompressionBudgetState;
+}): CindyCompressionAction {
+ if (!input.local) return 'none';
+ if (input.bytes === 'violated') return 'strip';
+ if (input.tokens === 'violated') return 'rebuild';
+ return 'none';
+}
+
+export type StripAttemptResult = 'recovered' | 'not-needed' | 'failed' | 'busy' | 'stale';
+
+/** 剥图之后:成功结束;busy/stale 中止且不得重建;已健康则按更新后的字节预算再判;失败则重建。 */
+export function afterStripAttempt(
+ result: StripAttemptResult,
+ rest: { local: boolean; tokens: CompressionBudgetState },
+): 'done' | CindyCompressionAction {
+ if (result === 'recovered') return 'done';
+ if (result === 'busy' || result === 'stale') return 'none';
+ if (result === 'failed') return 'rebuild';
+ return decideCindyCompression({ local: rest.local, bytes: 'ok', tokens: rest.tokens });
+}
diff --git a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
index 93c4668da2..98d508fc76 100644
--- a/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
+++ b/apps/desktop/src/main/maker-ipc/contextOverflowRollover.ts
@@ -1,16 +1,21 @@
/**
- * 同一任务里因上下文超限而隐藏重建原生 Agent 会话。
+ * 同一任务里的 Cindy 保底压缩执行器。
*
- * 抄 messageDeleteHandler 的 same-engine context_rebuild,不抄可见 agent_switch。
- * 规划函数是纯的,host 只负责关 live handle、落库、注入交接、wire 重放失败那条 user 消息。
+ * 决定「剥图还是交接重建」见 cindyContextCompression.ts。这里只执行:
+ * 关 live handle、剥图 relink、或 context_rebuild 交接 + 必要时 replay。
*/
-import { CONTEXT_OVERFLOW_REASON, isContextOverflowErrorMessage } from '@cindy/maker-core';
+import {
+ CODEX_HISTORY_OVERSIZED_REASON,
+ CONTEXT_OVERFLOW_REASON,
+ isContextOverflowErrorMessage,
+} from '@cindy/maker-core';
import {
projectAgentFacingText,
readAgentInputReferences,
} from '@cindy/maker-shared/agent-input-projection';
+import { afterStripAttempt, decideCindyCompression } from './cindyContextCompression.js';
import { buildHandoffText, extractPlainText, type HandoffSourceMessage } from './agentHandoff.js';
const SYNTHETIC_TRIGGER_PREFIX = '[UI_ACTION_TRIGGER]';
@@ -42,6 +47,13 @@ export function isContextOverflowErrorData(data: unknown): boolean {
);
}
+export function isOversizedHistoryErrorData(data: unknown): boolean {
+ if (!data || typeof data !== 'object') return false;
+ return (data as { reason?: unknown }).reason === CODEX_HISTORY_OVERSIZED_REASON;
+}
+
+export type CodexStripRelinkResult = 'recovered' | 'not-needed' | 'failed' | 'busy' | 'stale';
+
const PI_PROMPT_RPC_TIMEOUT_RE = /pi rpc timeout after \d+ms: prompt\b/i;
export function isPiPromptRpcTimeoutError(data: unknown): boolean {
@@ -267,6 +279,7 @@ export function findLatestRebuildableError(
const data = errorContentToData(message.content);
if (isContextOverflowErrorData(data)) return data;
if (allowPiPromptTimeout && isPiPromptRpcTimeoutError(data)) return data;
+ if (isOversizedHistoryErrorData(data)) return data;
return null;
}
if (message.role === 'assistant' && extractPlainText(message.content).trim().length > 0) {
@@ -287,7 +300,19 @@ export interface ContextOverflowRolloverDeps {
contextWindow?: number | null;
model?: string | null;
providerId?: string | null;
+ workingDir?: string | null;
} | null>;
+ /**
+ * Codex 字节病第一档:同任务剥图并 relink native thread。
+ * recovered = 已换干净 thread;not-needed = 当前 thread 已可发送;failed = 落到换窗。
+ */
+ tryStripOversizedCodexHistory?(args: {
+ sessionId: string;
+ threadId: string;
+ model: string | null;
+ providerId: string | null;
+ workingDir: string | null;
+ }): Promise<CodexStripRelinkResult>;
resolveVerifiedWindow?(
agentKind: string,
modelId: string,
@@ -343,11 +368,39 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
} {
const inFlight = new Set<string>();
+ const runStripRelink = async (
+ sessionId: string,
+ sessionRow: {
+ agentKind: string;
+ sdkSessionId?: string | null;
+ model?: string | null;
+ providerId?: string | null;
+ workingDir?: string | null;
+ },
+ ): Promise<CodexStripRelinkResult> => {
+ if (
+ sessionRow.agentKind !== 'codex' ||
+ !sessionRow.sdkSessionId ||
+ !deps.tryStripOversizedCodexHistory
+ ) {
+ return 'failed';
+ }
+ return deps.tryStripOversizedCodexHistory({
+ sessionId,
+ threadId: sessionRow.sdkSessionId,
+ model: sessionRow.model ?? null,
+ providerId: sessionRow.providerId ?? null,
+ workingDir: sessionRow.workingDir ?? null,
+ });
+ };
+
const runRecover = async (sessionId: string, errorData: unknown): Promise<boolean> => {
- if (!isContextOverflowErrorData(errorData)) return false;
+ const oversized = isOversizedHistoryErrorData(errorData);
+ if (!isContextOverflowErrorData(errorData) && !oversized) return false;
await deps.drainPersistQueue();
const sessionRow = await deps.getSessionRow(sessionId);
if (!sessionRow || sessionRow.status === 'deleted') return false;
+ // SSH only. device-link 会话落在被控桌面本地库,没有 remoteHostId,必须继续换窗。
if (sessionRow.remoteHostId) return false;
return deps.withCloseSuppressed(sessionId, async () => {
@@ -356,6 +409,30 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
deps.log.warn('context overflow rollover skipped: turn still running', { sessionId });
return false;
}
+ const tokens: 'violated' | 'unknown' = isContextOverflowErrorData(errorData)
+ ? 'violated'
+ : 'unknown';
+ let action = decideCindyCompression({
+ local: true,
+ bytes: oversized ? 'violated' : 'unknown',
+ tokens,
+ });
+ if (action === 'strip') {
+ const strip = await runStripRelink(sessionId, sessionRow);
+ const next = afterStripAttempt(strip, { local: true, tokens });
+ if (next === 'done') {
+ deps.onRebuilt?.(sessionId);
+ deps.log.info('codex oversized history strip settled', { sessionId, strip, next });
+ return true;
+ }
+ if (next === 'none') {
+ if (strip === 'not-needed') deps.onRebuilt?.(sessionId);
+ return strip === 'not-needed';
+ }
+ action = next;
+ deps.log.warn('codex oversized strip did not finish; rebuilding', { sessionId, strip });
+ }
+ if (action !== 'rebuild') return false;
const handoffGeneration = deps.readPendingHandoffGeneration?.(sessionId);
const [source, rebuildMeta] = await Promise.all([
deps.listMessages(sessionId),
@@ -425,6 +502,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
await deps.drainPersistQueue();
const sessionRow = await deps.getSessionRow(sessionId);
if (!sessionRow || sessionRow.status === 'deleted') return false;
+ // SSH only; device-link 会话在被控桌面是本地 session,继续换窗。
if (sessionRow.remoteHostId) return false;
if (!sessionRow.sdkSessionId) return false;
const live = deps.getLiveSession(sessionId);
@@ -436,7 +514,7 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
liveUsage !== undefined &&
Number.isFinite(liveUsage.contextTokens) &&
liveUsage.contextTokens >= 0;
- const tokens = hasLiveTokens
+ const usedTokens = hasLiveTokens
? liveUsage.contextTokens
: typeof sessionRow.contextTokens === 'number'
? sessionRow.contextTokens
@@ -454,9 +532,38 @@ export function createContextOverflowRollover(deps: ContextOverflowRolloverDeps)
sessionRow.agentKind,
);
const window = effectiveContextWindow(sessionRow.model, reportedWindow, verified);
- const pressure = shouldRebuildForContextPressure(tokens, window);
+ const pressure = shouldRebuildForContextPressure(usedTokens, window);
const compactFailed = liveUsage?.needsRollover === true;
- if (!lastError && !pressure && !compactFailed) return false;
+ const tokenViolated =
+ isContextOverflowErrorData(lastError) ||
+ isPiPromptRpcTimeoutError(lastError) ||
+ pressure ||
+ compactFailed;
+ let action = decideCindyCompression({
+ local: true,
+ bytes: isOversizedHistoryErrorData(lastError) ? 'violated' : 'unknown',
+ tokens: tokenViolated ? 'violated' : 'unknown',
+ });
+ if (action === 'none') return false;
+ if (action === 'strip') {
+ const strip = await runStripRelink(sessionId, sessionRow);
+ const next = afterStripAttempt(strip, {
+ local: true,
+ tokens: tokenViolated ? 'violated' : 'unknown',
+ });
+ if (next === 'done') {
+ deps.onRebuilt?.(sessionId);
+ deps.log.info('codex oversized history stripped before send', { sessionId });
+ return true;
+ }
+ if (next === 'none') return false;
+ action = next;
+ deps.log.warn('codex oversized strip did not finish before send; rebuilding', {
+ sessionId,
+ strip,
+ });
+ }
+ if (action !== 'rebuild') return false;
let lastUser: OverflowSourceMessage | undefined;
let lastUserIndex = -1;
for (let i = source.length - 1; i >= 0; i -= 1) {
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 2e3b12f3ae..1925552b8d 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -182,7 +182,11 @@ import {
import * as imageCacheStore from '../imageCacheStore.js';
import * as cindyChatAttachments from '../cindy-media/chatAttachments.js';
import { materializeGeneratedImage } from '../cindy-media/generatedMedia.js';
-import { getDbClient, isDbClientNotReadyError } from '../localDb/client/current.js';
+import {
+ getCurrentDbClientSnapshot,
+ getDbClient,
+ isDbClientNotReadyError,
+} from '../localDb/client/current.js';
import { getMessagesForHistory } from '../localDb/chatHistoryReader.js';
import {
awaitAgentInputQueueSnapshotPersistence,
@@ -737,11 +741,13 @@ import {
import {
createContextOverflowRollover,
isContextOverflowErrorData,
+ isOversizedHistoryErrorData,
isPiPromptRpcTimeoutError,
lookupVerifiedContextWindow,
persistedUserContentToWireMessage,
shouldRebuildPiNativeSession,
} from './contextOverflowRollover.js';
+import { classifyCodexHistoryOversized } from '../maker-host/codex-local-sessions.js';
import { hydrateQueuedAgentReferences } from './agentInputReferences.js';
import { agentHandoffPending } from './agentHandoffPendingSingleton.js';
import { clearSealedCodexPlanState, readCodexPlanState } from '../localDb/codexPlanState.js';
@@ -938,6 +944,7 @@ import {
} from './agentSkillListIpcBoundary.js';
import {
captureDataOwnerBroadcastScope,
+ isDataOwnerBroadcastScopeCurrent,
tapWindowBroadcast,
} from '../device-link/broadcast-tap.js';
import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast.js';
@@ -4448,7 +4455,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
!session.remoteHostId &&
event.type === 'error' &&
isTerminalTurnErrorEvent(event) &&
- isContextOverflowErrorData(event.data);
+ (isContextOverflowErrorData(event.data) ||
+ isOversizedHistoryErrorData(event.data));
if (suppressOverflowBroadcast) {
overflowSuppressedBroadcasts.set(session.id, {
sessionId: session.id,
@@ -4580,7 +4588,8 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
!isRemoteAuthRetry &&
!isGatewayProxyTokenRecovery &&
!autoResumeSuppressesPersist &&
- isContextOverflowErrorData(attributedEvent.data)
+ (isContextOverflowErrorData(attributedEvent.data) ||
+ isOversizedHistoryErrorData(attributedEvent.data))
? (contextOverflowRolloverHolder?.claim(session.id) ?? 'idle')
: 'idle';
if (overflowClaim === 'claimed') {
@@ -11954,12 +11963,113 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
contextWindow: sessions.contextWindow,
model: sessions.model,
providerId: sessions.providerId,
+ workingDir: sessions.workingDir,
})
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
return row ?? null;
},
+ tryStripOversizedCodexHistory: async ({ sessionId, threadId, model, providerId, workingDir }) => {
+ const ownerScope = captureDataOwnerBroadcastScope();
+ const dbSnapshot = getCurrentDbClientSnapshot();
+ let committed = false;
+ try {
+ const classified = await classifyCodexHistoryOversized(threadId);
+ if (
+ !isDataOwnerBroadcastScopeCurrent(ownerScope) ||
+ !dbSnapshot ||
+ getCurrentDbClientSnapshot()?.clientEpoch !== dbSnapshot.clientEpoch
+ ) {
+ return 'stale';
+ }
+ if (classified === 'healthy') return 'not-needed';
+ if (classified !== 'oversized') return 'failed';
+ const live = getMaker().getSession(sessionId);
+ // busy ≠ failed:外层已守卫 turn-running;这里若仍撞上,中止而不是升级成 rebuild。
+ if (live?.isTurnRunning()) return 'busy';
+ if (live) await getMaker().closeSession(sessionId);
+ const forked = await getMaker().forkSdkSession('codex', {
+ sourceSdkSessionId: threadId,
+ model: model ?? undefined,
+ providerId,
+ upToMessageId: undefined,
+ workingDir: workingDir ?? undefined,
+ stripEncryptedReasoning: true,
+ remoteHostId: null,
+ });
+ if (!isDataOwnerBroadcastScopeCurrent(ownerScope)) return 'stale';
+ const currentDb = getCurrentDbClientSnapshot();
+ if (!dbSnapshot || !currentDb || currentDb.clientEpoch !== dbSnapshot.clientEpoch) {
+ return 'stale';
+ }
+ const now = Date.now();
+ const write = await dbSnapshot.client
+ .drizzle.update(sessions)
+ .set({ sdkSessionId: forked.newSdkSessionId, updatedAt: now })
+ .where(and(eq(sessions.id, sessionId), eq(sessions.sdkSessionId, threadId)))
+ .run();
+ if (write.changes === 0) return 'failed';
+ committed = true;
+ try {
+ broadcastSessionPatched(
+ sessionId,
+ {
+ sdkSessionId: forked.newSdkSessionId,
+ updatedAt: new Date(now).toISOString(),
+ },
+ ownerScope,
+ );
+ const cardOwnerCurrent =
+ isDataOwnerBroadcastScopeCurrent(ownerScope) &&
+ getCurrentDbClientSnapshot()?.clientEpoch === dbSnapshot.clientEpoch;
+ if (!cardOwnerCurrent) {
+ log.warn('codex oversized history card skipped: owner changed after relink', {
+ sessionId,
+ threadId,
+ toThreadId: forked.newSdkSessionId,
+ });
+ } else {
+ await createDbMessage(
+ sessionId,
+ {
+ clientId: `context-rebuild-card:${createId()}`,
+ role: 'assistant',
+ content: '',
+ agentKind: 'codex',
+ agentMeta: { contextRebuild: { reason: 'codex-history-strip' } } as AgentMeta,
+ },
+ {
+ broadcastOwnerScope: ownerScope,
+ shouldBroadcast: () =>
+ isDataOwnerBroadcastScopeCurrent(ownerScope) &&
+ getCurrentDbClientSnapshot()?.clientEpoch === dbSnapshot.clientEpoch,
+ },
+ );
+ }
+ } catch (postError) {
+ log.warn('codex oversized history relink post-commit failed', {
+ sessionId,
+ threadId,
+ toThreadId: forked.newSdkSessionId,
+ error: postError instanceof Error ? postError.message : String(postError),
+ });
+ }
+ log.info('codex oversized history relinked in place', {
+ sessionId,
+ fromThreadId: threadId,
+ toThreadId: forked.newSdkSessionId,
+ });
+ return 'recovered';
+ } catch (error) {
+ log.warn('codex oversized history relink failed', {
+ sessionId,
+ threadId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ return committed ? 'recovered' : 'failed';
+ }
+ },
getAutoCompactThresholdPct: () => readCompactionPct(),
resolveVerifiedWindow: (agentKind, modelId, providerId) => {
const catalog = getActiveCatalog();
diff --git a/apps/desktop/src/main/maker-orchestration/fork.ts b/apps/desktop/src/main/maker-orchestration/fork.ts
index 799783a352..9545ea03de 100644
--- a/apps/desktop/src/main/maker-orchestration/fork.ts
+++ b/apps/desktop/src/main/maker-orchestration/fork.ts
@@ -8,7 +8,7 @@
* 变成"孤儿 jsonl",可接受(数量极少,留给后续清理脚本)。
*/
-import { eq, and, lt, gt, asc, isNull, or, sql } from 'drizzle-orm';
+import { eq, and, lt, gt, asc, desc, isNull, or, sql } from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
import { CodexResumePreparationBlockedError } from '@cindy/maker-core';
import { CODEX_RESUME_NOT_READY_WIRE_MESSAGE } from '@cindy/maker-shared/agent-input-projection';
@@ -41,6 +41,8 @@ export type ForkErrorCode =
| 'CODEX_FORK_STATE_UNAVAILABLE'
| 'UNSUPPORTED_HISTORY';
+const STRIP_FORK_TITLE_PREFIX = '[Fork·已剥离]';
+
function forkError(code: ForkErrorCode, message: string): Error {
const err = new Error(message);
(err as { code?: string }).code = code;
@@ -870,6 +872,20 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promis
throw forkError('SOURCE_NEVER_RAN', '原会话尚未运行,无法 fork');
}
+ const childRows = await db
+ .select()
+ .from(sessions)
+ .where(
+ and(eq(sessions.parentSessionId, sourceSessionId), isNull(sessions.forkedAtMessageId)),
+ );
+ const reused = childRows.reduce<(typeof childRows)[number] | null>((latest, row) => {
+ if (row.status === 'deleted' || !String(row.title).startsWith(STRIP_FORK_TITLE_PREFIX)) {
+ return latest;
+ }
+ if (!latest || Number(row.createdAt ?? 0) > Number(latest.createdAt ?? 0)) return row;
+ return latest;
+ }, null);
+
const sourceMessages = await db
.select()
.from(messages)
@@ -885,6 +901,23 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promis
(max, message) => Math.max(max, Number(message.createdAt ?? 0)),
0,
);
+ if (reused) {
+ const [latestCopied] = await db
+ .select({ createdAt: messages.createdAt })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.sessionId, reused.id),
+ isNull(messages.rewindAt),
+ lt(messages.createdAt, Number(reused.createdAt ?? 0)),
+ ),
+ )
+ .orderBy(desc(messages.createdAt), desc(messageRowid))
+ .limit(1);
+ if (Number(latestCopied?.createdAt ?? 0) >= maxCreatedAt) {
+ return sessionToCamel({ ...reused, messageCount: 0 });
+ }
+ }
const copyBeforeCreatedAt = maxCreatedAt + 1;
await assertForkRangeDoesNotCrossAgentSwitch(
@@ -893,9 +926,9 @@ export async function forkSessionStripEncrypted(sourceSessionId: string): Promis
copyBeforeCreatedAt,
);
- const newTitle = source.title.startsWith('[Fork·已剥离]')
+ const newTitle = source.title.startsWith(STRIP_FORK_TITLE_PREFIX)
? source.title
- : `[Fork·已剥离] ${source.title}`;
+ : `${STRIP_FORK_TITLE_PREFIX} ${source.title}`;
const { newSdkSessionId, uuidMap } = await getMaker()
.forkSdkSession('codex', {
sourceSdkSessionId: source.sdkSessionId,
diff --git a/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx b/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx
index c501d6d7db..bb1a022d65 100644
--- a/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/errorBannerStreamInterrupt.test.tsx
@@ -85,6 +85,59 @@ describe('ErrorBanner — LiteLLM 流中断', () => {
});
});
+describe('ErrorBanner — Codex oversized history', () => {
+ it('hides Retry locally and does not show a strip-fork button', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: 'oversized',
+ errorReason: 'codex_history_oversized',
+ retryText: 'retry-token',
+ onRetry: vi.fn(),
+ onForkStripEncrypted: vi.fn(),
+ agentKind: 'codex',
+ }),
+ );
+ expect(screen.getByText('logic.errors.codexHistoryOversized')).toBeTruthy();
+ expect(screen.queryByTitle('chat.errorBanner.retryTitle')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.forkStripOversizedHistoryTitle')).toBeNull();
+ });
+
+ it('hides Retry on SSH sessions and does not offer a local strip-fork', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: 'oversized',
+ errorReason: 'codex_history_oversized',
+ retryText: 'retry-token',
+ onRetry: vi.fn(),
+ onForkStripEncrypted: vi.fn(),
+ agentKind: 'codex',
+ remoteHostId: 'ssh-1',
+ }),
+ );
+ expect(screen.getByText('logic.errors.codexHistoryOversizedRemote')).toBeTruthy();
+ expect(screen.queryByTitle('chat.errorBanner.retryTitle')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.forkStripOversizedHistoryTitle')).toBeNull();
+ });
+
+ it('hides Retry on device-link and does not show a strip-fork button', () => {
+ render(
+ createElement(ErrorBanner, {
+ error: 'oversized',
+ errorReason: 'codex_history_oversized',
+ retryText: 'retry-token',
+ onRetry: vi.fn(),
+ onForkStripEncrypted: vi.fn(),
+ agentKind: 'codex',
+ deviceLinkDeviceId: 'device-1',
+ }),
+ );
+ expect(screen.getByText('logic.errors.codexHistoryOversized')).toBeTruthy();
+ expect(screen.queryByText('logic.errors.codexHistoryOversizedRemote')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.retryTitle')).toBeNull();
+ expect(screen.queryByTitle('chat.errorBanner.forkStripOversizedHistoryTitle')).toBeNull();
+ });
+});
+
const XAI_REJECTED_RAW = `OpenAI API error (400): ${JSON.stringify({
message: `litellm.BadRequestError: XaiException - ${JSON.stringify({
error: { message: 'Upstream rejected the request!', type: 'invalid_request_error' },
diff --git a/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts b/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
index b35a827062..bf4f6a12b4 100644
--- a/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
+++ b/apps/desktop/src/renderer/__tests__/errorMessageRestore.test.ts
@@ -58,6 +58,15 @@ describe('mapServerMessages — persisted terminal error rows', () => {
);
});
+ it('maps oversized Codex history to its own copy, not the reconnect timeout', () => {
+ expect(ERROR_REASON_I18N_KEYS.codex_history_oversized).toBe(
+ 'logic.errors.codexHistoryOversized',
+ );
+ expect(ERROR_REASON_I18N_KEYS.codex_history_oversized).not.toBe(
+ ERROR_REASON_I18N_KEYS.codex_reconnect_stalled,
+ );
+ });
+
it('maps an event-loop crash to the generic terminal failure copy', () => {
expect(ERROR_REASON_I18N_KEYS.session_event_loop_crashed).toBe('logic.errors.turnFailed');
});
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index ab9c02900c..a40f89b760 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -180,6 +180,10 @@ export function ErrorBanner({
!isAnyRemoteSession &&
!silentEncryptedRetryEnabled &&
isInvalidEncryptedContentError(error);
+ const isOversizedHistoryError =
+ agentKind === 'codex' && errorReason === 'codex_history_oversized';
+ // SSH 不能自动剥图。本机 / device-link 由 main 侧协调器就地恢复,横幅不给按钮。
+ const isSshRemoteSession = Boolean(remoteHostId);
// Codex 401 auth-missing detection 分三层:
// - isCodexAuthMissing: codex session + 401/Missing bearer pattern。
// - isCodexRemoteAuthMissing: 远端 codex + 上面命中 → 显「同步登录态」按钮。
@@ -309,6 +313,7 @@ export function ErrorBanner({
isGatewayProxyTokenInvalid ||
isCodexThreadStale ||
showInvalidEncryptedContentRecovery ||
+ isOversizedHistoryError ||
(isCodexRemoteAuthMissing && !syncedSinceError) ||
openAiReconnectRequired ||
isCodexLocalOAuthAuthMissing;
@@ -335,6 +340,12 @@ export function ErrorBanner({
displayError = t('chat.errorBanner.codexThreadStale');
} else if (showInvalidEncryptedContentRecovery) {
displayError = t('chat.errorBanner.invalidEncryptedContent');
+ } else if (isOversizedHistoryError) {
+ displayError = t(
+ isSshRemoteSession
+ ? 'logic.errors.codexHistoryOversizedRemote'
+ : 'logic.errors.codexHistoryOversized',
+ );
} else if (isCodexRemoteAuthMissing) {
displayError = syncedSinceError
? t('chat.errorBanner.codexAuthSynced')
diff --git a/apps/desktop/src/renderer/components/chat/SystemCard.tsx b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
index 4292f1a2ae..284f8d11aa 100644
--- a/apps/desktop/src/renderer/components/chat/SystemCard.tsx
+++ b/apps/desktop/src/renderer/components/chat/SystemCard.tsx
@@ -1139,11 +1139,18 @@ function ContextRebuildCard({ data }: { data?: Record<string, unknown> }) {
const { t } = useTranslation();
const [expanded, setExpanded] = useState(false);
const handoff = typeof data?.handoff === 'string' ? data.handoff : '';
- const reason = data?.reason === 'pi-prompt-timeout' ? 'timeout' : 'overflow';
+ const reason =
+ data?.reason === 'pi-prompt-timeout'
+ ? 'timeout'
+ : data?.reason === 'codex-history-strip'
+ ? 'strip'
+ : 'overflow';
const label = t(
reason === 'timeout'
? 'chat.systemCard.contextRebuild.labelTimeout'
- : 'chat.systemCard.contextRebuild.labelOverflow',
+ : reason === 'strip'
+ ? 'chat.systemCard.contextRebuild.labelStrip'
+ : 'chat.systemCard.contextRebuild.labelOverflow',
);
return (
diff --git a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
index 7e701b0c5a..f81a245a50 100644
--- a/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
+++ b/apps/desktop/src/renderer/components/chat/errorReasonI18n.ts
@@ -22,6 +22,7 @@ export const ERROR_REASON_I18N_KEYS: Record<string, string> = {
'host-shell-command-blocked': 'logic.errors.hostShellCommandBlocked',
upstream_response_idle_timeout: 'logic.errors.upstreamResponseIdleTimeout',
codex_reconnect_stalled: 'logic.errors.upstreamResponseIdleTimeout',
+ codex_history_oversized: 'logic.errors.codexHistoryOversized',
// 压缩风暴分两条:有切模型证据的才点名切模型。共用一条会让没切过模型(或已切回)
// 的用户看到「请切回原模型」这种无从执行的指令 —— 这里的文案会覆盖 maker-core
// 合成的 message,所以 reason 选错等于用户唯一看到的那句话就是错的。
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index b894655822..8c71540a9a 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -7457,6 +7457,9 @@
"forkStripEncrypted": "Fork and strip",
"forkStripEncryptedRunning": "Forking…",
"forkStripEncryptedTitle": "Fork and strip into a new session",
+ "forkStripOversizedHistory": "Slim history and continue",
+ "forkStripOversizedHistoryRunning": "Forking…",
+ "forkStripOversizedHistoryTitle": "Fork into a new task after removing oversized inline images",
"codexSessionExpiredLogin": "Reconnect ChatGPT",
"codexSessionReconnected": "ChatGPT is reconnected. Click “Retry” to continue.",
"networkUnreachable": "Network error: the service is temporarily unreachable. Click \"Retry\" to try again.",
@@ -7822,6 +7825,7 @@
"contextRebuild": {
"labelOverflow": "Context reorganized, continuing",
"labelTimeout": "Last turn didn't respond; context reorganized to continue",
+ "labelStrip": "Oversized images removed, continuing",
"toggleHint": "View handoff context",
"handoffTitle": "Handoff — the context summary sent to the next stretch of this conversation (not part of the chat transcript; shown only here)",
"handoffTitleEnglishSource": "Handoff — the context summary sent to the next stretch of this conversation (not part of the chat transcript; shown only here)"
@@ -10370,6 +10374,8 @@
"codexAutoReviewUnavailable": "Auto-review is temporarily unavailable. The current action was blocked and permissions switched to Default. Retry the request; Cindy will ask when needed.",
"hostShellCommandBlocked": "Cindy blocked a shell command that would bypass the embedded iOS Simulator. Use the iOS Simulator tool for device control, app launches, interaction, screenshots, and diagnostics.",
"upstreamResponseIdleTimeout": "The model stopped responding for a long time, so this turn was interrupted to avoid hanging forever. Completed tool calls are preserved — send the next message to continue.",
+ "codexHistoryOversized": "This task’s history includes oversized images, so remote compaction cannot finish. Cindy will omit those images and continue in this task.",
+ "codexHistoryOversizedRemote": "This task’s history includes oversized images, so remote compaction cannot finish. Open the task on the machine running Codex and send again; Cindy will omit those images there.",
"codexCompactionNotConverging": "Codex kept compacting the context without making progress, so this turn was interrupted to stop the loop. What's taking up the space usually isn't the conversation — the system prompt and tool definitions can't be compacted away. Start a new task to continue.",
"codexCompactionNotConvergingModelSwitch": "Codex kept compacting the context without making progress, so this turn was interrupted to stop the loop. This task switched model midway, and Codex still evaluates the context limit against the previous model. Switch back to that model to continue, or start a new task.",
"turnNoEventTimeout": "This turn showed no activity for a long time (model, tools and background processes were all silent), so it was interrupted to avoid hanging forever. Send the next message to continue."
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index b893991c26..ca30ffe0e9 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -7454,6 +7454,9 @@
"forkStripEncrypted": "Fork して切り離す",
"forkStripEncryptedRunning": "Fork 中…",
"forkStripEncryptedTitle": "暗号化推論を除いた新しいセッションを Fork で作成",
+ "forkStripOversizedHistory": "履歴を縮小して続ける",
+ "forkStripOversizedHistoryRunning": "Fork 中…",
+ "forkStripOversizedHistoryTitle": "過大なインライン画像を除いた新しいタスクへ Fork",
"codexSessionExpiredLogin": "ChatGPT に再接続",
"codexSessionReconnected": "ChatGPT に再接続しました。「再試行」をクリックして続行してください。",
"networkUnreachable": "ネットワークエラー:サービスに一時的に接続できません。「再試行」を押してください。",
@@ -7819,6 +7822,7 @@
"contextRebuild": {
"labelOverflow": "コンテキストを整理して続行しました",
"labelTimeout": "直前の応答がなかったため、整理して続行しました",
+ "labelStrip": "大きな画像を除いて続行しました",
"toggleHint": "引き継ぎ内容を表示",
"handoffTitle": "引き継ぎ内容——整理後にこの会話の続きへ渡したコンテキスト要約(チャット履歴には含まれず、ここでのみ表示)",
"handoffTitleEnglishSource": "引き継ぎ内容——整理後にこの会話の続きへ渡したコンテキスト要約。原文は英語(チャット履歴には含まれず、ここでのみ表示)"
@@ -10357,6 +10361,8 @@
"codexAutoReviewUnavailable": "自動レビューは一時的に利用できません。現在の操作をブロックし、デフォルト権限に切り替えました。もう一度実行してください。必要な場合は確認します。",
"hostShellCommandBlocked": "Cindy は内蔵 iOS シミュレータを迂回するシェルコマンドをブロックしました。デバイスの操作、アプリの起動、画面操作、スクリーンショット、診断には iOS シミュレータツールを使用してください。",
"upstreamResponseIdleTimeout": "モデルから長時間応答がなかったため、無限待機を避けるためこのターンを自動中断しました。完了したツール呼び出しは保持されています。次のメッセージを送信して続行できます。",
+ "codexHistoryOversized": "履歴に過大な画像があり、リモート圧縮を完了できません。Cindy がそれらの画像を省略し、このタスクのまま続けます。",
+ "codexHistoryOversizedRemote": "履歴に過大な画像があり、リモート圧縮を完了できません。Codex を実行している端末でこのタスクを開いて再送信してください。Cindy が画像を省略して続けます。",
"codexCompactionNotConverging": "Codex がコンテキストの圧縮を繰り返しても効果がないため、無限ループを避けるためこのターンを自動中断しました。容量を占めているのは会話ではなく、圧縮では削れないシステムプロンプトとツール定義であることがほとんどです。新しいセッションを開始してください。",
"codexCompactionNotConvergingModelSwitch": "Codex がコンテキストの圧縮を繰り返しても効果がないため、無限ループを避けるためこのターンを自動中断しました。このセッションは途中でモデルを切り替えており、Codex は切り替え前のモデルの上限でコンテキストを判定し続けています。元のモデルに戻すか、新しいセッションを開始してください。",
"turnNoEventTimeout": "このターンは長時間まったく進展がなかったため(モデル・ツール・バックグラウンド処理のすべてが無反応)、無限待機を避けるため自動中断しました。次のメッセージを送信して続行できます。"
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 9ea66f8116..c631a8ed85 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -7454,6 +7454,9 @@
"forkStripEncrypted": "Fork 및 분리",
"forkStripEncryptedRunning": "Fork 중…",
"forkStripEncryptedTitle": "암호화 추론을 제거한 새 세션으로 Fork",
+ "forkStripOversizedHistory": "기록을 줄인 뒤 계속",
+ "forkStripOversizedHistoryRunning": "Fork 중…",
+ "forkStripOversizedHistoryTitle": "과대한 인라인 이미지를 제거한 새 작업으로 Fork",
"codexSessionExpiredLogin": "ChatGPT 다시 연결",
"codexSessionReconnected": "ChatGPT가 다시 연결되었습니다. ‘다시 시도’를 눌러 계속하세요.",
"networkUnreachable": "네트워크 오류: 서비스에 일시적으로 연결할 수 없습니다. ‘다시 시도’를 눌러 주세요.",
@@ -7819,6 +7822,7 @@
"contextRebuild": {
"labelOverflow": "컨텍스트를 정리하고 계속합니다",
"labelTimeout": "직전 응답이 없어 정리한 뒤 계속합니다",
+ "labelStrip": "큰 이미지를 빼고 계속합니다",
"toggleHint": "인계 내용 보기",
"handoffTitle": "인계 내용——정리 후 이 대화의 이어서 넘긴 컨텍스트 요약(대화 기록에 포함되지 않으며 여기에서만 표시)",
"handoffTitleEnglishSource": "인계 내용——정리 후 이 대화의 이어서 넘긴 컨텍스트 요약. 원문은 영어(대화 기록에 포함되지 않으며 여기에서만 표시)"
@@ -10357,6 +10361,8 @@
"codexAutoReviewUnavailable": "자동 리뷰를 일시적으로 사용할 수 없습니다. 현재 작업을 차단하고 기본 권한으로 전환했습니다. 다시 시도하세요. 필요한 경우 확인을 요청합니다.",
"hostShellCommandBlocked": "Cindy가 내장 iOS 시뮬레이터를 우회하는 셸 명령을 차단했습니다. 기기 제어, 앱 실행, 화면 조작, 스크린샷, 진단에는 iOS 시뮬레이터 도구를 사용하세요.",
"upstreamResponseIdleTimeout": "모델이 오랫동안 응답하지 않아 무한 대기를 막기 위해 이번 턴을 자동으로 중단했습니다. 완료된 도구 호출은 유지되며, 다음 메시지를 보내 계속할 수 있습니다.",
+ "codexHistoryOversized": "기록에 과대한 이미지가 있어 원격 압축을 끝낼 수 없습니다. Cindy가 해당 이미지를 생략하고 이 작업에서 계속합니다.",
+ "codexHistoryOversizedRemote": "기록에 과대한 이미지가 있어 원격 압축을 끝낼 수 없습니다. Codex를 실행 중인 기기에서 이 작업을 연 뒤 다시 보내세요. Cindy가 이미지를 생략하고 계속합니다.",
"codexCompactionNotConverging": "Codex가 컨텍스트를 반복해서 압축했지만 줄어들지 않아, 무한 루프를 막기 위해 이번 턴을 자동으로 중단했습니다. 공간을 차지하는 것은 대화가 아니라 압축으로 줄일 수 없는 시스템 프롬프트와 도구 정의인 경우가 대부분입니다. 새 세션을 시작하세요.",
"codexCompactionNotConvergingModelSwitch": "Codex가 컨텍스트를 반복해서 압축했지만 줄어들지 않아, 무한 루프를 막기 위해 이번 턴을 자동으로 중단했습니다. 이 세션은 도중에 모델을 변경했고, Codex는 변경 전 모델의 컨텍스트 한도로 계속 판단하고 있습니다. 원래 모델로 되돌리거나 새 세션을 시작하세요.",
"turnNoEventTimeout": "이번 턴에서 오랫동안 아무런 진행이 없어(모델·도구·백그라운드 프로세스 모두 무응답) 무한 대기를 막기 위해 자동으로 중단했습니다. 다음 메시지를 보내 계속할 수 있습니다."
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 7c19a32a7c..2d41bb025b 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -7446,6 +7446,9 @@
"forkStripEncrypted": "Fork 并剥离",
"forkStripEncryptedRunning": "Fork 中…",
"forkStripEncryptedTitle": "Fork 并剥离出新任务(去掉加密推理内容)",
+ "forkStripOversizedHistory": "瘦身后继续",
+ "forkStripOversizedHistoryRunning": "Fork 中…",
+ "forkStripOversizedHistoryTitle": "去掉过大的历史图片后 Fork 成新任务",
"codexSessionExpiredLogin": "重新连接 ChatGPT",
"codexSessionReconnected": "ChatGPT 账号已重新连接。点击「重试」继续。",
"networkUnreachable": "网络异常,服务暂时不可达,可点击「重试」。",
@@ -7811,6 +7814,7 @@
"contextRebuild": {
"labelOverflow": "已整理上下文并继续",
"labelTimeout": "上一轮没有响应,已整理后继续",
+ "labelStrip": "已去掉过大图片并继续",
"toggleHint": "查看交接内容",
"handoffTitle": "交接内容——整理后发送给后续对话的上下文摘要(不计入对话记录,仅在此展示)",
"handoffTitleEnglishSource": "交接内容——整理后发送给后续对话的上下文摘要,原文为英文(不计入对话记录,仅在此展示)"
@@ -10349,6 +10353,8 @@
"codexAutoReviewUnavailable": "自动审批暂时不可用,当前操作已阻止并切换为默认权限。请重试,需要时会询问你。",
"hostShellCommandBlocked": "Cindy 已阻止会绕过内嵌模拟器的 Shell 命令。请改用模拟器工具控制设备、启动应用、操作界面、截图和诊断。",
"upstreamResponseIdleTimeout": "模型长时间没有任何响应,本轮已自动中断以免无限等待。已完成的工具调用都保留,可以直接发下一条消息继续。",
+ "codexHistoryOversized": "这段历史里有过大的图片,远端压缩发不出去。Cindy 会自动略去这些图片,并在当前任务里继续。",
+ "codexHistoryOversizedRemote": "这段历史里有过大的图片,远端压缩发不出去。请在运行 Codex 的那台电脑上打开任务后再发送,Cindy 会自动略去这些图片并继续。",
"codexCompactionNotConverging": "Codex 反复压缩上下文却压不动,本轮已自动中断以免无限循环。压不动的部分通常不在对话里——system prompt 与工具定义占掉的空间压缩清不掉。新开一个任务可以继续。",
"codexCompactionNotConvergingModelSwitch": "Codex 反复压缩上下文却压不动,本轮已自动中断以免无限循环。本任务中途切换过模型,而 Codex 仍按切换前那个模型的上下文上限来判断。切回原模型可以继续,或者新开一个任务。",
"turnNoEventTimeout": "本轮长时间没有任何进展(模型、工具与后台进程都没有动静),已自动中断以免无限等待。可以直接发下一条消息继续。"
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index b2e11e99d7..a653f8a63e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -7445,6 +7445,9 @@
"forkStripEncrypted": "Fork 並剝離",
"forkStripEncryptedRunning": "Fork 中…",
"forkStripEncryptedTitle": "Fork 並剝離出新任務(去掉加密推理內容)",
+ "forkStripOversizedHistory": "瘦身後繼續",
+ "forkStripOversizedHistoryRunning": "Fork 中…",
+ "forkStripOversizedHistoryTitle": "去掉過大的歷史圖片後 Fork 成新任務",
"codexSessionExpiredLogin": "重新連線 ChatGPT",
"codexSessionReconnected": "ChatGPT 帳號已重新連線。點選「重試」繼續。",
"networkUnreachable": "網路異常,服務暫時不可達,可點選「重試」。",
@@ -7810,6 +7813,7 @@
"contextRebuild": {
"labelOverflow": "已整理上下文並繼續",
"labelTimeout": "上一輪沒有回應,已整理後繼續",
+ "labelStrip": "已去掉過大圖片並繼續",
"toggleHint": "檢視交接內容",
"handoffTitle": "交接內容——整理後傳送給後續對話的上下文摘要(不計入對話記錄,僅在此展示)",
"handoffTitleEnglishSource": "交接內容——整理後傳送給後續對話的上下文摘要,原文為英文(不計入對話記錄,僅在此展示)"
@@ -10349,6 +10353,8 @@
"codexAutoReviewUnavailable": "自動審批暫時不可用,當前操作已阻止並切換為預設權限。請重試,需要時會詢問你。",
"hostShellCommandBlocked": "Cindy 已阻止會繞過內嵌模擬器的 Shell 命令。請改用模擬器工具控制裝置、啟動 App、操作介面、截圖和診斷。",
"upstreamResponseIdleTimeout": "模型長時間沒有任何響應,本輪已自動中斷以免無限等待。已完成的工具呼叫都保留,可以直接發下一條訊息繼續。",
+ "codexHistoryOversized": "這段歷史裡有過大的圖片,遠端壓縮送不出去。Cindy 會自動略去這些圖片,並在目前任務裡繼續。",
+ "codexHistoryOversizedRemote": "這段歷史裡有過大的圖片,遠端壓縮送不出去。請在執行 Codex 的那台電腦上打開任務後再傳送,Cindy 會自動略去這些圖片並繼續。",
"codexCompactionNotConverging": "Codex 反覆壓縮上下文卻壓不動,本輪已自動中斷以免無限迴圈。壓不動的部分通常不在對話裡——system prompt 與工具定義佔掉的空間壓縮清不掉。新開一個任務可以繼續。",
"codexCompactionNotConvergingModelSwitch": "Codex 反覆壓縮上下文卻壓不動,本輪已自動中斷以免無限迴圈。本任務中途切換過模型,而 Codex 仍按切換前那個模型的上下文上限來判斷。切回原模型可以繼續,或者新開一個任務。",
"turnNoEventTimeout": "本輪長時間沒有任何進展(模型、工具與後臺處理程序都沒有動靜),已自動中斷以免無限等待。可以直接發下一條訊息繼續。"
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 7ae6971d8e..b5c821e652 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -40,6 +40,21 @@ timeout 不得触发自动换窗或 replay。Codex 当前没有与 Claude `AutoC
自动 `/compact` 注入路径;未来若增加,仍须遵守同一评估和交接边界。手动压缩入口不受此规则影响,
手动 compact 失败不得锁存换窗。
+Cindy 保底压缩是**一套**流程,不是剥图 / 换窗两套功能。装得进当前约束就不动;
+字节预算破了(可剥的超大内联图)就剥图;token 预算破了或剥图失败,就交接重建。
+决定函数见 `cindyContextCompression.ts`。字节预算目前只有 Codex 能测量。工具输出
+不另开一档:官方 compact 会先清旧工具结果;官方失败后交接不带 tool_result 正文。
+可剥图不足一半的混合大尾巴有意不救。打开会话不触发;只在终态错误或下次发送时
+由 main 侧 claim。SSH 不承诺。不确定 fail closed。救援路径不得依赖额外模型调用。
+切模型预检的数学仍在 `assessModelSwitchContext`;确认切小窗后动作端应以
+`tokens='violated'` 调用同一决定走 rebuild,不再走独立 handoff(本版尚未并入)。
+token 破了只认:终态超限、占用 ≥ 100%、官方 compact 确定性失败;普通 timeout 不算。
+
+Codex 的 120 秒 reconnect watchdog 只是 fallback 收口,不是根因诊断。stderr 仍只作诊断日志,
+不得用 `remote compaction v2` 文案驱动恢复动作。普通 timeout、纯文本大历史和网络失败
+不得进入这套压缩,也不得进入自动续跑死循环。
+
+
> **适用范围与增量原则**:Agent 能力归属(下节 1)与代码优先确定性(下节 2)按增量
> 适用——约束新增和正在修改的代码,不要求为统一形式专项重构存量。但**核心指标不变量
> (下节 3)与 system prompt 改动门禁(下节 4)对所有触及相关路径的改动都生效,不分
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index c481ca3eee..6f6d4eaa1c 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -20373,6 +20373,43 @@ describe('CodexAgent.forkSdkSession', () => {
}
});
+ it('rewrites oversized tool-output images in the stripped fork copy', async () => {
+ const agent = new CodexAgent(createDeps());
+ let copied = '';
+ installFakeHost(agent, async (method, params) => {
+ if (method !== Method.ThreadFork) return undefined;
+ const forkPath = (params as { path?: string }).path;
+ if (forkPath) copied = await fs.readFile(forkPath, 'utf8');
+ return undefined;
+ });
+ const codexHome = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-codex-home-'));
+ try {
+ (agent as unknown as { codexHome: string }).codexHome = codexHome;
+ const sessionsDir = path.join(codexHome, 'sessions', '2026', '08', '26');
+ await fs.mkdir(sessionsDir, { recursive: true });
+ const sourceRollout = path.join(sessionsDir, 'rollout-2026-08-26-source-thread-id.jsonl');
+ const huge = `data:image/png;base64,${'A'.repeat(64 * 1024)}`;
+ await fs.writeFile(
+ sourceRollout,
+ `${[
+ JSON.stringify({ payload: { type: 'message', role: 'user' } }),
+ JSON.stringify({ payload: { type: 'custom_tool_call_output', call_id: 'shot', output: huge } }),
+ ].join('\n')}\n`,
+ 'utf8',
+ );
+ await agent.forkSdkSession({
+ sourceSdkSessionId: 'source-thread-id',
+ upToMessageId: undefined,
+ stripEncryptedReasoning: true,
+ });
+ expect(copied).toContain('"shot"');
+ expect(copied).toContain('cindy-omitted-inline-image');
+ expect(copied).not.toContain(';base64,');
+ } finally {
+ await fs.rm(codexHome, { recursive: true, force: true });
+ }
+ });
+
it('uses the rollout path returned by imported-thread preparation when stripping', async () => {
const externalHome = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-codex-external-'));
const sourceRollout = path.join(externalHome, 'rollout-imported-thread.jsonl');
@@ -22479,6 +22516,44 @@ describe('CodexAgent turn lifecycle', () => {
await handle.close();
});
+ it('preserves structured Codex error info when failed turn only reports it on turn/completed', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-failed-with-structured-detail',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const subscribeCalls = host.subscribeThread.mock.calls as unknown as Array<[string, ThreadEventHandlers]>;
+ const handlers = subscribeCalls[0]?.[1];
+ expect(handlers).toBeDefined();
+ const iterator = handle.events()[Symbol.asyncIterator]();
+
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: {
+ id: 'turn-1',
+ status: 'failed',
+ error: {
+ message: 'context window exceeded',
+ codexErrorInfo: 'contextWindowExceeded',
+ },
+ },
+ });
+
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'error',
+ data: {
+ message: 'context window exceeded',
+ codexErrorInfo: 'contextWindowExceeded',
+ reason: 'context-overflow',
+ isTerminal: true,
+ },
+ });
+ expect(await nextEvent(iterator)).toMatchObject({ type: 'done' });
+ await handle.close();
+ });
it('does NOT emit a fallback error for an interrupted turn without error message', async () => {
// interrupted = 用户主动停止, 不算失败, 不该弹"执行失败"。
const agent = new CodexAgent(createDeps());
@@ -26151,6 +26226,87 @@ describe('CodexAgent reconnect-stall watchdog', () => {
}
});
+ it('classifies reconnect stall as oversized only when live-tail images are strip-worthy', async () => {
+ 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);
+ const find = vi.spyOn(proto, 'findRolloutPath').mockResolvedValue('/tmp/mock-oversized.jsonl');
+ const measure = vi.spyOn(await import('./rollout-sanitize.js'), 'measureRolloutLiveTailStats')
+ .mockResolvedValue({
+ tailBytes: 20 * 1024 * 1024,
+ projectedTailBytes: 800_000,
+ strippedBytes: 19 * 1024 * 1024,
+ rewrittenLines: 4,
+ unsafeLines: 0,
+ scannedBytes: 20 * 1024 * 1024,
+ });
+ try {
+ const { handle, handlers, seen } = await startReconnectTurn(agent, 'session-reconnect-oversized');
+ emitReconnect(handlers, 1);
+ await vi.advanceTimersByTimeAsync(RECONNECT_STALL_MS + 1);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(seen).toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({
+ reason: 'codex_history_oversized',
+ isTerminal: true,
+ }),
+ }));
+ expect(seen.filter((event) => event.type === 'error' && (event.data as { reason?: string }).reason === 'codex_history_oversized')).toHaveLength(1);
+ await handle.close();
+ } finally {
+ localHome.mockRestore();
+ find.mockRestore();
+ measure.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps reconnect-stalled when live tail is large but not image-heavy', async () => {
+ 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);
+ const find = vi.spyOn(proto, 'findRolloutPath').mockResolvedValue('/tmp/mock-text-only.jsonl');
+ const measure = vi.spyOn(await import('./rollout-sanitize.js'), 'measureRolloutLiveTailStats')
+ .mockResolvedValue({
+ tailBytes: 20 * 1024 * 1024,
+ projectedTailBytes: 20 * 1024 * 1024,
+ strippedBytes: 0,
+ rewrittenLines: 0,
+ unsafeLines: 0,
+ scannedBytes: 20 * 1024 * 1024,
+ });
+ try {
+ const { handle, handlers, seen } = await startReconnectTurn(agent, 'session-reconnect-text-only');
+ emitReconnect(handlers, 1);
+ await vi.advanceTimersByTimeAsync(RECONNECT_STALL_MS + 1);
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(seen).toContainEqual(expect.objectContaining({
+ type: 'error',
+ data: expect.objectContaining({ reason: 'codex_reconnect_stalled' }),
+ }));
+ expect(seen).not.toContainEqual(expect.objectContaining({
+ data: expect.objectContaining({ reason: 'codex_history_oversized' }),
+ }));
+ await handle.close();
+ } finally {
+ localHome.mockRestore();
+ find.mockRestore();
+ measure.mockRestore();
+ vi.useRealTimers();
+ }
+ });
+
it('graceful stop interrupt 被拒绝后重新武装同一 turn 的 reconnect watchdog', async () => {
vi.useFakeTimers();
try {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index e9b1cd6c0d..96df6baf13 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -129,6 +129,7 @@ import {
import {
newCodexRuntimeState,
isAuthRelatedErrorMessage,
+ classifyCodexError,
translateErrorNotification,
translateItemNotification,
beginCodexGenerationTurn,
@@ -162,6 +163,12 @@ import {
CompactionStormTracker,
buildCompactionStormTerminalError,
} from './compaction-storm.js';
+import {
+ CODEX_HISTORY_OVERSIZED_REASON,
+ isOversizedLiveTailStats,
+ measureRolloutLiveTailStats,
+ sanitizeCodexForkRolloutFile,
+} from './rollout-sanitize.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';
@@ -361,36 +368,6 @@ function isRemoteLikePath(p: string): boolean {
return p.startsWith('/') && process.platform === 'win32';
}
-function isReasoningPayload(payload: unknown): boolean {
- return Boolean(
- payload &&
- typeof payload === 'object' &&
- !Array.isArray(payload) &&
- (payload as Record<string, unknown>).type === 'reasoning',
- );
-}
-
-function isImageGenerationPayloadWithoutId(payload: unknown): boolean {
- if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return false;
- const record = payload as Record<string, unknown>;
- const type = record.type;
- if (typeof type !== 'string') return false;
- if (!type.startsWith('image_generation') && !type.startsWith('imageGeneration')) return false;
- const id = record.id;
- return typeof id !== 'string' || id.trim().length === 0;
-}
-
-function hasUnsafeForkRolloutPayload(line: string): boolean {
- try {
- const parsed: unknown = JSON.parse(line);
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false;
- const payload = (parsed as Record<string, unknown>).payload;
- return isReasoningPayload(payload) || isImageGenerationPayloadWithoutId(payload);
- } catch {
- return false;
- }
-}
-
function buildCodexDeveloperInstructions(parts: {
makerMemoryRules?: string;
contactsRules?: string;
@@ -2965,6 +2942,7 @@ export class CodexAgent extends BaseAgent {
reviewMode,
mcpProvidersCount: this.deps.mcpProviders?.length ?? 0,
});
+ const stallAgent = this;
// ── Maker Memory: 启动时预拉 MEMORY.md 索引 + 写入规范段 ────────────────
// thread/start 仍把 developerInstructions 写入新 thread; thread/resume 在普通非 proxy
@@ -6753,17 +6731,59 @@ export class CodexAgent extends BaseAgent {
clearReconnectStall();
return;
}
- onUpstreamIdleTimeout({
- reason: 'codex_reconnect_stalled',
- timeoutMs: CODEX_RECONNECT_STALL_TIMEOUT_MS,
- ignorePendingTools: true,
- allowPendingTurnStart: !isTurnInFlight,
- logLabel: 'codex reconnect watchdog tripped — interrupting stalled turn',
- message:
- `Codex app-server has been reconnecting for ${Math.round(CODEX_RECONNECT_STALL_TIMEOUT_MS / 1000)}s ` +
- 'without making progress; the turn was interrupted automatically. ' +
- 'You can send the next message to continue.',
- });
+ const stalledThreadId = threadId;
+ const stalledTurnGeneration = reconnectStallTurnGeneration;
+ const allowPendingTurnStart = !isTurnInFlight;
+ const stalledMessage =
+ `Codex app-server has been reconnecting for ${Math.round(CODEX_RECONNECT_STALL_TIMEOUT_MS / 1000)}s ` +
+ 'without making progress; the turn was interrupted automatically. ' +
+ 'You can send the next message to continue.';
+ const emitStalled = (reason: string, message: string): void => {
+ if (
+ !isReconnectStallCurrent() ||
+ threadId !== stalledThreadId ||
+ reconnectStallTurnGeneration !== stalledTurnGeneration
+ ) return;
+ onUpstreamIdleTimeout({
+ reason,
+ timeoutMs: CODEX_RECONNECT_STALL_TIMEOUT_MS,
+ ignorePendingTools: true,
+ allowPendingTurnStart,
+ logLabel: 'codex reconnect watchdog tripped — interrupting stalled turn',
+ message,
+ });
+ };
+ if (!stalledThreadId || opts.remoteHostId || !stallAgent.hasLocalCodexHome()) {
+ emitStalled('codex_reconnect_stalled', stalledMessage);
+ return;
+ }
+ void (async () => {
+ let reason = 'codex_reconnect_stalled';
+ let message = stalledMessage;
+ try {
+ const rolloutPath = await stallAgent.findRolloutPath(stalledThreadId);
+ const stats = await measureRolloutLiveTailStats(rolloutPath);
+ if (isOversizedLiveTailStats(stats)) {
+ reason = CODEX_HISTORY_OVERSIZED_REASON;
+ message =
+ 'Codex remote compaction cannot finish because this thread\'s live history is oversized. ' +
+ 'Fork and strip oversized inline images to continue.';
+ log.warn('codex reconnect stall classified as oversized live history', {
+ threadId: stalledThreadId,
+ tailBytes: stats.tailBytes,
+ projectedTailBytes: stats.projectedTailBytes,
+ strippedBytes: stats.strippedBytes,
+ thresholdBytes: stats.tailBytes,
+ });
+ }
+ } catch (error) {
+ log.debug('codex live-tail measure skipped', {
+ threadId: stalledThreadId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ }
+ emitStalled(reason, message);
+ })();
}, slice);
(reconnectStallTimer as unknown as { unref?: () => void }).unref?.();
}
@@ -6842,7 +6862,7 @@ export class CodexAgent extends BaseAgent {
armReconnectStall();
return;
}
- if (reconnectStallTimer && isReconnectRecoveryEvent(event)) {
+ if (isReconnectRecoveryEvent(event)) {
clearReconnectStall();
}
}
@@ -6870,7 +6890,9 @@ export class CodexAgent extends BaseAgent {
const msSinceLast =
upstreamIdleLastEventAt > 0 ? Date.now() - upstreamIdleLastEventAt : null;
const turnId = currentTurnId ?? pendingTurnId;
- const deferTurnCleanupUntilInterrupt = opts?.reason === 'codex_reconnect_stalled';
+ const deferTurnCleanupUntilInterrupt =
+ opts?.reason === 'codex_reconnect_stalled' ||
+ opts?.reason === CODEX_HISTORY_OVERSIZED_REASON;
if (deferTurnCleanupUntilInterrupt && !pendingTurnId && turnId) {
// Keep Session.isTurnRunning() true until the interrupt ACK (or the
// close/retire fallback) settles. Desktop may already have received
@@ -9049,9 +9071,13 @@ export class CodexAgent extends BaseAgent {
// Already reported above as the authoritative terminal outcome; the
// interrupt-derived message must not overwrite it.
} else if (turn.error?.message) {
+ const classified = classifyCodexError(turn.error);
eventQueue.push({
type: 'error',
- data: { message: turn.error.message, isTerminal: true },
+ data: {
+ ...classified.data,
+ isTerminal: true,
+ },
source: 'codex',
});
} else if (turn.status === 'failed') {
@@ -12428,6 +12454,10 @@ export class CodexAgent extends BaseAgent {
* opts.upToMessageId 在 Codex 这里被忽略。uuidMap 返回空 — Codex agentMeta 不存
* message uuid, maker 那边也找不到东西可 remap, 不会 break。
*/
+ private hasLocalCodexHome(): boolean {
+ return Boolean(this.codexHome) && !isRemoteLikePath(this.codexHome ?? '');
+ }
+
private async findRolloutPath(threadId: string, preferredPath?: string): Promise<string> {
if (preferredPath && !isRemoteLikePath(preferredPath)) {
try {
@@ -12485,14 +12515,14 @@ export class CodexAgent extends BaseAgent {
private async createSafeForkRolloutCopy(threadId: string, preferredPath?: string): Promise<string> {
const sourcePath = await this.findRolloutPath(threadId, preferredPath);
const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'xdt-codex-fork-'));
- const copyPath = path.join(tempDir, path.basename(sourcePath));
- const text = await fs.readFile(sourcePath, 'utf8');
- const out = text
- .split(/\r?\n/)
- .filter((line) => !line.trim() || !hasUnsafeForkRolloutPayload(line))
- .join('\n');
- await fs.writeFile(copyPath, out.endsWith('\n') || out.length === 0 ? out : `${out}\n`, 'utf8');
- return copyPath;
+ try {
+ const copyPath = path.join(tempDir, path.basename(sourcePath));
+ await sanitizeCodexForkRolloutFile(sourcePath, copyPath);
+ return copyPath;
+ } catch (error) {
+ await fs.rm(tempDir, { recursive: true, force: true }).catch(() => undefined);
+ throw error;
+ }
}
async forkSdkSession(opts: ForkSdkSessionOptions): Promise<ForkSdkSessionResult> {
diff --git a/packages/maker-core/src/agents/codex/rollout-sanitize.test.ts b/packages/maker-core/src/agents/codex/rollout-sanitize.test.ts
new file mode 100644
index 0000000000..63d51ffee4
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/rollout-sanitize.test.ts
@@ -0,0 +1,241 @@
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ CODEX_INLINE_IMAGE_STRIP_MIN_CHARS,
+ CODEX_LIVE_TAIL_OVERSIZED_BYTES,
+ CodexRolloutScanLimitError,
+ hasUnsafeForkRolloutPayload,
+ isOversizedLiveTailStats,
+ measureRolloutLiveTailBytesFromText,
+ measureRolloutLiveTailStats,
+ measureRolloutLiveTailStatsFromText,
+ rewriteOversizedToolOutputImages,
+ sanitizeCodexForkRollout,
+ sanitizeCodexForkRolloutFile,
+} from './rollout-sanitize.js';
+
+function bigPngDataUri(chars = CODEX_INLINE_IMAGE_STRIP_MIN_CHARS): string {
+ return `data:image/png;base64,${'A'.repeat(chars)}`;
+}
+
+function compactBoundary(): string {
+ return JSON.stringify({ type: 'compacted', payload: { replacement_history: [] } });
+}
+
+describe('hasUnsafeForkRolloutPayload', () => {
+ it('drops reasoning and image generation without id', () => {
+ expect(
+ hasUnsafeForkRolloutPayload(JSON.stringify({ payload: { type: 'reasoning', encrypted_content: 'gAAA' } })),
+ ).toBe(true);
+ expect(
+ hasUnsafeForkRolloutPayload(
+ JSON.stringify({ payload: { type: 'image_generation_end', call_id: 'ig_1' } }),
+ ),
+ ).toBe(true);
+ expect(
+ hasUnsafeForkRolloutPayload(
+ JSON.stringify({ payload: { type: 'image_generation_call', id: 'ig_1' } }),
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('rewriteOversizedToolOutputImages', () => {
+ it.each([
+ 'custom_tool_call_output',
+ 'function_call_output',
+ 'customToolCallOutput',
+ 'functionCallOutput',
+ ])('replaces oversized data URIs in %s without deleting the line', (type) => {
+ const line = JSON.stringify({ payload: { type, call_id: 'c1', output: bigPngDataUri() } });
+ const out = rewriteOversizedToolOutputImages(line);
+ expect(out).toContain(`"${type}"`);
+ expect(out).toContain('"c1"');
+ expect(out).not.toContain(';base64,');
+ expect(out).toContain('cindy-omitted-inline-image');
+ expect(() => JSON.parse(out)).not.toThrow();
+ });
+
+ it('leaves small images and non-tool payloads alone', () => {
+ const small = JSON.stringify({
+ payload: { type: 'custom_tool_call_output', output: 'data:image/png;base64,abc' },
+ });
+ expect(rewriteOversizedToolOutputImages(small)).toBe(small);
+ const generation = JSON.stringify({
+ payload: { type: 'image_generation_call', id: 'ig_1', result: bigPngDataUri() },
+ });
+ expect(rewriteOversizedToolOutputImages(generation)).toBe(generation);
+ });
+
+ it('turns oversized input_image blocks into input_text instead of invalid image_url', () => {
+ const first = bigPngDataUri(620406);
+ const second = bigPngDataUri(1366914);
+ const line = JSON.stringify({
+ timestamp: '2026-08-27T10:00:33.906Z',
+ type: 'response_item',
+ payload: {
+ type: 'custom_tool_call_output',
+ call_id: 'shot',
+ output: [
+ { type: 'input_text', text: 'Script completed\n' },
+ { type: 'input_image', image_url: first, detail: 'high' },
+ { type: 'input_image', image_url: { url: second }, detail: 'high' },
+ ],
+ },
+ });
+ const out = JSON.parse(rewriteOversizedToolOutputImages(line));
+ expect(out.payload.call_id).toBe('shot');
+ expect(out.payload.output).toEqual([
+ { type: 'input_text', text: 'Script completed\n' },
+ { type: 'input_text', text: `[cindy-omitted-inline-image chars=${first.length}]` },
+ { type: 'input_text', text: `[cindy-omitted-inline-image chars=${second.length}]` },
+ ]);
+ expect(JSON.stringify(out)).not.toMatch(/"image_url":"\[cindy-omitted/);
+ expect(JSON.stringify(out)).not.toContain(';base64,');
+ });
+
+ it('does not swallow trailing tool text after a data URI', () => {
+ const uri = bigPngDataUri();
+ const line = JSON.stringify({
+ payload: {
+ type: 'function_call_output',
+ call_id: 'c1',
+ output: `${uri} image generated successfully`,
+ },
+ });
+ const out = JSON.parse(rewriteOversizedToolOutputImages(line));
+ expect(out.payload.output).toBe(
+ `[cindy-omitted-inline-image chars=${uri.length}] image generated successfully`,
+ );
+ });
+
+ it('keeps sibling metadata when an oversized image_url is not an input_image block', () => {
+ const uri = bigPngDataUri();
+ const line = JSON.stringify({
+ payload: {
+ type: 'custom_tool_call_output',
+ call_id: 'shot',
+ output: {
+ type: 'tool_meta',
+ caption: 'login screen',
+ image_url: uri,
+ },
+ },
+ });
+ const out = JSON.parse(rewriteOversizedToolOutputImages(line));
+ expect(out.payload.output).toEqual({ type: 'tool_meta', caption: 'login screen' });
+ expect(JSON.stringify(out)).not.toContain(';base64,');
+ expect(JSON.stringify(out)).not.toMatch(/"image_url":"\[cindy-omitted/);
+ });
+});
+
+describe('sanitizeCodexForkRollout', () => {
+ it('drops unsafe lines and rewrites oversized tool images', () => {
+ const text = [
+ JSON.stringify({ payload: { type: 'message', role: 'user' } }),
+ JSON.stringify({ payload: { type: 'reasoning', encrypted_content: 'gAAA' } }),
+ JSON.stringify({ payload: { type: 'custom_tool_call_output', call_id: 'shot', output: bigPngDataUri() } }),
+ JSON.stringify({ payload: { type: 'message', role: 'assistant' } }),
+ ].join('\n');
+ const out = sanitizeCodexForkRollout(text);
+ expect(out).toContain('"user"');
+ expect(out).toContain('"assistant"');
+ expect(out).toContain('"shot"');
+ expect(out).not.toContain('encrypted_content');
+ expect(out).not.toContain(';base64,');
+ });
+
+ it('streams a sanitized copy and reports byte reductions', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-rollout-test-'));
+ const source = path.join(dir, 'source.jsonl');
+ const target = path.join(dir, 'target.jsonl');
+ const call = JSON.stringify({ payload: { type: 'custom_tool_call', call_id: 'shot' } });
+ const result = JSON.stringify({
+ payload: { type: 'custom_tool_call_output', call_id: 'shot', output: bigPngDataUri() },
+ });
+ await fs.writeFile(source, [call, result].join('\n'), 'utf8');
+ try {
+ const stats = await sanitizeCodexForkRolloutFile(source, target);
+ const out = await fs.readFile(target, 'utf8');
+ const lines = out.trimEnd().split('\n').map((line) => JSON.parse(line));
+ expect(lines).toHaveLength(2);
+ expect(lines[0].payload.call_id).toBe('shot');
+ expect(lines[1].payload.call_id).toBe('shot');
+ expect(out).not.toContain(';base64,');
+ expect(stats.rewrittenLines).toBe(1);
+ expect(stats.bytesAfter).toBeLessThan(stats.bytesBefore);
+ expect(stats.strippedBytes).toBeGreaterThan(CODEX_INLINE_IMAGE_STRIP_MIN_CHARS - 64);
+ } finally {
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+ });
+});
+
+describe('live-tail classification', () => {
+ it('counts bytes after the last real rollout compaction boundary', () => {
+ const tail = JSON.stringify({ payload: { type: 'custom_tool_call_output', output: 'x'.repeat(100) } });
+ const text = [
+ JSON.stringify({ payload: { type: 'message', role: 'user' } }),
+ compactBoundary(),
+ JSON.stringify({ type: 'event_msg', payload: { type: 'context_compacted' } }),
+ tail,
+ ].join('\n');
+ expect(measureRolloutLiveTailBytesFromText(text)).toBe(Buffer.byteLength(tail, 'utf8') + 1);
+ });
+
+ it('classifies image-heavy live tails as recoverable by strip-fork', () => {
+ const imageChars = CODEX_LIVE_TAIL_OVERSIZED_BYTES + CODEX_INLINE_IMAGE_STRIP_MIN_CHARS;
+ const text = [
+ compactBoundary(),
+ JSON.stringify({
+ payload: { type: 'custom_tool_call_output', call_id: 'shot', output: bigPngDataUri(imageChars) },
+ }),
+ ].join('\n');
+ const stats = measureRolloutLiveTailStatsFromText(text);
+ expect(stats.rewrittenLines).toBe(1);
+ expect(stats.projectedTailBytes).toBeLessThan(CODEX_LIVE_TAIL_OVERSIZED_BYTES);
+ expect(isOversizedLiveTailStats(stats)).toBe(true);
+ });
+
+ it('does not classify large pure-text history as an image problem', () => {
+ const text = [
+ compactBoundary(),
+ JSON.stringify({ payload: { type: 'message', role: 'user', content: 'x'.repeat(CODEX_LIVE_TAIL_OVERSIZED_BYTES + 1) } }),
+ ].join('\n');
+ const stats = measureRolloutLiveTailStatsFromText(text);
+ expect(stats.tailBytes).toBeGreaterThan(CODEX_LIVE_TAIL_OVERSIZED_BYTES);
+ expect(stats.strippedBytes).toBe(0);
+ expect(isOversizedLiveTailStats(stats)).toBe(false);
+ });
+
+ it('does not treat reasoning-heavy tails as an image problem', () => {
+ const blob = 'g'.repeat(CODEX_LIVE_TAIL_OVERSIZED_BYTES + 1);
+ const text = [
+ compactBoundary(),
+ JSON.stringify({ payload: { type: 'reasoning', encrypted_content: blob } }),
+ ].join('\n');
+ const stats = measureRolloutLiveTailStatsFromText(text);
+ expect(stats.tailBytes).toBeGreaterThan(CODEX_LIVE_TAIL_OVERSIZED_BYTES);
+ expect(stats.unsafeLines).toBe(1);
+ expect(stats.rewrittenLines).toBe(0);
+ expect(stats.strippedBytes).toBe(0);
+ expect(isOversizedLiveTailStats(stats)).toBe(false);
+ });
+
+ it('stops before a single JSONL line exceeds the byte cap', async () => {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-rollout-line-cap-'));
+ const source = path.join(dir, 'source.jsonl');
+ await fs.writeFile(source, `${'A'.repeat(200)}\n`, 'utf8');
+ try {
+ await expect(
+ measureRolloutLiveTailStats(source, { maxLineBytes: 50 }),
+ ).rejects.toBeInstanceOf(CodexRolloutScanLimitError);
+ } finally {
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/rollout-sanitize.ts b/packages/maker-core/src/agents/codex/rollout-sanitize.ts
new file mode 100644
index 0000000000..97bc307b62
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/rollout-sanitize.ts
@@ -0,0 +1,411 @@
+/**
+ * Codex fork 清洗与活尾巴测量。
+ *
+ * 超长订阅会话的 remote compaction v2 会把「上次 compact 之后」的 rollout
+ * 整段发给 chatgpt.com。工具输出里的内联截图按 token 很便宜、按字节极大,
+ * 于是出现 token 未满窗但压缩请求发不完的死锁。
+ *
+ * 清洗必须替换工具输出里的超大 data URI、不能删整行,以保住 call/output 配对。
+ * 最近一轮的图也不能豁免:实测死锁尾巴就是最后一次 compact 之后的截图。
+ */
+import { createReadStream, createWriteStream } from 'node:fs';
+import { once } from 'node:events';
+
+/** 与 compaction-storm 同族的终态 reason:磁盘实测活尾巴过大,不是普通 timeout。 */
+export const CODEX_HISTORY_OVERSIZED_REASON = 'codex_history_oversized';
+
+/** 活尾巴超过这个字节数才有资格进入历史过大判定。 */
+export const CODEX_LIVE_TAIL_OVERSIZED_BYTES = 8 * 1024 * 1024;
+
+/** 预计清洗后仍超过这个值时,不把「瘦身」误报成可靠恢复。 */
+export const CODEX_PROJECTED_LIVE_TAIL_MAX_BYTES = 8 * 1024 * 1024;
+
+/** 内联 data URI 达到这个字符数才替换。小图标留下。 */
+export const CODEX_INLINE_IMAGE_STRIP_MIN_CHARS = 64 * 1024;
+
+/** 扫描保护:历史过大判定不应无界读取异常文件。 */
+export const CODEX_ROLLOUT_SCAN_MAX_BYTES = 256 * 1024 * 1024;
+
+/** 单行上限:必须在拼出完整字符串之前截断,不能等 readline 整行进内存。 */
+export const CODEX_ROLLOUT_LINE_MAX_BYTES = 16 * 1024 * 1024;
+
+export class CodexRolloutScanLimitError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = 'CodexRolloutScanLimitError';
+ }
+}
+
+/** 只吃 base64 本体,不把后面的明文一起吞掉。空白也不能进字符集。 */
+const INLINE_IMAGE_DATA_RE =
+ /data:image\/[a-zA-Z0-9.+-]+;base64,[A-Za-z0-9+/]+={0,2}/g;
+
+function omittedInlineImagePlaceholder(chars: number): string {
+ return `[cindy-omitted-inline-image chars=${chars}]`;
+}
+
+function isOversizedInlineDataUri(value: string): boolean {
+ return (
+ value.startsWith('data:image/') &&
+ value.includes(';base64,') &&
+ value.length >= CODEX_INLINE_IMAGE_STRIP_MIN_CHARS
+ );
+}
+
+function imageUrlFromBlock(value: Record<string, unknown>): string | null {
+ if (typeof value.image_url === 'string') return value.image_url;
+ if (typeof value.imageUrl === 'string') return value.imageUrl;
+ if (isRecord(value.image_url) && typeof value.image_url.url === 'string') {
+ return value.image_url.url;
+ }
+ if (isRecord(value.imageUrl) && typeof value.imageUrl.url === 'string') {
+ return value.imageUrl.url;
+ }
+ return null;
+}
+
+const TOOL_OUTPUT_TYPES = new Set([
+ 'custom_tool_call_output',
+ 'function_call_output',
+ 'customToolCallOutput',
+ 'functionCallOutput',
+]);
+
+export interface RolloutLiveTailStats {
+ tailBytes: number;
+ projectedTailBytes: number;
+ strippedBytes: number;
+ rewrittenLines: number;
+ unsafeLines: number;
+ scannedBytes: number;
+}
+
+export interface RolloutSanitizeStats {
+ bytesBefore: number;
+ bytesAfter: number;
+ strippedBytes: number;
+ rewrittenLines: number;
+ unsafeLines: number;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value && typeof value === 'object' && !Array.isArray(value));
+}
+
+function isReasoningPayload(payload: unknown): boolean {
+ return isRecord(payload) && payload.type === 'reasoning';
+}
+
+function isImageGenerationPayloadWithoutId(payload: unknown): boolean {
+ if (!isRecord(payload)) return false;
+ const type = payload.type;
+ if (typeof type !== 'string') return false;
+ if (!type.startsWith('image_generation') && !type.startsWith('imageGeneration')) return false;
+ const id = payload.id;
+ return typeof id !== 'string' || id.trim().length === 0;
+}
+
+export function hasUnsafeForkRolloutPayload(line: string): boolean {
+ try {
+ const parsed: unknown = JSON.parse(line);
+ if (!isRecord(parsed)) return false;
+ const payload = parsed.payload;
+ return isReasoningPayload(payload) || isImageGenerationPayloadWithoutId(payload);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Rollout 的压缩边界不是 app-server item type:真实文件使用顶层 compacted,
+ * 并在 event_msg 中补一条 context_compacted。未知形态不猜,继续累加而不是清零。
+ */
+export function isCompactionBoundaryLine(line: string): boolean {
+ try {
+ const parsed: unknown = JSON.parse(line);
+ if (!isRecord(parsed)) return false;
+ if (parsed.type === 'compacted') return true;
+ return isRecord(parsed.payload) && parsed.type === 'event_msg' &&
+ parsed.payload.type === 'context_compacted';
+ } catch {
+ return false;
+ }
+}
+
+function isToolOutputPayload(payload: unknown): payload is Record<string, unknown> {
+ return isRecord(payload) && typeof payload.type === 'string' && TOOL_OUTPUT_TYPES.has(payload.type);
+}
+
+function imageBytesInLine(line: string): number {
+ if (!line.includes(';base64,')) return 0;
+ let total = 0;
+ for (const match of line.matchAll(INLINE_IMAGE_DATA_RE)) {
+ if (match[0].length >= CODEX_INLINE_IMAGE_STRIP_MIN_CHARS) {
+ total += Buffer.byteLength(match[0], 'utf8');
+ }
+ }
+ return total;
+}
+
+function rewriteDataUrisInText(text: string): string {
+ return text.replace(INLINE_IMAGE_DATA_RE, (match) => {
+ if (match.length < CODEX_INLINE_IMAGE_STRIP_MIN_CHARS) return match;
+ return omittedInlineImagePlaceholder(match.length);
+ });
+}
+
+/**
+ * 超大 data URI 不能留在 image_url 里:Responses 会按 URL 校验,占位字符串会 400。
+ * 结构化 input_image 改成 input_text;普通字符串输出才原位替换。
+ */
+function isInputImageBlock(value: Record<string, unknown>): boolean {
+ return value.type === 'input_image' || value.type === 'inputImage';
+}
+
+function rewriteToolOutputValue(value: unknown): unknown {
+ if (typeof value === 'string') return rewriteDataUrisInText(value);
+ if (Array.isArray(value)) return value.map(rewriteToolOutputValue);
+ if (!isRecord(value)) return value;
+ const imageUrl = imageUrlFromBlock(value);
+ if (imageUrl && isOversizedInlineDataUri(imageUrl)) {
+ if (isInputImageBlock(value)) {
+ return { type: 'input_text', text: omittedInlineImagePlaceholder(imageUrl.length) };
+ }
+ const next: Record<string, unknown> = {};
+ for (const [key, child] of Object.entries(value)) {
+ if (key === 'image_url' || key === 'imageUrl') continue;
+ next[key] = rewriteToolOutputValue(child);
+ }
+ return next;
+ }
+ const next: Record<string, unknown> = {};
+ for (const [key, child] of Object.entries(value)) {
+ next[key] = rewriteToolOutputValue(child);
+ }
+ return next;
+}
+
+export function rewriteOversizedToolOutputImages(line: string): string {
+ if (!line.includes(';base64,')) return line;
+ try {
+ const parsed: unknown = JSON.parse(line);
+ if (!isRecord(parsed) || !isToolOutputPayload(parsed.payload)) return line;
+ return JSON.stringify(rewriteToolOutputValue(parsed));
+ } catch {
+ return line;
+ }
+}
+
+export function sanitizeCodexForkRollout(text: string): string {
+ const lines = text.split(/\r?\n/);
+ const out: string[] = [];
+ for (const line of lines) {
+ if (!line.trim()) {
+ out.push(line);
+ continue;
+ }
+ if (hasUnsafeForkRolloutPayload(line)) continue;
+ out.push(rewriteOversizedToolOutputImages(line));
+ }
+ return out.join('\n');
+}
+
+function addLineStats(stats: RolloutLiveTailStats, line: string): void {
+ if (!line) return;
+ const lineBytes = Buffer.byteLength(line, 'utf8') + 1;
+ stats.tailBytes += lineBytes;
+ if (hasUnsafeForkRolloutPayload(line)) {
+ stats.unsafeLines += 1;
+ return;
+ }
+ const rewritten = rewriteOversizedToolOutputImages(line);
+ const rewrittenBytes = Buffer.byteLength(rewritten, 'utf8') + 1;
+ stats.projectedTailBytes += rewrittenBytes;
+ const imageBytes = imageBytesInLine(line);
+ if (imageBytes > 0 && rewritten !== line) stats.rewrittenLines += 1;
+ stats.strippedBytes += Math.max(0, lineBytes - rewrittenBytes);
+}
+
+export function measureRolloutLiveTailStatsFromText(text: string): RolloutLiveTailStats {
+ const stats: RolloutLiveTailStats = {
+ tailBytes: 0,
+ projectedTailBytes: 0,
+ strippedBytes: 0,
+ rewrittenLines: 0,
+ unsafeLines: 0,
+ scannedBytes: Buffer.byteLength(text, 'utf8'),
+ };
+ for (const line of text.split(/\r?\n/)) {
+ if (isCompactionBoundaryLine(line)) {
+ stats.tailBytes = 0;
+ stats.projectedTailBytes = 0;
+ stats.strippedBytes = 0;
+ stats.rewrittenLines = 0;
+ stats.unsafeLines = 0;
+ continue;
+ }
+ addLineStats(stats, line);
+ }
+ return stats;
+}
+
+export function measureRolloutLiveTailBytesFromText(text: string): number {
+ return measureRolloutLiveTailStatsFromText(text).tailBytes;
+}
+
+/** 是否有足够的可剥离证据,不把普通大文本历史误报为图片病。 */
+export function isOversizedLiveTailStats(stats: RolloutLiveTailStats): boolean {
+ return stats.rewrittenLines > 0 &&
+ stats.tailBytes > CODEX_LIVE_TAIL_OVERSIZED_BYTES &&
+ stats.strippedBytes >= stats.tailBytes / 2 &&
+ stats.projectedTailBytes <= CODEX_PROJECTED_LIVE_TAIL_MAX_BYTES;
+}
+
+function decodeRolloutLine(parts: Buffer[]): string {
+ const line = parts.length === 1 ? parts[0] : Buffer.concat(parts);
+ const end = line.length > 0 && line[line.length - 1] === 0x0d ? line.length - 1 : line.length;
+ return line.subarray(0, end).toString('utf8');
+}
+
+async function* iterateRolloutLines(
+ filePath: string,
+ opts: { maxBytes?: number; maxLineBytes?: number } = {},
+): AsyncGenerator<string> {
+ const maxBytes = opts.maxBytes ?? CODEX_ROLLOUT_SCAN_MAX_BYTES;
+ const maxLineBytes = opts.maxLineBytes ?? CODEX_ROLLOUT_LINE_MAX_BYTES;
+ const input = createReadStream(filePath);
+ let scanned = 0;
+ let pending: Buffer[] = [];
+ let pendingBytes = 0;
+ try {
+ for await (const chunk of input) {
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ scanned += buf.length;
+ if (scanned > maxBytes) {
+ throw new CodexRolloutScanLimitError(`Codex rollout scan exceeded ${maxBytes} bytes`);
+ }
+ let offset = 0;
+ while (offset < buf.length) {
+ const nl = buf.indexOf(0x0a, offset);
+ if (nl === -1) {
+ const rest = buf.subarray(offset);
+ if (pendingBytes + rest.length > maxLineBytes) {
+ throw new CodexRolloutScanLimitError(`Codex rollout line exceeded ${maxLineBytes} bytes`);
+ }
+ pending.push(rest);
+ pendingBytes += rest.length;
+ break;
+ }
+ const piece = buf.subarray(offset, nl);
+ if (pendingBytes + piece.length > maxLineBytes) {
+ throw new CodexRolloutScanLimitError(`Codex rollout line exceeded ${maxLineBytes} bytes`);
+ }
+ yield decodeRolloutLine(pendingBytes === 0 ? [piece] : [...pending, piece]);
+ pending = [];
+ pendingBytes = 0;
+ offset = nl + 1;
+ }
+ }
+ if (pendingBytes > 0) {
+ if (pendingBytes > maxLineBytes) {
+ throw new CodexRolloutScanLimitError(`Codex rollout line exceeded ${maxLineBytes} bytes`);
+ }
+ yield decodeRolloutLine(pending);
+ }
+ } finally {
+ input.destroy();
+ }
+}
+
+export async function measureRolloutLiveTailStats(
+ filePath: string,
+ opts: { maxBytes?: number; maxLineBytes?: number } = {},
+): Promise<RolloutLiveTailStats> {
+ const stats: RolloutLiveTailStats = {
+ tailBytes: 0,
+ projectedTailBytes: 0,
+ strippedBytes: 0,
+ rewrittenLines: 0,
+ unsafeLines: 0,
+ scannedBytes: 0,
+ };
+ for await (const line of iterateRolloutLines(filePath, opts)) {
+ stats.scannedBytes += Buffer.byteLength(line, 'utf8') + 1;
+ if (isCompactionBoundaryLine(line)) {
+ stats.tailBytes = 0;
+ stats.projectedTailBytes = 0;
+ stats.strippedBytes = 0;
+ stats.rewrittenLines = 0;
+ stats.unsafeLines = 0;
+ continue;
+ }
+ addLineStats(stats, line);
+ }
+ return stats;
+}
+
+export async function measureRolloutLiveTailBytes(filePath: string): Promise<number> {
+ return (await measureRolloutLiveTailStats(filePath)).tailBytes;
+}
+
+async function writeChunk(stream: ReturnType<typeof createWriteStream>, chunk: string): Promise<void> {
+ if (stream.write(chunk, 'utf8')) return;
+ await once(stream, 'drain');
+}
+
+export async function sanitizeCodexForkRolloutFile(
+ sourcePath: string,
+ copyPath: string,
+): Promise<RolloutSanitizeStats> {
+ const output = createWriteStream(copyPath, { encoding: 'utf8' });
+ const outputFailed = once(output, 'error').then((args) => {
+ const err = Array.isArray(args) ? args[0] : args;
+ throw err instanceof Error ? err : new Error(String(err));
+ });
+ void outputFailed.catch(() => undefined);
+ const stats: RolloutSanitizeStats = {
+ bytesBefore: 0,
+ bytesAfter: 0,
+ strippedBytes: 0,
+ rewrittenLines: 0,
+ unsafeLines: 0,
+ };
+ let first = true;
+ try {
+ await Promise.race([
+ (async () => {
+ for await (const line of iterateRolloutLines(sourcePath)) {
+ const newline = first ? '' : '\n';
+ first = false;
+ const originalBytes = Buffer.byteLength(line, 'utf8') + (newline ? 1 : 0);
+ stats.bytesBefore += originalBytes;
+ if (hasUnsafeForkRolloutPayload(line)) {
+ stats.unsafeLines += 1;
+ stats.strippedBytes += originalBytes;
+ continue;
+ }
+ const rewritten = rewriteOversizedToolOutputImages(line);
+ const result = `${newline}${rewritten}`;
+ const resultBytes = Buffer.byteLength(result, 'utf8');
+ stats.bytesAfter += resultBytes;
+ stats.strippedBytes += Math.max(0, originalBytes - resultBytes);
+ if (rewritten !== line) stats.rewrittenLines += 1;
+ await writeChunk(output, result);
+ }
+ if (!first) await writeChunk(output, '\n');
+ await new Promise<void>((resolve, reject) => {
+ output.end((error?: Error | null) => (error ? reject(error) : resolve()));
+ });
+ })(),
+ outputFailed,
+ ]);
+ } catch (error) {
+ output.destroy();
+ await outputFailed.catch(() => undefined);
+ throw error;
+ } finally {
+ if (!output.closed) output.destroy();
+ }
+ stats.bytesAfter += first ? 0 : 1;
+ return stats;
+}
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index 5ad92c76a2..64471f74ba 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -13,6 +13,7 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ classifyCodexError,
extractRolloutUpdatePlanFunctionCallEvent,
newCodexRuntimeState,
translateErrorNotification,
@@ -774,6 +775,24 @@ describe('translateErrorNotification', () => {
});
});
+ it('classifyCodexError 把 contextWindowExceeded 与 overload 映射成稳定 reason', () => {
+ expect(classifyCodexError({
+ message: 'window full',
+ codexErrorInfo: 'contextWindowExceeded',
+ })).toMatchObject({
+ reason: 'context-overflow',
+ errorInfoTag: 'contextWindowExceeded',
+ });
+ expect(classifyCodexError({
+ message: 'The upstream declined this request.',
+ codexErrorInfo: 'serverOverloaded',
+ }).reason).toBe('upstream-overload');
+ expect(classifyCodexError({
+ message: 'stream dropped',
+ codexErrorInfo: { responseStreamDisconnected: { httpStatusCode: 502 } },
+ }).errorInfoTag).toBe('responseStreamDisconnected');
+ });
+
it('Codex 结构化 contextWindowExceeded tag 不依赖错误文案措辞', async () => {
const rt = newCodexRuntimeState();
const q = createAsyncQueue<AgentEvent>();
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index e831838f07..b58a100db2 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -478,32 +478,72 @@ export function isAuthRelatedErrorMessage(message: string, errorStatus?: number)
.test(message);
}
-/** error notification (顶层非 item.*) → AgentEvent error。 */
-export function translateErrorNotification(
- params: ErrorNotification['params'],
- queue: AsyncQueue<AgentEvent>,
- ctx: CodexTranslateContext,
-): void {
- const message = params.error?.message ?? 'codex error';
- const hasMissingBearer = /\bMissing bearer\b/i.test(message);
+export interface ClassifiedCodexError {
+ message: string;
+ errorStatus?: number;
+ errorInfoTag?: string;
+ usageLimit: boolean;
+ isCapacityError: boolean;
+ reason?: string;
+ data: Record<string, unknown> & { message: string };
+}
+
+/**
+ * ErrorNotification 与 turn/completed.turn.error 共用的结构化分类。
+ * 只消费 Codex wire schema 的 codexErrorInfo;additionalDetails / stderr 不参与判定。
+ */
+export function classifyCodexError(error: {
+ message?: string;
+ codexErrorInfo?: import('./app-server/protocol.js').CodexErrorInfo | null;
+} | null | undefined): ClassifiedCodexError {
+ const rawMessage = error?.message ?? 'codex error';
+ const hasMissingBearer = /\bMissing bearer\b/i.test(rawMessage);
const hasAuthErrorMarker =
/\bauthentication_(?:error|failed)\b|\binvalid[\s_-]*api[\s_-]*key\b|\bapi key not valid\b/i.test(
- message,
+ rawMessage,
);
- const safeMessage = redactSensitiveText(message);
- const signals = extractNonSecretErrorSignals(message);
+ const message = redactSensitiveText(rawMessage);
+ const signals = extractNonSecretErrorSignals(rawMessage);
const errorStatus =
signals.errorStatus ?? (hasMissingBearer || hasAuthErrorMarker ? 401 : undefined);
- // 结构化错误标识。过载判定优先吃它(见下方 capacity 分支), 同时透出到 error data
- // 供诊断与下游归因。**不参与上面的 errorStatus 推断** —— 那条链路上挂着
- // renderer 的 401 banner 与 auth 修复 UX, 改推断依据会连带改这些行为。
- const errorInfoTag = codexErrorInfoTag(params.error?.codexErrorInfo);
- const safeErrorData = {
- message: safeMessage,
+ const errorInfoTag = codexErrorInfoTag(error?.codexErrorInfo);
+ const isCapacityError =
+ parseOverloadError(message, signals.errorStatus, errorInfoTag)?.kind === 'capacity';
+ const reason = isCapacityError
+ ? UPSTREAM_OVERLOAD_REASON
+ : errorInfoTag === 'contextWindowExceeded' || isContextOverflowErrorMessage(message)
+ ? CONTEXT_OVERFLOW_REASON
+ : undefined;
+ return {
+ message,
...(errorStatus !== undefined ? { errorStatus } : {}),
- ...(signals.usageLimit ? { usageLimit: true } : {}),
- ...(errorInfoTag !== undefined ? { codexErrorInfo: errorInfoTag } : {}),
+ ...(errorInfoTag !== undefined ? { errorInfoTag } : {}),
+ usageLimit: signals.usageLimit,
+ isCapacityError,
+ ...(reason ? { reason } : {}),
+ data: {
+ message,
+ ...(errorStatus !== undefined ? { errorStatus } : {}),
+ ...(signals.usageLimit ? { usageLimit: true } : {}),
+ ...(errorInfoTag !== undefined ? { codexErrorInfo: errorInfoTag } : {}),
+ ...(reason ? { reason } : {}),
+ },
};
+}
+
+/** error notification (顶层非 item.*) → AgentEvent error。 */
+export function translateErrorNotification(
+ params: ErrorNotification['params'],
+ queue: AsyncQueue<AgentEvent>,
+ ctx: CodexTranslateContext,
+): void {
+ const classified = classifyCodexError(params.error);
+ const message = classified.message;
+ const safeMessage = classified.message;
+ const errorStatus = classified.errorStatus;
+ const isCapacityError = classified.isCapacityError;
+ const errorInfoTag = classified.errorInfoTag;
+ const safeErrorData = classified.data;
// willRetry=true 的暂时错误 (transient API blip / 5xx blip), server 自己会重试 — 默认
// 不 emit error event 给 UI,否则会把瞬时错误暴露成用户可见失败。**但** auth 缺失
// (401/Unauthorized/Missing bearer) 是 daemon 怎么 retry 也不可能自愈的 —— 必须
@@ -566,20 +606,14 @@ export function translateErrorNotification(
// 由 agent 层接管退避重投。接管成功时透成非终止状态并带进度后缀, renderer
// 显示"模型繁忙, 正在重试 (N/M)"; 预算耗尽或条件不满足 (本 turn 已有产出)
// 时 tryTakeOverOverload 返回 null, 落回下面的终止错误路径。
- const isCapacityError =
- parseOverloadError(safeMessage, signals.errorStatus, errorInfoTag)?.kind === 'capacity';
- // 过载错误一律带上稳定 reason key。renderer 隔着 IPC 投影拿不到 codexErrorInfo,
- // 靠这个 key 判定"是否过载"(ErrorBanner 的本地化文案 + 重试进度 + hideRetry 都由它
- // 驱动)。不带的话 renderer 只能回退到文案匹配 —— codex 改一次措辞, 用户就会在整段
- // 重试窗口里看到英文原文, 也就是本次改动要消除的那个依赖在 UI 侧原样残留。
+ // 过载分类在函数入口已完成,避免同一判据在两处漂移。
const overloadReason = isCapacityError ? { reason: UPSTREAM_OVERLOAD_REASON } : {};
// 上下文超限同样带稳定 reason key(#1429): 原样重试必然再撞同一个 4xx, renderer 靠
// 它隐藏 Retry 并给出压缩 / 新开会话入口。结构化 contextWindowExceeded 优先,
// 文案匹配仅兼容旧版 app-server;与 capacity 互斥时 overload 优先 —— 它还驱动
// 退避重投接管,语义更具体。
const contextOverflowReason =
- !isCapacityError &&
- (errorInfoTag === 'contextWindowExceeded' || isContextOverflowErrorMessage(safeMessage))
+ !isCapacityError && classified.reason === CONTEXT_OVERFLOW_REASON
? { reason: CONTEXT_OVERFLOW_REASON }
: {};
if (!params.willRetry && isCapacityError) {
diff --git a/packages/maker-core/src/agents/index.ts b/packages/maker-core/src/agents/index.ts
index d810c30be5..275472b675 100644
--- a/packages/maker-core/src/agents/index.ts
+++ b/packages/maker-core/src/agents/index.ts
@@ -7,6 +7,12 @@ export type {
ClaudeSubagentModelAccessStatus,
} from './claude-code/subagent-model-access.js';
export { CodexAgent } from './codex/index.js';
+export {
+ CODEX_HISTORY_OVERSIZED_REASON,
+ CODEX_LIVE_TAIL_OVERSIZED_BYTES,
+ isOversizedLiveTailStats,
+ measureRolloutLiveTailStats,
+} from './codex/rollout-sanitize.js';
// host 导入本地 Codex rollout 历史时也要做 citation 归一化(流式路径在 translator
// 内部做,导入路径拿到的是 rollout 原文),复用同一实现避免口径分叉。
// finalizeCodexCitationText = 剥截断残尾 + 归一化(与流式 completed 完全同口径)。