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 脚本内的重复工具调用

Dash22a3c88832ea
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.md
index 37272791d3..255b06c1e3 100644
--- a/docs/dev-rules/maker-core-and-agent-behavior.md
+++ b/docs/dev-rules/maker-core-and-agent-behavior.md
@@ -50,6 +50,14 @@ 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 不带该标识,行为不变。
+
节奏与复核:一次普通调用若距上一次普通调用开始已有至少 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 396e40efe0..1813c25c39 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -12294,6 +12294,8 @@ 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 fd1105b446..bd1d6e7d82 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -129,6 +129,12 @@ 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 {
@@ -155,6 +161,7 @@ export function newCodexRuntimeState(): CodexRuntimeState {
emittedWebSearchInput: new Map(),
lastAuthErrorKey: null,
networkRetryNotice: null,
+ modelResponseSeq: 0,
};
}
@@ -432,13 +439,24 @@ 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'],
- queue: AsyncQueue<AgentEvent>,
+ eventQueue: AsyncQueue<AgentEvent>,
ctx: CodexTranslateContext,
): void {
const item = notification.item;
@@ -465,6 +483,12 @@ 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 c59a531763..70935c0886 100644
--- a/packages/maker-core/src/agents/shared/loop-guard.ts
+++ b/packages/maker-core/src/agents/shared/loop-guard.ts
@@ -179,6 +179,8 @@ interface PendingToolUse {
name: string;
input: unknown;
startedAt: number;
+ /** 发出该调用的模型回应;缺省表示每次调用各自对应一次模型回应。 */
+ modelResponseId?: string;
}
/**
@@ -261,6 +263,9 @@ export type ToolLoopGuardVerdict =
* 连续 finalConsecutiveLimit 次、完全相同结果持续 finalStreakMs)与长只读
* 轮转不经复核直接判定(final=true)。
*
+ * 调用带模型回应标识时,同一回应内重复的完整结果/调用不再推进 1-3 层与快速连续上限,
+ * 只续接完全相同结果的时长上限:一段脚本内的有界轮询不是模型在打转。
+ *
* 类本身不依赖 Electron / SDK / provider, 也不做 IO;调用方决定何时启用和如何中断。
*/
export class ToolLoopGuard {
@@ -300,6 +305,11 @@ 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;
@@ -329,12 +339,21 @@ export class ToolLoopGuard {
* 记录工具调用开始。stream_event 可能只有 id, 这种半信息不缓存;
* 后续 assistant 完整 tool_use 到达时会用 name/input 补齐。补齐时保留
* 首次开始时间,节奏判据按真实开始时刻计算。
+ *
+ * modelResponseId 标识发出该调用的模型回应。Codex code mode 下一次回应是一段脚本,
+ * 脚本内部的有界轮询会产生多次完全相同的调用;同一回应内重复的调用只计一次,
+ * 模型逐次回应重复同一调用才计入 1-3 层判据。
*/
- onToolUse(toolUseId: string, toolName: unknown, input: unknown): void {
+ onToolUse(toolUseId: string, toolName: unknown, input: unknown, modelResponseId?: string): void {
if (toolUseId.length === 0) return;
if (typeof toolName !== 'string' || toolName.length === 0) return;
- const startedAt = this.pendingToolUses.get(toolUseId)?.startedAt ?? this.now();
- this.pendingToolUses.set(toolUseId, { name: toolName, input, startedAt });
+ const previous = this.pendingToolUses.get(toolUseId);
+ this.pendingToolUses.set(toolUseId, {
+ name: toolName,
+ input,
+ startedAt: previous?.startedAt ?? this.now(),
+ modelResponseId: previous?.modelResponseId ?? modelResponseId,
+ });
}
/** 最近一次结果是否被纳入判定;为 true 且判定为 ok 说明此前的疑似模式已被打破。 */
@@ -407,6 +426,7 @@ 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;
@@ -479,7 +499,7 @@ export class ToolLoopGuard {
// 长只读轮转证据已足够强,不经复核
if (READ_ONLY_TOOL_NAMES.has(toolUse.name)) {
- this.stableReadWindow.push(fullFingerprint);
+ if (!repeatedInResponse.result) 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>();
@@ -500,7 +520,7 @@ export class ToolLoopGuard {
}
// 第 1 层: 连续 name+input+output 完全相同
- this.observeStreak(fullFingerprint, true);
+ this.observeStreak(fullFingerprint, !repeatedInResponse.result);
const final = this.finalVerdict(toolUse.name);
if (final.kind === 'hard') return final;
if (this.consecutiveStreak >= this.consecutiveLimit) {
@@ -514,6 +534,7 @@ export class ToolLoopGuard {
}
// 第 2/3 层: name+input 滑动窗口多样性坍缩(指纹不含 output)
+ if (repeatedInResponse.call) return { kind: 'ok' };
this.callWindow.push(callFingerprint);
const bufferSize = Math.max(this.windowSize, this.rotationWindowSize);
if (this.callWindow.length > bufferSize) this.callWindow.shift();
@@ -557,6 +578,36 @@ 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) {
@@ -604,6 +655,7 @@ 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.ts b/packages/maker-core/src/agents/shared/tool-loop-review.ts
index 5066869744..4b815b8d1c 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): void {
- this.guard.onToolUse(toolUseId, toolName, input);
+ onToolUse(toolUseId: string, toolName: unknown, input: unknown, modelResponseId?: string): void {
+ this.guard.onToolUse(toolUseId, toolName, input, modelResponseId);
}
onToolResult(
diff --git a/packages/maker-core/src/session.tool-loop.test.ts b/packages/maker-core/src/session.tool-loop.test.ts
index 3f5f972d4b..9567a88e64 100644
--- a/packages/maker-core/src/session.tool-loop.test.ts
+++ b/packages/maker-core/src/session.tool-loop.test.ts
@@ -336,6 +336,35 @@ 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 c537b72684..bb5e78d39e 100644
--- a/packages/maker-core/src/session.ts
+++ b/packages/maker-core/src/session.ts
@@ -3006,7 +3006,12 @@ 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);
+ control.toolLoopMonitor.onToolUse(
+ data.toolUseId,
+ data.toolName,
+ data.input,
+ event.modelResponseId,
+ );
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 5724a6471e..194415a968 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -176,6 +176,11 @@ export interface AgentEvent {
* boundaries.
*/
backgroundTurnStartedAt?: number;
+ /**
+ * 发出该 tool_use 的模型回应(Codex code mode 下一次回应是一段脚本,内部可有多次调用)。
+ * 只供 Session 的工具循环检测合并同一回应内的重复调用;缺省时每次调用各算一次回应。
+ */
+ modelResponseId?: string;
/**
* 本事件所属 turn 的发起来源,由 Session 在事件 fan-out 前打标(见 session.ts
* 的 currentTurnOrigin)。turn 结束(isTerminalTurnEvent)后清空,不污染下一轮。