Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
import { createHash, type Hash } from 'node:crypto';
import { normalizeDisplayCommand } from '@cindy/maker-shared/command-display';
/**
* 第 1 层(快路径):连续多少次 name+input+output 完全一字不差,判疑似循环。
* 稳定输出本身不能证明死循环,已知等待/轮询形态在下方排除。
*/
const DEFAULT_CONSECUTIVE_LIMIT = 4;
/**
* 第 2 层(核心):按 name+input 指纹(不含 output)维护的滑动窗口大小。
* 配合 distinct 阈值抓两类第 1 层抓不到的循环:
* - output 每次都变的重复(p4 / 带时间戳的命令反复跑);
* - ABAB 交替的 ping-pong(模型在两三个调用间来回打转)。
* 12 ≈ OpenHands Stuck Detector 的 6-cycle ping-pong 阈值。
*/
const DEFAULT_WINDOW_SIZE = 12;
/** 第 2 层:窗口填满后, distinct 指纹数 ≤ 此值即判循环(2 = 一直在 ≤2 种调用里转)。 */
const DEFAULT_WINDOW_DISTINCT_LIMIT = 2;
/**
* 第 3 层(轮转):更长窗口 + 更宽 distinct 上限,抓第 2 层漏掉的 3-4 个调用
* 轮转(ABCDABCD…)。实锤:xai/grok 单 turn 在 4 个不同 Grep 里轮转一千多次
* 调用(2026-08),distinct=4 > 2 从第 2 层漏网。16/4 = 每种指纹平均重复 4 次
* 才判,比直接把第 2 层 distinct 提到 4 的误判面小;连续 16 次调用零新指纹
* 的合法工作流(纯读排查也会穿插不同参数)实践中几乎不存在。
*/
const DEFAULT_ROTATION_WINDOW_SIZE = 16;
/** 第 3 层:轮转窗口填满后, distinct 指纹数 ≤ 此值即判循环。 */
const DEFAULT_ROTATION_DISTINCT_LIMIT = 4;
// Wider investigations need stronger evidence than the short input-only window:
// 128 completed reads, at most 32 exact name/input/output fingerprints, with
// >=90% of results in fingerprints seen at least four times. A write/command
// breaks this observation. The small tolerance admits occasional reordered
// search output, not a steadily expanding investigation.
const STABLE_READ_WINDOW_SIZE = 128;
const STABLE_READ_DISTINCT_LIMIT = 32;
const STABLE_READ_MIN_REPEATS = 4;
/** 突发重复判据最多记住多少种调用的开始时间。 */
const MAX_TRACKED_CALL_STARTS = 256;
const READ_ONLY_TOOL_NAMES = new Set(['Read', 'Grep', 'Glob', 'read', 'grep', 'find', 'ls']);
/**
* 节奏判据:本次普通调用距上一次普通调用开始至少这么久,或本次结果距上一次普通结果
* 到达至少这么久,说明模型在等外部进度(sleep 后再查 CI、命令内自带等待、慢推理),
* 不是快速空转。看结果间隔是因为模型可能一次发出多条相同的等待命令、再逐条排队执行:
* 发出时刻挨在一起,实际每条都等了很久。这类结果不计入第 1-3 层的重复判据,只受下方
* 两条最终上限约束。
*/
const DEFAULT_PACED_INTERVAL_MS = 30_000;
/** 最终上限:快速(非节奏)的完全相同调用连续达到此数,不经复核直接判定。 */
const DEFAULT_FINAL_CONSECUTIVE_LIMIT = 30;
/** 最终上限:完全相同的结果(含节奏轮询)持续重复超过此时长,不经复核直接判定。 */
const DEFAULT_FINAL_STREAK_MS = 60 * 60_000;
/**
* 复核材料:保留最近多少次普通调用,以及每段输入/输出截取的原文长度。这里只为
* 限制内存截取原文、不做脱敏;发送方必须先脱敏再截断到发送长度(远小于此值),
* 跨越发送截断点的凭证在脱敏时才是完整的。
*/
const EVIDENCE_SIZE = 12;
const EVIDENCE_CAPTURE_LIMIT = 4_000;
const EVIDENCE_MAX_DEPTH = 6;
const EVIDENCE_MAX_ENTRIES = 50;
/**
* 第 4 层(契约错误):同一工具连续多少次因**同类参数契约错误**被拒即止损。
* 与 1-3 层互补:那三层按 name+input 指纹抓"重复同一调用",而 malformed 参数每次
* input 都不同(2026-08 实锤:xai/grok 单 session 16 次 Edit 缺 file_path,
* old/new_string 各不相同 → 指纹恒新,三层全部漏网)。本层按 name+错误类别聚合,
* 阈值低于第 1 层:同类契约错误第 3 次就该停,不值得等第 4 次机械重复。
*/
const DEFAULT_CONTRACT_CONSECUTIVE_LIMIT = 3;
/**
* 参与契约错误分类的输出长度上限。这类错误全是短文本;成功输出(文件内容、
* 编辑回显、测试文件里恰好写着同款错误文案)可能包含相同短语,长度门把它们挡在
* 分类之外,避免"连续编辑三个含错误文案的文件"被误判成契约错误风暴。
*/
const CONTRACT_ERROR_MAX_OUTPUT_LENGTH = 600;
/** 稳定的契约错误类别。认不出的错误(other)一律不参与熔断,防 CC 文案漂移造成误伤。 */
export type ToolContractErrorCategory =
| 'missing_required_field'
| 'invalid_pages'
| 'stale_locator'
| 'ambiguous_locator'
| 'no_changes';
/**
* 逐类别匹配器:只认专一、跨版本稳定的错误文案;tools 限定该类别只对哪些工具生效
* (缺省 = 任意工具),进一步压误分类面。
*/
const CONTRACT_ERROR_MATCHERS: ReadonlyArray<{
category: ToolContractErrorCategory;
tools?: ReadonlySet<string>;
pattern: RegExp;
}> = [
{
category: 'missing_required_field',
// 只限有结构化参数校验的内置工具:Bash 会原样转发任意 CLI 的
// "missing required parameter --xxx" 输出,不限定工具会把用户脚本的正常
// 报错迭代误判成契约错误风暴。
tools: new Set(['Edit', 'Write', 'Read', 'NotebookEdit', 'AskUserQuestion']),
pattern: /required parameter[\s\S]{0,80}\bmissing\b|missing required parameter/i,
},
{
category: 'invalid_pages',
tools: new Set(['Read']),
pattern: /\bpages?\b[\s\S]{0,80}\b(invalid|only applicable|not applicable|out of range|must)\b|\binvalid\b[\s\S]{0,40}\bpages?\b/i,
},
{
category: 'stale_locator',
tools: new Set(['Edit', 'NotebookEdit']),
pattern: /string to replace not found|old_string[\s\S]{0,60}not found/i,
},
{
category: 'ambiguous_locator',
tools: new Set(['Edit', 'NotebookEdit']),
pattern: /found \d+ matches of the string/i,
},
{
category: 'no_changes',
tools: new Set(['Edit', 'NotebookEdit']),
pattern: /old_string and new_string are exactly the same|no changes to make/i,
},
];
/**
* 把一次工具结果分类成契约错误类别;认不出或输出超长(多半是成功输出)返回 null。
* 导出仅为单测;熔断逻辑在 ToolLoopGuard 内。
*/
export function classifyToolContractError(
toolName: string,
output: string,
): ToolContractErrorCategory | null {
if (output.length === 0 || output.length > CONTRACT_ERROR_MAX_OUTPUT_LENGTH) return null;
for (const matcher of CONTRACT_ERROR_MATCHERS) {
if (matcher.tools && !matcher.tools.has(toolName)) continue;
if (matcher.pattern.test(output)) return matcher.category;
}
return null;
}
/**
* TaskOutput 是 SDK 明确定义的等待/轮询工具。状态文本不变只代表任务仍在等待,
* 不能作为模型死循环证据。它本身不进入指纹,但也不重置普通工具的轨迹,
* 避免模型通过在重复调用间插入轮询来绕过检测。
*/
const LOOP_GUARD_EXEMPT_TOOL_NAMES = new Set([
'TaskOutput', 'write_stdin', 'wait', 'sleep',
// Codex translates native subagent waits to this name, often with a stable result.
'collab:wait',
// Codex translator retains the namespace of host dynamic tools.
'dynamic:functions:write_stdin', 'dynamic:functions:wait',
'dynamic:clock:sleep', 'mcp:clock:sleep',
]);
function isPollingTool(name: string, input: unknown, isError: boolean): boolean {
if (LOOP_GUARD_EXEMPT_TOOL_NAMES.has(name)) return true;
if (!input || typeof input !== 'object') return false;
const record = input as Record<string, unknown>;
if (!isError && (name === 'exec' || name === 'Bash' || name === 'bash' || name === 'powershell')) {
const command = record.command ?? record.cmd;
if (typeof command === 'string') {
// Reuse shell-wrapper recognition; this is a polling hint, not permission
// analysis. Only simple tail/Get-Content reads of literal .log paths are exempt.
// Mixed commands, substitutions, redirects and source-file reads remain
// ordinary observations. A failed tail is not evidence of healthy waiting.
const script = normalizeDisplayCommand(command) ?? command;
const logPath = String.raw`(?:[A-Za-z0-9_./:@%+=,-]+\.log|'[A-Za-z0-9_./ :@%+=,-]+\.log'|"[A-Za-z0-9_./ :@%+=,-]+\.log")`;
const tail = new RegExp(String.raw`^(?:/usr/bin/|/bin/)?tail\s+(?:(?:-\d+|-n\s+\d+)\s+)?${logPath}(?:\s+${logPath})*\s*$`);
const windowsLogPath = String.raw`(?:[A-Za-z0-9_./\\:@%+=-]+\.log|'[A-Za-z0-9_./\\ :@%+=-]+\.log'|"[A-Za-z0-9_./\\ :@%+=-]+\.log")`;
const target = String.raw`(?:(?:-Path|-LiteralPath)\s+)?${windowsLogPath}`;
const getContent = new RegExp(String.raw`^Get-Content\s+(?:-Tail\s+\d+\s+${target}|${target}\s+-Tail\s+\d+)\s*$`, 'i');
if (script.split(/;|&&/).every(part => tail.test(part.trim()) || getContent.test(part.trim()))) return true;
}
}
// Pi's native subagent status/list calls observe separately running work.
if (name !== 'subagent') return false;
const action = record.action;
return action === 'status' || action === 'list';
}
interface PendingToolUse {
name: string;
input: unknown;
startedAt: number;
/** 突发重复判据启用时,调用开始当下确定的指纹与是否突发重复;未启用时为 undefined。 */
callFingerprint?: string;
burstRepeat?: boolean;
}
/**
* 供复核用的一次普通调用摘要,均为未脱敏原文。input 保留原结构(不序列化,
* 发送方在未转义的字符串上逐个脱敏后再序列化),每个字符串最多截取 4000 字符。
*/
export interface ToolLoopEvidence {
toolName: string;
input: unknown;
output: string;
isError: boolean;
startedAt: number;
finishedAt: number;
}
interface ContractObservation {
toolName: string;
category: ToolContractErrorCategory;
}
export interface ToolLoopGuardOptions {
/** 第 1 层:连续完全相同(name+input+output)多少次判循环。 */
consecutiveLimit?: number;
/** 第 2 层:name+input 滑动窗口大小。 */
windowSize?: number;
/** 第 2 层:窗口内 distinct 指纹 ≤ 此值判循环。 */
windowDistinctLimit?: number;
/** 第 3 层:轮转检测的滑动窗口大小。 */
rotationWindowSize?: number;
/** 第 3 层:轮转窗口内 distinct 指纹 ≤ 此值判循环。 */
rotationDistinctLimit?: number;
/** 第 4 层:同工具同类契约错误连续多少次判止损。 */
contractConsecutiveLimit?: number;
/** 两次普通调用开始间隔或结果到达间隔达到此值即视为节奏轮询,不计入重复判据。 */
pacedIntervalMs?: number;
/**
* 突发重复判据(缺省关闭):同一调用(name+input 相同)距它上一次开始不足此值,是一阵突发,
* 不是一次新的模型回应——两次模型回应之间必有数秒采样。Codex code mode 下脚本在后台运行,
* app-server 只上报脚本内部的调用,不标注归属,脚本里点保存后反复截快照等页面更新的有界轮询
* (2026-10-18 误报)只能靠这个间隔与模型逐次重复区分。只看该调用自己的开始时间,
* 与其它调用、完成顺序、并发无关。突发重复不计入重复判据,也不取消进行中的复核。
*/
burstRepeatGapMs?: number;
/** 快速完全相同调用的最终上限(不经复核)。 */
finalConsecutiveLimit?: number;
/** 完全相同结果持续时长的最终上限(不经复核)。 */
finalStreakMs?: number;
/** 时钟,供测试注入。 */
now?: () => number;
}
/**
* 命中哪一层判据。consecutive=机械重复 / pingpong=短循环 / rotation=3-4 调用轮转 /
* contract=同类参数契约错误连续被拒(input 各不相同也计)。
*/
export type ToolLoopReason = 'consecutive' | 'pingpong' | 'rotation' | 'contract';
export type ToolLoopGuardVerdict =
| { kind: 'ok' }
| {
kind: 'hard';
reason: ToolLoopReason;
count: number;
toolName: string;
/** 仅 reason='contract' 时存在:命中的契约错误类别。 */
contractCategory?: ToolContractErrorCategory;
/**
* true = 证据已足以直接中断(最终上限、长只读轮转);false = 疑似,调用方
* 可交给辅助模型复核后再决定。
*/
final: boolean;
};
/**
* Result-aware tool loop detector(四层防御)。
*
* 只在非轮询工具结果返回后判断。任一层命中即返回 hard, 由调用方决定如何中断:
* 1. 连续完全相同(name+input+output)—— 快路径;
* 2. name+input 滑动窗口多样性坍缩 —— 抓 ABAB 交替 / output 易变的重复;
* 3. 轮转检测 —— 短窗口抓 3-4 个调用;长窗口只接受反复相同的只读结果;
* 4. 同工具同类契约错误连续被拒 —— 抓 input 各不相同、指纹层抓不到的 malformed 重试。
*
* 不按调用总数或任意长度的重复序列硬中断:仅凭工具 trace 无法区分合法批处理、
* 稳定状态轮询与死循环,有限窗口也只能移动误判/漏判边界。因此 1-4 层的命中
* 都是"疑似"(final=false),调用方可交给辅助模型复核;复核放行后由
* acceptCurrentPattern() 暂缓疑似判定。距上一次普通调用开始或上一次普通结果
* 到达 ≥ pacedIntervalMs 的结果视为节奏轮询,不计入重复判据。两条最终上限(快速完全相同
* 连续 finalConsecutiveLimit 次、完全相同结果持续 finalStreakMs)与长只读
* 轮转不经复核直接判定(final=true)。
*
* 类本身不依赖 Electron / SDK / provider, 也不做 IO;调用方决定何时启用和如何中断。
*/
export class ToolLoopGuard {
readonly consecutiveLimit: number;
readonly windowSize: number;
readonly windowDistinctLimit: number;
readonly rotationWindowSize: number;
readonly rotationDistinctLimit: number;
readonly contractConsecutiveLimit: number;
readonly pacedIntervalMs: number;
readonly burstRepeatGapMs: number | undefined;
readonly finalConsecutiveLimit: number;
readonly finalStreakMs: number;
private readonly now: () => number;
private pendingToolUses = new Map<string, PendingToolUse>();
/** 最近一次 onToolResult 是否真正参与了判定(未配对结果与等待/轮询工具不算)。 */
private lastResultObservedValue = false;
/** 最近一次被纳入判定的调用指纹(name+input)。 */
private lastResultCallFingerprintValue: string | null = null;
/** 最近一次疑似判定所指的调用集合(name+input 指纹),供复核判断模式是否已被替换。 */
private lastSuspectPatternValue: ReadonlySet<string> = new Set();
// 节奏判据与复核材料
private lastOrdinaryStartedAt: number | null = null;
private lastOrdinaryFinishedAt: number | null = null;
private evidence: ToolLoopEvidence[] = [];
/** 复核放行后,接下来还有多少次普通结果不报疑似。 */
private suspicionGraceResults = 0;
// 第 1 层状态:consecutiveStreak 只计非节奏结果;streakResults/streakStartedAt(首个结果到达时刻)覆盖整段
private lastFullFingerprint: string | null = null;
private consecutiveStreak = 0;
private streakResults = 0;
private streakStartedAt = 0;
// 第 2/3 层共用状态: 最近 max(windowSize, rotationWindowSize) 个 name+input 指纹
private callWindow: string[] = [];
private stableReadWindow: string[] = [];
// 每种调用(name+input)最近一次开始的时间,供突发重复判据使用;有界,淘汰最久未出现的。
private lastStartByCall = new Map<string, number>();
// 第 4 层无批次兼容状态: 最近一次契约错误的 name+类别键与连续计数
private lastContractKey: string | null = null;
private contractStreak = 0;
// 第 4 层批次状态: 一批 tool_result 是同一轮模型回应,不能按结果到达顺序
// 把批次内的成功/其它工具误当成新的模型轮次。只保留当前批次和上一批次
// 的 key, 让状态有界且按每个工具+错误类别分别累计。
private activeContractBatchId: string | null = null;
private activeContractKeys = new Set<string>();
private previousContractKeys = new Set<string>();
private contractStreakByKey = new Map<string, number>();
constructor(options: ToolLoopGuardOptions = {}) {
this.consecutiveLimit = options.consecutiveLimit ?? DEFAULT_CONSECUTIVE_LIMIT;
this.windowSize = options.windowSize ?? DEFAULT_WINDOW_SIZE;
this.windowDistinctLimit = options.windowDistinctLimit ?? DEFAULT_WINDOW_DISTINCT_LIMIT;
this.rotationWindowSize = options.rotationWindowSize ?? DEFAULT_ROTATION_WINDOW_SIZE;
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.burstRepeatGapMs = options.burstRepeatGapMs;
this.finalConsecutiveLimit = options.finalConsecutiveLimit ?? DEFAULT_FINAL_CONSECUTIVE_LIMIT;
this.finalStreakMs = options.finalStreakMs ?? DEFAULT_FINAL_STREAK_MS;
this.now = options.now ?? Date.now;
}
/**
* 记录工具调用开始。stream_event 可能只有 id, 这种半信息不缓存;
* 后续 assistant 完整 tool_use 到达时会用 name/input 补齐。补齐时保留
* 首次开始时间,节奏判据按真实开始时刻计算。
*/
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);
const startedAt = previous?.startedAt ?? this.now();
const pending: PendingToolUse = { name: toolName, input, startedAt };
if (this.burstRepeatGapMs !== undefined) {
// 突发关系在调用开始时就确定:并发的相邻调用可能乱序返回,结果到达时再看会漏掉尚未返回的邻居。
const callFingerprint = fingerprintToolCall(toolName, input, null);
if (previous?.callFingerprint === callFingerprint) {
pending.burstRepeat = previous.burstRepeat;
} else {
// 补齐后参数变了:撤销按半信息登记的开始时间,再按完整参数登记。
if (previous?.callFingerprint !== undefined
&& this.lastStartByCall.get(previous.callFingerprint) === startedAt) {
this.lastStartByCall.delete(previous.callFingerprint);
}
pending.burstRepeat = this.noteCallStart(callFingerprint, startedAt);
}
pending.callFingerprint = callFingerprint;
}
this.pendingToolUses.set(toolUseId, pending);
}
/** 最近一次结果是否被纳入判定;为 true 且判定为 ok 说明此前的疑似模式已被打破。 */
get lastResultObserved(): boolean {
return this.lastResultObservedValue;
}
/** 最近一次被纳入判定的调用指纹;复核期间不在被复核模式内即说明模式已被替换。 */
get lastResultCallFingerprint(): string | null {
return this.lastResultCallFingerprintValue;
}
/**
* 是否有在途(已开始、结果未到)的普通调用不属于给定的调用集合。等待/轮询工具不算。
* 纯查询,不改判定状态;在途调用的参数以最近一次 onToolUse 补齐后的为准。
*/
hasPendingCallOutside(pattern: ReadonlySet<string>): boolean {
for (const call of this.pendingToolUses.values()) {
if (isPollingTool(call.name, call.input, false)) continue;
if (!pattern.has(fingerprintToolCall(call.name, call.input, null))) return true;
}
return false;
}
/** 最近一次疑似判定涉及的调用集合。 */
get lastSuspectPattern(): ReadonlySet<string> {
return this.lastSuspectPatternValue;
}
/** 最近的普通调用摘要(旧→新),供辅助模型复核。 */
recentEvidence(): readonly ToolLoopEvidence[] {
return [...this.evidence];
}
/**
* 当前模式放行(有合理理由或证据不足):接下来 graceResults 次普通结果不再报疑似,
* 之后若模式仍在则重新报。最终上限不受影响。
*/
acceptCurrentPattern(graceResults: number): void {
this.suspicionGraceResults = Math.max(this.suspicionGraceResults, graceResults);
}
/**
* 工具结果到达后配对并按四层判据判断。没有配到完整 tool_use 时直接放行,
* 避免用不完整信息误判。契约错误层只接受明确标记为失败的结果;有批次标识时
* 先按完整批次聚合,由下一批次到达时提交重置,避免结果顺序影响 streak。
*/
onToolResult(
toolUseId: string,
output: string,
isError = false,
toolResultBatchId?: string,
): ToolLoopGuardVerdict {
const toolUse = this.pendingToolUses.get(toolUseId);
this.pendingToolUses.delete(toolUseId);
this.lastResultObservedValue = false;
this.lastResultCallFingerprintValue = null;
if (!toolUse) return { kind: 'ok' };
if (isPollingTool(toolUse.name, toolUse.input, isError)) return { kind: 'ok' };
this.lastResultObservedValue = true;
const finishedAt = this.now();
const paced = (this.lastOrdinaryStartedAt !== null
&& toolUse.startedAt - this.lastOrdinaryStartedAt >= this.pacedIntervalMs)
|| (this.lastOrdinaryFinishedAt !== null
&& finishedAt - this.lastOrdinaryFinishedAt >= this.pacedIntervalMs);
this.lastOrdinaryStartedAt = Math.max(this.lastOrdinaryStartedAt ?? toolUse.startedAt, toolUse.startedAt);
this.lastOrdinaryFinishedAt = finishedAt;
this.recordEvidence(toolUse, output, isError);
const fullFingerprint = fingerprintToolCall(toolUse.name, toolUse.input, output);
const callFingerprint = toolUse.callFingerprint ?? fingerprintToolCall(toolUse.name, toolUse.input, null);
this.lastResultCallFingerprintValue = callFingerprint;
const burstRepeat = toolUse.burstRepeat === true;
// 复核放行额度按普通结果计,节奏轮询同样消耗;突发重复不参与判定,也不消耗。
const inGrace = this.suspicionGraceResults > 0;
if (inGrace && !burstRepeat) this.suspicionGraceResults -= 1;
// 节奏轮询只参与完全相同 streak 的续接与最终时长上限,不计入任何疑似判据。
if (paced) {
// 写入或命令照常打断长只读窗口,节奏本身不改变这一点。
if (!READ_ONLY_TOOL_NAMES.has(toolUse.name)) this.stableReadWindow = [];
this.observeStreak(fullFingerprint, false);
return this.finalVerdict(toolUse.name);
}
// 突发重复:不计入任何疑似判据,也不算参与判定(不打破模式,进行中的复核不被它取消)。
// 只续接完全相同结果的时长上限;写入或命令照常打断长只读窗口,其余调用走原有判据。
if (burstRepeat) {
this.lastResultObservedValue = false;
if (!READ_ONLY_TOOL_NAMES.has(toolUse.name)) this.stableReadWindow = [];
if (fullFingerprint !== this.lastFullFingerprint) return { kind: 'ok' };
this.observeStreak(fullFingerprint, false);
return this.finalVerdict(toolUse.name);
}
const suspect = (verdict: ToolLoopGuardVerdict, pattern: Iterable<string>): ToolLoopGuardVerdict => {
if (inGrace) return { kind: 'ok' };
this.lastSuspectPatternValue = new Set(pattern);
return verdict;
};
// 第 4 层: 同工具同类契约错误连续出现(input 各不相同也计)。放在 1-3 层之前:
// 它的阈值(3)低于第 1 层(4),同 input 的重复契约错误也应更早止损。
// 有 batch id 时按“连续批次”计数, 同一批次每个 key 最多计一次; 成功/其它
// 工具结果不能因到达顺序把同批次的契约错误抹掉。没有 batch id 的旧调用方
// 保留原先逐结果计数语义。
const contractCategory = isError ? classifyToolContractError(toolUse.name, output) : null;
if (toolResultBatchId !== undefined) {
this.beginContractBatch(toolResultBatchId);
if (contractCategory !== null) {
const contractKey = `${toolUse.name}\n${contractCategory}`;
// Parallel results in one user message are one model attempt. Count this
// key only on its first result in the batch, regardless of result order.
if (!this.activeContractKeys.has(contractKey)) {
this.activeContractKeys.add(contractKey);
const streak = this.previousContractKeys.has(contractKey)
? (this.contractStreakByKey.get(contractKey) ?? 0) + 1
: 1;
this.contractStreakByKey.set(contractKey, streak);
if (streak >= this.contractConsecutiveLimit) {
return suspect({
kind: 'hard',
reason: 'contract',
count: streak,
toolName: toolUse.name,
contractCategory,
final: false,
}, [callFingerprint]);
}
}
}
} else {
// Legacy callers do not provide batch ids; preserve the original
// adjacent-result streak semantics for them.
this.resetContractBatchState();
if (contractCategory !== null) {
const contractKey = `${toolUse.name}\n${contractCategory}`;
this.contractStreak = contractKey === this.lastContractKey ? this.contractStreak + 1 : 1;
this.lastContractKey = contractKey;
if (this.contractStreak >= this.contractConsecutiveLimit) {
return suspect({
kind: 'hard',
reason: 'contract',
count: this.contractStreak,
toolName: toolUse.name,
contractCategory,
final: false,
}, [callFingerprint]);
}
} else {
this.lastContractKey = null;
this.contractStreak = 0;
}
}
// 长只读轮转证据已足够强,不经复核
if (READ_ONLY_TOOL_NAMES.has(toolUse.name)) {
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>();
for (const fingerprint of this.stableReadWindow) {
counts.set(fingerprint, (counts.get(fingerprint) ?? 0) + 1);
}
const repeated = [...counts.values()].reduce((sum, count) =>
sum + (count >= STABLE_READ_MIN_REPEATS ? count : 0), 0);
if (counts.size <= STABLE_READ_DISTINCT_LIMIT &&
repeated >= Math.ceil(STABLE_READ_WINDOW_SIZE * 0.9)) {
return {
kind: 'hard', reason: 'rotation', count: STABLE_READ_WINDOW_SIZE, toolName: toolUse.name, final: true,
};
}
}
} else {
this.stableReadWindow = [];
}
// 第 1 层: 连续 name+input+output 完全相同
this.observeStreak(fullFingerprint, true);
const final = this.finalVerdict(toolUse.name);
if (final.kind === 'hard') return final;
if (this.consecutiveStreak >= this.consecutiveLimit) {
return suspect({
kind: 'hard',
reason: 'consecutive',
count: this.consecutiveStreak,
toolName: toolUse.name,
final: false,
}, [callFingerprint]);
}
// 第 2/3 层: name+input 滑动窗口多样性坍缩(指纹不含 output)
this.callWindow.push(callFingerprint);
const bufferSize = Math.max(this.windowSize, this.rotationWindowSize);
if (this.callWindow.length > bufferSize) this.callWindow.shift();
// 第 2 层: 短窗口 ping-pong(≤2 种调用来回打转)
if (this.callWindow.length >= this.windowSize) {
const recent = this.callWindow.slice(-this.windowSize);
const distinct = new Set(recent).size;
if (distinct <= this.windowDistinctLimit) {
return suspect({
kind: 'hard',
reason: 'pingpong',
count: recent.length,
toolName: toolUse.name,
final: false,
}, recent);
}
}
// 第 3 层: 长窗口轮转(3-4 种调用 ABCD 轮转,第 2 层 distinct 上限盖不住)
if (this.callWindow.length >= this.rotationWindowSize) {
const recent = this.callWindow.slice(-this.rotationWindowSize);
const distinct = new Set(recent).size;
if (distinct <= this.rotationDistinctLimit) {
return suspect({
kind: 'hard',
reason: 'rotation',
count: recent.length,
toolName: toolUse.name,
final: false,
}, recent);
}
}
return { kind: 'ok' };
}
/** 每个 user turn 开始时重置, 避免跨 turn 的合法重复被累计。 */
resetTurn(): void {
this.pendingToolUses.clear();
this.resetPatternState();
}
/** 调用开始时登记其开始时间,返回它是否是距上一次同一调用不足 burstRepeatGapMs 的突发重复。 */
private noteCallStart(callFingerprint: string, startedAt: number): boolean {
const previous = this.lastStartByCall.get(callFingerprint);
this.lastStartByCall.delete(callFingerprint);
this.lastStartByCall.set(callFingerprint, previous === undefined ? startedAt : Math.max(previous, startedAt));
if (this.lastStartByCall.size > MAX_TRACKED_CALL_STARTS) {
const oldest = this.lastStartByCall.keys().next().value;
if (oldest !== undefined) this.lastStartByCall.delete(oldest);
}
return this.burstRepeatGapMs !== undefined && previous !== undefined
&& startedAt - previous < this.burstRepeatGapMs;
}
/** 续接或重开完全相同 streak;counted=false 的节奏结果只续接不计数。 */
private observeStreak(fingerprint: string, counted: boolean): void {
if (fingerprint === this.lastFullFingerprint) {
if (counted) this.consecutiveStreak += 1;
this.streakResults += 1;
return;
}
this.lastFullFingerprint = fingerprint;
this.consecutiveStreak = counted ? 1 : 0;
this.streakResults = 1;
// 时长上限衡量"相同结果持续了多久",从首个结果到达起算,不含首次调用本身的耗时。
this.streakStartedAt = this.now();
}
private finalVerdict(toolName: string): ToolLoopGuardVerdict {
if (this.consecutiveStreak >= this.finalConsecutiveLimit) {
return { kind: 'hard', reason: 'consecutive', count: this.consecutiveStreak, toolName, final: true };
}
if (this.streakResults >= this.consecutiveLimit && this.now() - this.streakStartedAt >= this.finalStreakMs) {
return { kind: 'hard', reason: 'consecutive', count: this.streakResults, toolName, final: true };
}
return { kind: 'ok' };
}
private recordEvidence(toolUse: PendingToolUse, output: string, isError: boolean): void {
this.evidence.push({
toolName: toolUse.name,
input: captureEvidenceValue(toolUse.input, 0),
output: captureEvidence(output),
isError,
startedAt: toolUse.startedAt,
finishedAt: this.now(),
});
if (this.evidence.length > EVIDENCE_SIZE) this.evidence.shift();
}
private resetPatternState(): void {
this.lastFullFingerprint = null;
this.consecutiveStreak = 0;
this.streakResults = 0;
this.streakStartedAt = 0;
this.lastOrdinaryStartedAt = null;
this.lastOrdinaryFinishedAt = null;
this.evidence = [];
this.suspicionGraceResults = 0;
this.callWindow = [];
this.stableReadWindow = [];
this.lastStartByCall.clear();
this.lastContractKey = null;
this.contractStreak = 0;
this.resetContractBatchState();
}
private beginContractBatch(batchId: string): void {
if (this.activeContractBatchId === batchId) return;
// A batch-id stream and the legacy no-id stream must never share a streak.
// Reset the compatibility counters when a new batch becomes authoritative.
this.lastContractKey = null;
this.contractStreak = 0;
this.previousContractKeys = this.activeContractKeys;
this.activeContractKeys = new Set<string>();
// A key only remains eligible to continue if it occurred in the immediately
// previous batch. This bounds memory and makes an intervening clean batch
// break the contract streak.
for (const key of this.contractStreakByKey.keys()) {
if (!this.previousContractKeys.has(key)) this.contractStreakByKey.delete(key);
}
this.activeContractBatchId = batchId;
}
private resetContractBatchState(): void {
this.activeContractBatchId = null;
this.activeContractKeys = new Set<string>();
this.previousContractKeys = new Set<string>();
this.contractStreakByKey = new Map<string, number>();
}
}
/** 复制工具输入的有界副本:字符串按长度截取,嵌套与元素个数设上限,不序列化。 */
function captureEvidenceValue(value: unknown, depth: number): unknown {
if (typeof value === 'string') return captureEvidence(value);
if (value === null || typeof value !== 'object') return value;
if (depth >= EVIDENCE_MAX_DEPTH) return '[nested]';
if (Array.isArray(value)) {
return value.slice(0, EVIDENCE_MAX_ENTRIES).map((item) => captureEvidenceValue(item, depth + 1));
}
const copy: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value).slice(0, EVIDENCE_MAX_ENTRIES)) {
copy[key] = captureEvidenceValue(item, depth + 1);
}
return copy;
}
/** 截取点之前可能被切断的令牌片段:字母数字与令牌常见符号的连续串。 */
const TRAILING_TOKEN_FRAGMENT_RE = /[A-Za-z0-9_\-+/=.:@%~]+$/;
/**
* 截取点可能落在凭证中间,残缺的凭证任何脱敏器都认不出,一律保守丢弃:
* 有换行时丢掉被截断的整行(凭证以行为界:赋值、参数、引号串);没有换行时丢掉末尾
* 连续串,若还剩未闭合的引号,从该引号起全部丢掉。
*/
export function captureEvidence(text: string): string {
if (text.length <= EVIDENCE_CAPTURE_LIMIT) return text;
const cut = text.slice(0, EVIDENCE_CAPTURE_LIMIT);
const lastNewline = cut.lastIndexOf('\n');
let kept = lastNewline >= 0 ? cut.slice(0, lastNewline + 1) : cut.replace(TRAILING_TOKEN_FRAGMENT_RE, '');
if (lastNewline < 0) {
for (const quote of ['"', "'"]) {
if ((kept.split(quote).length - 1) % 2 === 1) kept = kept.slice(0, kept.lastIndexOf(quote));
}
}
return `${kept}…(+${text.length - kept.length} chars)`;
}
/**
* 指纹: tool name + 稳定序列化 input (+ 可选 output)。
* output 传 null 时不参与 —— 第 2 层靠这个忽略易变输出, 只比 name+input。
*/
function fingerprintToolCall(toolName: string, input: unknown, output: string | null): string {
const hash = createHash('sha256');
hash.update('tool:');
hash.update(toolName);
hash.update('\ninput:');
writeStableValue(hash, input, new WeakSet<object>());
if (output !== null) {
hash.update('\noutput:');
hash.update(output);
}
return hash.digest('hex');
}
/**
* 稳定序列化到 hasher: 对象 key 排序, 不深拷贝、不构造大中间对象。
* Tool input 正常来自 JSON;遇到循环引用时写入占位符, 保证 guard 不抛错。
*/
function writeStableValue(hash: Hash, value: unknown, seen: WeakSet<object>): void {
if (value === null) {
hash.update('null');
return;
}
const t = typeof value;
if (t === 'string') {
hash.update(JSON.stringify(value));
return;
}
if (t === 'number' || t === 'boolean') {
hash.update(String(value));
return;
}
if (t === 'undefined') {
hash.update('undefined');
return;
}
if (t === 'bigint') {
hash.update(`bigint:${String(value)}`);
return;
}
if (t === 'symbol' || t === 'function') {
hash.update(t);
return;
}
const obj = value as object;
if (seen.has(obj)) {
hash.update('"[Circular]"');
return;
}
seen.add(obj);
if (Array.isArray(value)) {
hash.update('[');
for (let i = 0; i < value.length; i += 1) {
if (i > 0) hash.update(',');
writeStableValue(hash, value[i], seen);
}
hash.update(']');
seen.delete(obj);
return;
}
const record = value as Record<string, unknown>;
const keys = Object.keys(record).sort();
hash.update('{');
keys.forEach((key, index) => {
if (index > 0) hash.update(',');
hash.update(JSON.stringify(key));
hash.update(':');
writeStableValue(hash, record[key], seen);
});
hash.update('}');
seen.delete(obj);
}