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): 改按调用节奏识别 Codex 脚本连发,撤回按回应分组

Dash4a8dd73fe194
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 255b06c1e3..dad47fc750 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -50,13 +50,13 @@ Claude Code 在原有 per-sidechain 回调里检测所有模型;Pi / Codex 在
失败、混合执行、重定向或源文件读取不套用该例外。等待调用不清空普通调用的循环轨迹。
这仍是有界启发式,不是任意长度循环的证明,也不以没有文件改动作为失败依据。
-Codex code mode 下一次模型回应是一段脚本,app-server 只逐个上报脚本内部的工具调用,
-不上报脚本本身。translator 给 `tool_use` 标上 `modelResponseId`:回应结束时的
-`thread/tokenUsage/updated` 与新回应开头的 reasoning / agentMessage item 都推进回应边界,
-多推进只会把回应拆细、退回逐次计数。同一回应内重复出现的完整结果或调用不推进完全相同、
-短窗口、轮转与快速连续 30 次判据,只续接完全相同结果的 60 分钟时长上限;模型逐次回应
-重复同一调用照常计数(2026-10-18 脚本点保存后连续截快照等页面更新被误判)。
-Pi 与 Claude Code 不带该标识,行为不变。
+Codex code mode 下脚本在后台运行,模型同时继续回应;app-server 只逐个上报脚本内部的工具调用,
+不标注调用属于哪段脚本,用量通知与思考 item 也会落在同一段脚本的调用之间,所以不能按“模型回应”
+分组。Codex 的 Guard 改用调用节奏区分:本次调用开始距上一次普通结果到达不足 2 秒
+(`CODEX_SCRIPT_CHAINED_CALL_GAP_MS`,一次模型采样不可能这么快)视为脚本连发,按节奏轮询处理——
+不推进完全相同、窗口、轮转判据,也不取消进行中的复核,只续接完全相同结果的 60 分钟上限;
+模型逐次重复同一调用,每次间隔都有采样时间,照常计数。代价:脚本自身的无界死循环只会被
+60 分钟上限抓到(2026-10-18 脚本点保存后连续截快照等页面更新被误判)。Pi 与 Claude Code 不启用。
节奏与复核:一次普通调用若距上一次普通调用开始已有至少 30 秒(`sleep` 后再查 CI、
命令内自带等待或慢推理),或其结果距上一次普通结果到达已有至少 30 秒(模型一次发出
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 1813c25c39..396e40efe0 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -12294,8 +12294,6 @@ assertRouteCurrent();
tokenUsageUpdated: (params) => {
if (enqueueIfBufferedTurn(params.turnId, () => handlers.tokenUsageUpdated?.(params))) return;
if (shouldIgnoreStaleTurnEvent(params.turnId)) return;
- // 每次模型回应结束上报一次用量;多记一次边界只会让循环检测更保守。
- translatorRt.modelResponseSeq += 1;
const reportedWindow = params.tokenUsage?.modelContextWindow;
if (typeof reportedWindow === 'number' && Number.isFinite(reportedWindow) && reportedWindow > 0) {
lastNativeContextWindowTurnId = params.turnId || null;
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index bd1d6e7d82..fd1105b446 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -129,12 +129,6 @@ export interface CodexRuntimeState {
* turnStarted 时与 lastAuthErrorKey 一起清。
*/
networkRetryNotice: { key: string; count: number; emitted: boolean } | null;
- /**
- * 模型回应边界计数。回应结束时的 thread/tokenUsage/updated 与新回应开头的思考/文字
- * item 都会推进它;两次推进之间的工具调用来自同一次回应(code mode 下即同一段脚本),
- * 供工具循环检测合并脚本内的重复调用。多推进只会把回应拆细,检测退回逐次计数。
- */
- modelResponseSeq: number;
}
export function newCodexRuntimeState(): CodexRuntimeState {
@@ -161,7 +155,6 @@ export function newCodexRuntimeState(): CodexRuntimeState {
emittedWebSearchInput: new Map(),
lastAuthErrorKey: null,
networkRetryNotice: null,
- modelResponseSeq: 0,
};
}
@@ -439,24 +432,13 @@ export function finishCodexSamplingTurn(
return failure;
}
-/** 给工具调用标上发出它的模型回应,供 Session 的工具循环检测合并同一段脚本内的重复调用。 */
-function withModelResponseId(queue: AsyncQueue<AgentEvent>, modelResponseId: string): AsyncQueue<AgentEvent> {
- return {
- push: (event) => queue.push(event.type === 'tool_use' ? { ...event, modelResponseId } : event),
- end: () => queue.end(),
- clear: () => queue.clear(),
- get pending() { return queue.pending; },
- [Symbol.asyncIterator]: () => queue[Symbol.asyncIterator](),
- };
-}
-
export function translateItemNotification(
phase: ItemPhase,
notification:
| ItemStartedNotification['params']
| ItemUpdatedNotification['params']
| ItemCompletedNotification['params'],
- eventQueue: AsyncQueue<AgentEvent>,
+ queue: AsyncQueue<AgentEvent>,
ctx: CodexTranslateContext,
): void {
const item = notification.item;
@@ -483,12 +465,6 @@ export function translateItemNotification(
item as { id?: unknown; type?: unknown },
notification as { turnId?: unknown },
);
- const modelOutput = itemType === 'agentMessage' || itemType === 'reasoning';
- // 新的思考或文字说明一定属于一次新回应;用量通知缺失时也能分开相邻回应。
- if (modelOutput && phase === 'started') ctx.rt.modelResponseSeq += 1;
- const queue = modelOutput
- ? eventQueue
- : withModelResponseId(eventQueue, `${notification.turnId}:${ctx.rt.modelResponseSeq}`);
switch (itemType) {
case 'agentMessage':
diff --git a/packages/maker-core/src/agents/shared/loop-guard.ts b/packages/maker-core/src/agents/shared/loop-guard.ts
index 62fdc65228..824bba49b4 100644
--- a/packages/maker-core/src/agents/shared/loop-guard.ts
+++ b/packages/maker-core/src/agents/shared/loop-guard.ts
@@ -179,8 +179,6 @@ interface PendingToolUse {
name: string;
input: unknown;
startedAt: number;
- /** 发出该调用的模型回应;缺省表示每次调用各自对应一次模型回应。 */
- modelResponseId?: string;
}
/**
@@ -216,6 +214,13 @@ export interface ToolLoopGuardOptions {
contractConsecutiveLimit?: number;
/** 两次普通调用开始间隔或结果到达间隔达到此值即视为节奏轮询,不计入重复判据。 */
pacedIntervalMs?: number;
+ /**
+ * 连发判据(缺省关闭):本次调用开始距上一次普通调用结果到达不足此值,说明两次调用之间
+ * 没有模型采样,是同一段脚本在连着发起。Codex code mode 下脚本在后台运行,app-server 只上报
+ * 脚本内部的调用,不标注归属,脚本里点保存后反复截快照等页面更新的有界轮询
+ * (2026-10-18 误报)与模型逐次重复同一调用只能靠这个间隔区分。连发结果按节奏轮询处理。
+ */
+ chainedCallGapMs?: number;
/** 快速完全相同调用的最终上限(不经复核)。 */
finalConsecutiveLimit?: number;
/** 完全相同结果持续时长的最终上限(不经复核)。 */
@@ -263,9 +268,6 @@ export type ToolLoopGuardVerdict =
* 连续 finalConsecutiveLimit 次、完全相同结果持续 finalStreakMs)与长只读
* 轮转不经复核直接判定(final=true)。
*
- * 调用带模型回应标识时,同一回应内重复的完整结果/调用不再推进 1-3 层与快速连续上限,
- * 只续接完全相同结果的时长上限:一段脚本内的有界轮询不是模型在打转。
- *
* 类本身不依赖 Electron / SDK / provider, 也不做 IO;调用方决定何时启用和如何中断。
*/
export class ToolLoopGuard {
@@ -276,6 +278,7 @@ export class ToolLoopGuard {
readonly rotationDistinctLimit: number;
readonly contractConsecutiveLimit: number;
readonly pacedIntervalMs: number;
+ readonly chainedCallGapMs: number | undefined;
readonly finalConsecutiveLimit: number;
readonly finalStreakMs: number;
private readonly now: () => number;
@@ -305,11 +308,6 @@ export class ToolLoopGuard {
private callWindow: string[] = [];
private stableReadWindow: string[] = [];
- // 当前模型回应内已计入判据的指纹;同一回应内的重复只续接时长上限,不计入 1-3 层。
- private activeModelResponseId: string | null = null;
- private responseFullFingerprints = new Set<string>();
- private responseCallFingerprints = new Set<string>();
-
// 第 4 层无批次兼容状态: 最近一次契约错误的 name+类别键与连续计数
private lastContractKey: string | null = null;
private contractStreak = 0;
@@ -330,6 +328,7 @@ export class ToolLoopGuard {
this.rotationDistinctLimit = options.rotationDistinctLimit ?? DEFAULT_ROTATION_DISTINCT_LIMIT;
this.contractConsecutiveLimit = options.contractConsecutiveLimit ?? DEFAULT_CONTRACT_CONSECUTIVE_LIMIT;
this.pacedIntervalMs = options.pacedIntervalMs ?? DEFAULT_PACED_INTERVAL_MS;
+ this.chainedCallGapMs = options.chainedCallGapMs;
this.finalConsecutiveLimit = options.finalConsecutiveLimit ?? DEFAULT_FINAL_CONSECUTIVE_LIMIT;
this.finalStreakMs = options.finalStreakMs ?? DEFAULT_FINAL_STREAK_MS;
this.now = options.now ?? Date.now;
@@ -339,21 +338,12 @@ export class ToolLoopGuard {
* 记录工具调用开始。stream_event 可能只有 id, 这种半信息不缓存;
* 后续 assistant 完整 tool_use 到达时会用 name/input 补齐。补齐时保留
* 首次开始时间,节奏判据按真实开始时刻计算。
- *
- * modelResponseId 标识发出该调用的模型回应。Codex code mode 下一次回应是一段脚本,
- * 脚本内部的有界轮询会产生多次完全相同的调用;同一回应内重复的调用只计一次,
- * 模型逐次回应重复同一调用才计入 1-3 层判据。
*/
- onToolUse(toolUseId: string, toolName: unknown, input: unknown, modelResponseId?: string): void {
+ onToolUse(toolUseId: string, toolName: unknown, input: unknown): void {
if (toolUseId.length === 0) return;
if (typeof toolName !== 'string' || toolName.length === 0) return;
- const previous = this.pendingToolUses.get(toolUseId);
- this.pendingToolUses.set(toolUseId, {
- name: toolName,
- input,
- startedAt: previous?.startedAt ?? this.now(),
- modelResponseId: previous?.modelResponseId ?? modelResponseId,
- });
+ const startedAt = this.pendingToolUses.get(toolUseId)?.startedAt ?? this.now();
+ this.pendingToolUses.set(toolUseId, { name: toolName, input, startedAt });
}
/** 最近一次结果是否被纳入判定;为 true 且判定为 ok 说明此前的疑似模式已被打破。 */
@@ -416,7 +406,10 @@ export class ToolLoopGuard {
this.lastResultObservedValue = true;
const finishedAt = this.now();
- const paced = (this.lastOrdinaryStartedAt !== null
+ // 连发:上一次结果刚到、紧接着就又发出调用,中间没有模型采样的时间。
+ const chained = this.chainedCallGapMs !== undefined && this.lastOrdinaryFinishedAt !== null
+ && toolUse.startedAt - this.lastOrdinaryFinishedAt < this.chainedCallGapMs;
+ const paced = chained || (this.lastOrdinaryStartedAt !== null
&& toolUse.startedAt - this.lastOrdinaryStartedAt >= this.pacedIntervalMs)
|| (this.lastOrdinaryFinishedAt !== null
&& finishedAt - this.lastOrdinaryFinishedAt >= this.pacedIntervalMs);
@@ -426,12 +419,13 @@ export class ToolLoopGuard {
const fullFingerprint = fingerprintToolCall(toolUse.name, toolUse.input, output);
const callFingerprint = fingerprintToolCall(toolUse.name, toolUse.input, null);
this.lastResultCallFingerprintValue = callFingerprint;
- const repeatedInResponse = this.noteModelResponse(toolUse.modelResponseId, fullFingerprint, callFingerprint);
// 复核放行额度按普通结果计,节奏轮询同样消耗。
const inGrace = this.suspicionGraceResults > 0;
if (inGrace) this.suspicionGraceResults -= 1;
// 节奏轮询只参与完全相同 streak 的续接与最终时长上限,不计入任何疑似判据。
if (paced) {
+ // 连发不算参与判定:既不推进也不打破模式,进行中的复核因此不会被它取消。
+ if (chained) this.lastResultObservedValue = false;
// 写入或命令照常打断长只读窗口,节奏本身不改变这一点。
if (!READ_ONLY_TOOL_NAMES.has(toolUse.name)) this.stableReadWindow = [];
this.observeStreak(fullFingerprint, false);
@@ -499,7 +493,7 @@ export class ToolLoopGuard {
// 长只读轮转证据已足够强,不经复核
if (READ_ONLY_TOOL_NAMES.has(toolUse.name)) {
- if (!repeatedInResponse.result) this.stableReadWindow.push(fullFingerprint);
+ this.stableReadWindow.push(fullFingerprint);
if (this.stableReadWindow.length > STABLE_READ_WINDOW_SIZE) this.stableReadWindow.shift();
if (this.stableReadWindow.length === STABLE_READ_WINDOW_SIZE) {
const counts = new Map<string, number>();
@@ -520,7 +514,7 @@ export class ToolLoopGuard {
}
// 第 1 层: 连续 name+input+output 完全相同
- this.observeStreak(fullFingerprint, !repeatedInResponse.result);
+ this.observeStreak(fullFingerprint, true);
const final = this.finalVerdict(toolUse.name);
if (final.kind === 'hard') return final;
if (this.consecutiveStreak >= this.consecutiveLimit) {
@@ -534,11 +528,6 @@ export class ToolLoopGuard {
}
// 第 2/3 层: name+input 滑动窗口多样性坍缩(指纹不含 output)
- if (repeatedInResponse.call) {
- // 同回应内的重复既不推进也不打破窗口模式;不算参与判定,以免取消进行中的复核。
- this.lastResultObservedValue = false;
- return { kind: 'ok' };
- }
this.callWindow.push(callFingerprint);
const bufferSize = Math.max(this.windowSize, this.rotationWindowSize);
if (this.callWindow.length > bufferSize) this.callWindow.shift();
@@ -582,36 +571,6 @@ export class ToolLoopGuard {
this.resetPatternState();
}
- /**
- * 记录本次结果所属的模型回应,返回该回应内是否已出现过同一完整结果/同一调用。
- * 没有回应标识时每次调用自成一次回应,行为与旧调用方一致。
- */
- private noteModelResponse(
- modelResponseId: string | undefined,
- fullFingerprint: string,
- callFingerprint: string,
- ): { result: boolean; call: boolean } {
- if (modelResponseId === undefined) {
- this.resetModelResponseState();
- return { result: false, call: false };
- }
- if (modelResponseId !== this.activeModelResponseId) {
- this.resetModelResponseState();
- this.activeModelResponseId = modelResponseId;
- }
- const result = this.responseFullFingerprints.has(fullFingerprint);
- const call = this.responseCallFingerprints.has(callFingerprint);
- this.responseFullFingerprints.add(fullFingerprint);
- this.responseCallFingerprints.add(callFingerprint);
- return { result, call };
- }
-
- private resetModelResponseState(): void {
- this.activeModelResponseId = null;
- this.responseFullFingerprints.clear();
- this.responseCallFingerprints.clear();
- }
-
/** 续接或重开完全相同 streak;counted=false 的节奏结果只续接不计数。 */
private observeStreak(fingerprint: string, counted: boolean): void {
if (fingerprint === this.lastFullFingerprint) {
@@ -659,7 +618,6 @@ export class ToolLoopGuard {
this.suspicionGraceResults = 0;
this.callWindow = [];
this.stableReadWindow = [];
- this.resetModelResponseState();
this.lastContractKey = null;
this.contractStreak = 0;
this.resetContractBatchState();
diff --git a/packages/maker-core/src/agents/shared/tool-loop-review.test.ts b/packages/maker-core/src/agents/shared/tool-loop-review.test.ts
index 7bf0040adb..5c2967766e 100644
--- a/packages/maker-core/src/agents/shared/tool-loop-review.test.ts
+++ b/packages/maker-core/src/agents/shared/tool-loop-review.test.ts
@@ -134,21 +134,27 @@ describe('ToolLoopMonitor', () => {
expect(t.stops).toEqual([]);
});
- // greptile P1(#6388):同一模型回应内的重复调用不计数,但也不能当作「模式已打破」取消复核。
- it('keeps a pending review when a repeat inside one model response is ignored', async () => {
+ // greptile P1(#6388):连发调用不计数,但也不能当作「模式已打破」取消进行中的复核。
+ it('keeps a pending review when a chained script call is ignored', async () => {
+ vi.useFakeTimers();
const { reviewer, pending } = deferredReviewer();
- const t = setup(reviewer);
+ const stops: HardToolLoopVerdict[] = [];
+ const monitor = new ToolLoopMonitor(new ToolLoopGuard({ chainedCallGapMs: 2_000 }), {
+ reviewer, context: () => ({ sessionId: 's1', agentKind: 'codex', model: 'm1' }),
+ onReviewedStop: (verdict) => stops.push(verdict), logger,
+ });
for (let i = 0; i < 12; i++) {
- t.monitor.onToolUse(`r${i}`, 'read', { path: 'same.ts' }, `response-${i}`);
- expect(t.monitor.onToolResult(`r${i}`, `changed ${i}`).kind).toBe('ok');
+ vi.advanceTimersByTime(3_000);
+ monitor.onToolUse(`r${i}`, 'read', { path: 'same.ts' });
+ expect(monitor.onToolResult(`r${i}`, `changed ${i}`).kind).toBe('ok');
}
expect(reviewer).toHaveBeenCalledTimes(1);
- t.monitor.onToolUse('dup', 'read', { path: 'same.ts' }, 'response-11');
- expect(t.monitor.onToolResult('dup', 'changed again').kind).toBe('ok');
+ monitor.onToolUse('chained', 'read', { path: 'same.ts' });
+ expect(monitor.onToolResult('chained', 'changed again').kind).toBe('ok');
expect(pending[0]?.signal.aborted).toBe(false);
pending[0]?.resolve('stop');
await vi.advanceTimersByTimeAsync(0);
- expect(t.stops).toHaveLength(1);
+ expect(stops).toHaveLength(1);
});
it('discards a pending review once a different call replaces the flagged pattern', async () => {
diff --git a/packages/maker-core/src/agents/shared/tool-loop-review.ts b/packages/maker-core/src/agents/shared/tool-loop-review.ts
index 4b815b8d1c..5066869744 100644
--- a/packages/maker-core/src/agents/shared/tool-loop-review.ts
+++ b/packages/maker-core/src/agents/shared/tool-loop-review.ts
@@ -68,8 +68,8 @@ export class ToolLoopMonitor {
this.budget = opts.reviewBudget ?? { used: 0 };
}
- onToolUse(toolUseId: string, toolName: unknown, input: unknown, modelResponseId?: string): void {
- this.guard.onToolUse(toolUseId, toolName, input, modelResponseId);
+ onToolUse(toolUseId: string, toolName: unknown, input: unknown): void {
+ this.guard.onToolUse(toolUseId, toolName, input);
}
onToolResult(
diff --git a/packages/maker-core/src/session.tool-loop.test.ts b/packages/maker-core/src/session.tool-loop.test.ts
index 9567a88e64..4b5b6367b1 100644
--- a/packages/maker-core/src/session.tool-loop.test.ts
+++ b/packages/maker-core/src/session.tool-loop.test.ts
@@ -39,7 +39,9 @@ function setup(agentKind: 'pi' | 'codex', hangAbort = false, toolLoopReviewer?:
sessions.push(session);
const seen: AgentEvent[] = [];
session.onEvent((event) => seen.push(event));
+ // Each call follows a model sampling (seconds), unlike one script issuing calls back to back.
const tool = async (id: string, extra: Partial<AgentEvent> = {}, name = 'read', input: unknown = { path: 'same.ts' }) => {
+ await vi.advanceTimersByTimeAsync(3_000);
queue.push({ type: 'tool_use', data: { toolUseId: id, toolName: name, input }, source: agentKind, ...extra });
queue.push({ type: 'tool_result_full', data: { toolUseId: id, fullText: 'same result' }, source: agentKind, ...extra });
queue.push({ type: 'tool_result', data: { toolUseIds: [id], summary: 'done' }, source: agentKind, ...extra });
@@ -128,6 +130,7 @@ describe.each(['pi', 'codex'] as const)('%s Session tool loop coverage', (agentK
await t.session.send('first');
const generation = t.session.getTurnGeneration();
for (let i = 0; i < 3; i++) await t.tool(String(i));
+ await vi.advanceTimersByTimeAsync(3_000);
t.queue.push({ type: 'tool_use', source: agentKind, data: { toolUseId: 'last', toolName: 'read', input: { path: 'same.ts' } } });
t.queue.push({ type: 'tool_result_full', source: agentKind, data: { toolUseId: 'last', fullText: 'same result' } });
t.queue.push({ type: 'tool_result', source: agentKind, data: { toolUseIds: ['unrelated'], summary: 'done' } });
@@ -258,6 +261,7 @@ describe.each(['pi', 'codex'] as const)('%s Session tool loop coverage', (agentK
const t = setup(agentKind, false, reviewer);
await t.session.send('investigate');
for (let i = 0; i < 3; i++) await t.tool(String(i));
+ await vi.advanceTimersByTimeAsync(3_000);
t.queue.push({ type: 'tool_use', source: agentKind, data: { toolUseId: 'last', toolName: 'read', input: { path: 'same.ts' } } });
t.queue.push({ type: 'tool_result_full', source: agentKind, data: { toolUseId: 'last', fullText: 'same result' } });
await vi.advanceTimersByTimeAsync(0);
@@ -306,6 +310,37 @@ describe.each(['pi', 'codex'] as const)('%s Session tool loop coverage', (agentK
});
});
+// 2026-10-18 误报:code mode 脚本在后台连着发起调用(点保存后反复截快照等页面更新),
+// app-server 不标注调用属于哪段脚本。连发(无模型采样间隔)不计数,模型逐次重复仍须中断。
+it('does not count Codex calls chained back to back by a script, but still stops a model repeating itself', async () => {
+ const t = setup('codex');
+ const context = { rt: newCodexRuntimeState(), log: { info() {}, warn() {}, error() {}, debug() {} } };
+ let n = 0;
+ const call = async (action: string, text: string) => {
+ const item = {
+ type: 'mcpToolCall', id: `exec-${n++}`, server: 'cindy_browser', tool: 'call_tool',
+ arguments: { name: 'browser', args: { action } }, status: 'completed',
+ result: { content: [{ type: 'text', text }] },
+ };
+ translateItemNotification('started', { threadId: 'thread', turnId: 'turn', item }, t.queue, context);
+ translateItemNotification('completed', { threadId: 'thread', turnId: 'turn', item }, t.queue, context);
+ await vi.advanceTimersByTimeAsync(0);
+ };
+ await t.session.send('upload the icons');
+ await vi.advanceTimersByTimeAsync(3_000);
+ for (let i = 0; i < 30; i++) {
+ await call(i % 7 === 0 ? 'click' : 'snapshot', i % 7 === 0 ? 'clicked' : 'saving');
+ await vi.advanceTimersByTimeAsync(800);
+ }
+ expect(t.errors()).toHaveLength(0);
+ for (let i = 0; i < 4; i++) {
+ await vi.advanceTimersByTimeAsync(3_000);
+ await call('snapshot', 'saving');
+ }
+ expect(t.errors()).toHaveLength(1);
+ expect(t.errors()[0]).toMatchObject({ data: { toolLoop: { kind: 'consecutive', count: 4 } } });
+});
+
it.each([false, true])('keeps translated Codex waits alive with agent states=%s', async (hasAgentStates) => {
const t = setup('codex');
const context = { rt: newCodexRuntimeState(), log: { info() {}, warn() {}, error() {}, debug() {} } };
@@ -336,35 +371,6 @@ it.each([false, true])('keeps translated Codex waits alive with agent states=%s'
expect(t.handle.abort).not.toHaveBeenCalled();
});
-// 2026-10-18 误报:code mode 下一次回应是一段脚本,脚本里点保存后反复截快照等页面更新,
-// 同一回应内的相同调用被当成模型连续四次重复而中断。模型逐次回应重复同一调用仍须中断。
-it('counts repeats per Codex model response, not per call inside one code-mode script', async () => {
- const t = setup('codex');
- const context = { rt: newCodexRuntimeState(), log: { info() {}, warn() {}, error() {}, debug() {} } };
- let seq = 0;
- const respond = (calls: Array<'snapshot' | 'click'>) => {
- translateItemNotification('started', {
- threadId: 'thread', turnId: 'turn', item: { type: 'reasoning', id: `reasoning-${seq}`, summary: [], content: [] },
- }, t.queue, context);
- for (const action of calls) {
- const item = {
- type: 'mcpToolCall', id: `call-${seq++}`, server: 'cindy_browser', tool: 'call_tool',
- arguments: { name: 'browser', args: { action } }, status: 'completed',
- result: { content: [{ type: 'text', text: `${action}: saving` }] },
- };
- translateItemNotification('started', { threadId: 'thread', turnId: 'turn', item }, t.queue, context);
- translateItemNotification('completed', { threadId: 'thread', turnId: 'turn', item }, t.queue, context);
- }
- return vi.advanceTimersByTimeAsync(0);
- };
- await t.session.send('upload the icons');
- await respond(['snapshot', 'click', ...Array.from({ length: 11 }, (_, i) => i % 2 ? 'click' as const : 'snapshot' as const)]);
- expect(t.errors()).toHaveLength(0);
- for (let i = 0; i < 4; i++) await respond(['snapshot']);
- expect(t.errors()).toHaveLength(1);
- expect(t.errors()[0]).toMatchObject({ data: { toolLoop: { kind: 'consecutive', count: 4 } } });
-});
-
it('pairs real Pi translator tool events without changing their results', async () => {
const t = setup('pi');
const logger: Logger = { trace() {}, debug() {}, info() {}, warn() {}, error() {}, fatal() {}, child() { return logger; } };
diff --git a/packages/maker-core/src/session.ts b/packages/maker-core/src/session.ts
index bb5e78d39e..e149489731 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -133,6 +133,12 @@ export const STALL_ABORT_RECOVERY_GRACE_MS = 10_000;
* 端到端最长不超过 15s(review #944 第十一轮末尾调优)。
*/
export const MANUAL_ABORT_RECOVERY_GRACE_MS = 15_000;
+/**
+ * Codex tool calls arriving sooner than this after the previous result cannot have
+ * had a model sampling in between (one sampling takes seconds), so they come from a
+ * script issuing them in sequence rather than from the model repeating itself.
+ */
+const CODEX_SCRIPT_CHAINED_CALL_GAP_MS = 2_000;
/** Shared confirmation budget for provider interrupt ACK and send acceptance. */
const GRACEFUL_STOP_CONFIRMATION_TIMEOUT_MS = 5_000;
@@ -2331,6 +2337,9 @@ export class Session {
// not enable the retry-count rule without that evidence. Claude also
// disables category-only retries; repetition rules stay active.
contractConsecutiveLimit: Number.POSITIVE_INFINITY,
+ // Codex code mode: calls issued back-to-back by one background script
+ // carry no ownership marker; see ToolLoopGuardOptions.chainedCallGapMs.
+ ...(this.agentKind === 'codex' ? { chainedCallGapMs: CODEX_SCRIPT_CHAINED_CALL_GAP_MS } : {}),
}), {
reviewer: this.toolLoopReviewer,
context: () => ({ sessionId: this.id, agentKind: this.agentKind, model: this.handle.model }),
@@ -3006,12 +3015,7 @@ export class Session {
}
if (typeof data.toolUseId !== 'string' || control.pendingToolLoop) return;
if (event.type === 'tool_use') {
- control.toolLoopMonitor.onToolUse(
- data.toolUseId,
- data.toolName,
- data.input,
- event.modelResponseId,
- );
+ control.toolLoopMonitor.onToolUse(data.toolUseId, data.toolName, data.input);
return;
}
if (event.type !== 'tool_result_full' || typeof data.fullText !== 'string') return;
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index 194415a968..5724a6471e 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -176,11 +176,6 @@ export interface AgentEvent {
* boundaries.
*/
backgroundTurnStartedAt?: number;
- /**
- * 发出该 tool_use 的模型回应(Codex code mode 下一次回应是一段脚本,内部可有多次调用)。
- * 只供 Session 的工具循环检测合并同一回应内的重复调用;缺省时每次调用各算一次回应。
- */
- modelResponseId?: string;
/**
* 本事件所属 turn 的发起来源,由 Session 在事件 fan-out 前打标(见 session.ts
* 的 currentTurnOrigin)。turn 结束(isTerminalTurnEvent)后清空,不污染下一轮。