Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(maker-core): isolate cancelled yield turns and retry live wait cells

Dash9c8d3d8bea3c
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index bf4c0638a5..64c7248437 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -81,6 +81,9 @@ timeout 不得触发自动换窗或 replay。Codex 当前没有与 Claude `AutoC
判据;cell 跨 turn 存活性未证实前,续段失败必须诚实报 lost-handle,不得 replay 原请求
或重跑已执行命令。续段 claim 一旦挡住产品结束,所有非重试终态错误路径(不限
transport)都必须同步结算它,不能只推 Done 而让 `isTurnRunning()` 仍为 true。
+ 续段 `turn/start` 已被服务端接受后若本地取消,必须先凭响应里的 turn id 落墓碑并
+ best-effort interrupt,再抛/返回取消;`wait` 仍输出 running marker 视为 cell
+ 存活证据,重试预算内继续等,不得当空续段报 lost-handle。
Claude wake continuation 与 Codex yield continuation 先分账,不抽公共模块。
## 3. 守住四项核心数据指标
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index ea08df7e1c..6d9195d990 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -17528,7 +17528,9 @@ describe('CodexAgent yield continuation', () => {
const [, params] = yieldTurnStartCalls(host)[0] as [string, {
input: Array<{ text?: string }>;
}];
- expect(params.input[0]?.text).toContain('Wait for cell ID 229');
+ const prompt = params.input[0]?.text ?? '';
+ expect(prompt).toContain('cell ID 229');
+ expect(prompt).toContain('cell ID 11');
await handle.close();
});
@@ -17641,6 +17643,71 @@ describe('CodexAgent yield continuation', () => {
await handle.close();
});
+ it('retries a continuation when wait still reports the cell running', async () => {
+ const agent = new CodexAgent(createDeps());
+ let turnSeq = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ turnSeq += 1;
+ return { turn: { id: `turn-${turnSeq}` } };
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-wait-alive-retry',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemCompleted || !handlers.turnCompleted) {
+ throw new Error('expected item and turn handlers');
+ }
+ const events = await collectYieldEvents(handle);
+ await handle.send({ type: 'user', content: 'run typecheck' });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'item-exec-alive-retry',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226',
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await vi.waitFor(() => {
+ expect(yieldTurnStartCalls(host)).toHaveLength(1);
+ });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-2',
+ item: {
+ id: 'item-wait-alive-retry',
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '226', yield_time_ms: 1000 }),
+ content: [{ type: 'output_text', text: 'Script running with cell ID 226\nWall time 1.0 seconds\nOutput:\n' }],
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-2', status: 'completed' },
+ });
+ await vi.waitFor(() => {
+ expect(yieldTurnStartCalls(host)).toHaveLength(2);
+ });
+ expect(events.some((event) => (
+ event.type === 'error'
+ && String((event.data as { reason?: string }).reason ?? '') === 'yield-continuation-lost-handle'
+ ))).toBe(false);
+ expect(handle.isTurnRunning?.()).toBe(true);
+ await handle.close();
+ });
+
it('does not mint a claim for a finished command without a yield marker', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent, (method) => {
@@ -17904,6 +17971,70 @@ describe('CodexAgent yield continuation', () => {
await handle.close();
});
+ it('isolates a cancelled yield continuation before the turn/start response can activate it', async () => {
+ const agent = new CodexAgent(createDeps());
+ let turnStarts = 0;
+ const continuationStart = deferred<{ turn: { id: string } }>();
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ turnStarts += 1;
+ if (turnStarts === 1) return { turn: { id: 'turn-1' } };
+ return continuationStart.promise;
+ }
+ if (method === Method.TurnInterrupt) return {};
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-cancel-before-start-resp',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemCompleted || !handlers.turnCompleted || !handlers.turnStarted) {
+ throw new Error('expected item, turn, and started handlers');
+ }
+ const events = await collectYieldEvents(handle);
+ await handle.send({ type: 'user', content: 'run typecheck' });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'item-exec-cancel-before-resp',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226',
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => event.type === 'done' && event.turnContinuationId != null)).toBe(true);
+ });
+ await vi.waitFor(() => {
+ expect(turnStarts).toBe(2);
+ });
+ const claimedDone = events.find((event) => event.type === 'done' && event.turnContinuationId != null);
+ await handle.abort();
+ continuationStart.resolve({ turn: { id: 'turn-2' } });
+ await waitForExpectation(() => {
+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {
+ threadId: 'start-thread-id',
+ turnId: 'turn-2',
+ });
+ });
+ handlers.turnStarted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-2', status: 'inProgress' },
+ });
+ expect(handle.getCurrentTurnId?.()).not.toBe('turn-2');
+ const state = handle.beginTurnContinuationWait?.(claimedDone?.turnContinuationId);
+ expect(state === 'cancelled' || state === null).toBe(true);
+ await handle.close();
+ });
+
it('does not mint a claim from an agentMessage quoting a yield marker', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent, (method) => {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index ad5a2c9202..a02e9c5025 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -120,6 +120,7 @@ import { scanCodexCustomizations } from './customization-scanner.js';
import { commandExecutionDisplayInput } from './command-display.js';
import {
dedupeCells,
+ extractAliveYieldCellsFromCodexItem,
extractSettledYieldCellIdsFromCodexItem,
extractYieldedExecCellsFromCodexItem,
formatYieldContinuationPrompt,
@@ -3196,13 +3197,18 @@ export class CodexAgent extends BaseAgent {
? item as Record<string, unknown>
: null;
const itemId = yieldItemLedgerKey(record);
- const cells = extractYieldedExecCellsFromCodexItem(item);
+ const cells = dedupeCells([
+ ...extractYieldedExecCellsFromCodexItem(item),
+ ...extractAliveYieldCellsFromCodexItem(item),
+ ]);
const existing = yieldedExecCellsByTurnId.get(turnId) ?? new Map<string, YieldedExecCell[]>();
if (cells.length === 0) {
if (phase === 'completed' && itemId) existing.delete(itemId);
} else if (itemId) {
existing.set(itemId, cells);
} else {
+ // Nameless exec and wait share the same anonymous bucket. A later wait
+ // that is still running must accumulate, not replace the yielded exec.
const anonymous = existing.get('') ?? [];
existing.set('', dedupeCells([...anonymous, ...cells]));
}
@@ -8049,6 +8055,28 @@ export class CodexAgent extends BaseAgent {
return true;
}
+ function isolateCancelledTurnStart(
+ resp: TurnStartResponse | undefined,
+ sendOpts: SendOptions | undefined,
+ stage: string,
+ ): void {
+ if (!closed && sendOpts?.signal?.aborted !== true) return;
+ abandonBufferedTurns(`send cancelled ${stage}`);
+ const staleTurnId = resp?.turn?.id;
+ if (!staleTurnId) return;
+ terminalErroredTurnIds.add(staleTurnId);
+ if (!threadId) return;
+ host
+ .request(Method.TurnInterrupt, { threadId, turnId: staleTurnId })
+ .catch((error: unknown) => {
+ log.warn('cancelled turn/start interrupt failed (best-effort)', {
+ turnId: staleTurnId,
+ stage,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ });
+ }
+
function isLocalAcceptBoundaryError(err: unknown): boolean {
const text = err instanceof Error ? err.message : String(err);
return /Codex send (?:cancelled|cannot be accepted)/i.test(text);
@@ -11368,24 +11396,11 @@ export class CodexAgent extends BaseAgent {
});
markTurnConfigAccepted();
adoptUnidentifiedDeadTurn(resp, initialStartSeq);
+ // yield continuation 带 throwOnStartFailure + AbortSignal: 取消检查会
+ // 抛, 不能把墓碑/interrupt 写在 return 后面。先隔离已被 server 接受
+ // 的 turn, 再让取消检查抛/返回, 迟到的 turnStarted 才会撞墓碑。
+ isolateCancelledTurnStart(resp, sendOpts, 'after turn/start');
if (rejectClosedOrCancelledSend(sendOpts, 'after turn/start')) {
- // 本地取消边界直接 return: 挂起的 buffered 请求没有 settle 者
- // (codex R17 P2), 统一释放。
- abandonBufferedTurns('send cancelled after turn/start');
- const staleTurnId = resp.turn?.id;
- if (staleTurnId) {
- terminalErroredTurnIds.add(staleTurnId);
- if (threadId) {
- host
- .request(Method.TurnInterrupt, { threadId, turnId: staleTurnId })
- .catch((error: unknown) => {
- log.warn('cancelled yield continuation interrupt failed (best-effort)', {
- turnId: staleTurnId,
- error: error instanceof Error ? error.message : String(error),
- });
- });
- }
- }
return;
}
handleTurnStartResp(resp, initialStartSeq);
@@ -11479,8 +11494,8 @@ export class CodexAgent extends BaseAgent {
});
markTurnConfigAccepted();
adoptUnidentifiedDeadTurn(resp, initialStartSeq);
+ isolateCancelledTurnStart(resp, sendOpts, 'after turn/start retry');
if (rejectClosedOrCancelledSend(sendOpts, 'after turn/start retry')) {
- abandonBufferedTurns('send cancelled after turn/start retry');
return;
}
handleTurnStartResp(resp, initialStartSeq);
diff --git a/packages/maker-core/src/agents/codex/yielded-exec-cell.test.ts b/packages/maker-core/src/agents/codex/yielded-exec-cell.test.ts
index e4f9d3d807..749b86df32 100644
--- a/packages/maker-core/src/agents/codex/yielded-exec-cell.test.ts
+++ b/packages/maker-core/src/agents/codex/yielded-exec-cell.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
+ extractAliveYieldCellsFromCodexItem,
extractSettledYieldCellIdsFromCodexItem,
extractYieldedExecCellIds,
extractYieldedExecCellsFromCodexItem,
@@ -127,6 +128,26 @@ describe('extractSettledYieldCellIdsFromCodexItem', () => {
});
});
+describe('extractAliveYieldCellsFromCodexItem', () => {
+ it('treats a wait still printing the running marker as proof the cell is alive', () => {
+ expect(extractAliveYieldCellsFromCodexItem({
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '226', yield_time_ms: 1000 }),
+ content: [{ type: 'output_text', text: 'Script running with cell ID 226\nWall time 1.0 seconds\nOutput:\n' }],
+ })).toEqual([{ cellId: '226' }]);
+ });
+
+ it('does not treat a completed wait as an alive cell', () => {
+ expect(extractAliveYieldCellsFromCodexItem({
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '226', max_tokens: 1000 }),
+ content: [{ type: 'output_text', text: 'Script completed\nWall time 0.1 seconds\nOutput:\n' }],
+ })).toEqual([]);
+ });
+});
+
describe('formatYieldContinuationPrompt', () => {
it('asks the next provider turn to wait the same cells', () => {
const prompt = formatYieldContinuationPrompt([
diff --git a/packages/maker-core/src/agents/codex/yielded-exec-cell.ts b/packages/maker-core/src/agents/codex/yielded-exec-cell.ts
index 2ca64061ec..e9fd94142a 100644
--- a/packages/maker-core/src/agents/codex/yielded-exec-cell.ts
+++ b/packages/maker-core/src/agents/codex/yielded-exec-cell.ts
@@ -61,6 +61,22 @@ export function extractSettledYieldCellIdsFromCodexItem(item: unknown): string[]
return [cellId];
}
+/**
+ * A wait that still prints the running marker proves the claimed cell is alive.
+ * The original exec item keeps the yield marker forever, so this is the only
+ * evidence a later empty continuation can use to retry instead of lost-handle.
+ */
+export function extractAliveYieldCellsFromCodexItem(item: unknown): YieldedExecCell[] {
+ const record = asRecord(item);
+ if (!record || !isWaitItem(record)) return [];
+ const args = parseJsonObject(record.arguments) ?? asRecord(record.input);
+ const cellId = firstString(args, ['cell_id', 'cellId']);
+ if (!cellId) return [];
+ const output = collectItemText(record);
+ if (!extractYieldedExecCellIds(output).includes(cellId)) return [];
+ return [{ cellId }];
+}
+
export function formatYieldContinuationPrompt(cells: readonly YieldedExecCell[]): string {
const unique = dedupeCells(cells);
const cellList = unique.map((cell) => {