import { createHash } from 'node:crypto'; import type { ToolCall, ToolResult } from '../types.js'; function hash(value: string): string { return createHash('sha256').update(value).digest('hex'); } export interface StallObservation { stalled: boolean; reason?: 'repeated_failure' | 'no_progress'; signature?: string; attempts?: string[]; } /** Run-local deterministic guard. It never persists arguments or result text. */ export class StallGuard { #lastFailure = ''; #lastFailureCall = ''; #failureCount = 0; #lastBatch = ''; #batchCount = 0; #sequence = 0; readonly #observed = new Set(); readonly #problems = new Map; attempts: string[]; notified: boolean }>(); /** After a successful consultation the failing path may be tried again: the * repeated-call rejection and the open problems start from zero. */ noteConsultation(): void { this.#problems.clear(); this.#failureCount = 0; this.#lastFailureCall = ''; this.#lastFailure = ''; } /** Called immediately after execution, so a serial batch cannot run attempt 3 * before its second failure has reached the advisor coordinator. */ observeAttempt(call: ToolCall, result: ToolResult): StallObservation { if (this.#observed.has(call.id)) return { stalled: false }; this.#observed.add(call.id); if (call.function.name === 'Advisor' || (!result.ok && (result.disposition === 'deferred' || result.error === 'aborted'))) return { stalled: false }; const callSignature = hash(`${call.function.name}\0${call.function.arguments}`); const failed = result.problem?.outcome === 'failed' || !result.ok || result.metadata?.kind === 'process_execution' && result.metadata.status === 'failed'; if (!failed) { for (const [key, problem] of this.#problems) { if (result.problem?.outcome === 'resolved' ? key === `problem:${result.problem.id}` : problem.calls.has(callSignature)) this.#problems.delete(key); } if (this.#lastFailureCall === callSignature) { this.#failureCount = 0; this.#lastFailureCall = ''; this.#lastFailure = ''; } return { stalled: false }; } const error = result.ok ? result.content : result.error; // Keep target names/paths/acceptance items. Only volatile decoration is // removed; errors without an explicit problem id stay scoped to the call. const cleaned = error.replace(/\x1b\[[0-9;]*m/g, '') .replace(/\b\d+(?:\.\d+)?\s*(?:ms|seconds?|秒)\b/g, '') .split('\n').map((line) => line.trim()).filter(Boolean); const diagnostics = cleaned.filter((line) => /error|failed|exception|assert|失败|不通过/i.test(line)); const normalized = (diagnostics.length ? diagnostics : cleaned).slice(-3).join('\n'); const key = result.problem?.id ? `problem:${result.problem.id}` : hash(`${callSignature}\0${normalized}`); const exactFailure = hash(`${callSignature}\0${error}`); this.#failureCount = this.#lastFailure === exactFailure ? this.#failureCount + 1 : 1; this.#lastFailure = exactFailure; this.#lastFailureCall = callSignature; let problem = this.#problems.get(key); if (!problem) { problem = { signature: hash(`${key}:${++this.#sequence}`).slice(0, 16), calls: new Set(), attempts: [], notified: false }; this.#problems.set(key, problem); } problem.calls.add(callSignature); problem.attempts.push(`[${call.id}] ${call.function.name} ${call.function.arguments.slice(0, 1500)}\n失败/验收未通过:${error.slice(0, 2500)}`); problem.attempts = problem.attempts.slice(-2); if (problem.attempts.length < 2 || problem.notified) return { stalled: false }; problem.notified = true; return { stalled: true, reason: 'repeated_failure', signature: problem.signature, attempts: [...problem.attempts] }; } shouldReject(call: ToolCall): boolean { return ( this.#failureCount >= 2 && this.#lastFailureCall === hash(`${call.function.name}\0${call.function.arguments}`) ); } observe( calls: readonly ToolCall[], results: readonly ToolResult[], assistantText: string, ): StallObservation { let failure: StallObservation = { stalled: false }; for (let index = 0; index < calls.length; index += 1) { const observation = this.observeAttempt(calls[index]!, results[index]!); if (observation.stalled) failure = observation; } if (failure.stalled) return failure; const batchItems = calls .map((call, index) => ({ call, result: results[index]! })) .filter(({ result }) => result.ok || result.disposition !== 'deferred'); if (batchItems.length === 0) return { stalled: false }; const batch = hash( batchItems .map(({ call, result }) => { return `${call.function.name}\0${call.function.arguments}\0${result.ok ? result.content : result.error}`; }) .join('\x01'), ); if (assistantText.trim().length === 0 && batch === this.#lastBatch) this.#batchCount += 1; else { this.#lastBatch = batch; this.#batchCount = assistantText.trim().length === 0 ? 1 : 0; } return this.#batchCount >= 3 ? { stalled: true, reason: 'no_progress', signature: batch.slice(0, 16) } : { stalled: false }; } }