@goodandready/dsh-agent-loop-guard 0.2.4 → 0.2.6

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/docs/README.zh.md CHANGED
@@ -16,11 +16,21 @@
16
16
  </p>
17
17
 
18
18
  <p align="center">
19
- <a href="../README.md"><b>🇬🇧 English</b></a> •
19
+ <a href="README.md"><b>🇬🇧 English</b></a> •
20
20
  <a href="README.ru.md"><b>🇷🇺 Русский</b></a> •
21
21
  <a href="README.zh.md"><b>🇨🇳 中文说明</b></a>
22
22
  </p>
23
23
 
24
+ <table align="center">
25
+ <tr>
26
+ <td align="center">
27
+ ⭐ <strong>如果您喜欢这个插件,请在 GitHub 上为它点亮 Star</strong> — 这能让我知道插件对您有用,并鼓励我继续开发和维护它。
28
+ <br><br>
29
+ 🐛 <strong>如果您发现 Bug 或希望增加功能</strong>,请使用任意语言在 GitHub 上提交 Issue — 我会评估您的建议,并在后续版本中实现有价值的改进。
30
+ </td>
31
+ </tr>
32
+ </table>
33
+
24
34
  </div>
25
35
 
26
36
  ---
@@ -144,7 +154,10 @@ dsh-agent-loop-guard:
144
154
  | `maxProgressToolCallsPerTurn` | `number` | `16` | 进度标记工具(`todo_write`)连续无进展调用的上限。 |
145
155
  | `progressToolNames` | `array` | `["todo_write"]` | 标记任务进度的工具名称数组。 |
146
156
  | `maxCallsPerRepeatGroup` | `number` | `5` | 同一组工具未产生新结果时允许调用的最大次数。 |
157
+ | `strictTools` | `array` | `[]` | 受到更严格重复调用限制的敏感/修改类工具名称列表。 |
158
+ | `strictToolLimit` | `number` | `3` | `strictTools` 列表中工具的最大允许重复次数。 |
147
159
  | `blockExactDuplicates` | `boolean` | `true` | 是否立即拦截结果毫无变化的连续相同调用。 |
160
+ | `dryRunMode` | `boolean` | `false` | 审计模式:记录告警与遥测指标,但不实际拦截工具调用。 |
148
161
  | `assistantOutputGuard` | `boolean` | `true` | 是否开启助手流式文本输出防死循环监测。 |
149
162
  | `maxRepeatedAssistantLines` | `number` | `5` | 触发输出中断的连续相同单行阈值。 |
150
163
  | `maxRepeatedAssistantBlocks` | `number` | `5` | 触发输出中断的连续重复段落阈值。 |
@@ -154,7 +167,7 @@ dsh-agent-loop-guard:
154
167
 
155
168
  ## 🧪 测试与校验
156
169
 
157
- 运行全部 31 个单元测试及静态代码检查:
170
+ 运行全部 37 个自动化单元测试及静态代码检查:
158
171
 
159
172
  ```bash
160
173
  npm test
@@ -169,6 +182,22 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
169
182
 
170
183
  ---
171
184
 
185
+ ## v0.2.6 更新日志
186
+
187
+ - **浏览器 ModuleLoader 导入修复**:在 `lib/client.js` 的 factory 函数中显式声明 `var exports = module.exports;`,彻底修复 DSH 网页端 ModuleLoader 动态加载时抛出的 `ReferenceError: exports is not defined` 异常 (#31)。
188
+ - **客户端测试用例**:新增 `test/client.test.js`,通过 Node.js VM 模拟浏览器端模块加载环境并自动化验证 (#31)。
189
+
190
+ ## v0.2.5 更新日志
191
+
192
+ - **一键平滑更新**:集成宿主端更新器(`lib/plugin-updater.js`),提供 `/api/@goodandready/dsh-agent-loop-guard/update` 接口与设置界面更新状态/按钮 (#29)。
193
+ - **敏感工具严格配额**:新增 `strictTools` 与 `strictToolLimit` 配置,强化对高危/文件修改工具的重复调用限制 (#29)。
194
+ - **审计模式 (Dry-Run)**:新增 `dryRunMode` 配置,支持在不阻断智能体调用的前提下记录告警与度量数据 (#29)。
195
+ - **防护遥测与监控**:实时统计拦截指标(`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`),提供 `/api/@goodandready/dsh-agent-loop-guard/telemetry` 接口与一键重置 (#29)。
196
+ - **LLM 智能恢复引导**:在拦截消息中为 DeepSeek-R1 / V3 等模型提供结构化的破局指导与操作建议 (#29)。
197
+ - **严格多语言规范**:代码库仅保留标准英文(`en`)与中文(`zh`),俄语本地化转入 Issue #197 (`goodandready/dsh-russian-lang`) 处理 (#29)。
198
+ - **设计契约**:按照 `project-design-contract` 标准建立 `docs/design/DESIGN.md` (#29)。
199
+ - **扩展自动化测试**:总测试用例扩充至 37 个,涵盖更新器语义版本、请求安全性、严格工具配额与审计模式 (#29)。
200
+
172
201
  ## v0.2.4 更新日志
173
202
 
174
203
  - **设置界面**:修复 `maxToolAttemptsPerTurn` 保存为 `0` 的问题,允许正常禁用单回合工具调用上限 (#28)。
@@ -0,0 +1,94 @@
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.5 (активная разработка расширений: One-Click Updater, EN/ZH i18n, телеметрия, адаптивные квоты, dry-run).
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`, `maxCallsPerToolPerTurn`, `maxRepeatedAssistantLines`, `maxRepeatedAssistantBlocks`, `maxAssistantBlockChars`), чекбоксы (`blockExactDuplicates`, `assistantOutputGuard`, `dryRunMode`), текстовые списки (`progressToolNames`, `strictTools`).
17
+ - Кнопка сохранения с индикацией статуса (`Saving...`, `Saved`, ошибки валидации).
18
+ - **API:**
19
+ - Route: `/api/@goodandready/dsh-agent-loop-guard/update` (GET — статус версий, POST — доверенное обновление).
20
+ - **CLI:**
21
+ - Установка и обновление через штатный DSH CLI: `dsh plugin --profile web add @goodandready/dsh-agent-loop-guard`.
22
+ - **Документация:**
23
+ - `README.md` (English, canonical)
24
+ - `docs/README.ru.md` (Русский, синхронизированная проектная документация)
25
+ - `docs/README.zh.md` (中文, обязательная пользовательская документация)
26
+ - `AGENTS.md` (правила архитектуры и зафиксированные решения)
27
+
28
+ ## Visual Direction
29
+ - **Атмосфера:** Утилитарный, надёжный, сдержанный инженерный интерфейс системной безопасности. Интеграция «как родной» в дизайн-систему DeepSeek Harness.
30
+ - **Утверждённые референсы:** Нативные компоненты DSH Web UI (`settingsScope`, css-переменные темы `--dsw-alias-*`).
31
+ - **Не копировать:** Кастомные несогласованные темы, яркие несистемные градиенты, сторонние тяжелые библиотеки компонентов (MUI, AntD).
32
+
33
+ ## Foundations
34
+ - **Цвета и роли:**
35
+ - Фон карточки: `var(--dsw-alias-bg-layer-3)`
36
+ - Границы: `var(--dsw-alias-border-l2)`
37
+ - Основной текст: `var(--dsw-alias-label-primary)`
38
+ - Вторичный текст / подписи полей: `var(--dsw-alias-label-secondary)`
39
+ - Третичный текст / стрелки: `var(--dsw-alias-label-tertiary)`
40
+ - Акцент обновления / бейдж: `var(--dsw-alias-accent-primary, #3b82f6)`
41
+ - Предупреждения / ошибки: `var(--dsw-alias-status-danger, #ef4444)`
42
+ - Успешное сохранение / актуальность: `var(--dsw-alias-status-success, #22c55e)`
43
+ - **Типографика:**
44
+ - Системный шрифт DSH (`Plus Jakarta Sans` / системный UI стек, моноширинный для кодов и версий).
45
+ - Размеры: Заголовок 15px (font-weight: 600), подзаголовок 13px, метки полей 13px, числовые поля 13px.
46
+ - **Сетка, отступы, responsive:**
47
+ - Скругление карточки: `12px`.
48
+ - Внутренние отступы шапки: `14px 16px`.
49
+ - Отступы полей ввода: `padding: 10px 0`, расстояние между меткой и полем `6px`.
50
+ - Адаптивность: 100% ширина контейнера, резиновые поля.
51
+ - **Accessibility:**
52
+ - Семантические теги `<label>`, ассоциированные с input.
53
+ - Атрибут `aria-expanded` для сворачиваемой карточки.
54
+ - Достаточный контраст текста по шкале WCAG AA через системные CSS-переменные.
55
+
56
+ ## Components And States
57
+ - **Компоненты:**
58
+ 1. `PluginCard`: Сворачиваемый контейнер карточки настроек.
59
+ 2. `UpdateSection`: Блок проверки и запуска one-click обновления с npm.
60
+ 3. `TelemetryBadge`: Индикатор защитных срабатываний в текущем процессе DSH.
61
+ 4. `SettingsForm`: Набор типизированных полей ввода.
62
+ 5. `SaveButton`: Кнопка фиксации настроек через `scope.set()`.
63
+ - **Loading / empty / error / success:**
64
+ - `status === 'loading'`: отображение скелетона/загрузки данных из `settingsScope`.
65
+ - `status === 'unavailable'`: отображение предупреждения о недоступности пространства настроек (блокировка полей ввода от ложного редактирования).
66
+ - `status === 'ready'`: интерактивная форма со значениями по умолчанию или сохранёнными настройками.
67
+ - Сохранение: отображение `Saving...` (`正在保存…`), при успехе `Saved` (`已保存`), при ошибках перечисление ключей.
68
+ - Обновление: `Checking updates...`, `Up to date` (`已是最新版本`), `Update available: vX.Y.Z` (`发现新版本`), `Updating...` (`正在更新…`), `Restart required` (`需要重启服务`).
69
+
70
+ ## User Flows
71
+ - **Критический сценарий 1 (Пресечение зацикливания инструмента):**
72
+ 1. Агент вызывает инструмент (например, `read_file`) с теми же аргументами без изменения результата или превышает квоту группы.
73
+ 2. Guard блокирует вызов с кодом `LOOP_GUARD_DUPLICATE` / `LOOP_GUARD_REPEAT`.
74
+ 3. Модель получает структурированную инструкцию `[LOOP_GUARD_DUPLICATE] ... STOP repeating this action ...`.
75
+ 4. Модель переключается на альтернативный инструмент или переходит к синтезу ответа.
76
+ 5. В телеметрии карточки инкрементируется счётчик нарушений.
77
+ - **Критический сценарий 2 (One-Click обновление плагина):**
78
+ 1. Администратор открывает Настройки → Плагины → Agent Loop Guard.
79
+ 2. Карточка запрашивает `/api/@goodandready/dsh-agent-loop-guard/update`.
80
+ 3. При наличии новой версии отображается кнопка «Update Now».
81
+ 4. Пользователь нажимает кнопку. Отправляется POST-запрос с `x-dsh-plugin-update: 1`.
82
+ 5. DSH CLI устанавливает точную версию. Кнопка блокируется от повторных кликов.
83
+ 6. Интерфейс сообщает: `Updated successfully. Restart DSH service to apply changes.`.
84
+
85
+ ## Internationalization & Localization (Do / Don't)
86
+ - **Do:**
87
+ - Код плагина, схемы настроек, логи и системные сообщения — **English (`en`)**.
88
+ - Пользовательский интерфейс плагина обязан поддерживать **English (`en`)** и **Chinese (`zh`)**.
89
+ - Все новые ключи для русского перевода регистрируются через issue в Gitea `goodandready/dsh-russian-lang` со сравнительной таблицей `Key | English | Chinese | Proposed Russian`.
90
+ - Документация в репозитории ведётся на 3 языках (`README.md`, `docs/README.ru.md`, `docs/README.zh.md`).
91
+ - **Don't:**
92
+ - **Запрещено** хардкодить русские строки, русские дефолты или русский словарь `ru` внутри кода плагина (`lib/client.js`, `lib/index.js`).
93
+ - **Запрещено** удалять существующие описания фич в документации при релизе (только additive-обновление).
94
+ - **Запрещено** менять вторую цифру версии $y$ без явной прямой команды пользователя.
package/lib/client.js CHANGED
@@ -2,40 +2,79 @@ window.__ModuleLoader__.load({
2
2
  id: '@goodandready/dsh-agent-loop-guard',
3
3
  factory: (require) => {
4
4
  var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
5
7
  const React = require('react');
6
8
  const NS = '@goodandready/dsh-agent-loop-guard';
7
9
 
8
10
  const en = {
9
11
  title: 'Agent Loop Guard',
10
12
  sub: 'Fail-closed tool-call and assistant-output loop limits',
11
- maxToolAttemptsPerTurn: 'Max tool attempts per turn',
13
+ version: 'Version',
14
+ updateChecking: 'Checking updates…',
15
+ updateAvailable: 'Update available: v{v}',
16
+ upToDate: 'Up to date',
17
+ updateNow: 'Update Now',
18
+ updating: 'Updating…',
19
+ updateSuccess: 'Updated to v{v}. Restart DSH service to apply changes.',
20
+ updateFailed: 'Update failed: {msg}',
21
+ checkUpdateFailed: 'Check failed',
22
+ telemetryTitle: 'Protection Telemetry',
23
+ totalBlocked: 'Loops Prevented',
24
+ lastViolation: 'Last Incident',
25
+ noViolations: 'No loop violations detected in current runtime.',
26
+ resetStats: 'Reset Stats',
27
+ statsResetDone: 'Stats reset',
28
+ maxToolAttemptsPerTurn: 'Max tool attempts per turn (0 = disabled)',
12
29
  maxProgressToolCallsPerTurn: 'Max progress tool calls per turn',
13
30
  maxCallsPerRepeatGroup: 'Max calls per repeat group',
31
+ strictTools: 'Strict tools (comma-separated, lower limit)',
32
+ strictToolLimit: 'Strict tools limit',
14
33
  blockExactDuplicates: 'Block exact duplicate tool calls',
34
+ dryRunMode: 'Dry-run / Audit mode (log only, do not reject)',
15
35
  assistantOutputGuard: 'Assistant output guard',
16
36
  maxRepeatedAssistantLines: 'Max repeated assistant lines',
17
37
  maxRepeatedAssistantBlocks: 'Max repeated assistant blocks',
18
38
  maxAssistantBlockChars: 'Max assistant block chars',
19
39
  progressToolNames: 'Progress tool names (comma-separated)',
20
40
  saving: 'Saving…',
21
- ready: 'Save',
41
+ ready: 'Save Settings',
22
42
  saved: 'Saved',
23
43
  };
24
- const ru = {
44
+
45
+ const zh = {
25
46
  title: 'Agent Loop Guard',
26
- sub: 'Жёсткие лимиты на петли tool-call и повторы ответа ассистента',
27
- maxToolAttemptsPerTurn: 'Макс. попыток tool за ход',
28
- maxProgressToolCallsPerTurn: 'Макс. progress-tool за ход',
29
- maxCallsPerRepeatGroup: 'Макс. вызовов в repeat-группе',
30
- blockExactDuplicates: 'Блокировать точные дубликаты tool-call',
31
- assistantOutputGuard: 'Охрана повторов ответа ассистента',
32
- maxRepeatedAssistantLines: 'Макс. повторов строк',
33
- maxRepeatedAssistantBlocks: 'Макс. повторов блоков',
34
- maxAssistantBlockChars: 'Макс. символов блока',
35
- progressToolNames: 'Progress-инструменты (через запятую)',
36
- saving: 'Сохранение…',
37
- ready: 'Сохранить',
38
- saved: 'Сохранено',
47
+ sub: '工具调用与助手输出防死循环熔断限制',
48
+ version: '版本',
49
+ updateChecking: '正在检查更新…',
50
+ updateAvailable: '发现新版本: v{v}',
51
+ upToDate: '已是最新版本',
52
+ updateNow: '立即更新',
53
+ updating: '正在更新…',
54
+ updateSuccess: '已更新至 v{v}。请重启 DSH 服务以生效变更。',
55
+ updateFailed: '更新失败: {msg}',
56
+ checkUpdateFailed: '检查更新失败',
57
+ telemetryTitle: '防护运行遥测',
58
+ totalBlocked: '已拦截死循环',
59
+ lastViolation: '最近拦截事件',
60
+ noViolations: '当前运行时未检测到死循环违规。',
61
+ resetStats: '重置统计',
62
+ statsResetDone: '统计已重置',
63
+ maxToolAttemptsPerTurn: '单回合最大工具尝试次数(0 表示禁用)',
64
+ maxProgressToolCallsPerTurn: '单回合最大进度工具调用次数',
65
+ maxCallsPerRepeatGroup: '同组工具最大重复调用次数',
66
+ strictTools: '严格限制工具(逗号分隔,触发更低阈值)',
67
+ strictToolLimit: '严格工具调用上限',
68
+ blockExactDuplicates: '立即拦截完全相同的重复工具调用',
69
+ dryRunMode: '审计模拟模式(仅记录日志,不实际拦截)',
70
+ assistantOutputGuard: '助手文本输出防循环守卫',
71
+ maxRepeatedAssistantLines: '最大单行重复次数',
72
+ maxRepeatedAssistantBlocks: '最大段落重复次数',
73
+ maxAssistantBlockChars: '最大段落判定字符数',
74
+ progressToolNames: '进度标记工具(逗号分隔)',
75
+ saving: '正在保存…',
76
+ ready: '保存配置',
77
+ saved: '配置已保存',
39
78
  };
40
79
 
41
80
  const DEFAULTS = {
@@ -43,7 +82,10 @@ window.__ModuleLoader__.load({
43
82
  maxProgressToolCallsPerTurn: 16,
44
83
  progressToolNames: ['todo_write'],
45
84
  maxCallsPerRepeatGroup: 5,
85
+ strictTools: [],
86
+ strictToolLimit: 3,
46
87
  blockExactDuplicates: true,
88
+ dryRunMode: false,
47
89
  assistantOutputGuard: true,
48
90
  maxRepeatedAssistantLines: 5,
49
91
  maxRepeatedAssistantBlocks: 5,
@@ -52,17 +94,52 @@ window.__ModuleLoader__.load({
52
94
 
53
95
  function PluginCard({ ctx: _ctx, t }) {
54
96
  const [expanded, setExpanded] = React.useState(false);
55
- const [draft, setDraft] = React.useState({ ...DEFAULTS, progressToolNamesText: 'todo_write' });
97
+ const [draft, setDraft] = React.useState({
98
+ ...DEFAULTS,
99
+ progressToolNamesText: 'todo_write',
100
+ strictToolsText: '',
101
+ });
56
102
  const [status, setStatus] = React.useState('loading');
57
103
  const [saving, setSaving] = React.useState(false);
58
104
  const [msg, setMsg] = React.useState('');
105
+
106
+ // Updater state
107
+ const [updateState, setUpdateState] = React.useState({
108
+ checking: false,
109
+ updateAvailable: false,
110
+ currentVersion: '0.2.5',
111
+ latestVersion: '',
112
+ updating: false,
113
+ notice: '',
114
+ error: '',
115
+ });
116
+
117
+ // Telemetry state
118
+ const [telemetry, setTelemetry] = React.useState({
119
+ totalViolations: 0,
120
+ byCode: {},
121
+ lastViolation: null,
122
+ });
123
+
59
124
  const scopeRef = React.useRef(null);
60
125
  if (!scopeRef.current && _ctx && _ctx.settingsScope) {
61
126
  try { scopeRef.current = _ctx.settingsScope.bind({ namespace: NS }); } catch (e) { scopeRef.current = null; }
62
127
  }
63
128
  const scope = scopeRef.current;
64
- const tt = t || ((k) => en[k] || k);
65
129
 
130
+ const currentLang = (_ctx?.locale?.get?.() || navigator.language || 'en').startsWith('zh') ? 'zh' : 'en';
131
+ const dict = currentLang === 'zh' ? zh : en;
132
+ const tt = (k, params) => {
133
+ let str = (typeof t === 'function' ? t(k) : null) || dict[k] || en[k] || k;
134
+ if (params && typeof params === 'object') {
135
+ for (const [pk, pv] of Object.entries(params)) {
136
+ str = str.replace(new RegExp('\\{' + pk + '\\}', 'g'), String(pv));
137
+ }
138
+ }
139
+ return str;
140
+ };
141
+
142
+ // Load settings
66
143
  React.useEffect(() => {
67
144
  if (!scope) { setStatus('unavailable'); return; }
68
145
  let cancelled = false;
@@ -77,7 +154,14 @@ window.__ModuleLoader__.load({
77
154
  const vals = snap && snap.values ? snap.values : snap;
78
155
  if (vals && typeof vals === 'object') {
79
156
  const names = Array.isArray(vals.progressToolNames) ? vals.progressToolNames : DEFAULTS.progressToolNames;
80
- setDraft((d) => ({ ...d, ...DEFAULTS, ...vals, progressToolNamesText: names.join(', ') }));
157
+ const strict = Array.isArray(vals.strictTools) ? vals.strictTools : DEFAULTS.strictTools;
158
+ setDraft((d) => ({
159
+ ...d,
160
+ ...DEFAULTS,
161
+ ...vals,
162
+ progressToolNamesText: names.join(', '),
163
+ strictToolsText: strict.join(', '),
164
+ }));
81
165
  }
82
166
  setStatus('ready');
83
167
  } catch (e) {
@@ -87,6 +171,46 @@ window.__ModuleLoader__.load({
87
171
  return () => { cancelled = true; };
88
172
  }, [scope]);
89
173
 
174
+ // Check updater and telemetry on expand
175
+ React.useEffect(() => {
176
+ if (!expanded) return;
177
+ let cancelled = false;
178
+
179
+ // Fetch update status
180
+ (async () => {
181
+ setUpdateState((s) => ({ ...s, checking: true, error: '', notice: '' }));
182
+ try {
183
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/update');
184
+ if (!res.ok) throw new Error('HTTP ' + res.status);
185
+ const data = await res.json();
186
+ if (cancelled) return;
187
+ setUpdateState((s) => ({
188
+ ...s,
189
+ checking: false,
190
+ currentVersion: data.currentVersion || '0.2.5',
191
+ latestVersion: data.latestVersion || '',
192
+ updateAvailable: !!data.updateAvailable,
193
+ }));
194
+ } catch (err) {
195
+ if (cancelled) return;
196
+ setUpdateState((s) => ({ ...s, checking: false, error: tt('checkUpdateFailed') }));
197
+ }
198
+ })();
199
+
200
+ // Fetch telemetry
201
+ (async () => {
202
+ try {
203
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry');
204
+ if (!res.ok) return;
205
+ const data = await res.json();
206
+ if (cancelled) return;
207
+ setTelemetry(data);
208
+ } catch {}
209
+ })();
210
+
211
+ return () => { cancelled = true; };
212
+ }, [expanded]);
213
+
90
214
  async function onSave() {
91
215
  if (!scope) { setMsg('Settings unavailable'); return; }
92
216
  setSaving(true); setMsg('');
@@ -94,12 +218,19 @@ window.__ModuleLoader__.load({
94
218
  .split(',')
95
219
  .map((s) => s.trim())
96
220
  .filter(Boolean);
221
+ const strictNames = String(draft.strictToolsText || '')
222
+ .split(',')
223
+ .map((s) => s.trim())
224
+ .filter(Boolean);
97
225
  const maxToolAttempts = Number(draft.maxToolAttemptsPerTurn);
98
226
  const payload = {
99
227
  maxToolAttemptsPerTurn: Number.isFinite(maxToolAttempts) && maxToolAttempts >= 0 ? maxToolAttempts : 64,
100
228
  maxProgressToolCallsPerTurn: Number(draft.maxProgressToolCallsPerTurn) || 16,
101
229
  maxCallsPerRepeatGroup: Number(draft.maxCallsPerRepeatGroup) || 5,
230
+ strictToolLimit: Number(draft.strictToolLimit) || 3,
231
+ strictTools: strictNames,
102
232
  blockExactDuplicates: !!draft.blockExactDuplicates,
233
+ dryRunMode: !!draft.dryRunMode,
103
234
  assistantOutputGuard: !!draft.assistantOutputGuard,
104
235
  maxRepeatedAssistantLines: Number(draft.maxRepeatedAssistantLines) || 5,
105
236
  maxRepeatedAssistantBlocks: Number(draft.maxRepeatedAssistantBlocks) || 5,
@@ -114,6 +245,42 @@ window.__ModuleLoader__.load({
114
245
  setMsg(errs.length ? errs.join('; ') : tt('saved'));
115
246
  }
116
247
 
248
+ async function onTriggerUpdate() {
249
+ if (updateState.updating) return;
250
+ setUpdateState((s) => ({ ...s, updating: true, error: '', notice: '' }));
251
+ try {
252
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/update', {
253
+ method: 'POST',
254
+ headers: { 'x-dsh-plugin-update': '1' },
255
+ });
256
+ const data = await res.json();
257
+ if (!res.ok || data.error) {
258
+ throw new Error(data.error || 'Update failed with HTTP ' + res.status);
259
+ }
260
+ setUpdateState((s) => ({
261
+ ...s,
262
+ updating: false,
263
+ updateAvailable: false,
264
+ currentVersion: data.updatedVersion || s.latestVersion,
265
+ notice: tt('updateSuccess', { v: data.updatedVersion || s.latestVersion }),
266
+ }));
267
+ } catch (err) {
268
+ setUpdateState((s) => ({
269
+ ...s,
270
+ updating: false,
271
+ error: tt('updateFailed', { msg: err.message || String(err) }),
272
+ }));
273
+ }
274
+ }
275
+
276
+ async function onResetTelemetry() {
277
+ try {
278
+ await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry', { method: 'POST' });
279
+ setTelemetry({ totalViolations: 0, byCode: {}, lastViolation: null });
280
+ setMsg(tt('statsResetDone'));
281
+ } catch {}
282
+ }
283
+
117
284
  const field = (key, input) => React.createElement('div', {
118
285
  className: 'alg-field',
119
286
  style: { display: 'flex', flexDirection: 'column', gap: 6, padding: '10px 0' }
@@ -121,12 +288,20 @@ window.__ModuleLoader__.load({
121
288
  React.createElement('label', { style: { fontSize: 13, color: 'var(--dsw-alias-label-secondary)' } }, tt(key)),
122
289
  input
123
290
  );
291
+
124
292
  const num = (key) => React.createElement('input', {
125
293
  type: 'number', value: draft[key],
126
294
  onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
127
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 }
128
296
  });
129
- const check = (key) => React.createElement('label', { style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 } },
297
+
298
+ const str = (key) => React.createElement('input', {
299
+ type: 'text', value: draft[key],
300
+ 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
+ });
303
+
304
+ const check = (key) => React.createElement('label', { style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--dsw-alias-label-primary)', cursor: 'pointer', padding: '6px 0' } },
130
305
  React.createElement('input', {
131
306
  type: 'checkbox', checked: !!draft[key],
132
307
  onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.checked }))
@@ -136,7 +311,7 @@ window.__ModuleLoader__.load({
136
311
 
137
312
  return React.createElement('li', {
138
313
  className: 'alg-card',
139
- style: { border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', borderRadius: 12, listStyle: 'none' }
314
+ style: { border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', borderRadius: 12, listStyle: 'none', marginBottom: 12 }
140
315
  },
141
316
  React.createElement('button', {
142
317
  onClick: () => setExpanded(!expanded),
@@ -144,63 +319,108 @@ window.__ModuleLoader__.load({
144
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' }
145
320
  },
146
321
  React.createElement('span', { style: { display: 'flex', flexDirection: 'column' } },
147
- React.createElement('span', { style: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600 } }, tt('title')),
322
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 } },
323
+ '🛑 ' + tt('title'),
324
+ React.createElement('span', { style: { fontSize: 11, fontWeight: 500, padding: '2px 6px', borderRadius: 6, background: 'rgba(59,130,246,0.15)', color: 'var(--dsw-alias-accent-primary, #3b82f6)' } }, 'v' + updateState.currentVersion)
325
+ ),
148
326
  React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, tt('sub'))
149
327
  ),
150
328
  React.createElement('span', { style: { marginLeft: 'auto', color: 'var(--dsw-alias-label-tertiary)' } }, expanded ? '▲' : '▼')
151
329
  ),
152
- expanded ? React.createElement('div', { style: { borderTop: '1px solid var(--dsw-alias-border-l2)', margin: '0 16px', paddingBottom: 8 } },
153
- status === 'loading' ? React.createElement('div', { style: { padding: 12 } }, 'Loading…') :
154
- status === 'unavailable' ? React.createElement('div', { style: { padding: 12 } }, 'Settings unavailable') :
155
- React.createElement(React.Fragment, null,
156
- field('maxToolAttemptsPerTurn', num('maxToolAttemptsPerTurn')),
157
- field('maxProgressToolCallsPerTurn', num('maxProgressToolCallsPerTurn')),
158
- field('maxCallsPerRepeatGroup', num('maxCallsPerRepeatGroup')),
159
- field('progressToolNames', React.createElement('input', {
160
- type: 'text', value: draft.progressToolNamesText || '',
161
- onChange: (e) => setDraft((d) => ({ ...d, progressToolNamesText: e.target.value })),
162
- 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 }
163
- })),
164
- React.createElement('div', { style: { padding: '8px 0' } }, check('blockExactDuplicates')),
165
- React.createElement('div', { style: { padding: '8px 0' } }, check('assistantOutputGuard')),
166
- field('maxRepeatedAssistantLines', num('maxRepeatedAssistantLines')),
167
- field('maxRepeatedAssistantBlocks', num('maxRepeatedAssistantBlocks')),
168
- field('maxAssistantBlockChars', num('maxAssistantBlockChars')),
169
- msg ? React.createElement('div', { style: { fontSize: 12, color: msg === tt('saved') ? 'var(--dsw-alias-label-secondary)' : '#d73a4a', padding: '4px 0' } }, msg) : null,
170
- React.createElement('div', { style: { display: 'flex', justifyContent: 'flex-end', padding: '12px 0 4px', borderTop: '1px solid var(--dsw-alias-border-l2)' } },
171
- React.createElement('button', {
172
- onClick: onSave, disabled: saving,
173
- style: { appearance: 'none', font: 'inherit', cursor: 'pointer', border: '1px solid transparent', borderRadius: 8, padding: '5px 14px', fontSize: 13, background: 'var(--dsw-alias-label-primary)', color: 'var(--dsw-alias-bg-layer-3)', opacity: saving ? 0.6 : 1 }
174
- }, saving ? tt('saving') : tt('ready'))
330
+ expanded && React.createElement('div', {
331
+ className: 'alg-body',
332
+ style: { padding: '0 16px 16px', borderTop: '1px solid var(--dsw-alias-border-l2)' }
333
+ },
334
+ // Section: One-Click Updater
335
+ React.createElement('div', {
336
+ style: { padding: '12px 14px', margin: '14px 0', background: 'rgba(255,255,255,0.03)', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }
337
+ },
338
+ 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),
340
+ 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: '#f59e0b', fontWeight: 600, fontSize: 12 } }, tt('updateAvailable', { v: updateState.latestVersion })),
342
+ !updateState.checking && !updateState.updateAvailable && !updateState.error && React.createElement('span', { style: { color: '#10b981', fontSize: 12 } }, '✓ ' + tt('upToDate')),
343
+ updateState.error && React.createElement('span', { style: { color: '#ef4444', fontSize: 12 } }, updateState.error)
344
+ ),
345
+ updateState.updateAvailable && React.createElement('button', {
346
+ onClick: onTriggerUpdate,
347
+ 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
+ }, updateState.updating ? tt('updating') : tt('updateNow'))
350
+ ),
351
+ updateState.notice && React.createElement('div', {
352
+ style: { padding: '8px 12px', marginBottom: 12, background: 'rgba(16,185,129,0.1)', color: '#10b981', borderRadius: 6, fontSize: 12, border: '1px solid rgba(16,185,129,0.2)' }
353
+ }, updateState.notice),
354
+
355
+ // Section: Protection Telemetry
356
+ React.createElement('div', {
357
+ style: { padding: '12px 14px', margin: '14px 0', background: 'rgba(255,255,255,0.02)', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)' }
358
+ },
359
+ 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)' } }, '📊 ' + tt('telemetryTitle')),
361
+ telemetry.totalViolations > 0 && React.createElement('button', {
362
+ 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
+ }, tt('resetStats'))
365
+ ),
366
+ React.createElement('div', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
367
+ telemetry.totalViolations > 0
368
+ ? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
369
+ React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: '#f59e0b' } }, telemetry.totalViolations)),
370
+ telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
371
+ tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
372
+ )
373
+ )
374
+ : React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
175
375
  )
376
+ ),
377
+
378
+ // Form fields
379
+ field('maxToolAttemptsPerTurn', num('maxToolAttemptsPerTurn')),
380
+ field('maxProgressToolCallsPerTurn', num('maxProgressToolCallsPerTurn')),
381
+ field('maxCallsPerRepeatGroup', num('maxCallsPerRepeatGroup')),
382
+ field('strictTools', str('strictToolsText')),
383
+ field('strictToolLimit', num('strictToolLimit')),
384
+ check('blockExactDuplicates'),
385
+ check('dryRunMode'),
386
+ check('assistantOutputGuard'),
387
+ field('maxRepeatedAssistantLines', num('maxRepeatedAssistantLines')),
388
+ field('maxRepeatedAssistantBlocks', num('maxRepeatedAssistantBlocks')),
389
+ field('maxAssistantBlockChars', num('maxAssistantBlockChars')),
390
+ field('progressToolNames', str('progressToolNamesText')),
391
+
392
+ // Save button and status
393
+ React.createElement('div', {
394
+ style: { display: 'flex', alignItems: 'center', gap: 12, paddingTop: 14, borderTop: '1px solid var(--dsw-alias-border-l2)', marginTop: 10 }
395
+ },
396
+ React.createElement('button', {
397
+ onClick: onSave,
398
+ 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
+ }, saving ? tt('saving') : tt('ready')),
401
+ msg && React.createElement('span', { style: { fontSize: 13, color: msg === tt('saved') || msg === tt('statsResetDone') ? '#10b981' : '#f87171' } }, msg)
176
402
  )
177
- ) : null
403
+ )
178
404
  );
179
405
  }
180
406
 
181
- module.exports.inject = ['slots', 'locale'];
182
- module.exports.apply = function apply(ctx) {
183
- try { ctx.locale.register(NS, { en, ru }); } catch (e) {}
184
- if (!ctx.slots) return;
185
- const register = () => {
186
- try {
187
- return ctx.slots.register({
188
- name: 'settings.plugin.item',
189
- key: NS,
190
- locale: NS,
191
- inject: () => ({ ctx }),
192
- }, PluginCard);
193
- } catch (e) {
194
- console.warn('[dsh-agent-loop-guard] settings.plugin.item register failed', e && e.message || e);
195
- }
196
- };
197
- if (typeof ctx.slots.inject === 'function') {
198
- try { ctx.slots.inject('settings.plugin.item', register); }
199
- catch (e) { try { register(); } catch (e2) {} }
200
- } else {
201
- register();
407
+ exports.inject = ['slots', 'settingsScope', 'locale'];
408
+ exports.apply = function apply(ctx) {
409
+ if (typeof ctx.locale?.register === 'function') {
410
+ try { ctx.locale.register(NS, { en, zh }); } catch {}
202
411
  }
412
+
413
+ ctx.slots.register(
414
+ {
415
+ name: 'settings.plugin.item',
416
+ id: NS,
417
+ order: 95,
418
+ locale: NS,
419
+ },
420
+ PluginCard
421
+ );
203
422
  };
423
+
204
424
  return module.exports;
205
425
  },
206
- });
426
+ });