@goodandready/dsh-agent-loop-guard 0.2.7 → 0.2.9
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/README.md +30 -1
- package/README.ru.md +29 -0
- package/README.zh.md +29 -0
- package/lib/client.js +259 -47
- package/lib/guard-state.js +8 -10
- package/lib/index.js +63 -54
- package/lib/plugin-updater.js +38 -8
- package/package.json +1 -2
- package/docs/README.ru.md +0 -215
- package/docs/README.zh.md +0 -213
- package/docs/architecture/baseline.md +0 -37
- package/docs/design/DESIGN.md +0 -94
- package/docs/research/reuse-first.md +0 -17
- package/docs/testing/test-plan.md +0 -21
package/README.md
CHANGED
|
@@ -101,7 +101,7 @@ When a loop is detected, the guard rejects the call with structured diagnostics
|
|
|
101
101
|
|
|
102
102
|
| Guard Code | Trigger Condition | Default Limit | Guard Action |
|
|
103
103
|
|:---|:---|:---|:---|
|
|
104
|
-
| `LOOP_GUARD_STOP` | User sent stop command (`stop`, `halt`, `cancel`, `остановись`, `прекрати`, `ответь`, `петля`) | Immediate | Rejects tool call; requires immediate text reply |
|
|
104
|
+
| `LOOP_GUARD_STOP` | User sent stop command (`stop`, `halt`, `cancel`, `стоп`, `остановись`, `прекрати`, `ответь`, `петля`) | Immediate | Rejects tool call; requires immediate text reply |
|
|
105
105
|
| `LOOP_GUARD_DUPLICATE` | Identical call arguments with identical result to previous attempt | 1 retry | Blocks exact repeat; demands alternative approach |
|
|
106
106
|
| `LOOP_GUARD_REPEAT` | Repeated calls within current group without state change | `maxCallsPerRepeatGroup` (5) | Prevents spinning on single tool |
|
|
107
107
|
| `LOOP_GUARD_LIMIT` | Total non-productive tool attempts since last successful progress | `maxToolAttemptsPerTurn` (64) | Caps turn exploratory budget |
|
|
@@ -164,6 +164,7 @@ dsh-agent-loop-guard:
|
|
|
164
164
|
| `maxProgressToolCallsPerTurn` | `number` | `16` | Maximum consecutive calls to progress tools (`todo_write`) without substantive progress. |
|
|
165
165
|
| `progressToolNames` | `array` | `["todo_write"]` | Array of tool names considered progress markers. |
|
|
166
166
|
| `maxCallsPerRepeatGroup` | `number` | `5` | Maximum tool calls allowed within the same repeat group without producing a new result. |
|
|
167
|
+
| `maxCallsPerToolPerTurn` | `number` | `5` | *(Deprecated)* Legacy alias for `maxCallsPerRepeatGroup`. If both are specified, `maxCallsPerRepeatGroup` takes precedence. Omitted from UI card to avoid confusion. |
|
|
167
168
|
| `strictTools` | `array` | `[]` | Array of tool names subjected to lower repeat tolerance (e.g. mutating tools). |
|
|
168
169
|
| `strictToolLimit` | `number` | `3` | Maximum repeat count allowed for tools specified in `strictTools`. |
|
|
169
170
|
| `blockExactDuplicates` | `boolean` | `true` | Immediately block consecutive identical calls with zero state change. |
|
|
@@ -190,6 +191,34 @@ npm run check
|
|
|
190
191
|
|
|
191
192
|
MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
192
193
|
|
|
194
|
+
## Changed in v0.2.9
|
|
195
|
+
|
|
196
|
+
- **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).
|
|
197
|
+
- **Updater Resilience**: hardened `currentVersion` and status endpoint against corrupted, non-JSON or missing manifests, returning safe fallback status without throwing unhandled exceptions (#47).
|
|
198
|
+
- **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).
|
|
199
|
+
- **Test Suite**: expanded to 51 automated tests covering theme token compliance and manifest corruption handling.
|
|
200
|
+
|
|
201
|
+
## Changed in v0.2.8
|
|
202
|
+
|
|
203
|
+
- **Host & Security Engine Hardening**:
|
|
204
|
+
- Expanded stop keyword detector with Russian keyword `'стоп'` for multilingual interrupt safety (#43).
|
|
205
|
+
- Enforced loopback and same-origin validation on `/telemetry` endpoint (#37).
|
|
206
|
+
- Eliminated dead `if(true)` branch and unused `releaseCall` method in core guard engine (#44).
|
|
207
|
+
- Deprecated legacy alias `maxCallsPerToolPerTurn` in configuration schema per standard (#48).
|
|
208
|
+
- Replaced empty catch blocks with structured debug logging via `ctx.logger('loop-guard')` (#49).
|
|
209
|
+
- **WebUI Client & Design System Alignment**:
|
|
210
|
+
- Aligned settings card with DSH standard CSS variables `--dsw-alias-*` and primitive chevron icon with smooth 180° rotation (#39).
|
|
211
|
+
- Removed emoji headers (`🛑`, `📊`) for a clean, professional interface (#39).
|
|
212
|
+
- Fixed localization reactivity by resolving locale from `ctx.locale.getLocale()` and registering within `ctx.effect` lifecycle (#40, #41).
|
|
213
|
+
- Removed hardcoded version strings; version is dynamically verified from updater endpoint (#42).
|
|
214
|
+
- Enhanced accessibility: all form controls now link `<label>` with `<input>` using `htmlFor` and explicit IDs (#45).
|
|
215
|
+
- Added robust HTTP error checking (`res.ok`) and user-facing error indicators for updater and telemetry actions (#49).
|
|
216
|
+
- **Distribution & Repository Hygiene**:
|
|
217
|
+
- Cleaned repository root from temporary tarballs and pruned 15 merged branches (#46).
|
|
218
|
+
- Removed internal planning and architectural documentation from the public package (#35, #36).
|
|
219
|
+
- Documented canonical updater architecture and rationale in `DESIGN.md` (#47).
|
|
220
|
+
- Full automated test suite expanded to 49 comprehensive unit and integration tests.
|
|
221
|
+
|
|
193
222
|
## Changed in v0.2.7
|
|
194
223
|
|
|
195
224
|
- **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).
|
package/README.ru.md
CHANGED
|
@@ -156,6 +156,7 @@ dsh-agent-loop-guard:
|
|
|
156
156
|
| `maxProgressToolCallsPerTurn` | `number` | `16` | Максимум вызовов progress-инструментов (`todo_write`) подряд без изменений. |
|
|
157
157
|
| `progressToolNames` | `array` | `["todo_write"]` | Список имён инструментов, маркирующих прогресс задач. |
|
|
158
158
|
| `maxCallsPerRepeatGroup` | `number` | `5` | Максимум повторений инструментов одной группы без смены результата. |
|
|
159
|
+
| `maxCallsPerToolPerTurn` | `number` | `5` | *(Устарело)* Устаревший алиас для `maxCallsPerRepeatGroup`. При указании обоих параметров приоритет имеет `maxCallsPerRepeatGroup`. В UI-карточке опущен во избежание дублирования. |
|
|
159
160
|
| `strictTools` | `array` | `[]` | Список имён инструментов с пониженным лимитом повторов (например, изменяющие файлы/состояние). |
|
|
160
161
|
| `strictToolLimit` | `number` | `3` | Максимальный лимит повторов для инструментов из списка `strictTools`. |
|
|
161
162
|
| `blockExactDuplicates` | `boolean` | `true` | Немедленно блокировать повторные идентичные вызовы без изменения состояния. |
|
|
@@ -184,6 +185,34 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
|
184
185
|
|
|
185
186
|
---
|
|
186
187
|
|
|
188
|
+
## Изменения в версии v0.2.9
|
|
189
|
+
|
|
190
|
+
- **Дизайн-система и тест-страж**: устранены 100% хардкод-цветов (hex и rgba) в `lib/client.js` в CSS-стилях и инлайн-разметке JSX, выполнен полный переход на CSS-переменные DSH (`var(--dsw-alias-*)`) и `color-mix(in srgb, ...)`; добавлен тест-страж `test/theme-guard.test.js`, гарантирующий нулевое присутствие hex/rgba в клиенте (#53, #39).
|
|
191
|
+
- **Отказоустойчивость апдейтера**: защищён разбор `currentVersion` и эндпоинта обновлений при повреждённых или не-JSON файлах манифеста, возвращается безопасный статус вместо неотловленного исключения (#47).
|
|
192
|
+
- **Чистота репозитория и пакета**: каталог `docs` исключён из распространяемого npm-пакета через белый список `files` в `package.json`; в `lib/client.js` пустой `catch` заменён на диагностический warning с аннотацией `bestEffort`; удалена смерженная ветка и очищены устаревшие `.worktrees` (#54).
|
|
193
|
+
- **Тесты**: тестовый набор расширен до 51 автотеста, включая проверку дизайн-токенов и отказоустойчивости манифеста.
|
|
194
|
+
|
|
195
|
+
## Изменения в версии v0.2.8
|
|
196
|
+
|
|
197
|
+
- **Усиление серверного движка и безопасности**:
|
|
198
|
+
- Расширен список стоп-слов русским ключевым словом `'стоп'` для мультиязычного безопасного прерывания циклов (#43).
|
|
199
|
+
- Реализована строгая валидация loopback и same-origin для эндпоинта `/telemetry` (#37).
|
|
200
|
+
- Удалена мертвая ветка `if(true)` и неиспользуемый метод `releaseCall` в ядре guard (#44).
|
|
201
|
+
- Устаревший алиас `maxCallsPerToolPerTurn` корректно помечен как deprecated в схеме параметров (#48).
|
|
202
|
+
- Пустые блоки `catch {}` заменены структурированным логированием через `ctx.logger('loop-guard')` (#49).
|
|
203
|
+
- **Клиентский интерфейс и дизайн-система DSH**:
|
|
204
|
+
- Карточка настроек переведена на стандартные CSS-переменные DSH `--dsw-alias-*` и системный шеврон с плавной ротацией на 180° (#39).
|
|
205
|
+
- Удалены эмодзи из заголовков (`🛑`, `📊`) для соответствия строгому нативному стилю DSH (#39).
|
|
206
|
+
- Исправлена реактивность локализации через `ctx.locale.getLocale()` и регистрацию в жизненном цикле `ctx.effect` (#40, #41).
|
|
207
|
+
- Удалены захардкоженные версии; актуальная версия динамически проверяется через эндпоинт обновления (#42).
|
|
208
|
+
- Доступность (a11y): все поля формы связывают `<label>` и `<input>` через `htmlFor` и явные ID (#45).
|
|
209
|
+
- Добавлена проверка `res.ok` и отображение понятных сообщений об ошибках при сбое сети в обновлении и телеметрии (#49).
|
|
210
|
+
- **Дистрибуция и репозиторий**:
|
|
211
|
+
- Очищен корень проекта от временных `.tgz` архивов, удалены 15 смерженных устаревших веток (#46).
|
|
212
|
+
- Внутренние архитектурные и проектные черновики исключены из публичного пакета (#35, #36).
|
|
213
|
+
- Зафиксирована архитектура канонического апдейтера в `DESIGN.md` (#47).
|
|
214
|
+
- Полный набор автоматических тестов расширен до 49 тестов.
|
|
215
|
+
|
|
187
216
|
## Изменения в версии v0.2.7
|
|
188
217
|
|
|
189
218
|
- **Отложенная инъекция слота настроек**: регистрация карточки `settings.plugin.item` обёрнута в `registerSlotWhenReady` с использованием `ctx.slots.inject`, что исключает ошибку `slot "settings.plugin.item" is not declared` при ранней загрузке плагина в браузере (#33).
|
package/README.zh.md
CHANGED
|
@@ -154,6 +154,7 @@ dsh-agent-loop-guard:
|
|
|
154
154
|
| `maxProgressToolCallsPerTurn` | `number` | `16` | 进度标记工具(`todo_write`)连续无进展调用的上限。 |
|
|
155
155
|
| `progressToolNames` | `array` | `["todo_write"]` | 标记任务进度的工具名称数组。 |
|
|
156
156
|
| `maxCallsPerRepeatGroup` | `number` | `5` | 同一组工具未产生新结果时允许调用的最大次数。 |
|
|
157
|
+
| `maxCallsPerToolPerTurn` | `number` | `5` | *(已废弃)* `maxCallsPerRepeatGroup` 的向后兼容别名。两者同时存在时优先使用 `maxCallsPerRepeatGroup`。UI 卡片中有意隐藏以避免混淆。 |
|
|
157
158
|
| `strictTools` | `array` | `[]` | 受到更严格重复调用限制的敏感/修改类工具名称列表。 |
|
|
158
159
|
| `strictToolLimit` | `number` | `3` | `strictTools` 列表中工具的最大允许重复次数。 |
|
|
159
160
|
| `blockExactDuplicates` | `boolean` | `true` | 是否立即拦截结果毫无变化的连续相同调用。 |
|
|
@@ -182,6 +183,34 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
|
|
|
182
183
|
|
|
183
184
|
---
|
|
184
185
|
|
|
186
|
+
## v0.2.9 更新日志
|
|
187
|
+
|
|
188
|
+
- **设计规范与主题守卫**:彻底移除 `lib/client.js` 中 CSS 与 JSX 内联样式的所有硬编码十六进制与 rgba 颜色,全面接入 DSH 官方设计变量(`var(--dsw-alias-*)` 与 `color-mix(in srgb, ...)`);新增自动化守卫测试 `test/theme-guard.test.js`,严格确保客户端零硬编码颜色 (#53, #39)。
|
|
189
|
+
- **更新器容错防护**:对 `currentVersion` 与更新状态端点的清单解析增加 `try/catch` 保护,防止损坏的非 JSON 清单导致未捕获异常 (#47)。
|
|
190
|
+
- **包体精简与清理**:从 `package.json` 的 `files` 白名单中移除 `docs` 目录,防止内部文档打包至 npm 发行包中;客户端 primitives 加载处的空 catch 替换为具备 `bestEffort` 注释的诊断警告;清理已合并分支与过期 worktrees (#54)。
|
|
191
|
+
- **自动化测试**:测试集扩展至 51 个单元与集成测试。
|
|
192
|
+
|
|
193
|
+
## v0.2.8 更新日志
|
|
194
|
+
|
|
195
|
+
- **服务端引擎与安全强化**:
|
|
196
|
+
- 停止关键词识别器支持俄语关键词 `'стоп'`,增强跨语言安全熔断保护 (#43)。
|
|
197
|
+
- `/telemetry` 接口严格强制本地环回 (loopback) 与同源 (same-origin) 校验 (#37)。
|
|
198
|
+
- 移除核心防护引擎中的冗余 `if(true)` 代码块与未使用的 `releaseCall` 方法 (#44)。
|
|
199
|
+
- 在配置模型中将旧版别名 `maxCallsPerToolPerTurn` 规范标记为 deprecated 弃用 (#48)。
|
|
200
|
+
- 将空异常捕获代码块替换为结构化调试日志 `ctx.logger('loop-guard')` (#49)。
|
|
201
|
+
- **WebUI 客户端与设计规范对齐**:
|
|
202
|
+
- 设置卡片完全适配 DSH 规范 CSS 变量 `--dsw-alias-*`,并采用原生 Chevron 图标(带 180° 展开旋转动效)(#39)。
|
|
203
|
+
- 移除标题表情符号(`🛑`、`📊`),符合沉稳的原生界面风格 (#39)。
|
|
204
|
+
- 修复语言切换响应性:通过 `ctx.locale.getLocale()` 获取语言快照并在 `ctx.effect` 生命周期内正确注册 (#40, #41)。
|
|
205
|
+
- 移除硬编码版本号,版本信息通过更新接口动态验证 (#42)。
|
|
206
|
+
- 可访问性强化:所有表单控件通过 `htmlFor` 与显式 ID 绑定 `<label>` 与 `<input>` (#45)。
|
|
207
|
+
- 完善网络请求验证 (`res.ok`),在更新与遥测接口异常时向用户展示友好错误提示 (#49)。
|
|
208
|
+
- **发布规范与仓库清理**:
|
|
209
|
+
- 清理根目录残留 `.tgz` 打包产物,安全删除 15 个已合入的陈旧分支 (#46)。
|
|
210
|
+
- 从公开发布包中剔除内部架构与规划文档 (#35, #36)。
|
|
211
|
+
- 在 `DESIGN.md` 中规范记录更新器架构与设计决策 (#47)。
|
|
212
|
+
- 全自动化测试集扩充至 49 个单元与集成测试。
|
|
213
|
+
|
|
185
214
|
## v0.2.7 更新日志
|
|
186
215
|
|
|
187
216
|
- **延迟插槽注入机制**:使用 `registerSlotWhenReady` 与 `ctx.slots.inject` 包装 `settings.plugin.item` 注册逻辑,防止插件在浏览器前端初始化时因插槽未提前声明而抛出 `slot "settings.plugin.item" is not declared` 崩溃异常 (#33)。
|
package/lib/client.js
CHANGED
|
@@ -7,6 +7,155 @@ window.__ModuleLoader__.load({
|
|
|
7
7
|
const React = require('react');
|
|
8
8
|
const NS = '@goodandready/dsh-agent-loop-guard';
|
|
9
9
|
|
|
10
|
+
let PrimitivesChevron = null;
|
|
11
|
+
try {
|
|
12
|
+
const prim = require('@deepseek-ai/dsh-client-ui-primitives');
|
|
13
|
+
if (prim && (prim.IconChevronDownOutline14 || prim.IconChevronDown || prim.IconChevronDown16)) {
|
|
14
|
+
PrimitivesChevron = prim.IconChevronDownOutline14 || prim.IconChevronDown || prim.IconChevronDown16;
|
|
15
|
+
}
|
|
16
|
+
} catch (err) {
|
|
17
|
+
/* bestEffort */
|
|
18
|
+
console.warn?.('[dsh-agent-loop-guard] primitives unavailable, using SVG fallback:', err?.message || String(err));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const CSS_STYLES = `
|
|
22
|
+
.alg-card {
|
|
23
|
+
border: 1px solid var(--dsw-alias-border-l2);
|
|
24
|
+
background: var(--dsw-alias-bg-layer-3);
|
|
25
|
+
border-radius: 12px;
|
|
26
|
+
list-style: none;
|
|
27
|
+
margin-bottom: 12px;
|
|
28
|
+
overflow: hidden;
|
|
29
|
+
transition: border-color 0.15s ease;
|
|
30
|
+
}
|
|
31
|
+
.alg-card:hover {
|
|
32
|
+
border-color: var(--dsw-alias-border-l1, var(--dsw-alias-border-l2));
|
|
33
|
+
}
|
|
34
|
+
.alg-header-btn {
|
|
35
|
+
appearance: none;
|
|
36
|
+
width: 100%;
|
|
37
|
+
font: inherit;
|
|
38
|
+
color: inherit;
|
|
39
|
+
text-align: left;
|
|
40
|
+
cursor: pointer;
|
|
41
|
+
background: transparent;
|
|
42
|
+
border: 0;
|
|
43
|
+
border-radius: 12px;
|
|
44
|
+
display: flex;
|
|
45
|
+
align-items: center;
|
|
46
|
+
gap: 12px;
|
|
47
|
+
padding: 14px 16px;
|
|
48
|
+
transition: background 0.15s ease;
|
|
49
|
+
}
|
|
50
|
+
.alg-header-btn:hover {
|
|
51
|
+
background: var(--dsw-alias-bg-hover, var(--dsw-alias-bg-layer-hover));
|
|
52
|
+
}
|
|
53
|
+
.alg-chevron {
|
|
54
|
+
margin-left: auto;
|
|
55
|
+
color: var(--dsw-alias-label-tertiary);
|
|
56
|
+
display: flex;
|
|
57
|
+
align-items: center;
|
|
58
|
+
justify-content: center;
|
|
59
|
+
transition: transform 0.2s ease;
|
|
60
|
+
}
|
|
61
|
+
.alg-chevron.expanded {
|
|
62
|
+
transform: rotate(180deg);
|
|
63
|
+
}
|
|
64
|
+
.alg-body {
|
|
65
|
+
padding: 0 16px 16px;
|
|
66
|
+
border-top: 1px solid var(--dsw-alias-border-l2);
|
|
67
|
+
}
|
|
68
|
+
.alg-field {
|
|
69
|
+
display: flex;
|
|
70
|
+
flex-direction: column;
|
|
71
|
+
gap: 6px;
|
|
72
|
+
padding: 10px 0;
|
|
73
|
+
}
|
|
74
|
+
.alg-field label {
|
|
75
|
+
font-size: 13px;
|
|
76
|
+
color: var(--dsw-alias-label-secondary);
|
|
77
|
+
cursor: pointer;
|
|
78
|
+
}
|
|
79
|
+
.alg-input {
|
|
80
|
+
height: 34px;
|
|
81
|
+
border: 1px solid var(--dsw-alias-border-l2);
|
|
82
|
+
background: var(--dsw-alias-bg-layer-3);
|
|
83
|
+
color: var(--dsw-alias-label-primary);
|
|
84
|
+
border-radius: 8px;
|
|
85
|
+
padding: 0 12px;
|
|
86
|
+
font-size: 13px;
|
|
87
|
+
outline: none;
|
|
88
|
+
transition: border-color 0.15s ease;
|
|
89
|
+
}
|
|
90
|
+
.alg-input:focus {
|
|
91
|
+
border-color: var(--dsw-alias-accent-primary);
|
|
92
|
+
}
|
|
93
|
+
.alg-checkbox-label {
|
|
94
|
+
display: flex;
|
|
95
|
+
align-items: center;
|
|
96
|
+
gap: 8px;
|
|
97
|
+
font-size: 13px;
|
|
98
|
+
color: var(--dsw-alias-label-primary);
|
|
99
|
+
cursor: pointer;
|
|
100
|
+
padding: 6px 0;
|
|
101
|
+
}
|
|
102
|
+
.alg-btn-primary {
|
|
103
|
+
height: 34px;
|
|
104
|
+
padding: 0 18px;
|
|
105
|
+
border: 0;
|
|
106
|
+
border-radius: 8px;
|
|
107
|
+
background: var(--dsw-alias-accent-primary);
|
|
108
|
+
color: var(--dsw-alias-label-inverse);
|
|
109
|
+
font-size: 13px;
|
|
110
|
+
font-weight: 600;
|
|
111
|
+
cursor: pointer;
|
|
112
|
+
transition: opacity 0.15s ease;
|
|
113
|
+
}
|
|
114
|
+
.alg-btn-primary:disabled {
|
|
115
|
+
opacity: 0.6;
|
|
116
|
+
cursor: default;
|
|
117
|
+
}
|
|
118
|
+
.alg-btn-updater {
|
|
119
|
+
padding: 6px 14px;
|
|
120
|
+
border-radius: 6px;
|
|
121
|
+
background: var(--dsw-alias-accent-primary);
|
|
122
|
+
color: var(--dsw-alias-label-inverse);
|
|
123
|
+
border: 0;
|
|
124
|
+
font-size: 12px;
|
|
125
|
+
font-weight: 600;
|
|
126
|
+
cursor: pointer;
|
|
127
|
+
}
|
|
128
|
+
.alg-btn-updater:disabled {
|
|
129
|
+
opacity: 0.6;
|
|
130
|
+
cursor: default;
|
|
131
|
+
}
|
|
132
|
+
.alg-btn-ghost {
|
|
133
|
+
background: transparent;
|
|
134
|
+
border: 1px solid var(--dsw-alias-border-l2);
|
|
135
|
+
color: var(--dsw-alias-label-tertiary);
|
|
136
|
+
border-radius: 4px;
|
|
137
|
+
padding: 2px 8px;
|
|
138
|
+
font-size: 11px;
|
|
139
|
+
cursor: pointer;
|
|
140
|
+
transition: color 0.15s ease, border-color 0.15s ease;
|
|
141
|
+
}
|
|
142
|
+
.alg-btn-ghost:hover {
|
|
143
|
+
color: var(--dsw-alias-label-primary);
|
|
144
|
+
border-color: var(--dsw-alias-label-secondary);
|
|
145
|
+
}
|
|
146
|
+
`;
|
|
147
|
+
|
|
148
|
+
if (typeof document !== 'undefined') {
|
|
149
|
+
const styleId = 'dsh-agent-loop-guard-styles';
|
|
150
|
+
if (!document.getElementById(styleId)) {
|
|
151
|
+
const style = document.createElement('style');
|
|
152
|
+
style.id = styleId;
|
|
153
|
+
style.setAttribute('data-dsh-plugin', '@goodandready/dsh-agent-loop-guard');
|
|
154
|
+
style.textContent = CSS_STYLES;
|
|
155
|
+
document.head.appendChild(style);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
10
159
|
const en = {
|
|
11
160
|
title: 'Agent Loop Guard',
|
|
12
161
|
sub: 'Fail-closed tool-call and assistant-output loop limits',
|
|
@@ -20,11 +169,13 @@ window.__ModuleLoader__.load({
|
|
|
20
169
|
updateFailed: 'Update failed: {msg}',
|
|
21
170
|
checkUpdateFailed: 'Check failed',
|
|
22
171
|
telemetryTitle: 'Protection Telemetry',
|
|
172
|
+
telemetryLoadFailed: 'Failed to load telemetry',
|
|
23
173
|
totalBlocked: 'Loops Prevented',
|
|
24
174
|
lastViolation: 'Last Incident',
|
|
25
175
|
noViolations: 'No loop violations detected in current runtime.',
|
|
26
176
|
resetStats: 'Reset Stats',
|
|
27
177
|
statsResetDone: 'Stats reset',
|
|
178
|
+
statsResetFailed: 'Failed to reset stats',
|
|
28
179
|
maxToolAttemptsPerTurn: 'Max tool attempts per turn (0 = disabled)',
|
|
29
180
|
maxProgressToolCallsPerTurn: 'Max progress tool calls per turn',
|
|
30
181
|
maxCallsPerRepeatGroup: 'Max calls per repeat group',
|
|
@@ -55,11 +206,13 @@ window.__ModuleLoader__.load({
|
|
|
55
206
|
updateFailed: '更新失败: {msg}',
|
|
56
207
|
checkUpdateFailed: '检查更新失败',
|
|
57
208
|
telemetryTitle: '防护运行遥测',
|
|
209
|
+
telemetryLoadFailed: '获取遥测数据失败',
|
|
58
210
|
totalBlocked: '已拦截死循环',
|
|
59
211
|
lastViolation: '最近拦截事件',
|
|
60
212
|
noViolations: '当前运行时未检测到死循环违规。',
|
|
61
213
|
resetStats: '重置统计',
|
|
62
214
|
statsResetDone: '统计已重置',
|
|
215
|
+
statsResetFailed: '重置统计失败',
|
|
63
216
|
maxToolAttemptsPerTurn: '单回合最大工具尝试次数(0 表示禁用)',
|
|
64
217
|
maxProgressToolCallsPerTurn: '单回合最大进度工具调用次数',
|
|
65
218
|
maxCallsPerRepeatGroup: '同组工具最大重复调用次数',
|
|
@@ -107,7 +260,7 @@ window.__ModuleLoader__.load({
|
|
|
107
260
|
const [updateState, setUpdateState] = React.useState({
|
|
108
261
|
checking: false,
|
|
109
262
|
updateAvailable: false,
|
|
110
|
-
currentVersion: '
|
|
263
|
+
currentVersion: '',
|
|
111
264
|
latestVersion: '',
|
|
112
265
|
updating: false,
|
|
113
266
|
notice: '',
|
|
@@ -127,7 +280,22 @@ window.__ModuleLoader__.load({
|
|
|
127
280
|
}
|
|
128
281
|
const scope = scopeRef.current;
|
|
129
282
|
|
|
130
|
-
const
|
|
283
|
+
const [, setLocaleTick] = React.useState(0);
|
|
284
|
+
React.useEffect(() => {
|
|
285
|
+
if (typeof _ctx?.locale?.subscribe === 'function') {
|
|
286
|
+
return _ctx.locale.subscribe(() => setLocaleTick((c) => c + 1));
|
|
287
|
+
}
|
|
288
|
+
}, []);
|
|
289
|
+
|
|
290
|
+
const getActiveLocale = () => {
|
|
291
|
+
const snap = typeof _ctx?.locale?.getLocale === 'function'
|
|
292
|
+
? _ctx.locale.getLocale()
|
|
293
|
+
: (typeof _ctx?.locale?.getSnapshot === 'function' ? _ctx.locale.getSnapshot() : null);
|
|
294
|
+
const loc = typeof snap === 'string' ? snap : (snap?.locale || snap?.id);
|
|
295
|
+
if (loc) return loc;
|
|
296
|
+
return typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en';
|
|
297
|
+
};
|
|
298
|
+
const currentLang = String(getActiveLocale()).toLowerCase().startsWith('zh') ? 'zh' : 'en';
|
|
131
299
|
const dict = currentLang === 'zh' ? zh : en;
|
|
132
300
|
const tt = (k, params) => {
|
|
133
301
|
let str = (typeof t === 'function' ? t(k) : null) || dict[k] || en[k] || k;
|
|
@@ -187,7 +355,7 @@ window.__ModuleLoader__.load({
|
|
|
187
355
|
setUpdateState((s) => ({
|
|
188
356
|
...s,
|
|
189
357
|
checking: false,
|
|
190
|
-
currentVersion: data.currentVersion || '
|
|
358
|
+
currentVersion: data.currentVersion || '',
|
|
191
359
|
latestVersion: data.latestVersion || '',
|
|
192
360
|
updateAvailable: !!data.updateAvailable,
|
|
193
361
|
}));
|
|
@@ -201,11 +369,19 @@ window.__ModuleLoader__.load({
|
|
|
201
369
|
(async () => {
|
|
202
370
|
try {
|
|
203
371
|
const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry');
|
|
204
|
-
if (!res.ok)
|
|
372
|
+
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
205
373
|
const data = await res.json();
|
|
206
374
|
if (cancelled) return;
|
|
207
|
-
setTelemetry(
|
|
208
|
-
|
|
375
|
+
setTelemetry({
|
|
376
|
+
totalViolations: Number(data.totalViolations) || 0,
|
|
377
|
+
byCode: data.byCode || {},
|
|
378
|
+
lastViolation: data.lastViolation || null,
|
|
379
|
+
error: null,
|
|
380
|
+
});
|
|
381
|
+
} catch (err) {
|
|
382
|
+
if (cancelled) return;
|
|
383
|
+
setTelemetry((t) => ({ ...t, error: tt('telemetryLoadFailed') }));
|
|
384
|
+
}
|
|
209
385
|
})();
|
|
210
386
|
|
|
211
387
|
return () => { cancelled = true; };
|
|
@@ -275,33 +451,65 @@ window.__ModuleLoader__.load({
|
|
|
275
451
|
|
|
276
452
|
async function onResetTelemetry() {
|
|
277
453
|
try {
|
|
278
|
-
await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry', {
|
|
279
|
-
|
|
454
|
+
const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry', {
|
|
455
|
+
method: 'POST',
|
|
456
|
+
headers: { 'x-dsh-loop-guard': '1' },
|
|
457
|
+
});
|
|
458
|
+
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
459
|
+
setTelemetry({ totalViolations: 0, byCode: {}, lastViolation: null, error: null });
|
|
280
460
|
setMsg(tt('statsResetDone'));
|
|
281
|
-
} catch {
|
|
461
|
+
} catch (err) {
|
|
462
|
+
setMsg(tt('statsResetFailed'));
|
|
463
|
+
}
|
|
282
464
|
}
|
|
283
465
|
|
|
284
|
-
const
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
466
|
+
const renderChevron = () => {
|
|
467
|
+
if (PrimitivesChevron) {
|
|
468
|
+
return React.createElement(PrimitivesChevron, {
|
|
469
|
+
className: 'alg-chevron' + (expanded ? ' expanded' : ''),
|
|
470
|
+
style: { width: 14, height: 14, color: 'inherit' }
|
|
471
|
+
});
|
|
472
|
+
}
|
|
473
|
+
return React.createElement('svg', {
|
|
474
|
+
className: 'alg-chevron' + (expanded ? ' expanded' : ''),
|
|
475
|
+
width: 14,
|
|
476
|
+
height: 14,
|
|
477
|
+
viewBox: '0 0 24 24',
|
|
478
|
+
fill: 'none',
|
|
479
|
+
stroke: 'currentColor',
|
|
480
|
+
strokeWidth: 2,
|
|
481
|
+
strokeLinecap: 'round',
|
|
482
|
+
strokeLinejoin: 'round',
|
|
483
|
+
style: { flexShrink: 0 }
|
|
484
|
+
}, React.createElement('polyline', { points: '6 9 12 15 18 9' }));
|
|
485
|
+
};
|
|
486
|
+
|
|
487
|
+
const field = (key, input) => {
|
|
488
|
+
const id = 'alg-' + key;
|
|
489
|
+
const linkedInput = React.isValidElement && React.isValidElement(input)
|
|
490
|
+
? React.cloneElement(input, { id })
|
|
491
|
+
: input;
|
|
492
|
+
return React.createElement('div', { className: 'alg-field' },
|
|
493
|
+
React.createElement('label', { htmlFor: id }, tt(key)),
|
|
494
|
+
linkedInput
|
|
495
|
+
);
|
|
496
|
+
};
|
|
291
497
|
|
|
292
498
|
const num = (key) => React.createElement('input', {
|
|
293
|
-
type: 'number',
|
|
499
|
+
type: 'number',
|
|
500
|
+
className: 'alg-input',
|
|
501
|
+
value: draft[key],
|
|
294
502
|
onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
|
|
295
|
-
style: { height: 34, border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', color: 'var(--dsw-alias-label-primary)', borderRadius: 8, padding: '0 12px', fontSize: 13 }
|
|
296
503
|
});
|
|
297
504
|
|
|
298
505
|
const str = (key) => React.createElement('input', {
|
|
299
|
-
type: 'text',
|
|
506
|
+
type: 'text',
|
|
507
|
+
className: 'alg-input',
|
|
508
|
+
value: draft[key],
|
|
300
509
|
onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
|
|
301
|
-
style: { height: 34, border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', color: 'var(--dsw-alias-label-primary)', borderRadius: 8, padding: '0 12px', fontSize: 13 }
|
|
302
510
|
});
|
|
303
511
|
|
|
304
|
-
const check = (key) => React.createElement('label', {
|
|
512
|
+
const check = (key) => React.createElement('label', { className: 'alg-checkbox-label' },
|
|
305
513
|
React.createElement('input', {
|
|
306
514
|
type: 'checkbox', checked: !!draft[key],
|
|
307
515
|
onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.checked }))
|
|
@@ -311,67 +519,67 @@ window.__ModuleLoader__.load({
|
|
|
311
519
|
|
|
312
520
|
return React.createElement('li', {
|
|
313
521
|
className: 'alg-card',
|
|
314
|
-
style: { border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', borderRadius: 12, listStyle: 'none', marginBottom: 12 }
|
|
315
522
|
},
|
|
316
523
|
React.createElement('button', {
|
|
524
|
+
className: 'alg-header-btn',
|
|
317
525
|
onClick: () => setExpanded(!expanded),
|
|
318
526
|
'aria-expanded': expanded,
|
|
319
|
-
style: { appearance: 'none', width: '100%', font: 'inherit', color: 'inherit', textAlign: 'left', cursor: 'pointer', background: '0 0', border: 0, borderRadius: 12, display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }
|
|
320
527
|
},
|
|
321
528
|
React.createElement('span', { style: { display: 'flex', flexDirection: 'column' } },
|
|
322
529
|
React.createElement('span', { style: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 } },
|
|
323
|
-
|
|
324
|
-
React.createElement('span', { style: { fontSize: 11, fontWeight: 500, padding: '2px 6px', borderRadius: 6, background: '
|
|
530
|
+
tt('title'),
|
|
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 ? '…' : '—'))
|
|
325
532
|
),
|
|
326
533
|
React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, tt('sub'))
|
|
327
534
|
),
|
|
328
|
-
|
|
535
|
+
renderChevron()
|
|
329
536
|
),
|
|
330
537
|
expanded && React.createElement('div', {
|
|
331
538
|
className: 'alg-body',
|
|
332
|
-
style: { padding: '0 16px 16px', borderTop: '1px solid var(--dsw-alias-border-l2)' }
|
|
333
539
|
},
|
|
334
540
|
// Section: One-Click Updater
|
|
335
541
|
React.createElement('div', {
|
|
336
|
-
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 }
|
|
337
543
|
},
|
|
338
544
|
React.createElement('div', { style: { fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 } },
|
|
339
|
-
React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)' } }, tt('version') + ': ' + updateState.currentVersion),
|
|
545
|
+
React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)' } }, tt('version') + ': ' + (updateState.currentVersion || (updateState.checking ? '…' : '—'))),
|
|
340
546
|
updateState.checking && React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12 } }, tt('updateChecking')),
|
|
341
|
-
!updateState.checking && updateState.updateAvailable && React.createElement('span', { style: { color: '
|
|
342
|
-
!updateState.checking && !updateState.updateAvailable && !updateState.error && React.createElement('span', { style: { color: '
|
|
343
|
-
updateState.error && React.createElement('span', { style: { color: '
|
|
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)
|
|
344
550
|
),
|
|
345
551
|
updateState.updateAvailable && React.createElement('button', {
|
|
552
|
+
className: 'alg-btn-updater',
|
|
346
553
|
onClick: onTriggerUpdate,
|
|
347
554
|
disabled: updateState.updating,
|
|
348
|
-
style: { padding: '6px 14px', borderRadius: 6, background: 'var(--dsw-alias-accent-primary, #3b82f6)', color: '#fff', border: 0, fontSize: 12, fontWeight: 600, cursor: updateState.updating ? 'default' : 'pointer' }
|
|
349
555
|
}, updateState.updating ? tt('updating') : tt('updateNow'))
|
|
350
556
|
),
|
|
351
557
|
updateState.notice && React.createElement('div', {
|
|
352
|
-
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)' }
|
|
353
559
|
}, updateState.notice),
|
|
354
560
|
|
|
355
561
|
// Section: Protection Telemetry
|
|
356
562
|
React.createElement('div', {
|
|
357
|
-
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)' }
|
|
358
564
|
},
|
|
359
565
|
React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
|
|
360
|
-
React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } },
|
|
566
|
+
React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, tt('telemetryTitle')),
|
|
361
567
|
telemetry.totalViolations > 0 && React.createElement('button', {
|
|
568
|
+
className: 'alg-btn-ghost',
|
|
362
569
|
onClick: onResetTelemetry,
|
|
363
|
-
style: { background: 'transparent', border: '1px solid var(--dsw-alias-border-l2)', color: 'var(--dsw-alias-label-tertiary)', borderRadius: 4, padding: '2px 8px', fontSize: 11, cursor: 'pointer' }
|
|
364
570
|
}, tt('resetStats'))
|
|
365
571
|
),
|
|
366
572
|
React.createElement('div', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
|
|
367
|
-
telemetry.
|
|
368
|
-
? React.createElement('
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
tt('
|
|
573
|
+
telemetry.error
|
|
574
|
+
? React.createElement('span', { style: { color: 'var(--dsw-alias-status-danger)' } }, telemetry.error)
|
|
575
|
+
: telemetry.totalViolations > 0
|
|
576
|
+
? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
|
|
577
|
+
React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-status-warning)' } }, telemetry.totalViolations)),
|
|
578
|
+
telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
|
|
579
|
+
tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
|
|
580
|
+
)
|
|
372
581
|
)
|
|
373
|
-
)
|
|
374
|
-
: React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
|
|
582
|
+
: React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
|
|
375
583
|
)
|
|
376
584
|
),
|
|
377
585
|
|
|
@@ -394,11 +602,11 @@ window.__ModuleLoader__.load({
|
|
|
394
602
|
style: { display: 'flex', alignItems: 'center', gap: 12, paddingTop: 14, borderTop: '1px solid var(--dsw-alias-border-l2)', marginTop: 10 }
|
|
395
603
|
},
|
|
396
604
|
React.createElement('button', {
|
|
605
|
+
className: 'alg-btn-primary',
|
|
397
606
|
onClick: onSave,
|
|
398
607
|
disabled: saving || status !== 'ready',
|
|
399
|
-
style: { height: 34, padding: '0 18px', border: 0, borderRadius: 8, background: 'var(--dsw-alias-accent-primary, #3b82f6)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: saving ? 'default' : 'pointer' }
|
|
400
608
|
}, saving ? tt('saving') : tt('ready')),
|
|
401
|
-
msg && React.createElement('span', { style: { fontSize: 13, color: msg === tt('saved') || msg === tt('statsResetDone') ? '
|
|
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)
|
|
402
610
|
)
|
|
403
611
|
)
|
|
404
612
|
);
|
|
@@ -407,7 +615,11 @@ window.__ModuleLoader__.load({
|
|
|
407
615
|
exports.inject = ['slots', 'settingsScope', 'locale'];
|
|
408
616
|
exports.apply = function apply(ctx) {
|
|
409
617
|
if (typeof ctx.locale?.register === 'function') {
|
|
410
|
-
|
|
618
|
+
if (typeof ctx.effect === 'function') {
|
|
619
|
+
ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'dsh-agent-loop-guard: locale');
|
|
620
|
+
} else {
|
|
621
|
+
ctx.locale.register(NS, { en, zh });
|
|
622
|
+
}
|
|
411
623
|
}
|
|
412
624
|
|
|
413
625
|
function registerSlotWhenReady(slotName, registerFn) {
|
package/lib/guard-state.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const STOP_REQUEST_PATTERN = /(?:\b(?:stop|halt|cancel|answer(?:\s+now)?)\b|останов(?:ись|ить)|прекрати|хватит|ответь|петл[яиюе])/iu;
|
|
1
|
+
const STOP_REQUEST_PATTERN = /(?:\b(?:stop|halt|cancel|answer(?:\s+now)?)\b|(?<![\p{L}\p{N}_-])стоп(?![\p{L}\p{N}_-])|останов(?:ись|ить)|прекрати|хватит|ответь|петл[яиюе])/iu;
|
|
2
2
|
const SECRET_KEY_PATTERN = /(?:token|secret|password|authorization|api[-_]?key|cookie)/iu;
|
|
3
3
|
|
|
4
4
|
function stableJson(value) {
|
|
@@ -124,6 +124,7 @@ export class LoopGuardState {
|
|
|
124
124
|
dryRunMode: Boolean(config.dryRunMode),
|
|
125
125
|
blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : true,
|
|
126
126
|
};
|
|
127
|
+
this.logger = config.logger;
|
|
127
128
|
this.onViolation = typeof config.onViolation === 'function' ? config.onViolation : undefined;
|
|
128
129
|
this.progressToolNames = new Set(progressToolNames);
|
|
129
130
|
this.strictTools = new Set(strictTools);
|
|
@@ -166,6 +167,7 @@ export class LoopGuardState {
|
|
|
166
167
|
dryRunMode: config.dryRunMode !== undefined ? Boolean(config.dryRunMode) : Boolean(this.config.dryRunMode),
|
|
167
168
|
blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : this.config.blockExactDuplicates,
|
|
168
169
|
};
|
|
170
|
+
if (config.logger !== undefined) this.logger = config.logger;
|
|
169
171
|
this.progressToolNames = new Set(progressToolNames);
|
|
170
172
|
this.strictTools = new Set(strictTools);
|
|
171
173
|
}
|
|
@@ -291,7 +293,11 @@ export class LoopGuardState {
|
|
|
291
293
|
dryRun: Boolean(this.config.dryRunMode),
|
|
292
294
|
...summary,
|
|
293
295
|
};
|
|
294
|
-
try {
|
|
296
|
+
try {
|
|
297
|
+
this.onViolation?.(event);
|
|
298
|
+
} catch (error) {
|
|
299
|
+
this.logger?.debug?.('dsh-agent-loop-guard: onViolation callback failed: ' + (error instanceof Error ? error.message : String(error)));
|
|
300
|
+
}
|
|
295
301
|
|
|
296
302
|
if (this.config.dryRunMode) {
|
|
297
303
|
return undefined;
|
|
@@ -430,12 +436,4 @@ export class LoopGuardState {
|
|
|
430
436
|
}
|
|
431
437
|
return { known: outcome.known, productive };
|
|
432
438
|
}
|
|
433
|
-
|
|
434
|
-
releaseCall(agent, callId) {
|
|
435
|
-
const state = this.stateFor(agent);
|
|
436
|
-
const call = this.findCall(state, callId);
|
|
437
|
-
if (call === undefined) return;
|
|
438
|
-
call.released = true;
|
|
439
|
-
this.decrementReservations(state, call);
|
|
440
|
-
}
|
|
441
439
|
}
|