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): keep Codex product turns open across exec yield

Dashbc827d35ef86
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index b5d9479dff..ec1682b1ce 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -71,6 +71,16 @@ timeout 不得触发自动换窗或 replay。Codex 当前没有与 Claude `AutoC
- 打算用 prompt 解决某个问题前先自问:这件事用代码能不能做?能就用代码。
- 把本应由代码保证的确定性逻辑(格式校验、字段抽取、流程跳转、是否调用某个工具等)
交给模型自由发挥,会引入不可复现的行为漂移,属于本规则明确禁止的做法。
+- **产品 turn 未结算不得结束。** provider `turn/completed` 可以立刻给 SDK turn 落墓碑并
+ 结算 usage;只有原子挂在该终态边界上的显式 continuation claim 才能挡住产品结束。
+ Codex `functions.exec` yield 没有协议级 execution handle(cell / wait 活在
+ `codex-rs` daemon),近期检测只能是 adapter 内、用真实 rollout fixture 锁死的启发式,
+ 用来铸造有界 claim,再由宿主确定性开续段让模型 wait 同一 cell。同 turn 或续段里
+ 后续 `wait` 输出 `Script completed` / `Script terminated` 后视为该 cell 已结算,不得
+ 再铸 claim,也不得报 lost-handle。禁止把 `last_agent_message == null` 或开场白当结算
+ 判据;cell 跨 turn 存活性未证实前,续段失败必须诚实报 lost-handle,不得 replay 原请求
+ 或重跑已执行命令。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 868adcee1a..0b5ebd79d8 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -17336,6 +17336,855 @@ describe('CodexAgent MCP thread context hooks', () => {
});
});
+describe('CodexAgent yield continuation', () => {
+ async function collectYieldEvents(handle: AgentSessionHandle): Promise<AgentEvent[]> {
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) {
+ events.push(event);
+ }
+ })();
+ return events;
+ }
+
+ function yieldTurnStartCalls(host: ReturnType<typeof installFakeHost>) {
+ return host.request.mock.calls.filter(([method, params]) => (
+ method === Method.TurnStart
+ && String((params as { input?: Array<{ text?: string }> }).input?.[0]?.text ?? '')
+ .includes('A foreground exec cell is still running')
+ ));
+ }
+
+ it('keeps the product turn open and waits the yielded cell after commandExecution completes', 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-command-execution',
+ 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-1',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226\nWall time 11.0 seconds\nOutput:\n',
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+
+ await waitForExpectation(() => {
+ const done = events.filter((event) => event.type === 'done');
+ expect(done).toHaveLength(1);
+ expect(done[0]?.turnContinuationId).toEqual(expect.any(Number));
+ expect(events.some((event) => (
+ event.type === 'status'
+ && (event.data as { isRunning?: boolean }).isRunning === false
+ && event.turnContinuationId === done[0]?.turnContinuationId
+ ))).toBe(true);
+ });
+ expect(handle.isTurnRunning?.()).toBe(true);
+ expect(handle.beginTurnContinuationWait?.(events.find((event) => event.type === 'done')?.turnContinuationId))
+ .toBe('active');
+ await vi.waitFor(() => {
+ expect(yieldTurnStartCalls(host)).toHaveLength(1);
+ });
+ const [, params] = yieldTurnStartCalls(host)[0] as [string, {
+ input: Array<{ text?: string }>;
+ }];
+ expect(params.input[0]?.text).toContain('Wait for cell ID 226');
+ expect(params.input[0]?.text).not.toContain('run typecheck');
+ await handle.close();
+ });
+
+ it('detects Responses/proxy function_call(exec_command) yield output', 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-function-call',
+ 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-call',
+ type: 'function_call',
+ name: 'exec_command',
+ arguments: JSON.stringify({
+ cmd: 'pnpm --filter desktop run typecheck',
+ yield_time_ms: 10_000,
+ }),
+ content: [{ type: 'output_text', text: 'Script running with cell ID 229' }],
+ },
+ });
+ 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(yieldTurnStartCalls(host)).toHaveLength(1);
+ });
+ const [, params] = yieldTurnStartCalls(host)[0] as [string, {
+ input: Array<{ text?: string }>;
+ }];
+ expect(params.input[0]?.text).toContain('Wait for cell ID 229');
+ await handle.close();
+ });
+
+ it('does not mint a claim after wait settles the yielded cell in the same turn', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-then-wait-settled',
+ 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-yield',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226\nWall time 11.0 seconds\nOutput:\n',
+ },
+ });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'item-wait-226',
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '226', max_tokens: 1000 }),
+ content: [{ type: 'output_text', text: 'Script completed\nWall time 4.2 seconds\nOutput:\n' }],
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => event.type === 'done')).toBe(true);
+ });
+ expect(events.find((event) => event.type === 'done')?.turnContinuationId).toBeUndefined();
+ expect(yieldTurnStartCalls(host)).toHaveLength(0);
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('keeps the claim when wait still yields the same cell', 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-still-running',
+ 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-still-running',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226\nWall time 11.0 seconds\nOutput:\n',
+ },
+ });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'item-wait-still-running',
+ 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-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => event.type === 'done' && event.turnContinuationId != null)).toBe(true);
+ });
+ await vi.waitFor(() => {
+ expect(yieldTurnStartCalls(host)).toHaveLength(1);
+ });
+ 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) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-finished-command',
+ 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-done',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Exit 0',
+ exitCode: 0,
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => event.type === 'done')).toBe(true);
+ });
+ expect(events.find((event) => event.type === 'done')?.turnContinuationId).toBeUndefined();
+ expect(handle.isTurnRunning?.()).toBe(false);
+ expect(yieldTurnStartCalls(host)).toHaveLength(0);
+ await handle.close();
+ });
+
+ it('does not mint a claim from a late item after turn/completed', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-late-item',
+ 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.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => event.type === 'done')).toBe(true);
+ });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'item-late',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226',
+ },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(events.filter((event) => event.type === 'done')).toHaveLength(1);
+ expect(events.find((event) => event.type === 'done')?.turnContinuationId).toBeUndefined();
+ expect(yieldTurnStartCalls(host)).toHaveLength(0);
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('emits a terminal error when the yield continuation cannot start', async () => {
+ const agent = new CodexAgent(createDeps());
+ let turnStarts = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ turnStarts += 1;
+ if (turnStarts === 1) return { turn: { id: 'turn-1' } };
+ throw new Error('Codex send cannot be accepted: stale host before turn/start');
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-start-fails',
+ 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-fail-start',
+ 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 === 'error'
+ && String((event.data as { reason?: string }).reason ?? '').includes('yield-continuation-start-failed')
+ ))).toBe(true);
+ });
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('cancels an awaiting yield continuation on Stop without replaying the original request', async () => {
+ const agent = new CodexAgent(createDeps());
+ let turnStarts = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ turnStarts += 1;
+ return { turn: { id: `turn-${turnStarts}` } };
+ }
+ if (method === Method.TurnInterrupt) return {};
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-stop',
+ 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-stop',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226',
+ },
+ });
+ handlers.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'inProgress' },
+ });
+ 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(yieldTurnStartCalls(host)).toHaveLength(1);
+ });
+ const claimedDone = events.find((event) => event.type === 'done' && event.turnContinuationId != null);
+ expect(claimedDone?.turnContinuationId).toEqual(expect.any(Number));
+ await handle.abort();
+ await waitForExpectation(() => {
+ const state = handle.beginTurnContinuationWait?.(claimedDone?.turnContinuationId);
+ expect(state === 'cancelled' || state === null).toBe(true);
+ });
+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {
+ threadId: 'start-thread-id',
+ turnId: 'turn-2',
+ });
+ 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) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-quoted-message',
+ 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-quoted',
+ type: 'agentMessage',
+ text: 'I will wait. Script running with cell ID 777',
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => event.type === 'done')).toBe(true);
+ });
+ expect(events.find((event) => event.type === 'done')?.turnContinuationId).toBeUndefined();
+ expect(yieldTurnStartCalls(host)).toHaveLength(0);
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('forgets an itemUpdated yield snapshot when the completed item has no marker', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-updated-then-finished',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemUpdated || !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.itemUpdated({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'item-exec-updated',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'inProgress',
+ aggregatedOutput: 'Script running with cell ID 226',
+ },
+ });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ item: {
+ id: 'item-exec-updated',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Exit 0',
+ exitCode: 0,
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => event.type === 'done')).toBe(true);
+ });
+ expect(events.find((event) => event.type === 'done')?.turnContinuationId).toBeUndefined();
+ expect(yieldTurnStartCalls(host)).toHaveLength(0);
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('emits a terminal error when a later continuation start is rejected without throwing', async () => {
+ const agent = new CodexAgent(createDeps());
+ let turnStarts = 0;
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ turnStarts += 1;
+ if (turnStarts === 1) return { turn: { id: 'turn-1' } };
+ throw new Error('turn/start failed: timeout');
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-ordinary-start-fail',
+ 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-timeout',
+ 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 === 'error'
+ && String((event.data as { reason?: string }).reason ?? '').includes('yield-continuation-start-failed')
+ ))).toBe(true);
+ });
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('settles the product turn after the continuation waits the yielded cell', 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-continuation-wait-settled',
+ 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-cross-turn',
+ type: 'commandExecution',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226\nWall time 11.0 seconds\nOutput:\n',
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await vi.waitFor(() => {
+ expect(yieldTurnStartCalls(host)).toHaveLength(1);
+ });
+ handlers.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-2', status: 'inProgress' },
+ });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-2',
+ item: {
+ id: 'item-wait-cross-turn',
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '226', max_tokens: 1000 }),
+ content: [{ type: 'output_text', text: 'Script completed\nWall time 4.2 seconds\nOutput:\n' }],
+ },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-2', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.filter((event) => event.type === 'done')).toHaveLength(2);
+ });
+ expect(events.some((event) => (
+ event.type === 'error'
+ && String((event.data as { reason?: string }).reason ?? '') === 'yield-continuation-lost-handle'
+ ))).toBe(false);
+ const dones = events.filter((event) => event.type === 'done');
+ expect(dones[0]?.turnContinuationId).toEqual(expect.any(Number));
+ expect(dones[1]?.turnContinuationId).toBeUndefined();
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('emits lost-handle without a later successful done after an empty continuation', 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-empty-continuation',
+ 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-empty',
+ 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.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-2', status: 'inProgress' },
+ });
+ handlers.turnCompleted({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-2', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.filter((event) => (
+ event.type === 'error'
+ && String((event.data as { reason?: string }).reason ?? '') === 'yield-continuation-lost-handle'
+ ))).toHaveLength(1);
+ });
+ const claimedDone = events.find((event) => event.type === 'done' && event.turnContinuationId != null);
+ expect(claimedDone).toBeDefined();
+ expect(events.filter((event) => event.type === 'done' && event.turnContinuationId == null)).toHaveLength(0);
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('does not append a successful done after exhausting yield retries', 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-retry-exhausted',
+ 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-retry-1',
+ 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.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-2', status: 'inProgress' },
+ });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-2',
+ item: {
+ id: 'item-exec-retry-2',
+ 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-2', status: 'completed' },
+ });
+ await vi.waitFor(() => {
+ expect(yieldTurnStartCalls(host)).toHaveLength(2);
+ });
+ handlers.turnStarted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-3', status: 'inProgress' },
+ });
+ handlers.itemCompleted({
+ threadId: 'start-thread-id',
+ turnId: 'turn-3',
+ item: {
+ id: 'item-exec-retry-3',
+ 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-3', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.filter((event) => (
+ event.type === 'error'
+ && String((event.data as { reason?: string }).reason ?? '') === 'yield-continuation-lost-handle'
+ ))).toHaveLength(1);
+ });
+ expect(events.filter((event) => event.type === 'done' && event.turnContinuationId == null)).toHaveLength(0);
+ expect(handle.isTurnRunning?.()).toBe(false);
+ await handle.close();
+ });
+
+ it('releases a yield claim on transport error so the session is not permanently busy', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-yield-transport-error',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.itemCompleted || !handlers.turnCompleted || !handlers.error) {
+ throw new Error('expected item, turn, and error 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-transport',
+ 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);
+ });
+ expect(handle.isTurnRunning?.()).toBe(true);
+ handlers.error({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ scope: 'transport',
+ willRetry: false,
+ error: { message: 'app-server disconnected' },
+ });
+ await waitForExpectation(() => {
+ expect(handle.isTurnRunning?.()).toBe(false);
+ });
+ await handle.close();
+ });
+});
+
describe('CodexAgent steer', () => {
it('rejects when the session is already closed before steering', async () => {
const agent = new CodexAgent(createDeps());
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 06df5ba3b9..8cfd290639 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -118,6 +118,13 @@ import {
} from './capability-routing.js';
import { scanCodexCustomizations } from './customization-scanner.js';
import { commandExecutionDisplayInput } from './command-display.js';
+import {
+ dedupeCells,
+ extractSettledYieldCellIdsFromCodexItem,
+ extractYieldedExecCellsFromCodexItem,
+ formatYieldContinuationPrompt,
+ type YieldedExecCell,
+} from './yielded-exec-cell.js';
import {
newCodexRuntimeState,
isAuthRelatedErrorMessage,
@@ -1156,9 +1163,21 @@ const CODEX_INHERITED_CAPABILITY_SELECTION = Symbol('codexInheritedCapabilitySel
// 计划实施/修订 turn 的**审查意图**:这些 turn 的 message 是固定内部串('Implement the plan.'),
// 直接拿它当 review intent 会让灰区 reviewer 完全看不到用户原始请求与获批计划(codex 报)。
const CODEX_AUTO_REVIEW_INTENT = Symbol('codexAutoReviewIntent');
+const CODEX_YIELD_CONTINUATION = Symbol('codexYieldContinuation');
+const YIELD_CONTINUATION_MAX_ATTEMPTS = 2;
type CodexInternalSendOptions = SendOptions & {
[CODEX_INHERITED_CAPABILITY_SELECTION]?: string;
[CODEX_AUTO_REVIEW_INTENT]?: string;
+ [CODEX_YIELD_CONTINUATION]?: number;
+};
+type YieldContinuationClaim = {
+ id: number;
+ state: 'awaiting' | 'active' | 'cancelled';
+ cells: YieldedExecCell[];
+ settledCellIds: Set<string>;
+ pendingBoundaryEvents: number;
+ settled: boolean;
+ retryCount: number;
};
const SYSTEM_PLAN_REVIEW_DISMISSAL_REASONS = new Set([
'no_listener_attached',
@@ -3101,6 +3120,238 @@ export class CodexAgent extends BaseAgent {
});
};
let isTurnInFlight = false;
+ const yieldedExecCellsByTurnId = new Map<string, Map<string, YieldedExecCell[]>>();
+ const yieldContinuationClaims = new Map<number, YieldContinuationClaim>();
+ const yieldContinuationListeners = new Set<(
+ continuationId: number,
+ state: 'awaiting' | 'active' | 'cancelled',
+ ) => void>();
+ let nextYieldContinuationId = 1;
+ let activeYieldContinuationId: number | null = null;
+ let yieldContinuationInFlight = false;
+ let yieldContinuationAbort: AbortController | null = null;
+ const emitYieldContinuationState = (
+ continuationId: number,
+ state: 'awaiting' | 'active' | 'cancelled',
+ ): void => {
+ for (const listener of [...yieldContinuationListeners]) {
+ try {
+ listener(continuationId, state);
+ } catch (e) {
+ log.warn('yield continuation listener threw', { error: String(e) });
+ }
+ }
+ };
+ const activeYieldContinuationClaim = (): YieldContinuationClaim | null =>
+ activeYieldContinuationId === null
+ ? null
+ : yieldContinuationClaims.get(activeYieldContinuationId) ?? null;
+ const releaseSettledYieldContinuationClaim = (claim: YieldContinuationClaim): void => {
+ if (!claim.settled || claim.pendingBoundaryEvents > 0) return;
+ yieldContinuationClaims.delete(claim.id);
+ };
+ const abortYieldContinuationSend = (): void => {
+ const pending = yieldContinuationAbort;
+ yieldContinuationAbort = null;
+ try {
+ pending?.abort();
+ } catch (error) {
+ log.debug('yield continuation abort controller threw', { error: String(error) });
+ }
+ };
+ const forgetSettledYieldCells = (turnId: string, item: unknown): void => {
+ const settledIds = extractSettledYieldCellIdsFromCodexItem(item);
+ if (settledIds.length === 0) return;
+ const existing = yieldedExecCellsByTurnId.get(turnId);
+ if (existing) {
+ for (const [itemId, cells] of [...existing.entries()]) {
+ const remaining = cells.filter((cell) => !settledIds.includes(cell.cellId));
+ if (remaining.length === 0) existing.delete(itemId);
+ else existing.set(itemId, remaining);
+ }
+ if (existing.size === 0) yieldedExecCellsByTurnId.delete(turnId);
+ }
+ const claim = activeYieldContinuationClaim();
+ if (!claim) return;
+ for (const cellId of settledIds) claim.settledCellIds.add(cellId);
+ };
+ const rememberYieldedExecCells = (
+ turnId: string | undefined,
+ item: unknown,
+ phase: 'updated' | 'completed',
+ ): void => {
+ if (!turnId) return;
+ if (completedTurnIds.has(turnId) || terminalErroredTurnIds.has(turnId)) return;
+ const record = item && typeof item === 'object' && !Array.isArray(item)
+ ? item as Record<string, unknown>
+ : null;
+ const itemId = typeof record?.id === 'string' && record.id
+ ? record.id
+ : '';
+ const cells = extractYieldedExecCellsFromCodexItem(item);
+ const existing = yieldedExecCellsByTurnId.get(turnId) ?? new Map<string, YieldedExecCell[]>();
+ if (cells.length === 0) {
+ if (phase === 'completed') existing.delete(itemId);
+ } else {
+ existing.set(itemId, cells);
+ }
+ if (existing.size === 0) yieldedExecCellsByTurnId.delete(turnId);
+ else yieldedExecCellsByTurnId.set(turnId, existing);
+ forgetSettledYieldCells(turnId, item);
+ };
+ const cellsForCompletedTurn = (turnId: string): YieldedExecCell[] => {
+ const byItem = yieldedExecCellsByTurnId.get(turnId);
+ if (!byItem) return [];
+ return dedupeCells([...byItem.values()].flat());
+ };
+ const attachYieldContinuationClaim = (
+ event: AgentEvent,
+ claim: YieldContinuationClaim,
+ ): void => {
+ event.turnContinuationId = claim.id;
+ claim.pendingBoundaryEvents += 1;
+ };
+ const mintYieldContinuationClaim = (
+ cells: YieldedExecCell[],
+ retryCount: number,
+ ): YieldContinuationClaim => {
+ const claim: YieldContinuationClaim = {
+ id: nextYieldContinuationId++,
+ state: 'awaiting',
+ cells,
+ settledCellIds: new Set(),
+ pendingBoundaryEvents: 0,
+ settled: false,
+ retryCount,
+ };
+ yieldContinuationClaims.set(claim.id, claim);
+ activeYieldContinuationId = claim.id;
+ log.info('yield continuation claim created', {
+ continuationId: claim.id,
+ cellIds: cells.map((cell) => cell.cellId),
+ retryCount,
+ });
+ return claim;
+ };
+ const cancelActiveYieldContinuation = (reason: string): YieldContinuationClaim | null => {
+ const claim = activeYieldContinuationClaim();
+ abortYieldContinuationSend();
+ if (!claim || claim.settled) return null;
+ claim.state = 'cancelled';
+ claim.settled = true;
+ activeYieldContinuationId = null;
+ yieldContinuationInFlight = false;
+ log.info('yield continuation cancelled', { reason, continuationId: claim.id });
+ emitYieldContinuationState(claim.id, 'cancelled');
+ releaseSettledYieldContinuationClaim(claim);
+ return claim;
+ };
+ const discardYieldContinuationClaims = (reason: string): void => {
+ abortYieldContinuationSend();
+ if (yieldContinuationClaims.size > 0) {
+ log.debug('discarding yield continuation claims', {
+ reason,
+ continuationIds: [...yieldContinuationClaims.keys()],
+ });
+ }
+ activeYieldContinuationId = null;
+ yieldContinuationInFlight = false;
+ yieldedExecCellsByTurnId.clear();
+ for (const claim of yieldContinuationClaims.values()) {
+ claim.settled = true;
+ releaseSettledYieldContinuationClaim(claim);
+ }
+ yieldContinuationClaims.clear();
+ };
+ const releaseYieldContinuationEvent = (event: AgentEvent): void => {
+ if (event.turnContinuationId === undefined) return;
+ const claim = yieldContinuationClaims.get(event.turnContinuationId);
+ if (!claim) return;
+ claim.pendingBoundaryEvents = Math.max(0, claim.pendingBoundaryEvents - 1);
+ releaseSettledYieldContinuationClaim(claim);
+ };
+ const emitYieldContinuationFailure = (opts: {
+ reason: 'yield-continuation-start-failed' | 'yield-continuation-lost-handle';
+ message: string;
+ cells: YieldedExecCell[];
+ detail?: string;
+ }): void => {
+ log.warn(
+ opts.reason === 'yield-continuation-start-failed'
+ ? 'yield continuation turn failed to start'
+ : 'yield continuation lost exec cell',
+ {
+ reason: opts.reason,
+ ...(opts.detail ? { detail: opts.detail } : {}),
+ cellIds: opts.cells.map((cell) => cell.cellId),
+ },
+ );
+ eventQueue.push({
+ type: 'error',
+ data: {
+ message: opts.message,
+ isTerminal: true,
+ reason: opts.reason,
+ },
+ source: 'codex',
+ });
+ eventQueue.push({
+ type: 'status',
+ data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },
+ source: 'codex',
+ });
+ };
+ const emitYieldContinuationStartFailure = (error: unknown, cells: YieldedExecCell[]): void => {
+ emitYieldContinuationFailure({
+ reason: 'yield-continuation-start-failed',
+ message: `yield continuation turn failed to start: ${String(error)}`,
+ cells,
+ detail: String(error),
+ });
+ };
+ const emitYieldContinuationLostHandle = (cells: YieldedExecCell[], reason: string): void => {
+ emitYieldContinuationFailure({
+ reason: 'yield-continuation-lost-handle',
+ message: `Foreground exec cell ${cells.map((cell) => cell.cellId).join(', ')} was lost after the previous turn completed.`,
+ cells,
+ detail: reason,
+ });
+ };
+ async function startYieldContinuation(claim: YieldContinuationClaim): Promise<void> {
+ if (closed || yieldContinuationInFlight || claim.state !== 'awaiting' || claim.settled) return;
+ yieldContinuationInFlight = true;
+ claim.state = 'active';
+ emitYieldContinuationState(claim.id, 'active');
+ const abort = new AbortController();
+ yieldContinuationAbort = abort;
+ const sendOptions: CodexInternalSendOptions = {
+ [CODEX_YIELD_CONTINUATION]: claim.retryCount + 1,
+ throwOnStartFailure: true,
+ signal: abort.signal,
+ };
+ try {
+ await handle.send(
+ { type: 'user', content: formatYieldContinuationPrompt(claim.cells) },
+ sendOptions,
+ );
+ } catch (error) {
+ const alreadySettled = claim.settled || abort.signal.aborted;
+ if (activeYieldContinuationId === claim.id) activeYieldContinuationId = null;
+ yieldContinuationInFlight = false;
+ if (alreadySettled) {
+ releaseSettledYieldContinuationClaim(claim);
+ return;
+ }
+ claim.settled = true;
+ emitYieldContinuationStartFailure(error, claim.cells);
+ releaseSettledYieldContinuationClaim(claim);
+ } finally {
+ if (yieldContinuationAbort === abort) yieldContinuationAbort = null;
+ if (claim.settled || activeYieldContinuationId !== claim.id) {
+ yieldContinuationInFlight = false;
+ }
+ }
+ }
/**
* 本 handle 上「起过多少个 turn」的单调计数器,每个新 turn 首次被置活时 +1。
*
@@ -6247,7 +6498,7 @@ export class CodexAgent extends BaseAgent {
clearUpstreamIdle();
if (upstreamIdleTimeoutMs <= 0) return;
if (closed || !isTurnInFlight) return;
- // 工具执行 / 等审批期间 ball 不在上游,不计 idle 配额。
+ // 工具执行 / 等审批 / yield cell 等待期间 ball 不在上游,不计 idle 配额。
if (pendingToolItemIds.size > 0) return;
upstreamIdleRemainingMs = upstreamIdleTimeoutMs;
armUpstreamIdleSlice();
@@ -6697,7 +6948,9 @@ export class CodexAgent extends BaseAgent {
armUpstreamIdle();
observeReconnectStallEvent(ev);
}
- return rawEventQueuePush(ev);
+ const accepted = rawEventQueuePush(ev);
+ if (!accepted) releaseYieldContinuationEvent(ev);
+ return accepted;
};
// ── ServerRequest handlers (Phase 2 approval, Phase 5 dismiss-on-mode-change) ──
@@ -8482,6 +8735,8 @@ export class CodexAgent extends BaseAgent {
detachPendingAskUserForSuccessfulTurn(turn.id);
} else {
dismissPendingUserInputForTurn(turn.id, `turn_${turn.status}`);
+ yieldedExecCellsByTurnId.delete(turn.id);
+ cancelActiveYieldContinuation(`turn_${turn.status}`);
}
clearActiveToolContextsForTurn(turn.id);
const overlapsActiveTurn = suppressTerminalUi && currentTurnId !== null && currentTurnId !== turn.id;
@@ -8651,42 +8906,88 @@ export class CodexAgent extends BaseAgent {
return;
}
- eventQueue.push({
- type: 'status',
- data: {
- status: 'Done',
- ...attachLiveGeneration(endSnap, {
- outputTokens: realTurnUsage.output,
- closedDurationMs: translatorRt.generationDurationMs,
- openStartedAt: null,
- reliable: translatorRt.generationTimingReliable,
- }),
- isRunning: false,
- },
- source: 'codex',
- });
- // 真实 per-turn 用量 (host 的 today chip / daily_model_usage 记账消费):
- // promptTokens = 本 turn 未命中缓存的输入 (不再是 contextTokens 上下文快照)
- // completionTokens = 本 turn outputTokens(已包含 reasoning 子集,不重复相加)
- // reasoningTokens = reasoning 明细子集,仅展示/诊断,不再参与总量求和
- // cachedTokens = 本 turn 命中缓存的输入
- // segments = 每次 total cursor 前进对应的请求级 usage;定价方必须
- // 逐段选长上下文档位后再求和,不能拿 turn aggregate 选档
- // 契约: 本 payload **永远是 per-turn 增量语义**, 消费方 (today chip /
- // daily_model_usage 记账) 直接累加, 不做任何 delta 化。整个 turn 没收到
- // tokenUsage/updated 时就是全 0 (该 turn 不记账) — 不退回 contextTokens:
- // 在直接累加的消费方手里, 上下文快照会被当成一笔巨额输入, 高估远糟于漏记。
- eventQueue.push({
- type: 'done',
- data: {
- type: 'codex/event/task_complete',
- usage: codexDoneUsage,
- raw: turn,
- plan: latestPlanByTurn.get(turn.id) ?? null,
- },
- source: 'codex',
- });
+ const existingYieldClaim = activeYieldContinuationClaim();
+ const yieldedCells = cellsForCompletedTurn(turn.id);
+ yieldedExecCellsByTurnId.delete(turn.id);
+ let yieldClaim: YieldContinuationClaim | null = null;
+ let suppressSuccessfulYieldBoundary = false;
+ if (existingYieldClaim?.state === 'awaiting') {
+ yieldClaim = existingYieldClaim;
+ if (yieldedCells.length > 0) {
+ yieldClaim.cells = dedupeCells([...yieldClaim.cells, ...yieldedCells]);
+ }
+ } else if (existingYieldClaim?.state === 'active') {
+ existingYieldClaim.settled = true;
+ activeYieldContinuationId = null;
+ yieldContinuationInFlight = false;
+ releaseSettledYieldContinuationClaim(existingYieldClaim);
+ const outstandingCells = dedupeCells([
+ ...existingYieldClaim.cells,
+ ...yieldedCells,
+ ]).filter((cell) => !existingYieldClaim.settledCellIds.has(cell.cellId));
+ const retryCount = existingYieldClaim.retryCount + 1;
+ if (outstandingCells.length === 0) {
+ // Continuation waited the claimed cell(s) to completion. This is the
+ // product terminal, not a lost handle.
+ } else if (yieldedCells.length === 0 || retryCount >= YIELD_CONTINUATION_MAX_ATTEMPTS) {
+ emitYieldContinuationLostHandle(
+ outstandingCells,
+ yieldedCells.length === 0 ? 'empty_completion' : 'retry_exhausted',
+ );
+ suppressSuccessfulYieldBoundary = true;
+ } else {
+ yieldClaim = mintYieldContinuationClaim(outstandingCells, retryCount);
+ }
+ } else if (yieldedCells.length > 0) {
+ yieldClaim = mintYieldContinuationClaim(yieldedCells, 0);
+ }
+ if (!suppressSuccessfulYieldBoundary) {
+ const idleStatusEvent: AgentEvent = {
+ type: 'status',
+ data: {
+ status: 'Done',
+ ...attachLiveGeneration(endSnap, {
+ outputTokens: realTurnUsage.output,
+ closedDurationMs: translatorRt.generationDurationMs,
+ openStartedAt: null,
+ reliable: translatorRt.generationTimingReliable,
+ }),
+ isRunning: false,
+ },
+ source: 'codex',
+ };
+ const doneEvent: AgentEvent = {
+ type: 'done',
+ data: {
+ type: 'codex/event/task_complete',
+ usage: codexDoneUsage,
+ raw: turn,
+ plan: latestPlanByTurn.get(turn.id) ?? null,
+ },
+ source: 'codex',
+ };
+ if (yieldClaim?.state === 'awaiting') {
+ attachYieldContinuationClaim(idleStatusEvent, yieldClaim);
+ attachYieldContinuationClaim(doneEvent, yieldClaim);
+ }
+ eventQueue.push(idleStatusEvent);
+ // 真实 per-turn 用量 (host 的 today chip / daily_model_usage 记账消费):
+ // promptTokens = 本 turn 未命中缓存的输入 (不再是 contextTokens 上下文快照)
+ // completionTokens = 本 turn outputTokens(已包含 reasoning 子集,不重复相加)
+ // reasoningTokens = reasoning 明细子集,仅展示/诊断,不再参与总量求和
+ // cachedTokens = 本 turn 命中缓存的输入
+ // segments = 每次 total cursor 前进对应的请求级 usage;定价方必须
+ // 逐段选长上下文档位后再求和,不能拿 turn aggregate 选档
+ // 契约: 本 payload **永远是 per-turn 增量语义**, 消费方 (today chip /
+ // daily_model_usage 记账) 直接累加, 不做任何 delta 化。整个 turn 没收到
+ // tokenUsage/updated 时就是全 0 (该 turn 不记账) — 不退回 contextTokens:
+ // 在直接累加的消费方手里, 上下文快照会被当成一笔巨额输入, 高估远糟于漏记。
+ eventQueue.push(doneEvent);
+ }
latestPlanByTurn.delete(turn.id);
+ if (yieldClaim?.state === 'awaiting') {
+ void startYieldContinuation(yieldClaim);
+ }
// 计划模式: plan turn 正常收尾且产出了 proposed plan → 发起审批闭环。
// 放在 done 之后 (AsyncQueue FIFO), renderer 先做完 turn 收尾再挂 plan 卡片。
// 空跑(模型没产出 <proposed_plan>, 例如直接回答了问题) → 循环结束,
@@ -9448,12 +9749,15 @@ export class CodexAgent extends BaseAgent {
const hadPendingWork =
isTurnInFlight
|| isTurnStartPending
- || overloadRetryPending();
+ || overloadRetryPending()
+ || yieldContinuationInFlight
+ || activeYieldContinuationClaim() != null;
if (!hadPendingWork) {
log.info('idle Codex session invalidated by forced host retirement', { threadId });
eventQueue.end();
return;
}
+ discardYieldContinuationClaims('app-server force-retired');
// turn/start 可能尚未返回 id。先把所有在途请求标为已收口并隔离,随后 RPC
// reject/迟到 resolve 时复用既有 finally/墓碑路径,不再发第二组终态。
@@ -9919,6 +10223,7 @@ export class CodexAgent extends BaseAgent {
producedOutputTurnIds.add(params.turnId);
}
noteActiveToolContext(params.item, params.turnId);
+ rememberYieldedExecCells(params.turnId, params.item, 'updated');
// updated 也要登记映射,顺序与 started / completed 一致(先登记 → 翻译 → 后发重放帧)。
// V1 的 spawn 是长跑 item(started → updated* → completed):started 那帧若没到我们手里
// (turn 缓冲、stale turn 丢弃、上游省略),映射就要一直等到 completed 才建立 —— 期间
@@ -9982,6 +10287,7 @@ export class CodexAgent extends BaseAgent {
producedOutputTurnIds.add(params.turnId);
}
completeActiveToolContext(params.item, params.turnId);
+ rememberYieldedExecCells(params.turnId, params.item, 'completed');
// This late item belongs to an already-terminal parent. The parent
// cleanup already cleared its pending tools; touching the shared
// lifecycle set here would re-arm the currently active turn's idle
@@ -10147,7 +10453,6 @@ export class CodexAgent extends BaseAgent {
// codex R12 P1): 合法 → 激活后重放走正常终端路径收口 send; 孤儿 →
// 丢弃, 不得让孤儿 error 终结合法 send。
if (enqueueIfBufferedTurn(params.turnId, () => handlers.error?.(params))) return;
- if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
let effectiveParams = params;
let isTerminalError = params.willRetry !== true;
const isTransportError = params.scope === 'transport';
@@ -10169,7 +10474,9 @@ export class CodexAgent extends BaseAgent {
terminalDescendantTurnIds.clear();
submittedUserInputByTurn.clear();
clearAllPendingUserInputInteractions();
+ cancelActiveYieldContinuation('transport error');
}
+ if (!isTransportError && shouldIgnoreStaleTurnEvent(params.turnId)) return;
const targetsPendingTurn = isTurnStartPending && currentTurnId === null && Boolean(params.turnId);
// 空 turnId 的容量拒绝: 过载重投的 RPC 还在飞、而它的 turnStarted 尚未到达时,
// currentTurnId 是 null 且 isTurnInFlight 是 false —— 上面两条既有判据都不成立,
@@ -10336,7 +10643,11 @@ export class CodexAgent extends BaseAgent {
}
}
}
- const wasTurnRunning = isTurnInFlight || targetsPendingTurn;
+ const wasTurnRunning =
+ isTurnInFlight
+ || targetsPendingTurn
+ || yieldContinuationInFlight
+ || activeYieldContinuationClaim() != null;
if (isTerminalError && targetsCurrentTurn && !isTransportError) {
const recoveryTurnId = effectiveParams.turnId || currentTurnId || '';
// error notification 只登记恢复意图并保持 logical turn 运行;
@@ -10464,6 +10775,7 @@ export class CodexAgent extends BaseAgent {
// close 时 buffer 里可能还有等对账的挂起请求 (codex R17 P2):
// 统一按拒绝释放, 否则 handler 永远悬挂, dispatchServerRequest
// 永不返回, server 侧请求卡死。
+ discardYieldContinuationClaims('session closed');
abandonBufferedTurns('session closed');
abandonPendingCapabilitySteers();
// 把挂起的 approval 强制 deny + emit interaction_dismissed (UI 关 dialog),
@@ -10520,6 +10832,10 @@ export class CodexAgent extends BaseAgent {
if (rejectClosedOrCancelledSend(sendOpts, 'before start')) {
return;
}
+ const yieldAttempt = (sendOpts as CodexInternalSendOptions | undefined)?.[CODEX_YIELD_CONTINUATION];
+ if (yieldAttempt == null) {
+ cancelActiveYieldContinuation('new send');
+ }
// 用户开启新 turn = 旧重连序列作废;deadline 不得跨 turn 误伤新请求。
clearReconnectStall();
if (sendOpts) handle.validateSendOptions?.(sendOpts);
@@ -11037,6 +11353,20 @@ export class CodexAgent extends BaseAgent {
// 本地取消边界直接 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);
@@ -11495,6 +11825,22 @@ export class CodexAgent extends BaseAgent {
},
async abort() {
+ const cancelledYield = cancelActiveYieldContinuation('aborted');
+ if (cancelledYield && !currentTurnId) {
+ eventQueue.push({
+ type: 'done',
+ data: {
+ type: 'codex/event/task_complete',
+ cancelled: true,
+ },
+ source: 'codex',
+ });
+ eventQueue.push({
+ type: 'status',
+ data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },
+ source: 'codex',
+ });
+ }
clearReconnectStall();
// 用户点 Stop = 明确不想继续这一轮,挂起的过载重投必须一起撤掉。
// 放在 currentTurnId 判空之前:重投等待期间 turn 已死、currentTurnId 为
@@ -11537,7 +11883,16 @@ export class CodexAgent extends BaseAgent {
},
events(): AsyncIterable<AgentEvent> {
- return eventQueue;
+ const consumedEventStream = async function* (): AsyncGenerator<AgentEvent> {
+ for await (const event of eventQueue) {
+ try {
+ yield event;
+ } finally {
+ releaseYieldContinuationEvent(event);
+ }
+ }
+ };
+ return consumedEventStream();
},
getUsageSnapshot(): UsageSnapshot {
@@ -11824,7 +12179,23 @@ export class CodexAgent extends BaseAgent {
// idle 语义——终态先于 turn/start 响应到达时(协议允许的乱序),
// coordinator 要看到 idle 才能收口,否则 send 挂死(既有用例
// "accepts terminal error before TurnStartResponse…" 锁的就是这条)。
- return isTurnInFlight || overloadRetryPending();
+ //
+ // yield continuation claim 把 provider turn/completed 与产品结束拆开:
+ // 等 cell / 续段尚未启动时 isTurnInFlight 已是 false, 但仍是同一产品请求。
+ return isTurnInFlight
+ || overloadRetryPending()
+ || yieldContinuationInFlight
+ || activeYieldContinuationClaim() != null;
+ },
+
+ beginTurnContinuationWait(continuationId?: number) {
+ if (continuationId === undefined) return null;
+ return yieldContinuationClaims.get(continuationId)?.state ?? null;
+ },
+
+ onTurnContinuationChange(listener) {
+ yieldContinuationListeners.add(listener);
+ return () => yieldContinuationListeners.delete(listener);
},
};
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
new file mode 100644
index 0000000000..e4f9d3d807
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/yielded-exec-cell.test.ts
@@ -0,0 +1,140 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ extractSettledYieldCellIdsFromCodexItem,
+ extractYieldedExecCellIds,
+ extractYieldedExecCellsFromCodexItem,
+ formatYieldContinuationPrompt,
+} from './yielded-exec-cell.js';
+
+describe('extractYieldedExecCellIds', () => {
+ it('locks the #3179 rollout yield shape', () => {
+ expect(extractYieldedExecCellIds(
+ 'Script running with cell ID 226\nWall time 11.0 seconds\nOutput:\n',
+ )).toEqual(['226']);
+ });
+
+ it('keeps later cells in order and dedupes repeats', () => {
+ expect(extractYieldedExecCellIds([
+ 'Script running with cell ID 226',
+ 'Script running with cell ID 229 Wall time 11.0 seconds Output:',
+ 'Script running with cell ID 226',
+ ].join('\n'))).toEqual(['226', '229']);
+ });
+
+ it('ignores finished command output without a yield marker', () => {
+ expect(extractYieldedExecCellIds('Exit 0\n\n> tsc --noEmit\n')).toEqual([]);
+ });
+});
+
+describe('extractYieldedExecCellsFromCodexItem', () => {
+ it('reads commandExecution.aggregatedOutput', () => {
+ expect(extractYieldedExecCellsFromCodexItem({
+ type: 'commandExecution',
+ id: 'item-1',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Script running with cell ID 226 Wall time 11.0 seconds Output:',
+ })).toEqual([{
+ cellId: '226',
+ command: 'pnpm --filter desktop run typecheck',
+ }]);
+ });
+
+ it('reads Responses/proxy function_call(exec_command) output text', () => {
+ expect(extractYieldedExecCellsFromCodexItem({
+ type: 'function_call',
+ name: 'exec_command',
+ arguments: JSON.stringify({
+ cmd: 'pnpm --filter desktop run typecheck',
+ workdir: '/repo',
+ yield_time_ms: 10_000,
+ }),
+ content: [{ type: 'output_text', text: 'Script running with cell ID 229' }],
+ })).toEqual([{
+ cellId: '229',
+ command: 'pnpm --filter desktop run typecheck',
+ }]);
+ });
+
+ it('does not treat a finished exec item as a yielded cell', () => {
+ expect(extractYieldedExecCellsFromCodexItem({
+ type: 'commandExecution',
+ id: 'item-2',
+ command: 'pnpm --filter desktop run typecheck',
+ status: 'completed',
+ aggregatedOutput: 'Exit 0',
+ exitCode: 0,
+ })).toEqual([]);
+ });
+
+ it('ignores yield text quoted by an agentMessage', () => {
+ expect(extractYieldedExecCellsFromCodexItem({
+ type: 'agentMessage',
+ text: 'I will wait. Script running with cell ID 777',
+ })).toEqual([]);
+ });
+
+ it('still finds a yield marker near the end of a long exec output', () => {
+ const padding = 'x'.repeat(20_000);
+ expect(extractYieldedExecCellsFromCodexItem({
+ type: 'commandExecution',
+ id: 'item-late-marker',
+ command: 'pnpm --filter desktop run typecheck',
+ aggregatedOutput: `${padding}\nScript running with cell ID 226`,
+ })).toEqual([{
+ cellId: '226',
+ command: 'pnpm --filter desktop run typecheck',
+ }]);
+ });
+});
+
+describe('extractSettledYieldCellIdsFromCodexItem', () => {
+ it('clears a cell after wait reports Script completed', () => {
+ expect(extractSettledYieldCellIdsFromCodexItem({
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '11', max_tokens: 1000 }),
+ content: [{ type: 'output_text', text: 'Script completed\nWall time 0.1 seconds\nOutput:\n' }],
+ })).toEqual(['11']);
+ });
+
+ it('keeps a cell outstanding when wait still yields the same cell', () => {
+ expect(extractSettledYieldCellIdsFromCodexItem({
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '11', yield_time_ms: 1000 }),
+ content: [{ type: 'output_text', text: 'Script running with cell ID 11\nWall time 1.0 seconds\nOutput:\n' }],
+ })).toEqual([]);
+ });
+
+ it('does not settle on a wait adapter error', () => {
+ expect(extractSettledYieldCellIdsFromCodexItem({
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '11' }),
+ content: [{ type: 'output_text', text: 'unexpected adapter error' }],
+ })).toEqual([]);
+ });
+
+ it('does not settle cell 11 from a running marker for a different cell', () => {
+ expect(extractSettledYieldCellIdsFromCodexItem({
+ type: 'function_call',
+ name: 'wait',
+ arguments: JSON.stringify({ cell_id: '11' }),
+ content: [{ type: 'output_text', text: 'Script running with cell ID 12' }],
+ })).toEqual([]);
+ });
+});
+
+describe('formatYieldContinuationPrompt', () => {
+ it('asks the next provider turn to wait the same cells', () => {
+ const prompt = formatYieldContinuationPrompt([
+ { cellId: '226', command: 'pnpm --filter desktop run typecheck' },
+ ]);
+ expect(prompt).toContain('Wait for cell ID 226');
+ expect(prompt).toContain('Do not start a new task');
+ expect(prompt).toContain('report that it was lost');
+ expect(prompt).not.toContain('pnpm --filter desktop run typecheck'.repeat(2));
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/yielded-exec-cell.ts b/packages/maker-core/src/agents/codex/yielded-exec-cell.ts
new file mode 100644
index 0000000000..2ca64061ec
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/yielded-exec-cell.ts
@@ -0,0 +1,180 @@
+/**
+ * Codex adapter-local detector for `functions.exec` yield.
+ *
+ * app-server 不暴露 cell 状态或 wait RPC。yield 的权威产物目前只活在工具输出文案里
+ * (#3179 rollout: "Script running with cell ID 226")。本模块把那条文案降格为
+ * **检测启发式**:只用来铸造有界 continuation claim,不参与产品「是否交付完」判断。
+ *
+ * 协议级 executionHandle 是跨仓长期项;在那之前,漏判等于今天的假完成,误判只是
+ * 多跑一轮有界续段。
+ */
+
+export interface YieldedExecCell {
+ cellId: string;
+ command?: string;
+}
+
+/** Locked to the #3179 Codex rollout shape. Do not loosen without a new fixture. */
+export const YIELDED_EXEC_CELL_RE = /Script running with cell ID[ \t]+(\d+)/gi;
+
+const MAX_SCAN_CHARS = 16_384;
+
+export function extractYieldedExecCellIds(text: string | null | undefined): string[] {
+ if (!text) return [];
+ const sample = textForScan(text);
+ const ids: string[] = [];
+ const seen = new Set<string>();
+ YIELDED_EXEC_CELL_RE.lastIndex = 0;
+ for (const match of sample.matchAll(YIELDED_EXEC_CELL_RE)) {
+ const cellId = match[1];
+ if (!cellId || seen.has(cellId)) continue;
+ seen.add(cellId);
+ ids.push(cellId);
+ }
+ return ids;
+}
+
+export function extractYieldedExecCellsFromCodexItem(item: unknown): YieldedExecCell[] {
+ const record = asRecord(item);
+ if (!record || !isApprovedYieldItem(record)) return [];
+ const command = commandFromCodexItem(record);
+ const ids = extractYieldedExecCellIds(collectItemText(record));
+ return ids.map((cellId) => (
+ command ? { cellId, command } : { cellId }
+ ));
+}
+
+/**
+ * Healthy Codex turns yield an exec cell, then call `wait` until that cell
+ * finishes. The original exec item still contains the yield marker, so the
+ * wait result is the only signal that the cell is no longer outstanding.
+ */
+export function extractSettledYieldCellIdsFromCodexItem(item: unknown): string[] {
+ 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 (!WAIT_SETTLED_RE.test(output)) return [];
+ if (extractYieldedExecCellIds(output).includes(cellId)) return [];
+ return [cellId];
+}
+
+export function formatYieldContinuationPrompt(cells: readonly YieldedExecCell[]): string {
+ const unique = dedupeCells(cells);
+ const cellList = unique.map((cell) => {
+ const command = cell.command?.trim();
+ return command
+ ? `- cell ID ${cell.cellId} (\`${truncateCommand(command)}\`)`
+ : `- cell ID ${cell.cellId}`;
+ }).join('\n');
+ return [
+ 'A foreground exec cell is still running after the previous turn completed.',
+ 'Wait for every listed cell and finish the original user request. Do not start a new task.',
+ 'If a cell is gone, report that it was lost instead of rerunning the command.',
+ unique.length === 1 ? `Wait for cell ID ${unique[0]!.cellId}.` : 'Wait for:',
+ ...(unique.length > 1 ? [cellList] : []),
+ ].join('\n');
+}
+
+const WAIT_SETTLED_RE = /Script (?:completed|terminated)/i;
+
+function isApprovedYieldItem(record: Record<string, unknown>): boolean {
+ if (record.type === 'commandExecution') return true;
+ return record.type === 'function_call' && record.name === 'exec_command';
+}
+
+function isWaitItem(record: Record<string, unknown>): boolean {
+ return record.type === 'function_call' && record.name === 'wait';
+}
+
+function textForScan(text: string): string {
+ if (text.length <= MAX_SCAN_CHARS) return text;
+ return `${text.slice(0, MAX_SCAN_CHARS)}\n${text.slice(-MAX_SCAN_CHARS)}`;
+}
+
+export function dedupeCells(cells: readonly YieldedExecCell[]): YieldedExecCell[] {
+ const seen = new Set<string>();
+ const out: YieldedExecCell[] = [];
+ for (const cell of cells) {
+ if (seen.has(cell.cellId)) continue;
+ seen.add(cell.cellId);
+ out.push(cell);
+ }
+ return out;
+}
+
+function truncateCommand(command: string): string {
+ const compact = command.replace(/\s+/g, ' ').trim();
+ return compact.length > 160 ? `${compact.slice(0, 157)}...` : compact;
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value && typeof value === 'object' && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null;
+}
+
+function commandFromCodexItem(record: Record<string, unknown>): string | undefined {
+ if (typeof record.command === 'string' && record.command.trim()) return record.command;
+ if (record.type === 'function_call' && record.name === 'exec_command') {
+ const args = parseJsonObject(record.arguments);
+ const command = firstString(args, ['cmd', 'command']);
+ if (command) return command;
+ }
+ const nestedArgs = asRecord(record.arguments) ?? asRecord(record.input);
+ return firstString(nestedArgs, ['cmd', 'command']);
+}
+
+function collectItemText(record: Record<string, unknown>): string {
+ const parts: string[] = [];
+ pushText(parts, record.aggregatedOutput);
+ pushText(parts, record.output);
+ pushText(parts, record.result);
+ pushText(parts, record.text);
+ if (Array.isArray(record.content)) {
+ for (const entry of record.content) {
+ if (typeof entry === 'string') pushText(parts, entry);
+ const nested = asRecord(entry);
+ if (!nested) continue;
+ pushText(parts, nested.text);
+ pushText(parts, nested.output);
+ }
+ } else {
+ pushText(parts, record.content);
+ }
+ if (Array.isArray(record.contentItems)) {
+ for (const entry of record.contentItems) {
+ const nested = asRecord(entry);
+ if (!nested) continue;
+ pushText(parts, nested.text);
+ }
+ }
+ return parts.join('\n');
+}
+
+function pushText(parts: string[], value: unknown): void {
+ if (typeof value === 'string' && value) parts.push(value);
+}
+
+function parseJsonObject(value: unknown): Record<string, unknown> | null {
+ if (typeof value !== 'string') return asRecord(value);
+ try {
+ return asRecord(JSON.parse(value));
+ } catch {
+ return null;
+ }
+}
+
+function firstString(
+ record: Record<string, unknown> | null,
+ keys: readonly string[],
+): string | undefined {
+ if (!record) return undefined;
+ for (const key of keys) {
+ const value = record[key];
+ if (typeof value === 'string' && value.trim()) return value;
+ }
+ return undefined;
+}