@goodandready/dsh-agent-loop-guard 0.2.29 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +19 -0
- package/README.md +6 -1
- package/README.ru.md +6 -1
- package/README.zh.md +6 -1
- package/lib/client.js +242 -237
- package/lib/guard-helpers.js +594 -264
- package/lib/guard-state.js +135 -88
- package/lib/index.js +9 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.3.1] - 2026-11-16
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- **Target Quota Guard (#146, gh-3)**: Multi-layer protection against runaway per-file loop operations (such as repeated reads of unchanged files or endless edit-fail-retry loops on a single file).
|
|
7
|
+
- **Canonical Path & Target Key Extraction (`extractTargetKey`)**: Unifies and normalizes target parameters across diverse tool schemas (`path`, `file`, `filePath`, `target`, `filename`, `uri`, `dest`, `destination`, `src`, `source`, `params.path`, `params.file`), standardizing backslashes (`\` to `/`), stripping `file://`, trimming whitespace, and collapsing redundant relative path segments.
|
|
8
|
+
- **Unchanged Re-Read Protection (`maxUnchangedReadsPerTarget`)**: Tracks content fingerprints (`resultFingerprint`) across file reads per session turn. Rejects re-reads when the content has not changed and exceeds `maxUnchangedReadsPerTarget` (default: 3). Resets automatically when the target is successfully modified.
|
|
9
|
+
- **Per-Target Operation Quotas (`maxReadsPerTarget`, `maxEditsPerTarget`, `maxTargetAttempts`)**: Prevents excessive operations on any single target within a turn, independent of argument variations or interleaved tool calls.
|
|
10
|
+
- **Non-Latching Denial Architecture (`LOOP_GUARD_TARGET_QUOTA`, `LOOP_GUARD_UNREFRESHED_READ`)**: Target-specific violations reject *only* the offending tool call to that target, without latching the session into global `answerOnly` mode. The agent remains free to explore alternative files, call other tools, or execute cleanup commands.
|
|
11
|
+
- **UI & Presets Integration**: Added 5 user-facing fields to `Config` with `.volatile()` reactivity, native UI controls in DSH Web UI Settings Card with complete localization in English, Russian, and Chinese, and updated `Strict`, `Balanced`, and `Autonomous` presets.
|
|
12
|
+
|
|
13
|
+
## [0.3.0] - 2026-11-14
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
- **Error Thrashing Guard (#141)**: Automatic detection and cancellation of tool failure loops (`LOOP_GUARD_ERROR_THRASHING`). Extracts normalized error signatures (`FS_ENOENT`, `FS_EPERM`, `FS_ENOSPC`, `EXIT_*`, `HTTP_*`, `TIMEOUT`, `CONN_REFUSED`) across tool calls with different parameters. Halts runaway retry cycles when failures exceed `maxConsecutiveFailures` (default: 4, configurable). Resets immediately on productive tool progress.
|
|
17
|
+
- **Smart Steering (#142)**: 2-stage defensive mechanism that provides actionable steering directives (`[LOOP_GUARD_STEER] Warning: ...`) before hard cancellation. Injects contextual guidance prompting the agent to change tool parameters, switch tools, diagnose root causes, or provide a text answer. Escalates to hard stop (`answerOnly`) if the agent ignores the directive. Configurable via `adaptiveSteering` (boolean, default: true).
|
|
18
|
+
- **Incident Journal & Post-Mortem in UI (#143)**: Circular buffer (capacity 30) capturing all violations and steering events with timestamp, session, code, tool name, reason, and call chain history. Exposed via `/api/@goodandready/dsh-agent-loop-guard/telemetry` with reverse chronological order (last 20). Integrated into DSH Web UI Settings Card with incident list and 1-click "Copy Diagnostic Dump" button for rapid troubleshooting and bug reports.
|
|
19
|
+
- **Sensitivity Presets (#144)**: 1-click preset selector in DSH Web UI Settings Card offering 3 tuned profiles: `Strict` (tight limits for small or hallucinating models), `Balanced` (default optimal limits for production workloads), and `Autonomous Coding` (expanded limits for deep multi-file refactoring). Exported `GUARD_PRESETS` in public API. Complete localization in EN, RU, and ZH.
|
|
20
|
+
|
|
21
|
+
|
|
3
22
|
## [0.2.29] - 2026-11-12
|
|
4
23
|
|
|
5
24
|
### Added
|
package/README.md
CHANGED
|
@@ -44,7 +44,12 @@ When autonomous AI coding agents encounter unexpected tool failures, ambiguous i
|
|
|
44
44
|
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.
|
|
45
45
|
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.
|
|
46
46
|
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.
|
|
47
|
-
4. **
|
|
47
|
+
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.
|
|
48
|
+
5. **Error Thrashing Guard**: Halts runaway failure cycles sharing normalized error signatures (`FS_ENOENT`, `FS_EPERM`, `EXIT_*`, `HTTP_*`, etc.) even when parameters vary.
|
|
49
|
+
6. **Smart Steering**: 2-stage defense injecting actionable self-correction directives (`[LOOP_GUARD_STEER]`) before escalating to hard cancellation.
|
|
50
|
+
7. **Incident Journal & Diagnostic Dump**: Circular telemetry buffer tracking recent incidents with execution chains and 1-click dump copying in Web UI.
|
|
51
|
+
8. **Sensitivity Presets**: 1-click preset selector (`Strict`, `Balanced`, `Autonomous Coding`) for immediate threshold configuration.
|
|
52
|
+
9. **Zero Core Modifications**: Implemented purely through Cordis lifecycle hooks (`ctx.tools.guard`, `agent/pre-step`, `tools/execute`, `session/event`).
|
|
48
53
|
|
|
49
54
|
---
|
|
50
55
|
|
package/README.ru.md
CHANGED
|
@@ -44,7 +44,12 @@
|
|
|
44
44
|
1. **Контроль прогресса инструментов (Progress-Aware Epochs)**: повторные вызовы инструментов блокируются *только тогда*, когда с прошлой попытки не изменилось состояние системы или результат. Легитимные продуктивные циклы (например, `чтение` ➔ `правка` ➔ `чтение` ➔ `правка`) выполняются абсолютно свободно.
|
|
45
45
|
2. **Предохранитель генерации текста (Assistant Output Loop Guard)**: отслеживает повторение отдельных строк и целых многострочных абзацев между шагами и ходами, выполняя мягкую отмену генерации без потери истории диалога.
|
|
46
46
|
3. **Безопасный переход в режим ответа (Answer-Only Mode)**: при фиксации зацикливания инструмент не просто падает с ошибкой, а возвращает структурированный отказ, обязывающий модель сформулировать текстовый ответ пользователю с объяснением проблемы.
|
|
47
|
-
4.
|
|
47
|
+
4. **Target Quota Guard & защита от повторных чтений**: Предотвращает бесконечное сжигание токенов на отдельных файлах (например, 20+ повторных чтений файла без изменений). Канонизирует пути файлов (`extractTargetKey`), отслеживает неизмененный контент (`LOOP_GUARD_UNREFRESHED_READ`) и лимитирует операции над файлом (`LOOP_GUARD_TARGET_QUOTA`) с мягким неканоническим отказом без блокировки других инструментов.
|
|
48
|
+
5. **Error Thrashing Guard**: Предотвращение серий одинаковых ошибок инструментов (`FS_ENOENT`, `FS_EPERM`, `EXIT_*`, `HTTP_*` и др.) даже при разных параметрах.
|
|
49
|
+
6. **Smart Steering**: Двухступенчатая защита с упреждающей подсказкой самоисправления (`[LOOP_GUARD_STEER]`) до применения жесткого cancel.
|
|
50
|
+
7. **Журнал инцидентов и дамп диагностики**: Кольцевой буфер инцидентов с цепочками вызовов и кнопка быстрого копирования дампа в Web UI.
|
|
51
|
+
8. **Пресеты чувствительности**: Переключение профилей в один клик (`Strict`, `Balanced`, `Autonomous Coding`) в карточке настроек.
|
|
52
|
+
9. **Маскирование секретов в журналах**: любые ключи доступа, токены и пароли автоматически заменяются на `[redacted]` в диагностических логах.
|
|
48
53
|
|
|
49
54
|
---
|
|
50
55
|
|
package/README.zh.md
CHANGED
|
@@ -44,7 +44,12 @@
|
|
|
44
44
|
1. **进度感知型工具防循环(Progress-Aware Epochs)**:仅在工具调用未产生任何状态变化或新证据时判定为死循环。合法的有效迭代(如 `读` ➔ `写` ➔ `读` ➔ `写`)完全不受限制。
|
|
45
45
|
2. **文本输出流防死循环(Assistant Output Guard)**:实时监测智能体流式输出,精准识别跨回合或跨步骤的单行及多行 Markdown 段落重复,安全中断生成而不破坏历史对话。
|
|
46
46
|
3. **平滑降级至仅回答模式(Answer-Only Mode)**:触发死循环拦截时,向模型返回结构化 DSH 拒绝信息,强制要求模型输出文本向用户说明当前遇到的瓶颈。
|
|
47
|
-
4.
|
|
47
|
+
4. **目标配额守卫与无变化重复读取保护(Target Quota Guard)**:防止智能体针对单个文件无限空转消耗 Token(如重复读取未变动文件 20+ 次)。自动规范化跨平台路径(`extractTargetKey`),检测无变化内容哈希(`LOOP_GUARD_UNREFRESHED_READ`),施加单目标调用配额(`LOOP_GUARD_TARGET_QUOTA`),并提供非全局锁定的点对点拒绝机制。
|
|
48
|
+
5. **工具重复报错拦截(Error Thrashing Guard)**:即使调用参数不同,也能归一化识别相同错误类型(`FS_ENOENT`、`EXIT_*`、`HTTP_*` 等)并阻断无效重试。
|
|
49
|
+
6. **智能自纠正引导(Smart Steering)**:两阶段保护机制,在硬熔断前提供纠偏提示(`[LOOP_GUARD_STEER]`),引导模型自主改变策略。
|
|
50
|
+
7. **拦截日志与一键诊断包**:环形遥测缓冲区记录最近事件及其调用链,并在设置面板提供一键复制诊断数据功能。
|
|
51
|
+
8. **灵敏度预设(Presets)**:设置卡片提供 Strict / Balanced / Autonomous 一键预设切换。
|
|
52
|
+
9. **日志隐私脱敏**:所有安全警告日志自动对 Token、密码、API Key 等敏感数据进行 `[redacted]` 掩码处理。
|
|
48
53
|
|
|
49
54
|
---
|
|
50
55
|
|