@goodandready/dsh-agent-loop-guard 0.2.8 → 0.2.10
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 +73 -0
- package/README.md +10 -52
- package/README.ru.md +17 -55
- package/README.zh.md +16 -55
- package/lib/client.js +20 -17
- package/lib/plugin-updater.js +18 -7
- package/package.json +2 -2
- package/docs/design/DESIGN.md +0 -104
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
+
|
|
8
|
+
## [0.2.10] - 2026-09-18
|
|
9
|
+
|
|
10
|
+
- **Documentation & Packaging Architecture**:
|
|
11
|
+
- Migrated cumulative version changelogs from all three README files (`README.md`, `README.ru.md`, `README.zh.md`) to canonical root `CHANGELOG.md` adhering to Keep a Changelog standard (#56).
|
|
12
|
+
- Explicitly added `CHANGELOG.md` to `files` whitelist in `package.json` for npm distribution.
|
|
13
|
+
- Expanded thematic feature sections across all three language documentations with dedicated coverage of Native WebUI Settings Card, Protection Telemetry, and One-Click In-Place Updater.
|
|
14
|
+
- Synchronized automated test count to 51 tests across Russian and Chinese documentations.
|
|
15
|
+
- Updated design contract status and documentation standards in `docs/design/DESIGN.md`.
|
|
16
|
+
|
|
17
|
+
## [0.2.9] - 2026-09-18
|
|
18
|
+
|
|
19
|
+
- **Theme Guard & Token Integrity**: eliminated 100% of hardcoded hex and rgba colors from `lib/client.js` in both CSS styles and JSX inline markup, switching entirely to DSH design tokens (`var(--dsw-alias-*)`) and `color-mix(in srgb, ...)`; added automated regression test `test/theme-guard.test.js` enforcing zero hex/rgba literals (#53, #39).
|
|
20
|
+
- **Updater Resilience**: hardened `currentVersion` and status endpoint against corrupted, non-JSON or missing manifests, returning safe fallback status without throwing unhandled exceptions (#47).
|
|
21
|
+
- **Distribution & Package Hygiene**: removed internal `docs` directory from npm distribution package `files` whitelist; added diagnostic warning with `bestEffort` annotation to client primitives loader; pruned stale branches and worktrees (#54).
|
|
22
|
+
- **Test Suite**: expanded to 51 automated tests covering theme token compliance and manifest corruption handling.
|
|
23
|
+
|
|
24
|
+
## [0.2.8] - 2026-09-18
|
|
25
|
+
|
|
26
|
+
- **Host & Security Engine Hardening**:
|
|
27
|
+
- Expanded stop keyword detector with Russian keyword `'стоп'` for multilingual interrupt safety (#43).
|
|
28
|
+
- Enforced loopback and same-origin validation on `/telemetry` endpoint (#37).
|
|
29
|
+
- Eliminated dead `if(true)` branch and unused `releaseCall` method in core guard engine (#44).
|
|
30
|
+
- Deprecated legacy alias `maxCallsPerToolPerTurn` in configuration schema per standard (#48).
|
|
31
|
+
- Replaced empty catch blocks with structured debug logging via `ctx.logger('loop-guard')` (#49).
|
|
32
|
+
- **WebUI Client & Design System Alignment**:
|
|
33
|
+
- Aligned settings card with DSH standard CSS variables `--dsw-alias-*` and primitive chevron icon with smooth 180° rotation (#39).
|
|
34
|
+
- Removed emoji headers (`🛑`, `📊`) for a clean, professional interface (#39).
|
|
35
|
+
- Fixed localization reactivity by resolving locale from `ctx.locale.getLocale()` and registering within `ctx.effect` lifecycle (#40, #41).
|
|
36
|
+
- Removed hardcoded version strings; version is dynamically verified from updater endpoint (#42).
|
|
37
|
+
- Enhanced accessibility: all form controls now link `<label>` with `<input>` using `htmlFor` and explicit IDs (#45).
|
|
38
|
+
- Added robust HTTP error checking (`res.ok`) and user-facing error indicators for updater and telemetry actions (#49).
|
|
39
|
+
- **Distribution & Repository Hygiene**:
|
|
40
|
+
- Cleaned repository root from temporary tarballs and pruned 15 merged branches (#46).
|
|
41
|
+
- Removed internal planning and architectural documentation from the public package (#35, #36).
|
|
42
|
+
- Documented canonical updater architecture and rationale in `DESIGN.md` (#47).
|
|
43
|
+
- Full automated test suite expanded to 49 comprehensive unit and integration tests.
|
|
44
|
+
|
|
45
|
+
## [0.2.7] - 2026-09-17
|
|
46
|
+
|
|
47
|
+
- **Deferred Slot Injection**: wrapped `settings.plugin.item` registration in `registerSlotWhenReady` with `ctx.slots.inject` to prevent `slot "settings.plugin.item" is not declared` crash during early plugin initialization (#33).
|
|
48
|
+
- **Slot Specification Compliance**: aligned slot registration descriptor to use `key: NS` and `inject: () => ({ ctx })` according to `dsh-plugin-authoring` standard (#33).
|
|
49
|
+
- **Automated Client Suite**: added tests in `test/client.test.js` validating deferred slot injection and safe fallback (#33).
|
|
50
|
+
|
|
51
|
+
## [0.2.6] - 2026-09-16
|
|
52
|
+
|
|
53
|
+
- **Browser ModuleLoader Fix**: added explicit `var exports = module.exports;` in `lib/client.js` factory function to prevent `ReferenceError: exports is not defined` when client bundle is imported by DSH WebUI ModuleLoader (#31).
|
|
54
|
+
- **Client Test Suite**: added automated VM test in `test/client.test.js` validating client script execution in strict ModuleLoader environment (#31).
|
|
55
|
+
|
|
56
|
+
## [0.2.5] - 2026-09-15
|
|
57
|
+
|
|
58
|
+
- **One-Click Updater**: integrated reusable host-side updater (`lib/plugin-updater.js`) with endpoint `/api/@goodandready/dsh-agent-loop-guard/update` and settings UI button/status (#29).
|
|
59
|
+
- **Strict Tools & Adaptive Budgets**: added `strictTools` and `strictToolLimit` to impose tighter quotas on sensitive or mutating commands (#29).
|
|
60
|
+
- **Dry-Run / Audit-Only Mode**: added `dryRunMode` setting to audit agent execution and record metrics without breaking active tool calls (#29).
|
|
61
|
+
- **Protection Telemetry & Observability**: live incident counters (`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`) exposed via endpoint `/api/@goodandready/dsh-agent-loop-guard/telemetry` and rendered in the UI card with one-click reset (#29).
|
|
62
|
+
- **Smart Recovery Guidance**: violation messages now provide structured steering instructions for LLMs (e.g. DeepSeek-R1 / V3) indicating exact corrective actions (#29).
|
|
63
|
+
- **Strict Multilingual Standards**: codebase cleaned to canonical English (`en`) and complete Chinese (`zh`) with zero internal Russian code, registered translation issue #197 in `goodandready/dsh-russian-lang` (#29).
|
|
64
|
+
- **Design Contract**: created mandatory `docs/design/DESIGN.md` per `project-design-contract` standard (#29).
|
|
65
|
+
- **Expanded Test Suite**: 37 automated tests covering updater semver/security, telemetry tracking, strict tool thresholds, and dry-run mode (#29).
|
|
66
|
+
|
|
67
|
+
## [0.2.4] - 2026-09-14
|
|
68
|
+
|
|
69
|
+
- **Settings UI**: allow saving `0` for `maxToolAttemptsPerTurn` to cleanly disable aggregate turn budget (#28).
|
|
70
|
+
- **Outcome Analysis**: recognize `{ error: null }` and `{ error: false }` as non-failures in execution outcome evaluation (#28).
|
|
71
|
+
- **Alternating Loop Breaker**: track prior results per tool fingerprint (`state.lastResults`) to block alternating non-productive loops (A ➔ B ➔ A ➔ B) (#28).
|
|
72
|
+
- **Settings Card**: add reactive `settings.plugin.item` card in DSH Settings with live configuration updates (#26).
|
|
73
|
+
- **Test Suite**: expanded to 31 automated tests covering error edge cases and alternating loop enforcement (#28).
|
package/README.md
CHANGED
|
@@ -123,6 +123,13 @@ All loop guard warning logs automatically redact sensitive credentials:
|
|
|
123
123
|
* Bearer tokens, passwords, cookies, and query parameter secrets (`token=`, `api-key=`, `secret=`) are replaced with `[redacted]` before reaching logs.
|
|
124
124
|
* Deeply nested argument trees are bounded to prevent memory leaks during massive JSON payloads.
|
|
125
125
|
|
|
126
|
+
### 5. Native WebUI Settings, Telemetry & One-Click Updater
|
|
127
|
+
|
|
128
|
+
* **Integrated Settings Card**: Placed directly inside DSH Web UI under *Settings ➔ Plugins ➔ Plugin Settings* (`settings.plugin.item`, order 95).
|
|
129
|
+
* **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.
|
|
130
|
+
* **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`.
|
|
131
|
+
* **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`).
|
|
132
|
+
|
|
126
133
|
---
|
|
127
134
|
|
|
128
135
|
## 📦 Installation
|
|
@@ -189,55 +196,6 @@ npm run check
|
|
|
189
196
|
|
|
190
197
|
## 📄 License
|
|
191
198
|
|
|
192
|
-
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
- **Host & Security Engine Hardening**:
|
|
197
|
-
- Expanded stop keyword detector with Russian keyword `'стоп'` for multilingual interrupt safety (#43).
|
|
198
|
-
- Enforced loopback and same-origin validation on `/telemetry` endpoint (#37).
|
|
199
|
-
- Eliminated dead `if(true)` branch and unused `releaseCall` method in core guard engine (#44).
|
|
200
|
-
- Deprecated legacy alias `maxCallsPerToolPerTurn` in configuration schema per standard (#48).
|
|
201
|
-
- Replaced empty catch blocks with structured debug logging via `ctx.logger('loop-guard')` (#49).
|
|
202
|
-
- **WebUI Client & Design System Alignment**:
|
|
203
|
-
- Aligned settings card with DSH standard CSS variables `--dsw-alias-*` and primitive chevron icon with smooth 180° rotation (#39).
|
|
204
|
-
- Removed emoji headers (`🛑`, `📊`) for a clean, professional interface (#39).
|
|
205
|
-
- Fixed localization reactivity by resolving locale from `ctx.locale.getLocale()` and registering within `ctx.effect` lifecycle (#40, #41).
|
|
206
|
-
- Removed hardcoded version strings; version is dynamically verified from updater endpoint (#42).
|
|
207
|
-
- Enhanced accessibility: all form controls now link `<label>` with `<input>` using `htmlFor` and explicit IDs (#45).
|
|
208
|
-
- Added robust HTTP error checking (`res.ok`) and user-facing error indicators for updater and telemetry actions (#49).
|
|
209
|
-
- **Distribution & Repository Hygiene**:
|
|
210
|
-
- Cleaned repository root from temporary tarballs and pruned 15 merged branches (#46).
|
|
211
|
-
- Removed internal planning and architectural documentation from the public package (#35, #36).
|
|
212
|
-
- Documented canonical updater architecture and rationale in `DESIGN.md` (#47).
|
|
213
|
-
- Full automated test suite expanded to 49 comprehensive unit and integration tests.
|
|
214
|
-
|
|
215
|
-
## Changed in v0.2.7
|
|
216
|
-
|
|
217
|
-
- **Deferred Slot Injection**: wrapped `settings.plugin.item` registration in `registerSlotWhenReady` with `ctx.slots.inject` to prevent `slot "settings.plugin.item" is not declared` crash during early plugin initialization (#33).
|
|
218
|
-
- **Slot Specification Compliance**: aligned slot registration descriptor to use `key: NS` and `inject: () => ({ ctx })` according to `dsh-plugin-authoring` standard (#33).
|
|
219
|
-
- **Automated Client Suite**: added tests in `test/client.test.js` validating deferred slot injection and safe fallback (#33).
|
|
220
|
-
|
|
221
|
-
## Changed in v0.2.6
|
|
222
|
-
|
|
223
|
-
- **Browser ModuleLoader Fix**: added explicit `var exports = module.exports;` in `lib/client.js` factory function to prevent `ReferenceError: exports is not defined` when client bundle is imported by DSH WebUI ModuleLoader (#31).
|
|
224
|
-
- **Client Test Suite**: added automated VM test in `test/client.test.js` validating client script execution in strict ModuleLoader environment (#31).
|
|
225
|
-
|
|
226
|
-
## Changed in v0.2.5
|
|
227
|
-
|
|
228
|
-
- **One-Click Updater**: integrated reusable host-side updater (`lib/plugin-updater.js`) with endpoint `/api/@goodandready/dsh-agent-loop-guard/update` and settings UI button/status (#29).
|
|
229
|
-
- **Strict Tools & Adaptive Budgets**: added `strictTools` and `strictToolLimit` to impose tighter quotas on sensitive or mutating commands (#29).
|
|
230
|
-
- **Dry-Run / Audit-Only Mode**: added `dryRunMode` setting to audit agent execution and record metrics without breaking active tool calls (#29).
|
|
231
|
-
- **Protection Telemetry & Observability**: live incident counters (`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`) exposed via endpoint `/api/@goodandready/dsh-agent-loop-guard/telemetry` and rendered in the UI card with one-click reset (#29).
|
|
232
|
-
- **Smart Recovery Guidance**: violation messages now provide structured steering instructions for LLMs (e.g. DeepSeek-R1 / V3) indicating exact corrective actions (#29).
|
|
233
|
-
- **Strict Multilingual Standards**: codebase cleaned to canonical English (`en`) and complete Chinese (`zh`) with zero internal Russian code, registered translation issue #197 in `goodandready/dsh-russian-lang` (#29).
|
|
234
|
-
- **Design Contract**: created mandatory `docs/design/DESIGN.md` per `project-design-contract` standard (#29).
|
|
235
|
-
- **Expanded Test Suite**: 37 automated tests covering updater semver/security, telemetry tracking, strict tool thresholds, and dry-run mode (#29).
|
|
236
|
-
|
|
237
|
-
## Changed in v0.2.4
|
|
238
|
-
|
|
239
|
-
- **Settings UI**: allow saving `0` for `maxToolAttemptsPerTurn` to cleanly disable aggregate turn budget (#28).
|
|
240
|
-
- **Outcome Analysis**: recognize `{ error: null }` and `{ error: false }` as non-failures in execution outcome evaluation (#28).
|
|
241
|
-
- **Alternating Loop Breaker**: track prior results per tool fingerprint (`state.lastResults`) to block alternating non-productive loops (A ➔ B ➔ A ➔ B) (#28).
|
|
242
|
-
- **Settings Card**: add reactive `settings.plugin.item` card in DSH Settings with live configuration updates (#26).
|
|
243
|
-
- **Test Suite**: expanded to 31 automated tests covering error edge cases and alternating loop enforcement (#28).
|
|
199
|
+
* **License**: MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
200
|
+
* **Changelog**: Detailed release history and migration notes are maintained in [CHANGELOG.md](CHANGELOG.md).
|
|
201
|
+
|
package/README.ru.md
CHANGED
|
@@ -115,6 +115,19 @@ graph TD
|
|
|
115
115
|
* **Иммунитет во время выполнения инструментов**: пока агент ждёт завершения длительной команды, отмена текста временно блокируется.
|
|
116
116
|
* **Чистый сброс**: при отправке нового сообщения пользователем состояние детектора полностью очищается.
|
|
117
117
|
|
|
118
|
+
### 4. Санитизация журналов и защита приватности
|
|
119
|
+
|
|
120
|
+
Все предупреждающие записи журнала автоматически маскируют чувствительные учетные данные:
|
|
121
|
+
* Токены Bearer, пароли, cookie и секреты в query-параметрах (`token=`, `api-key=`, `secret=`) заменяются на `[redacted]` до записи в лог.
|
|
122
|
+
* Ограничена глубина вложенности деревьев аргументов для предотвращения утечек памяти при разборе крупных JSON-структур.
|
|
123
|
+
|
|
124
|
+
### 5. Веб-интерфейс, живая телеметрия и обновление в один клик
|
|
125
|
+
|
|
126
|
+
* **Интегрированная карточка настроек**: нативно встроена во вкладку *«Настройки → Плагины → Настройки плагинов»* (`settings.plugin.item`, order 95).
|
|
127
|
+
* **Дизайн-система DSH**: построена строго на системных переменных DSH (`--dsw-alias-*`), доступных связках `<label>`/`<input>` (`htmlFor`/`id`) и нативном шевроне с плавной анимацией без тяжёлых сторонних UI-библиотек.
|
|
128
|
+
* **Телеметрия инцидентов**: живые счётчики заблокированных петель (`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`) с возможностью мгновенного сброса через защищённый маршрут `/api/@goodandready/dsh-agent-loop-guard/telemetry`.
|
|
129
|
+
* **One-Click Updater**: проверка актуальных версий в реестре npm и обновление плагина в один клик через защищённый loopback API (`/api/@goodandready/dsh-agent-loop-guard/update`).
|
|
130
|
+
|
|
118
131
|
---
|
|
119
132
|
|
|
120
133
|
## 📦 Установка
|
|
@@ -170,7 +183,7 @@ dsh-agent-loop-guard:
|
|
|
170
183
|
|
|
171
184
|
## 🧪 Тестирование
|
|
172
185
|
|
|
173
|
-
Запуск набора из
|
|
186
|
+
Запуск полного набора из 51 автоматизированного теста и статической проверки:
|
|
174
187
|
|
|
175
188
|
```bash
|
|
176
189
|
npm test
|
|
@@ -181,57 +194,6 @@ npm run check
|
|
|
181
194
|
|
|
182
195
|
## 📄 Лицензия
|
|
183
196
|
|
|
184
|
-
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
## Изменения в версии v0.2.8
|
|
189
|
-
|
|
190
|
-
- **Усиление серверного движка и безопасности**:
|
|
191
|
-
- Расширен список стоп-слов русским ключевым словом `'стоп'` для мультиязычного безопасного прерывания циклов (#43).
|
|
192
|
-
- Реализована строгая валидация loopback и same-origin для эндпоинта `/telemetry` (#37).
|
|
193
|
-
- Удалена мертвая ветка `if(true)` и неиспользуемый метод `releaseCall` в ядре guard (#44).
|
|
194
|
-
- Устаревший алиас `maxCallsPerToolPerTurn` корректно помечен как deprecated в схеме параметров (#48).
|
|
195
|
-
- Пустые блоки `catch {}` заменены структурированным логированием через `ctx.logger('loop-guard')` (#49).
|
|
196
|
-
- **Клиентский интерфейс и дизайн-система DSH**:
|
|
197
|
-
- Карточка настроек переведена на стандартные CSS-переменные DSH `--dsw-alias-*` и системный шеврон с плавной ротацией на 180° (#39).
|
|
198
|
-
- Удалены эмодзи из заголовков (`🛑`, `📊`) для соответствия строгому нативному стилю DSH (#39).
|
|
199
|
-
- Исправлена реактивность локализации через `ctx.locale.getLocale()` и регистрацию в жизненном цикле `ctx.effect` (#40, #41).
|
|
200
|
-
- Удалены захардкоженные версии; актуальная версия динамически проверяется через эндпоинт обновления (#42).
|
|
201
|
-
- Доступность (a11y): все поля формы связывают `<label>` и `<input>` через `htmlFor` и явные ID (#45).
|
|
202
|
-
- Добавлена проверка `res.ok` и отображение понятных сообщений об ошибках при сбое сети в обновлении и телеметрии (#49).
|
|
203
|
-
- **Дистрибуция и репозиторий**:
|
|
204
|
-
- Очищен корень проекта от временных `.tgz` архивов, удалены 15 смерженных устаревших веток (#46).
|
|
205
|
-
- Внутренние архитектурные и проектные черновики исключены из публичного пакета (#35, #36).
|
|
206
|
-
- Зафиксирована архитектура канонического апдейтера в `DESIGN.md` (#47).
|
|
207
|
-
- Полный набор автоматических тестов расширен до 49 тестов.
|
|
208
|
-
|
|
209
|
-
## Изменения в версии v0.2.7
|
|
210
|
-
|
|
211
|
-
- **Отложенная инъекция слота настроек**: регистрация карточки `settings.plugin.item` обёрнута в `registerSlotWhenReady` с использованием `ctx.slots.inject`, что исключает ошибку `slot "settings.plugin.item" is not declared` при ранней загрузке плагина в браузере (#33).
|
|
212
|
-
- **Соответствие стандарту слотов DSH**: дескриптор слота переведён на `key: NS` и `inject: () => ({ ctx })` согласно стандарту `dsh-plugin-authoring` (#33).
|
|
213
|
-
- **Автотесты клиента**: расширен тестовый набор `test/client.test.js` с проверкой подписки через `slots.inject` и безопасного fallback-поведения (#33).
|
|
214
|
-
|
|
215
|
-
## Изменения в версии v0.2.6
|
|
216
|
-
|
|
217
|
-
- **Исправление загрузчика браузера**: добавлена явная инициализация `var exports = module.exports;` в функции factory `lib/client.js`, исключающая ошибку `ReferenceError: exports is not defined` при импорте клиентского бандла загрузчиком веб-интерфейса DSH ModuleLoader (#31).
|
|
218
|
-
- **Тестирование клиентского бандла**: добавлен автоматический тест `test/client.test.js` с изолированным контекстом Node VM для проверки клиентского скрипта (#31).
|
|
219
|
-
|
|
220
|
-
## Изменения в версии v0.2.5
|
|
221
|
-
|
|
222
|
-
- **Обновление в один клик**: интеграция хостового модуля обновления (`lib/plugin-updater.js`), эндпоинта `/api/@goodandready/dsh-agent-loop-guard/update` и кнопки/индикатора в карточке настроек (#29).
|
|
223
|
-
- **Строгий контроль чувствительных инструментов**: добавлены настройки `strictTools` и `strictToolLimit` для ужесточения лимитов на мутирующие операции (#29).
|
|
224
|
-
- **Режим аудита (Dry-Run)**: добавлен параметр `dryRunMode` для аудита работы агента и сбора телеметрии без блокировки вызовов (#29).
|
|
225
|
-
- **Телеметрия инцидентов**: фиксация счетчиков нарушений (`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`), эндпоинт `/api/@goodandready/dsh-agent-loop-guard/telemetry`, панель метрик в карточке и кнопка сброса (#29).
|
|
226
|
-
- **Инструкции по восстановлению для LLM**: при блокировках агенту отправляются структурированные подсказки по изменению стратегии (#29).
|
|
227
|
-
- **Строгая локализация EN/ZH**: кодовая база очищена до канонического английского (`en`) и китайского (`zh`), русификация выделена в Issue #197 проекта `goodandready/dsh-russian-lang` (#29).
|
|
228
|
-
- **Дизайн-контракт**: оформлен документ `docs/design/DESIGN.md` согласно стандарту `project-design-contract` (#29).
|
|
229
|
-
- **Расширенный тестовый набор**: 37 тестов, покрывающих обновление, безопасность, квоты и аудит (#29).
|
|
230
|
-
|
|
231
|
-
## Изменения в версии v0.2.4
|
|
232
|
-
|
|
233
|
-
- **Интерфейс настроек**: исправлено сохранение `0` для `maxToolAttemptsPerTurn` — теперь общий лимит попыток можно отключить через карточку плагина (#28).
|
|
234
|
-
- **Анализ результатов**: возвращаемые объектами поля `{ error: null }` и `{ error: false }` больше не считаются ошибками и не блокируют продвижение эпохи (#28).
|
|
235
|
-
- **Защита от чередующихся циклов**: добавлено отслеживание результатов по каждому инструменту (`state.lastResults`), исключающее зацикливание агента вида A ➔ B ➔ A ➔ B без изменения состояния (#28).
|
|
236
|
-
- **Карточка настроек**: внедрена стандартная карточка `settings.plugin.item` с динамическим обновлением параметров на лету (#26).
|
|
237
|
-
- **Набор тестов**: расширен до 31 автоматизированного теста.
|
|
197
|
+
* **Лицензия**: MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
198
|
+
* **История изменений**: Подробная хронология всех релизов и миграций ведётся в [CHANGELOG.md](CHANGELOG.md).
|
|
199
|
+
|
package/README.zh.md
CHANGED
|
@@ -113,6 +113,19 @@ graph TD
|
|
|
113
113
|
* **长耗时工具豁免**:在工具实际执行期间,文本中断检测自动保持静默,避免长任务被误杀。
|
|
114
114
|
* **用户输入无损重置**:用户发起新对话轮次时,检测状态自动全量清理重置。
|
|
115
115
|
|
|
116
|
+
### 4. 凭证脱敏与日志隐私防护
|
|
117
|
+
|
|
118
|
+
所有防护告警日志均会自动针对敏感凭证执行脱敏处理:
|
|
119
|
+
* Bearer 令牌、密码、Cookie 与查询参数凭据(`token=`, `api-key=`, `secret=`)在写入日志前一律替换为 `[redacted]`。
|
|
120
|
+
* 对深度嵌套的参数对象执行深度与宽度截断,杜绝超大 JSON 解析引发的内存泄漏。
|
|
121
|
+
|
|
122
|
+
### 5. 原生 WebUI 设置卡片、实时防护遥测与一键平滑更新
|
|
123
|
+
|
|
124
|
+
* **原生设置面板集成**:直接内嵌于 DSH Web 控制台「设置 ➔ 插件 ➔ 插件设置」卡片列表中(`settings.plugin.item`, order 95)。
|
|
125
|
+
* **对齐 DSH 设计规范**:完全基于 DSH 标准设计令牌变量(`--dsw-alias-*`)与无障碍标签绑定(`htmlFor`/`id`),搭配轻量级平滑展开 Chevron 图标,零外部重型 UI 库依赖。
|
|
126
|
+
* **实时防护遥测看板**:在设置卡片中直观呈现当前运行时拦截的死循环总数(`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`),支持通过 `/api/@goodandready/dsh-agent-loop-guard/telemetry` 安全端点一键重置计数。
|
|
127
|
+
* **一键无缝在线更新**:卡片自动联动 npm 官方源检查最新版本,支持通过经过鉴权的本地环回 API(`/api/@goodandready/dsh-agent-loop-guard/update`)在后台安全完成版本升级。
|
|
128
|
+
|
|
116
129
|
---
|
|
117
130
|
|
|
118
131
|
## 📦 快速安装
|
|
@@ -168,7 +181,7 @@ dsh-agent-loop-guard:
|
|
|
168
181
|
|
|
169
182
|
## 🧪 测试与校验
|
|
170
183
|
|
|
171
|
-
运行全部
|
|
184
|
+
运行全部 51 个自动化单元与集成测试及静态代码检查:
|
|
172
185
|
|
|
173
186
|
```bash
|
|
174
187
|
npm test
|
|
@@ -179,57 +192,5 @@ npm run check
|
|
|
179
192
|
|
|
180
193
|
## 📄 开源许可证
|
|
181
194
|
|
|
182
|
-
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
183
|
-
|
|
184
|
-
---
|
|
185
|
-
|
|
186
|
-
## v0.2.8 更新日志
|
|
187
|
-
|
|
188
|
-
- **服务端引擎与安全强化**:
|
|
189
|
-
- 停止关键词识别器支持俄语关键词 `'стоп'`,增强跨语言安全熔断保护 (#43)。
|
|
190
|
-
- `/telemetry` 接口严格强制本地环回 (loopback) 与同源 (same-origin) 校验 (#37)。
|
|
191
|
-
- 移除核心防护引擎中的冗余 `if(true)` 代码块与未使用的 `releaseCall` 方法 (#44)。
|
|
192
|
-
- 在配置模型中将旧版别名 `maxCallsPerToolPerTurn` 规范标记为 deprecated 弃用 (#48)。
|
|
193
|
-
- 将空异常捕获代码块替换为结构化调试日志 `ctx.logger('loop-guard')` (#49)。
|
|
194
|
-
- **WebUI 客户端与设计规范对齐**:
|
|
195
|
-
- 设置卡片完全适配 DSH 规范 CSS 变量 `--dsw-alias-*`,并采用原生 Chevron 图标(带 180° 展开旋转动效)(#39)。
|
|
196
|
-
- 移除标题表情符号(`🛑`、`📊`),符合沉稳的原生界面风格 (#39)。
|
|
197
|
-
- 修复语言切换响应性:通过 `ctx.locale.getLocale()` 获取语言快照并在 `ctx.effect` 生命周期内正确注册 (#40, #41)。
|
|
198
|
-
- 移除硬编码版本号,版本信息通过更新接口动态验证 (#42)。
|
|
199
|
-
- 可访问性强化:所有表单控件通过 `htmlFor` 与显式 ID 绑定 `<label>` 与 `<input>` (#45)。
|
|
200
|
-
- 完善网络请求验证 (`res.ok`),在更新与遥测接口异常时向用户展示友好错误提示 (#49)。
|
|
201
|
-
- **发布规范与仓库清理**:
|
|
202
|
-
- 清理根目录残留 `.tgz` 打包产物,安全删除 15 个已合入的陈旧分支 (#46)。
|
|
203
|
-
- 从公开发布包中剔除内部架构与规划文档 (#35, #36)。
|
|
204
|
-
- 在 `DESIGN.md` 中规范记录更新器架构与设计决策 (#47)。
|
|
205
|
-
- 全自动化测试集扩充至 49 个单元与集成测试。
|
|
206
|
-
|
|
207
|
-
## v0.2.7 更新日志
|
|
208
|
-
|
|
209
|
-
- **延迟插槽注入机制**:使用 `registerSlotWhenReady` 与 `ctx.slots.inject` 包装 `settings.plugin.item` 注册逻辑,防止插件在浏览器前端初始化时因插槽未提前声明而抛出 `slot "settings.plugin.item" is not declared` 崩溃异常 (#33)。
|
|
210
|
-
- **插槽规范对齐**:根据 `dsh-plugin-authoring` 标准,将插槽注册参数调整为 `key: NS` 并注入 `inject: () => ({ ctx })` (#33)。
|
|
211
|
-
- **客户端自动化测试**:扩展 `test/client.test.js`,全面验证插槽延迟注入逻辑与缺失回退机制 (#33)。
|
|
212
|
-
|
|
213
|
-
## v0.2.6 更新日志
|
|
214
|
-
|
|
215
|
-
- **浏览器 ModuleLoader 导入修复**:在 `lib/client.js` 的 factory 函数中显式声明 `var exports = module.exports;`,彻底修复 DSH 网页端 ModuleLoader 动态加载时抛出的 `ReferenceError: exports is not defined` 异常 (#31)。
|
|
216
|
-
- **客户端测试用例**:新增 `test/client.test.js`,通过 Node.js VM 模拟浏览器端模块加载环境并自动化验证 (#31)。
|
|
217
|
-
|
|
218
|
-
## v0.2.5 更新日志
|
|
219
|
-
|
|
220
|
-
- **一键平滑更新**:集成宿主端更新器(`lib/plugin-updater.js`),提供 `/api/@goodandready/dsh-agent-loop-guard/update` 接口与设置界面更新状态/按钮 (#29)。
|
|
221
|
-
- **敏感工具严格配额**:新增 `strictTools` 与 `strictToolLimit` 配置,强化对高危/文件修改工具的重复调用限制 (#29)。
|
|
222
|
-
- **审计模式 (Dry-Run)**:新增 `dryRunMode` 配置,支持在不阻断智能体调用的前提下记录告警与度量数据 (#29)。
|
|
223
|
-
- **防护遥测与监控**:实时统计拦截指标(`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`),提供 `/api/@goodandready/dsh-agent-loop-guard/telemetry` 接口与一键重置 (#29)。
|
|
224
|
-
- **LLM 智能恢复引导**:在拦截消息中为 DeepSeek-R1 / V3 等模型提供结构化的破局指导与操作建议 (#29)。
|
|
225
|
-
- **严格多语言规范**:代码库仅保留标准英文(`en`)与中文(`zh`),俄语本地化转入 Issue #197 (`goodandready/dsh-russian-lang`) 处理 (#29)。
|
|
226
|
-
- **设计契约**:按照 `project-design-contract` 标准建立 `docs/design/DESIGN.md` (#29)。
|
|
227
|
-
- **扩展自动化测试**:总测试用例扩充至 37 个,涵盖更新器语义版本、请求安全性、严格工具配额与审计模式 (#29)。
|
|
228
|
-
|
|
229
|
-
## v0.2.4 更新日志
|
|
230
|
-
|
|
231
|
-
- **设置界面**:修复 `maxToolAttemptsPerTurn` 保存为 `0` 的问题,允许正常禁用单回合工具调用上限 (#28)。
|
|
232
|
-
- **结果解析**:对象中的 `{ error: null }` 与 `{ error: false }` 正确识别为非错误,不再阻碍进展推进 (#28)。
|
|
233
|
-
- **交替循环拦截**:通过 `state.lastResults` 跟踪每个工具的先前结果,有效拦截无实质进展的交替循环调用 (A ➔ B ➔ A ➔ B) (#28)。
|
|
234
|
-
- **设置卡片**:集成标准 `settings.plugin.item` 配置卡片,支持动态热重载 (#26)。
|
|
235
|
-
- **测试用例**:自动化测试扩展至 31 个测试。
|
|
195
|
+
* **开源许可证**: MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
196
|
+
* **更新历史**: 完整版本演进历史与特性发布记录详见 [CHANGELOG.md](CHANGELOG.md)。
|
package/lib/client.js
CHANGED
|
@@ -13,7 +13,10 @@ window.__ModuleLoader__.load({
|
|
|
13
13
|
if (prim && (prim.IconChevronDownOutline14 || prim.IconChevronDown || prim.IconChevronDown16)) {
|
|
14
14
|
PrimitivesChevron = prim.IconChevronDownOutline14 || prim.IconChevronDown || prim.IconChevronDown16;
|
|
15
15
|
}
|
|
16
|
-
} catch {
|
|
16
|
+
} catch (err) {
|
|
17
|
+
/* bestEffort */
|
|
18
|
+
console.warn?.('[dsh-agent-loop-guard] primitives unavailable, using SVG fallback:', err?.message || String(err));
|
|
19
|
+
}
|
|
17
20
|
|
|
18
21
|
const CSS_STYLES = `
|
|
19
22
|
.alg-card {
|
|
@@ -45,7 +48,7 @@ window.__ModuleLoader__.load({
|
|
|
45
48
|
transition: background 0.15s ease;
|
|
46
49
|
}
|
|
47
50
|
.alg-header-btn:hover {
|
|
48
|
-
background: var(--dsw-alias-bg-
|
|
51
|
+
background: var(--dsw-alias-bg-hover, var(--dsw-alias-bg-layer-hover));
|
|
49
52
|
}
|
|
50
53
|
.alg-chevron {
|
|
51
54
|
margin-left: auto;
|
|
@@ -85,7 +88,7 @@ window.__ModuleLoader__.load({
|
|
|
85
88
|
transition: border-color 0.15s ease;
|
|
86
89
|
}
|
|
87
90
|
.alg-input:focus {
|
|
88
|
-
border-color: var(--dsw-alias-accent-primary
|
|
91
|
+
border-color: var(--dsw-alias-accent-primary);
|
|
89
92
|
}
|
|
90
93
|
.alg-checkbox-label {
|
|
91
94
|
display: flex;
|
|
@@ -101,8 +104,8 @@ window.__ModuleLoader__.load({
|
|
|
101
104
|
padding: 0 18px;
|
|
102
105
|
border: 0;
|
|
103
106
|
border-radius: 8px;
|
|
104
|
-
background: var(--dsw-alias-accent-primary
|
|
105
|
-
color:
|
|
107
|
+
background: var(--dsw-alias-accent-primary);
|
|
108
|
+
color: var(--dsw-alias-label-inverse);
|
|
106
109
|
font-size: 13px;
|
|
107
110
|
font-weight: 600;
|
|
108
111
|
cursor: pointer;
|
|
@@ -115,8 +118,8 @@ window.__ModuleLoader__.load({
|
|
|
115
118
|
.alg-btn-updater {
|
|
116
119
|
padding: 6px 14px;
|
|
117
120
|
border-radius: 6px;
|
|
118
|
-
background: var(--dsw-alias-accent-primary
|
|
119
|
-
color:
|
|
121
|
+
background: var(--dsw-alias-accent-primary);
|
|
122
|
+
color: var(--dsw-alias-label-inverse);
|
|
120
123
|
border: 0;
|
|
121
124
|
font-size: 12px;
|
|
122
125
|
font-weight: 600;
|
|
@@ -525,7 +528,7 @@ window.__ModuleLoader__.load({
|
|
|
525
528
|
React.createElement('span', { style: { display: 'flex', flexDirection: 'column' } },
|
|
526
529
|
React.createElement('span', { style: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 } },
|
|
527
530
|
tt('title'),
|
|
528
|
-
React.createElement('span', { style: { fontSize: 11, fontWeight: 500, padding: '2px 6px', borderRadius: 6, background: '
|
|
531
|
+
React.createElement('span', { style: { fontSize: 11, fontWeight: 500, padding: '2px 6px', borderRadius: 6, background: 'color-mix(in srgb, var(--dsw-alias-accent-primary) 15%, transparent)', color: 'var(--dsw-alias-accent-primary)' } }, updateState.currentVersion ? 'v' + updateState.currentVersion : (updateState.checking ? '…' : '—'))
|
|
529
532
|
),
|
|
530
533
|
React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, tt('sub'))
|
|
531
534
|
),
|
|
@@ -536,14 +539,14 @@ window.__ModuleLoader__.load({
|
|
|
536
539
|
},
|
|
537
540
|
// Section: One-Click Updater
|
|
538
541
|
React.createElement('div', {
|
|
539
|
-
style: { padding: '12px 14px', margin: '14px 0', background: '
|
|
542
|
+
style: { padding: '12px 14px', margin: '14px 0', background: 'color-mix(in srgb, var(--dsw-alias-label-primary) 4%, transparent)', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }
|
|
540
543
|
},
|
|
541
544
|
React.createElement('div', { style: { fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 } },
|
|
542
545
|
React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)' } }, tt('version') + ': ' + (updateState.currentVersion || (updateState.checking ? '…' : '—'))),
|
|
543
546
|
updateState.checking && React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12 } }, tt('updateChecking')),
|
|
544
|
-
!updateState.checking && updateState.updateAvailable && React.createElement('span', { style: { color: '
|
|
545
|
-
!updateState.checking && !updateState.updateAvailable && !updateState.error && React.createElement('span', { style: { color: '
|
|
546
|
-
updateState.error && React.createElement('span', { style: { color: 'var(--dsw-alias-status-danger
|
|
547
|
+
!updateState.checking && updateState.updateAvailable && React.createElement('span', { style: { color: 'var(--dsw-alias-status-warning)', fontWeight: 600, fontSize: 12 } }, tt('updateAvailable', { v: updateState.latestVersion })),
|
|
548
|
+
!updateState.checking && !updateState.updateAvailable && !updateState.error && React.createElement('span', { style: { color: 'var(--dsw-alias-status-success)', fontSize: 12 } }, '✓ ' + tt('upToDate')),
|
|
549
|
+
updateState.error && React.createElement('span', { style: { color: 'var(--dsw-alias-status-danger)', fontSize: 12 } }, updateState.error)
|
|
547
550
|
),
|
|
548
551
|
updateState.updateAvailable && React.createElement('button', {
|
|
549
552
|
className: 'alg-btn-updater',
|
|
@@ -552,12 +555,12 @@ window.__ModuleLoader__.load({
|
|
|
552
555
|
}, updateState.updating ? tt('updating') : tt('updateNow'))
|
|
553
556
|
),
|
|
554
557
|
updateState.notice && React.createElement('div', {
|
|
555
|
-
style: { padding: '8px 12px', marginBottom: 12, background: '
|
|
558
|
+
style: { padding: '8px 12px', marginBottom: 12, background: 'color-mix(in srgb, var(--dsw-alias-status-success) 10%, transparent)', color: 'var(--dsw-alias-status-success)', borderRadius: 6, fontSize: 12, border: '1px solid color-mix(in srgb, var(--dsw-alias-status-success) 20%, transparent)' }
|
|
556
559
|
}, updateState.notice),
|
|
557
560
|
|
|
558
561
|
// Section: Protection Telemetry
|
|
559
562
|
React.createElement('div', {
|
|
560
|
-
style: { padding: '12px 14px', margin: '14px 0', background: '
|
|
563
|
+
style: { padding: '12px 14px', margin: '14px 0', background: 'color-mix(in srgb, var(--dsw-alias-label-primary) 2%, transparent)', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)' }
|
|
561
564
|
},
|
|
562
565
|
React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
|
|
563
566
|
React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, tt('telemetryTitle')),
|
|
@@ -568,10 +571,10 @@ window.__ModuleLoader__.load({
|
|
|
568
571
|
),
|
|
569
572
|
React.createElement('div', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
|
|
570
573
|
telemetry.error
|
|
571
|
-
? React.createElement('span', { style: { color: 'var(--dsw-alias-status-danger
|
|
574
|
+
? React.createElement('span', { style: { color: 'var(--dsw-alias-status-danger)' } }, telemetry.error)
|
|
572
575
|
: telemetry.totalViolations > 0
|
|
573
576
|
? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
|
|
574
|
-
React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: '
|
|
577
|
+
React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-status-warning)' } }, telemetry.totalViolations)),
|
|
575
578
|
telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
|
|
576
579
|
tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
|
|
577
580
|
)
|
|
@@ -603,7 +606,7 @@ window.__ModuleLoader__.load({
|
|
|
603
606
|
onClick: onSave,
|
|
604
607
|
disabled: saving || status !== 'ready',
|
|
605
608
|
}, saving ? tt('saving') : tt('ready')),
|
|
606
|
-
msg && React.createElement('span', { style: { fontSize: 13, color: msg === tt('saved') || msg === tt('statsResetDone') ? 'var(--dsw-alias-status-success
|
|
609
|
+
msg && React.createElement('span', { style: { fontSize: 13, color: msg === tt('saved') || msg === tt('statsResetDone') ? 'var(--dsw-alias-status-success)' : 'var(--dsw-alias-status-danger)' } }, msg)
|
|
607
610
|
)
|
|
608
611
|
)
|
|
609
612
|
);
|
package/lib/plugin-updater.js
CHANGED
|
@@ -167,21 +167,32 @@ async function latestVersion(packageName, registry) {
|
|
|
167
167
|
}
|
|
168
168
|
}
|
|
169
169
|
|
|
170
|
-
async function currentVersion(manifestUrl) {
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
170
|
+
export async function currentVersion(manifestUrl) {
|
|
171
|
+
try {
|
|
172
|
+
const raw = await readFile(manifestUrl, 'utf8');
|
|
173
|
+
const value = JSON.parse(raw);
|
|
174
|
+
if (typeof value?.version !== 'string' || value.version === '') return 'unknown';
|
|
175
|
+
return value.version;
|
|
176
|
+
} catch {
|
|
177
|
+
return 'unknown';
|
|
178
|
+
}
|
|
174
179
|
}
|
|
175
180
|
|
|
176
181
|
async function status(options, target) {
|
|
177
|
-
|
|
182
|
+
let current = 'unknown';
|
|
183
|
+
try {
|
|
184
|
+
current = await currentVersion(options.manifestUrl);
|
|
185
|
+
} catch {
|
|
186
|
+
current = 'unknown';
|
|
187
|
+
}
|
|
178
188
|
const latest = await latestVersion(options.packageName, options.registry ?? 'https://registry.npmjs.org');
|
|
189
|
+
const validCurrent = current !== 'unknown';
|
|
179
190
|
return {
|
|
180
191
|
packageName: options.packageName,
|
|
181
192
|
currentVersion: current,
|
|
182
193
|
...(latest === undefined ? {} : { latestVersion: latest }),
|
|
183
|
-
latestCheckFailed: latest === undefined,
|
|
184
|
-
updateAvailable: latest !== undefined && isNewerVersion(current, latest),
|
|
194
|
+
latestCheckFailed: latest === undefined || !validCurrent,
|
|
195
|
+
updateAvailable: latest !== undefined && validCurrent && isNewerVersion(current, latest),
|
|
185
196
|
profileName: target.profileName,
|
|
186
197
|
canAutoUpdate: target.cliEntry !== undefined,
|
|
187
198
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-agent-loop-guard",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.10",
|
|
4
4
|
"description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"README.md",
|
|
17
17
|
"README.ru.md",
|
|
18
18
|
"README.zh.md",
|
|
19
|
-
"
|
|
19
|
+
"CHANGELOG.md",
|
|
20
20
|
"LICENSE"
|
|
21
21
|
],
|
|
22
22
|
"scripts": {
|
package/docs/design/DESIGN.md
DELETED
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
# DESIGN.md — @goodandready/dsh-agent-loop-guard
|
|
2
|
-
|
|
3
|
-
## Product / Purpose
|
|
4
|
-
- **Назначение:** Отказоустойчивый runtime-предохранитель среды выполнения DeepSeek Harness для предотвращения бесконечных циклов вызовов инструментов (tool calls) и зацикливания потокового вывода ассистента (streaming assistant output).
|
|
5
|
-
- **Аудитория:** Разработчики, администраторы и пользователи автономных агентных систем на базе DeepSeek Harness, сталкивающиеся с расходом контекста, токенов и зависанием сессий.
|
|
6
|
-
- **Статус:** Production-плагин, v0.2.8 (расширения: One-Click Updater, EN/ZH i18n, телеметрия, адаптивные квоты, dry-run, a11y, DSH design system).
|
|
7
|
-
|
|
8
|
-
## User Surfaces
|
|
9
|
-
- **Web/UI:** Карточка настроек плагина во вкладке «Настройки → Плагины → Настройки плагинов» (`settings.plugin.item`). Свой раздел в боковом списке отсутствует (согласно `dsh-plugin-authoring`).
|
|
10
|
-
- **DSH UI / settings / slots:**
|
|
11
|
-
- Слот: `settings.plugin.item`, `order: 95`, `locale: @goodandready/dsh-agent-loop-guard`.
|
|
12
|
-
- Элементы карточки:
|
|
13
|
-
- Заголовок с иконкой и версионным бейджем.
|
|
14
|
-
- Секция One-Click обновления (индикатор проверки, кнопка «Update Now» при наличии новой версии в npm).
|
|
15
|
-
- Секция телеметрии живой защиты (счётчики заблокированных петель сессии).
|
|
16
|
-
- Форма параметров: числовые поля (`maxToolAttemptsPerTurn`, `maxProgressToolCallsPerTurn`, `maxCallsPerRepeatGroup`, `maxRepeatedAssistantLines`, `maxRepeatedAssistantBlocks`, `maxAssistantBlockChars`; устаревший алиас `maxCallsPerToolPerTurn` сохранён в схеме для обратной совместимости, но опущен в UI), чекбоксы (`blockExactDuplicates`, `assistantOutputGuard`, `dryRunMode`), текстовые списки (`progressToolNames`, `strictTools`).
|
|
17
|
-
- Кнопка сохранения с индикацией статуса (`Saving...`, `Saved`, ошибки валидации).
|
|
18
|
-
- **API:**
|
|
19
|
-
- Route: `/api/@goodandready/dsh-agent-loop-guard/update` (GET — статус версий, POST — доверенное обновление с обязательной проверкой x-dsh-plugin-update, loopback и same-origin).
|
|
20
|
-
- Route: `/api/@goodandready/dsh-agent-loop-guard/telemetry` (GET — данные телеметрии петлезащиты для loopback/same-origin; POST — доверенный сброс счётчиков с проверкой loopback remoteAddress, sec-fetch-site и совпадения origin/host, 403 при cross-origin или не-loopback).
|
|
21
|
-
- **CLI:**
|
|
22
|
-
- Установка и обновление через штатный DSH CLI: `dsh plugin --profile web add @goodandready/dsh-agent-loop-guard`.
|
|
23
|
-
- **Документация:**
|
|
24
|
-
- `README.md` (English, canonical)
|
|
25
|
-
- `README.ru.md` (Русский, синхронизированная проектная документация)
|
|
26
|
-
- `README.zh.md` (中文, обязательная пользовательская документация)
|
|
27
|
-
|
|
28
|
-
## Visual Direction
|
|
29
|
-
- **Атмосфера:** Утилитарный, надёжный, сдержанный инженерный интерфейс системной безопасности. Интеграция «как родной» в дизайн-систему DeepSeek Harness.
|
|
30
|
-
- **Утверждённые референсы:** Нативные компоненты DSH Web UI (`settingsScope`, css-переменные темы `--dsw-alias-*`, примитивы `@deepseek-ai/dsh-client-ui-primitives`).
|
|
31
|
-
- **Не копировать:** Кастомные несогласованные темы, яркие несистемные градиенты, сторонние тяжелые библиотеки компонентов (MUI, AntD), эмодзи-заголовки.
|
|
32
|
-
- **Стилизация и анимации:**
|
|
33
|
-
- CSS внедряется через `<style id="dsh-agent-loop-guard-styles" data-dsh-plugin="...">` с изолированными классами `.alg-*`.
|
|
34
|
-
- Заголовки разделов и шапка оформлены в строгом нативном стиле без визуального шума и эмодзи (`title`, `telemetryTitle`).
|
|
35
|
-
- Стрелка раскрытия карточки использует системный примитив `IconChevronDownOutline14` (с fallback на нативный SVG-шеврон) с плавным поворотом `transform: rotate(180deg)` при разворачивании.
|
|
36
|
-
|
|
37
|
-
## Foundations
|
|
38
|
-
- **Цвета и роли:**
|
|
39
|
-
- Фон карточки: `var(--dsw-alias-bg-layer-3)`
|
|
40
|
-
- Границы: `var(--dsw-alias-border-l2)`, hover: `var(--dsw-alias-border-l1)`
|
|
41
|
-
- Основной текст: `var(--dsw-alias-label-primary)`
|
|
42
|
-
- Вторичный текст / подписи полей: `var(--dsw-alias-label-secondary)`
|
|
43
|
-
- Третичный текст / шевроны: `var(--dsw-alias-label-tertiary)`
|
|
44
|
-
- Акцент обновления / кнопки сохранения: `var(--dsw-alias-accent-primary, #3b82f6)`
|
|
45
|
-
- Предупреждения / ошибки: `var(--dsw-alias-status-danger, #ef4444)`
|
|
46
|
-
- Успешное сохранение / актуальность: `var(--dsw-alias-status-success, #10b981)`
|
|
47
|
-
- **Типографика:**
|
|
48
|
-
- Системный шрифт DSH (`Plus Jakarta Sans` / системный UI стек, моноширинный для кодов и версий).
|
|
49
|
-
- Размеры: Заголовок 15px (font-weight: 600), подзаголовок 13px, метки полей 13px, числовые поля 13px.
|
|
50
|
-
- **Сетка, отступы, responsive:**
|
|
51
|
-
- Скругление карточки: `12px`.
|
|
52
|
-
- Внутренние отступы шапки: `14px 16px`.
|
|
53
|
-
- Отступы полей ввода: `padding: 10px 0`, расстояние между меткой и полем `6px`.
|
|
54
|
-
- Адаптивность: 100% ширина контейнера, резиновые поля.
|
|
55
|
-
- **Accessibility:**
|
|
56
|
-
- Семантические теги `<label>`, ассоциированные с input через `htmlFor` и уникальные `id` (`alg-<key>`).
|
|
57
|
-
- Атрибут `aria-expanded` для сворачиваемой карточки.
|
|
58
|
-
- Достаточный контраст текста по шкале WCAG AA через системные CSS-переменные.
|
|
59
|
-
|
|
60
|
-
## Components And States
|
|
61
|
-
- **Компоненты:**
|
|
62
|
-
1. `PluginCard`: Сворачиваемый контейнер карточки настроек с шевроном поворота на 180°.
|
|
63
|
-
2. `UpdateSection`: Блок проверки и запуска one-click обновления с npm.
|
|
64
|
-
3. `TelemetryBadge`: Индикатор защитных срабатываний в текущем процессе DSH.
|
|
65
|
-
4. `SettingsForm`: Набор типизированных полей ввода.
|
|
66
|
-
5. `SaveButton`: Кнопка фиксации настроек через `scope.set()`.
|
|
67
|
-
- **Loading / empty / error / success:**
|
|
68
|
-
- `status === 'loading'`: отображение скелетона/загрузки данных из `settingsScope`.
|
|
69
|
-
- `status === 'unavailable'`: отображение предупреждения о недоступности пространства настроек (блокировка полей ввода от ложного редактирования).
|
|
70
|
-
- `status === 'ready'`: интерактивная форма со значениями по умолчанию или сохранёнными настройками.
|
|
71
|
-
- Сохранение: отображение `Saving...` (`正在保存…`), при успехе `Saved` (`已保存`), при ошибках перечисление ключей.
|
|
72
|
-
- Обновление: `Checking updates...`, `Up to date` (`已是最新版本`), `Update available: vX.Y.Z` (`发现新版本`), `Updating...` (`正在更新…`), `Restart required` (`需要重启服务`).
|
|
73
|
-
|
|
74
|
-
## User Flows
|
|
75
|
-
- **Критический сценарий 1 (Пресечение зацикливания инструмента):**
|
|
76
|
-
1. Агент вызывает инструмент (например, `read_file`) с теми же аргументами без изменения результата или превышает квоту группы.
|
|
77
|
-
2. Guard блокирует вызов с кодом `LOOP_GUARD_DUPLICATE` / `LOOP_GUARD_REPEAT`.
|
|
78
|
-
3. Модель получает структурированную инструкцию `[LOOP_GUARD_DUPLICATE] ... STOP repeating this action ...`.
|
|
79
|
-
4. Модель переключается на альтернативный инструмент или переходит к синтезу ответа.
|
|
80
|
-
5. В телеметрии карточки инкрементируется счётчик нарушений.
|
|
81
|
-
- **Критический сценарий 2 (One-Click обновление плагина):**
|
|
82
|
-
1. Администратор открывает Настройки → Плагины → Agent Loop Guard.
|
|
83
|
-
2. Карточка запрашивает `/api/@goodandready/dsh-agent-loop-guard/update`.
|
|
84
|
-
3. При наличии новой версии отображается кнопка «Update Now».
|
|
85
|
-
4. Пользователь нажимает кнопку. Отправляется POST-запрос с `x-dsh-plugin-update: 1`.
|
|
86
|
-
5. DSH CLI устанавливает точную версию. Кнопка блокируется от повторных кликов.
|
|
87
|
-
6. Интерфейс сообщает: `Updated successfully. Restart DSH service to apply changes.`.
|
|
88
|
-
|
|
89
|
-
## Architecture & Reusable Components
|
|
90
|
-
- **Plugin Updater (`lib/plugin-updater.js`):**
|
|
91
|
-
- Реализация основана на каноническом шаблоне `references/plugin-updater.ts` с поддержкой безопасной проверки версий semver, loopback/same-origin валидации и флага `x-dsh-plugin-update`.
|
|
92
|
-
- Маршрут эндпоинта зафиксирован как `/api/@goodandready/dsh-agent-loop-guard/update` (совпадает с полным именем npm-пакета плагина для изоляции пространства имён роутера DSH Web).
|
|
93
|
-
- Флаг `--config.minimumReleaseAge=0` задействован в CLI-командах установки для предотвращения задержек распространения новых npm-релизов в локальной среде pnpm.
|
|
94
|
-
|
|
95
|
-
## Internationalization & Localization (Do / Don't)
|
|
96
|
-
- **Do:**
|
|
97
|
-
- Код плагина, схемы настроек, логи и системные сообщения — **English (`en`)**.
|
|
98
|
-
- Пользовательский интерфейс плагина обязан поддерживать **English (`en`)** и **Chinese (`zh`)**.
|
|
99
|
-
- Все новые ключи для русского перевода регистрируются через issue в Gitea `goodandready/dsh-russian-lang` со сравнительной таблицей `Key | English | Chinese | Proposed Russian`.
|
|
100
|
-
- Документация в репозитории ведётся на 3 языках (`README.md`, `README.ru.md`, `README.zh.md`).
|
|
101
|
-
- **Don't:**
|
|
102
|
-
- **Запрещено** хардкодить русские строки, русские дефолты или русский словарь `ru` внутри кода плагина (`lib/client.js`, `lib/index.js`).
|
|
103
|
-
- **Запрещено** удалять существующие описания фич в документации при релизе (только additive-обновление).
|
|
104
|
-
- **Запрещено** менять вторую цифру версии $y$ без явной прямой команды пользователя.
|