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

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,17 @@ MIT © [GooDAnDReaDY](https://github.com/GooDAnDReaDY)
169
182
 
170
183
  ---
171
184
 
185
+ ## v0.2.5 更新日志
186
+
187
+ - **一键平滑更新**:集成宿主端更新器(`lib/plugin-updater.js`),提供 `/api/@goodandready/dsh-agent-loop-guard/update` 接口与设置界面更新状态/按钮 (#29)。
188
+ - **敏感工具严格配额**:新增 `strictTools` 与 `strictToolLimit` 配置,强化对高危/文件修改工具的重复调用限制 (#29)。
189
+ - **审计模式 (Dry-Run)**:新增 `dryRunMode` 配置,支持在不阻断智能体调用的前提下记录告警与度量数据 (#29)。
190
+ - **防护遥测与监控**:实时统计拦截指标(`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`),提供 `/api/@goodandready/dsh-agent-loop-guard/telemetry` 接口与一键重置 (#29)。
191
+ - **LLM 智能恢复引导**:在拦截消息中为 DeepSeek-R1 / V3 等模型提供结构化的破局指导与操作建议 (#29)。
192
+ - **严格多语言规范**:代码库仅保留标准英文(`en`)与中文(`zh`),俄语本地化转入 Issue #197 (`goodandready/dsh-russian-lang`) 处理 (#29)。
193
+ - **设计契约**:按照 `project-design-contract` 标准建立 `docs/design/DESIGN.md` (#29)。
194
+ - **扩展自动化测试**:总测试用例扩充至 37 个,涵盖更新器语义版本、请求安全性、严格工具配额与审计模式 (#29)。
195
+
172
196
  ## v0.2.4 更新日志
173
197
 
174
198
  - **设置界面**:修复 `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
@@ -8,34 +8,71 @@ window.__ModuleLoader__.load({
8
8
  const en = {
9
9
  title: 'Agent Loop Guard',
10
10
  sub: 'Fail-closed tool-call and assistant-output loop limits',
11
- maxToolAttemptsPerTurn: 'Max tool attempts per turn',
11
+ version: 'Version',
12
+ updateChecking: 'Checking updates…',
13
+ updateAvailable: 'Update available: v{v}',
14
+ upToDate: 'Up to date',
15
+ updateNow: 'Update Now',
16
+ updating: 'Updating…',
17
+ updateSuccess: 'Updated to v{v}. Restart DSH service to apply changes.',
18
+ updateFailed: 'Update failed: {msg}',
19
+ checkUpdateFailed: 'Check failed',
20
+ telemetryTitle: 'Protection Telemetry',
21
+ totalBlocked: 'Loops Prevented',
22
+ lastViolation: 'Last Incident',
23
+ noViolations: 'No loop violations detected in current runtime.',
24
+ resetStats: 'Reset Stats',
25
+ statsResetDone: 'Stats reset',
26
+ maxToolAttemptsPerTurn: 'Max tool attempts per turn (0 = disabled)',
12
27
  maxProgressToolCallsPerTurn: 'Max progress tool calls per turn',
13
28
  maxCallsPerRepeatGroup: 'Max calls per repeat group',
29
+ strictTools: 'Strict tools (comma-separated, lower limit)',
30
+ strictToolLimit: 'Strict tools limit',
14
31
  blockExactDuplicates: 'Block exact duplicate tool calls',
32
+ dryRunMode: 'Dry-run / Audit mode (log only, do not reject)',
15
33
  assistantOutputGuard: 'Assistant output guard',
16
34
  maxRepeatedAssistantLines: 'Max repeated assistant lines',
17
35
  maxRepeatedAssistantBlocks: 'Max repeated assistant blocks',
18
36
  maxAssistantBlockChars: 'Max assistant block chars',
19
37
  progressToolNames: 'Progress tool names (comma-separated)',
20
38
  saving: 'Saving…',
21
- ready: 'Save',
39
+ ready: 'Save Settings',
22
40
  saved: 'Saved',
23
41
  };
24
- const ru = {
42
+
43
+ const zh = {
25
44
  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: 'Сохранено',
45
+ sub: '工具调用与助手输出防死循环熔断限制',
46
+ version: '版本',
47
+ updateChecking: '正在检查更新…',
48
+ updateAvailable: '发现新版本: v{v}',
49
+ upToDate: '已是最新版本',
50
+ updateNow: '立即更新',
51
+ updating: '正在更新…',
52
+ updateSuccess: '已更新至 v{v}。请重启 DSH 服务以生效变更。',
53
+ updateFailed: '更新失败: {msg}',
54
+ checkUpdateFailed: '检查更新失败',
55
+ telemetryTitle: '防护运行遥测',
56
+ totalBlocked: '已拦截死循环',
57
+ lastViolation: '最近拦截事件',
58
+ noViolations: '当前运行时未检测到死循环违规。',
59
+ resetStats: '重置统计',
60
+ statsResetDone: '统计已重置',
61
+ maxToolAttemptsPerTurn: '单回合最大工具尝试次数(0 表示禁用)',
62
+ maxProgressToolCallsPerTurn: '单回合最大进度工具调用次数',
63
+ maxCallsPerRepeatGroup: '同组工具最大重复调用次数',
64
+ strictTools: '严格限制工具(逗号分隔,触发更低阈值)',
65
+ strictToolLimit: '严格工具调用上限',
66
+ blockExactDuplicates: '立即拦截完全相同的重复工具调用',
67
+ dryRunMode: '审计模拟模式(仅记录日志,不实际拦截)',
68
+ assistantOutputGuard: '助手文本输出防循环守卫',
69
+ maxRepeatedAssistantLines: '最大单行重复次数',
70
+ maxRepeatedAssistantBlocks: '最大段落重复次数',
71
+ maxAssistantBlockChars: '最大段落判定字符数',
72
+ progressToolNames: '进度标记工具(逗号分隔)',
73
+ saving: '正在保存…',
74
+ ready: '保存配置',
75
+ saved: '配置已保存',
39
76
  };
40
77
 
41
78
  const DEFAULTS = {
@@ -43,7 +80,10 @@ window.__ModuleLoader__.load({
43
80
  maxProgressToolCallsPerTurn: 16,
44
81
  progressToolNames: ['todo_write'],
45
82
  maxCallsPerRepeatGroup: 5,
83
+ strictTools: [],
84
+ strictToolLimit: 3,
46
85
  blockExactDuplicates: true,
86
+ dryRunMode: false,
47
87
  assistantOutputGuard: true,
48
88
  maxRepeatedAssistantLines: 5,
49
89
  maxRepeatedAssistantBlocks: 5,
@@ -52,17 +92,52 @@ window.__ModuleLoader__.load({
52
92
 
53
93
  function PluginCard({ ctx: _ctx, t }) {
54
94
  const [expanded, setExpanded] = React.useState(false);
55
- const [draft, setDraft] = React.useState({ ...DEFAULTS, progressToolNamesText: 'todo_write' });
95
+ const [draft, setDraft] = React.useState({
96
+ ...DEFAULTS,
97
+ progressToolNamesText: 'todo_write',
98
+ strictToolsText: '',
99
+ });
56
100
  const [status, setStatus] = React.useState('loading');
57
101
  const [saving, setSaving] = React.useState(false);
58
102
  const [msg, setMsg] = React.useState('');
103
+
104
+ // Updater state
105
+ const [updateState, setUpdateState] = React.useState({
106
+ checking: false,
107
+ updateAvailable: false,
108
+ currentVersion: '0.2.5',
109
+ latestVersion: '',
110
+ updating: false,
111
+ notice: '',
112
+ error: '',
113
+ });
114
+
115
+ // Telemetry state
116
+ const [telemetry, setTelemetry] = React.useState({
117
+ totalViolations: 0,
118
+ byCode: {},
119
+ lastViolation: null,
120
+ });
121
+
59
122
  const scopeRef = React.useRef(null);
60
123
  if (!scopeRef.current && _ctx && _ctx.settingsScope) {
61
124
  try { scopeRef.current = _ctx.settingsScope.bind({ namespace: NS }); } catch (e) { scopeRef.current = null; }
62
125
  }
63
126
  const scope = scopeRef.current;
64
- const tt = t || ((k) => en[k] || k);
65
127
 
128
+ const currentLang = (_ctx?.locale?.get?.() || navigator.language || 'en').startsWith('zh') ? 'zh' : 'en';
129
+ const dict = currentLang === 'zh' ? zh : en;
130
+ const tt = (k, params) => {
131
+ let str = (typeof t === 'function' ? t(k) : null) || dict[k] || en[k] || k;
132
+ if (params && typeof params === 'object') {
133
+ for (const [pk, pv] of Object.entries(params)) {
134
+ str = str.replace(new RegExp('\\{' + pk + '\\}', 'g'), String(pv));
135
+ }
136
+ }
137
+ return str;
138
+ };
139
+
140
+ // Load settings
66
141
  React.useEffect(() => {
67
142
  if (!scope) { setStatus('unavailable'); return; }
68
143
  let cancelled = false;
@@ -77,7 +152,14 @@ window.__ModuleLoader__.load({
77
152
  const vals = snap && snap.values ? snap.values : snap;
78
153
  if (vals && typeof vals === 'object') {
79
154
  const names = Array.isArray(vals.progressToolNames) ? vals.progressToolNames : DEFAULTS.progressToolNames;
80
- setDraft((d) => ({ ...d, ...DEFAULTS, ...vals, progressToolNamesText: names.join(', ') }));
155
+ const strict = Array.isArray(vals.strictTools) ? vals.strictTools : DEFAULTS.strictTools;
156
+ setDraft((d) => ({
157
+ ...d,
158
+ ...DEFAULTS,
159
+ ...vals,
160
+ progressToolNamesText: names.join(', '),
161
+ strictToolsText: strict.join(', '),
162
+ }));
81
163
  }
82
164
  setStatus('ready');
83
165
  } catch (e) {
@@ -87,6 +169,46 @@ window.__ModuleLoader__.load({
87
169
  return () => { cancelled = true; };
88
170
  }, [scope]);
89
171
 
172
+ // Check updater and telemetry on expand
173
+ React.useEffect(() => {
174
+ if (!expanded) return;
175
+ let cancelled = false;
176
+
177
+ // Fetch update status
178
+ (async () => {
179
+ setUpdateState((s) => ({ ...s, checking: true, error: '', notice: '' }));
180
+ try {
181
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/update');
182
+ if (!res.ok) throw new Error('HTTP ' + res.status);
183
+ const data = await res.json();
184
+ if (cancelled) return;
185
+ setUpdateState((s) => ({
186
+ ...s,
187
+ checking: false,
188
+ currentVersion: data.currentVersion || '0.2.5',
189
+ latestVersion: data.latestVersion || '',
190
+ updateAvailable: !!data.updateAvailable,
191
+ }));
192
+ } catch (err) {
193
+ if (cancelled) return;
194
+ setUpdateState((s) => ({ ...s, checking: false, error: tt('checkUpdateFailed') }));
195
+ }
196
+ })();
197
+
198
+ // Fetch telemetry
199
+ (async () => {
200
+ try {
201
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry');
202
+ if (!res.ok) return;
203
+ const data = await res.json();
204
+ if (cancelled) return;
205
+ setTelemetry(data);
206
+ } catch {}
207
+ })();
208
+
209
+ return () => { cancelled = true; };
210
+ }, [expanded]);
211
+
90
212
  async function onSave() {
91
213
  if (!scope) { setMsg('Settings unavailable'); return; }
92
214
  setSaving(true); setMsg('');
@@ -94,12 +216,19 @@ window.__ModuleLoader__.load({
94
216
  .split(',')
95
217
  .map((s) => s.trim())
96
218
  .filter(Boolean);
219
+ const strictNames = String(draft.strictToolsText || '')
220
+ .split(',')
221
+ .map((s) => s.trim())
222
+ .filter(Boolean);
97
223
  const maxToolAttempts = Number(draft.maxToolAttemptsPerTurn);
98
224
  const payload = {
99
225
  maxToolAttemptsPerTurn: Number.isFinite(maxToolAttempts) && maxToolAttempts >= 0 ? maxToolAttempts : 64,
100
226
  maxProgressToolCallsPerTurn: Number(draft.maxProgressToolCallsPerTurn) || 16,
101
227
  maxCallsPerRepeatGroup: Number(draft.maxCallsPerRepeatGroup) || 5,
228
+ strictToolLimit: Number(draft.strictToolLimit) || 3,
229
+ strictTools: strictNames,
102
230
  blockExactDuplicates: !!draft.blockExactDuplicates,
231
+ dryRunMode: !!draft.dryRunMode,
103
232
  assistantOutputGuard: !!draft.assistantOutputGuard,
104
233
  maxRepeatedAssistantLines: Number(draft.maxRepeatedAssistantLines) || 5,
105
234
  maxRepeatedAssistantBlocks: Number(draft.maxRepeatedAssistantBlocks) || 5,
@@ -114,6 +243,42 @@ window.__ModuleLoader__.load({
114
243
  setMsg(errs.length ? errs.join('; ') : tt('saved'));
115
244
  }
116
245
 
246
+ async function onTriggerUpdate() {
247
+ if (updateState.updating) return;
248
+ setUpdateState((s) => ({ ...s, updating: true, error: '', notice: '' }));
249
+ try {
250
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/update', {
251
+ method: 'POST',
252
+ headers: { 'x-dsh-plugin-update': '1' },
253
+ });
254
+ const data = await res.json();
255
+ if (!res.ok || data.error) {
256
+ throw new Error(data.error || 'Update failed with HTTP ' + res.status);
257
+ }
258
+ setUpdateState((s) => ({
259
+ ...s,
260
+ updating: false,
261
+ updateAvailable: false,
262
+ currentVersion: data.updatedVersion || s.latestVersion,
263
+ notice: tt('updateSuccess', { v: data.updatedVersion || s.latestVersion }),
264
+ }));
265
+ } catch (err) {
266
+ setUpdateState((s) => ({
267
+ ...s,
268
+ updating: false,
269
+ error: tt('updateFailed', { msg: err.message || String(err) }),
270
+ }));
271
+ }
272
+ }
273
+
274
+ async function onResetTelemetry() {
275
+ try {
276
+ await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry', { method: 'POST' });
277
+ setTelemetry({ totalViolations: 0, byCode: {}, lastViolation: null });
278
+ setMsg(tt('statsResetDone'));
279
+ } catch {}
280
+ }
281
+
117
282
  const field = (key, input) => React.createElement('div', {
118
283
  className: 'alg-field',
119
284
  style: { display: 'flex', flexDirection: 'column', gap: 6, padding: '10px 0' }
@@ -121,12 +286,20 @@ window.__ModuleLoader__.load({
121
286
  React.createElement('label', { style: { fontSize: 13, color: 'var(--dsw-alias-label-secondary)' } }, tt(key)),
122
287
  input
123
288
  );
289
+
124
290
  const num = (key) => React.createElement('input', {
125
291
  type: 'number', value: draft[key],
126
292
  onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
127
293
  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
294
  });
129
- const check = (key) => React.createElement('label', { style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 } },
295
+
296
+ const str = (key) => React.createElement('input', {
297
+ type: 'text', value: draft[key],
298
+ onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
299
+ 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 }
300
+ });
301
+
302
+ 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
303
  React.createElement('input', {
131
304
  type: 'checkbox', checked: !!draft[key],
132
305
  onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.checked }))
@@ -136,7 +309,7 @@ window.__ModuleLoader__.load({
136
309
 
137
310
  return React.createElement('li', {
138
311
  className: 'alg-card',
139
- style: { border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', borderRadius: 12, listStyle: 'none' }
312
+ style: { border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', borderRadius: 12, listStyle: 'none', marginBottom: 12 }
140
313
  },
141
314
  React.createElement('button', {
142
315
  onClick: () => setExpanded(!expanded),
@@ -144,63 +317,108 @@ window.__ModuleLoader__.load({
144
317
  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
318
  },
146
319
  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')),
320
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 } },
321
+ '🛑 ' + tt('title'),
322
+ 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)
323
+ ),
148
324
  React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, tt('sub'))
149
325
  ),
150
326
  React.createElement('span', { style: { marginLeft: 'auto', color: 'var(--dsw-alias-label-tertiary)' } }, expanded ? '▲' : '▼')
151
327
  ),
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'))
328
+ expanded && React.createElement('div', {
329
+ className: 'alg-body',
330
+ style: { padding: '0 16px 16px', borderTop: '1px solid var(--dsw-alias-border-l2)' }
331
+ },
332
+ // Section: One-Click Updater
333
+ React.createElement('div', {
334
+ 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 }
335
+ },
336
+ React.createElement('div', { style: { fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 } },
337
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)' } }, tt('version') + ': ' + updateState.currentVersion),
338
+ updateState.checking && React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12 } }, tt('updateChecking')),
339
+ !updateState.checking && updateState.updateAvailable && React.createElement('span', { style: { color: '#f59e0b', fontWeight: 600, fontSize: 12 } }, tt('updateAvailable', { v: updateState.latestVersion })),
340
+ !updateState.checking && !updateState.updateAvailable && !updateState.error && React.createElement('span', { style: { color: '#10b981', fontSize: 12 } }, '✓ ' + tt('upToDate')),
341
+ updateState.error && React.createElement('span', { style: { color: '#ef4444', fontSize: 12 } }, updateState.error)
342
+ ),
343
+ updateState.updateAvailable && React.createElement('button', {
344
+ onClick: onTriggerUpdate,
345
+ disabled: updateState.updating,
346
+ 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' }
347
+ }, updateState.updating ? tt('updating') : tt('updateNow'))
348
+ ),
349
+ updateState.notice && React.createElement('div', {
350
+ 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)' }
351
+ }, updateState.notice),
352
+
353
+ // Section: Protection Telemetry
354
+ React.createElement('div', {
355
+ style: { padding: '12px 14px', margin: '14px 0', background: 'rgba(255,255,255,0.02)', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)' }
356
+ },
357
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
358
+ React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, '📊 ' + tt('telemetryTitle')),
359
+ telemetry.totalViolations > 0 && React.createElement('button', {
360
+ onClick: onResetTelemetry,
361
+ 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' }
362
+ }, tt('resetStats'))
363
+ ),
364
+ React.createElement('div', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
365
+ telemetry.totalViolations > 0
366
+ ? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
367
+ React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: '#f59e0b' } }, telemetry.totalViolations)),
368
+ telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
369
+ tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
370
+ )
371
+ )
372
+ : React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
175
373
  )
374
+ ),
375
+
376
+ // Form fields
377
+ field('maxToolAttemptsPerTurn', num('maxToolAttemptsPerTurn')),
378
+ field('maxProgressToolCallsPerTurn', num('maxProgressToolCallsPerTurn')),
379
+ field('maxCallsPerRepeatGroup', num('maxCallsPerRepeatGroup')),
380
+ field('strictTools', str('strictToolsText')),
381
+ field('strictToolLimit', num('strictToolLimit')),
382
+ check('blockExactDuplicates'),
383
+ check('dryRunMode'),
384
+ check('assistantOutputGuard'),
385
+ field('maxRepeatedAssistantLines', num('maxRepeatedAssistantLines')),
386
+ field('maxRepeatedAssistantBlocks', num('maxRepeatedAssistantBlocks')),
387
+ field('maxAssistantBlockChars', num('maxAssistantBlockChars')),
388
+ field('progressToolNames', str('progressToolNamesText')),
389
+
390
+ // Save button and status
391
+ React.createElement('div', {
392
+ style: { display: 'flex', alignItems: 'center', gap: 12, paddingTop: 14, borderTop: '1px solid var(--dsw-alias-border-l2)', marginTop: 10 }
393
+ },
394
+ React.createElement('button', {
395
+ onClick: onSave,
396
+ disabled: saving || status !== 'ready',
397
+ 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' }
398
+ }, saving ? tt('saving') : tt('ready')),
399
+ msg && React.createElement('span', { style: { fontSize: 13, color: msg === tt('saved') || msg === tt('statsResetDone') ? '#10b981' : '#f87171' } }, msg)
176
400
  )
177
- ) : null
401
+ )
178
402
  );
179
403
  }
180
404
 
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();
405
+ exports.inject = ['slots', 'settingsScope', 'locale'];
406
+ exports.apply = function apply(ctx) {
407
+ if (typeof ctx.locale?.register === 'function') {
408
+ try { ctx.locale.register(NS, { en, zh }); } catch {}
202
409
  }
410
+
411
+ ctx.slots.register(
412
+ {
413
+ name: 'settings.plugin.item',
414
+ id: NS,
415
+ order: 95,
416
+ locale: NS,
417
+ },
418
+ PluginCard
419
+ );
203
420
  };
421
+
204
422
  return module.exports;
205
423
  },
206
- });
424
+ });