返回目录
模型与 MCP 插件

dsh-agent-loop-guard

GooDAnDReaDY/dsh-agent-loop-guard

Fail-closed runtime tool-call loop guard and assistant output repetition breaker for DeepSeek Harness

Stars
8
Forks
0
Issues
0
更新
5 天前

PROJECT TOPICS

项目标签

INSTALL REFERENCE

安装参考

未验证
dsh plugin --profile web add github:GooDAnDReaDY/dsh-agent-loop-guard

该命令指向仓库当前默认分支;尚无绑定当前 commit 的完整验证结果。

PROJECT README

README

📦 @goodandready/dsh-agent-loop-guard

Fail-Closed Runtime Tool-Call & Assistant Output Loop Breaker for DeepSeek Harness

npm version license DSH Plugin Node version

All Author Projects

🇬🇧 English • 🇷🇺 Русский • 🇨🇳 中文说明

⭐ If you like this plugin, please star it on GitHub — it shows me that the plugin is useful to you and motivates me to keep developing it.

🐛 If you find a bug or would like to request a feature, open a GitHub issue in any language — I will review your proposal and implement useful suggestions in a future plugin version.

⚡ Overview & Problem Solved

When autonomous AI coding agents encounter unexpected tool failures, ambiguous instructions, or hallucination loops, they often enter infinite retry cycles — repeatedly reading the same directory, editing identical lines without progress, or echoing identical output lines across streaming turns. These loops rapidly exhaust token budgets, lock execution threads, and waste API credits without ever completing user goals.

@goodandready/dsh-agent-loop-guard is a native host runtime plugin for DeepSeek Harness that intercepts and breaks loops before they spiral out of control:

  1. Progress-Aware Tool-Call Guard: Employs epoch-based state tracking so that repeated calls are blocked only when no meaningful state changes or new evidence appear. Legitimate productive iterations (e.g. read ➔ edit ➔ read ➔ edit) remain fully unrestricted.
  2. Assistant Output Loop Breaker: Detects text-only repetition (identical streaming lines or multi-line markdown blocks) across turns and steps, cleanly canceling runaway generation without damaging session history.
  3. Answer-Only Graceful Fallback: Instead of terminating abruptly, the plugin triggers structured DSH denials that guide the LLM into answering with text explaining the bottleneck.
  4. Target Quota Guard & Unchanged Re-Read Protection: Prevents runaway token-burning loops on individual files (such as 20+ re-reads of an unchanged file). Normalizes file paths across operating systems (extractTargetKey), detects identical content hashes (LOOP_GUARD_UNREFRESHED_READ), and enforces per-target quotas (LOOP_GUARD_TARGET_QUOTA) with non-latching denials preserving other tool operations.
  5. Error Thrashing Guard: Halts runaway failure cycles sharing normalized error signatures (FS_ENOENT, FS_EPERM, EXIT_*, HTTP_*, etc.) even when parameters vary.
  6. Smart Steering: 2-stage defense injecting actionable self-correction directives ([LOOP_GUARD_STEER]) before escalating to hard cancellation.
  7. Incident Journal & Diagnostic Dump: Circular telemetry buffer tracking recent incidents with execution chains and 1-click dump copying in Web UI.
  8. Sensitivity Presets: 1-click preset selector (Strict, Balanced, Autonomous Coding) for immediate threshold configuration.
  9. Zero Core Modifications: Implemented purely through Cordis lifecycle hooks (ctx.tools.guard, agent/pre-step, tools/execute, session/event).

🏗️ Architecture

graph TD
    subgraph DSH ["DeepSeek Harness Core Runtime"]
        Turn["Agent Turn Execution<br/>(LLM Reasoning & Tool Calls)"]
        Stream["Assistant Output Stream<br/>(text-delta & block-end)"]
        UserStop["User Message Analysis<br/>(Stop words: stop, halt, прекрати)"]
    end

    subgraph LoopGuard ["@goodandready/dsh-agent-loop-guard"]
        ToolInterceptor["ctx.tools.guard Interceptor<br/>(denyReason evaluation)"]
        ProgressEpoch["Progress Epoch Tracker<br/>(Result & Argument Fingerprints)"]
        OutputState["AssistantOutputGuardState<br/>(Line & Block Deduplication)"]
        SafeLogger["Sanitized Event Logger<br/>(Token/Secret Redaction)"]
    end

    subgraph Actions ["Enforcement Actions"]
        Allow["Allow Tool Execution<br/>(Fresh state or valid progress)"]
        Deny["Answer-Only Denial<br/>(Mandates text summary from agent)"]
        Cancel["Session Cancel<br/>(keepInbox: false on runaway text)"]
    end

    Turn -->|Pre-step & Tool call| ToolInterceptor
    ToolInterceptor --> ProgressEpoch
    ProgressEpoch -->|Productive Result Diff| Allow
    ProgressEpoch -->|Duplicate / Budget Exceeded| Deny
    Stream --> OutputState
    OutputState -->|Exceeds Line/Block Repeat Limit| Cancel
    UserStop -->|Immediate Latch| Deny
    Deny -.-> SafeLogger
    Cancel -.-> SafeLogger

✨ Full Feature Breakdown

1. Progress-Aware Tool Execution Tracking

Unlike naive counters that blindly limit tool invocations, dsh-agent-loop-guard distinguishes between productive iteration and stagnant loops:

  • Canonical Fingerprinting: Creates deterministic JSON signatures of tool arguments (callFingerprint) and results (resultFingerprint).
  • Progress Epochs: When an edit or command yields a different result, the session transitions to a new progress epoch, resetting the failure budget.
  • Granular HTTP/VCS Safety: Distinct endpoints and HTTP methods (e.g., Gitea API operations or curl scripts) are never collapsed under a shared base URL.
  • Progress Tool Whitelist: Designated progress tools (todo_write, etc.) maintain independent no-progress budgets so task checklists do not trigger false positives.

2. Guard Violation Codes & Enforcement Modes

When a loop is detected, the guard rejects the call with structured diagnostics and enforces Answer-Only Mode for the rest of the turn:

Guard Code Trigger Condition Default Limit Guard Action
LOOP_GUARD_STOP User sent stop command (stop, halt, cancel, стоп, остановись, прекрати) Immediate Rejects tool call; requires immediate text reply
LOOP_GUARD_DUPLICATE Identical call arguments with identical result to previous attempt 1 retry Blocks exact repeat; demands alternative approach
LOOP_GUARD_REPEAT Repeated calls within current group without state change maxCallsPerRepeatGroup (5) Prevents spinning on single tool
LOOP_GUARD_LIMIT Total non-productive tool attempts since last successful progress maxToolAttemptsPerTurn (64) Caps turn exploratory budget
LOOP_GUARD_PROGRESS_LIMIT Successive invocations of progress tools without content changes maxProgressToolCallsPerTurn (16) Prevents infinite todo-writing loops
LOOP_GUARD_OUTPUT Assistant generated identical lines or multi-line blocks maxRepeatedAssistantLines (5) Cancels session cleanly via agent.cancel()
LOOP_GUARD_PSEUDO_TOOL_CALL Consecutive completed turns outputting pseudo tool-call syntax (<invoke>, etc.) with 0 real tools pseudoToolCallThreshold (3) Cancels session cleanly via agent.cancel()
LOOP_GUARD_OSCILLATION Multi-tool alternating cycle (e.g. A ➔ B ➔ A ➔ B) repeated without state change maxOscillationRepeats (3) Blocks oscillating loop; provides actionable steering guidance
LOOP_GUARD_PAYLOAD_TRUNCATED Tool execution output exceeded maximum safe result size maxToolResultChars (65536) Safely truncates oversized payload (head + tail) with steering banner; records in telemetry

3. Assistant Output Stream Guard

Runaway LLM generation can manifest as repetitive narration without tool calls. The output guard monitors streaming text in real time:

  • Line Normalization: Collapses carriage returns and whitespace to catch formatted repetition.
  • Multi-Line Block Detection: Hashes blocks up to maxAssistantBlockChars (16,384 bytes) to detect cyclical paragraph generation.
  • Active Tool Immunity: While tool calls are executing, output cancellation is temporarily suppressed to avoid false alarms during long tasks.
  • Lossless Deduplication: Cleanses streaming chunks and message buffers without losing valid context.

4. Enterprise Privacy & Token Redaction

All loop guard warning logs automatically redact sensitive credentials:

  • Bearer tokens, passwords, cookies, and query parameter secrets (token=, api-key=, secret=) are replaced with [redacted] before reaching logs.
  • Deeply nested argument trees are bounded to prevent memory leaks during massive JSON payloads.

5. Native WebUI Settings, Telemetry & One-Click Updater

  • Integrated Settings Card: Placed directly inside DSH Web UI under Settings ➔ Plugins ➔ Plugin Settings (plugins.item / plugins.row.config).
  • Native DSH Design System: Styled exclusively using standard DSH design variables (--dsw-alias-*), accessible <label>/<input> associations (htmlFor/id), and smooth chevron rotation without external UI dependencies.
  • Live Protection Telemetry: Real-time counters of blocked loops (LOOP_GUARD_DUPLICATE, LOOP_GUARD_REPEAT, LOOP_GUARD_LIMIT, LOOP_GUARD_OUTPUT) with instant statistics reset via /api/@goodandready/dsh-agent-loop-guard/telemetry.
  • One-Click In-Place Updater: Seamless version verification against the npm registry and one-click upgrades via authenticated loopback API (/api/@goodandready/dsh-agent-loop-guard/update).

📦 Installation

Install via DeepSeek Harness CLI:

dsh plugin --profile web add @goodandready/dsh-agent-loop-guard

Restart DSH Web UI and reload your workspace.


⚙️ Configuration

Configure via config.yaml or through the Web UI settings:

# config.yaml
dsh-agent-loop-guard:
  maxToolAttemptsPerTurn: 64
  maxProgressToolCallsPerTurn: 16
  progressToolNames:
    - todo_write
  maxCallsPerRepeatGroup: 5
  blockExactDuplicates: true
  assistantOutputGuard: true
  maxRepeatedAssistantLines: 5
  maxRepeatedAssistantBlocks: 5
  maxAssistantBlockChars: 16384

Settings Reference Table

Key Type Default Description
maxToolAttemptsPerTurn number 64 Maximum un-productive tool attempts allowed before forcing an answer. Set to 0 to disable aggregate budget.
maxProgressToolCallsPerTurn number 16 Maximum consecutive calls to progress tools (todo_write) without substantive progress.
progressToolNames array ["todo_write"] Array of tool names considered progress markers.
maxCallsPerRepeatGroup number 5 Maximum tool calls allowed within the same repeat group without producing a new result.
maxCallsPerToolPerTurn number 5 (Deprecated) Legacy alias for maxCallsPerRepeatGroup. If both are specified, maxCallsPerRepeatGroup takes precedence. Omitted from UI card to avoid confusion.
strictTools array [] Array of tool names subjected to lower repeat tolerance (e.g. mutating tools).
strictToolLimit number 3 Maximum repeat count allowed for tools specified in strictTools.
blockExactDuplicates boolean true Immediately block consecutive identical calls with zero state change.
dryRunMode boolean false Audit mode: logs violations and tracks telemetry without aborting tool calls.
assistantOutputGuard boolean true Enable real-time detection and cancellation of repetitive assistant output loops.
maxRepeatedAssistantLines number 5 Threshold of consecutive identical output lines to trigger session cancellation.
maxRepeatedAssistantBlocks number 5 Threshold of repeated multi-line markdown blocks before aborting generation.
maxAssistantBlockChars number 16384 Maximum byte length captured for block fingerprinting.
pseudoToolCallThreshold number 3 Consecutive completed turns with pseudo tool calls and 0 real tools before cancellation (0 = disabled).
pseudoToolCallPatterns array [] Custom regex or string patterns for pseudo tool-call detection.
stopPatterns array [] Custom regex or string patterns for user stop commands.
oscillationDetection boolean true Enable detection of alternating ping-pong cycles across tools (e.g. A ➔ B ➔ A ➔ B).
maxOscillationRepeats number 3 Maximum cycles of 2-4 step oscillations permitted before loop block.
payloadBloatGuard boolean true Enable truncation and payload guard for oversized tool responses.
maxToolResultChars number 65536 Maximum allowed character length for tool results before truncating (0 = disabled).
errorThrashingGuard boolean true Enable fail-loop detection and fast-abort on repeated tool errors.
maxConsecutiveFailures number 4 Maximum consecutive tool errors before error thrashing block is enforced.
adaptiveSteering boolean true Enable smart steering to guide agents toward recovery before hard turn termination.
targetQuotaGuard boolean true Enable target-level per-file and per-resource quota protection.
maxUnchangedReadsPerTarget number 3 Maximum repeated reads of an unchanged file/resource target before refusal.
maxReadsPerTarget number 6 Maximum total read operations allowed on a single target per turn.
maxEditsPerTarget number 8 Maximum edit or write operations allowed on a single target per turn.
maxTargetAttempts number 12 Maximum total tool operations allowed across all actions for a single target per turn.

🧪 Testing & Verification

Run the full automated test suite covering all loop denial paths, streaming output guards, and progress epochs:

npm test
npm run check

📄 License

CLASSIFICATION EVIDENCE

分类依据

项目类型插件
功能分类模型与 MCP
规则置信度中

系统优先读取 GitHub Topics,再与站内分类词典和词根规则比对。当前命中: deepseek-harness。