@goodandready/dsh-agent-loop-guard 0.3.3 → 0.3.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/CHANGELOG.md +17 -0
- package/README.md +15 -2
- package/README.ru.md +16 -3
- package/README.zh.md +14 -1
- package/lib/client.js +48 -61
- package/lib/guard-state.js +8 -4
- package/lib/plugin-updater.js +22 -5
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.3.5] - 2026-11-18
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
- **Idempotent Denial Reason Across Blocked Calls (GH-4)**: Fixed self-referential prefix nesting where subsequent blocked tool calls in `answerOnly` mode prepended `LOOP_GUARD_DUPLICATE: ` on each iteration, causing linear string accumulation (22 bytes per call). `state.stopReason` now stores the un-prefixed root reason on the first violation, ensuring bounded O(1) denial text and compact incident telemetry.
|
|
7
|
+
|
|
8
|
+
## [0.3.4] - 2026-11-17
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **Windows Packaging & Portability (#153)**: Cross-platform npm invocation in `scripts/pack-release.mjs` supporting Windows `npm.cmd` with shell execution, and dynamic home directory resolution via `os.homedir()` across test suites.
|
|
12
|
+
- **Native Localization Standards (#154)**: Standardized `{ en, zh, ru }` client localization dictionaries registered in `ctx.locale.register(NS, { en, zh, ru })`, and localized summary text dynamically in `PluginItem`.
|
|
13
|
+
- **Bundle Parity Gate (#161)**: Added automated test `test/bundle-parity.test.js` validating that `lib/client.js` is byte-for-byte identical to the concatenated `src/client/*.js` fragments and strictly under the 600 line limit.
|
|
14
|
+
- **Documentation Parity Gate (#160)**: Synchronized all 28 `Config` schema settings across `README.md`, `README.ru.md`, and `README.zh.md`, enforced by automated test `test/docs-consistency.test.js`.
|
|
15
|
+
|
|
16
|
+
### Fixed
|
|
17
|
+
- **LAN Updater Authorization (#157)**: Fixed HTTP 403 when updating plugin over private LAN networks. Trusted LAN clients verified by DSH core connection service (`isPrivateLan` / `isLoopback`) are authorized to initiate updates.
|
|
18
|
+
- **Telemetry Precision & Incident Journal (#163)**: Isolated payload truncations (`LOOP_GUARD_PAYLOAD_TRUNCATED`) into dedicated `totalTruncations` metric so output truncation does not inflate "Loops Prevented" (`totalViolations`). Expanded incident journal display to show up to 12 recent incidents with timestamps, and added `role="status"` / `aria-live="polite"` accessibility semantics.
|
|
19
|
+
|
|
3
20
|
## [0.3.3] - 2026-11-16
|
|
4
21
|
|
|
5
22
|
### Added
|
package/README.md
CHANGED
|
@@ -106,7 +106,7 @@ When a loop is detected, the guard rejects the call with structured diagnostics
|
|
|
106
106
|
|
|
107
107
|
| Guard Code | Trigger Condition | Default Limit | Guard Action |
|
|
108
108
|
|:---|:---|:---|:---|
|
|
109
|
-
| `LOOP_GUARD_STOP` | User sent stop command (`stop`, `halt`, `cancel`, `стоп`, `остановись`,
|
|
109
|
+
| `LOOP_GUARD_STOP` | User sent stop command (`stop`, `halt`, `cancel`, `стоп`, `остановись`, `прекрати`) | Immediate | Rejects tool call; requires immediate text reply |
|
|
110
110
|
| `LOOP_GUARD_DUPLICATE` | Identical call arguments with identical result to previous attempt | 1 retry | Blocks exact repeat; demands alternative approach |
|
|
111
111
|
| `LOOP_GUARD_REPEAT` | Repeated calls within current group without state change | `maxCallsPerRepeatGroup` (5) | Prevents spinning on single tool |
|
|
112
112
|
| `LOOP_GUARD_LIMIT` | Total non-productive tool attempts since last successful progress | `maxToolAttemptsPerTurn` (64) | Caps turn exploratory budget |
|
|
@@ -133,7 +133,7 @@ All loop guard warning logs automatically redact sensitive credentials:
|
|
|
133
133
|
|
|
134
134
|
### 5. Native WebUI Settings, Telemetry & One-Click Updater
|
|
135
135
|
|
|
136
|
-
* **Integrated Settings Card**: Placed directly inside DSH Web UI under *Settings ➔ Plugins ➔ Plugin Settings* (`
|
|
136
|
+
* **Integrated Settings Card**: Placed directly inside DSH Web UI under *Settings ➔ Plugins ➔ Plugin Settings* (`plugins.item` / `plugins.row.config`).
|
|
137
137
|
* **Native DSH Design System**: Styled exclusively using standard DSH design variables (`--dsw-alias-*`), accessible `<label>`/`<input>` associations (`htmlFor`/`id`), and smooth chevron rotation without external UI dependencies.
|
|
138
138
|
* **Live Protection Telemetry**: Real-time counters of blocked loops (`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`) with instant statistics reset via `/api/@goodandready/dsh-agent-loop-guard/telemetry`.
|
|
139
139
|
* **One-Click In-Place Updater**: Seamless version verification against the npm registry and one-click upgrades via authenticated loopback API (`/api/@goodandready/dsh-agent-loop-guard/update`).
|
|
@@ -190,6 +190,19 @@ dsh-agent-loop-guard:
|
|
|
190
190
|
| `maxAssistantBlockChars` | `number` | `16384` | Maximum byte length captured for block fingerprinting. |
|
|
191
191
|
| `pseudoToolCallThreshold` | `number` | `3` | Consecutive completed turns with pseudo tool calls and 0 real tools before cancellation (0 = disabled). |
|
|
192
192
|
| `pseudoToolCallPatterns` | `array` | `[]` | Custom regex or string patterns for pseudo tool-call detection. |
|
|
193
|
+
| `stopPatterns` | `array` | `[]` | Custom regex or string patterns for user stop commands. |
|
|
194
|
+
| `oscillationDetection` | `boolean` | `true` | Enable detection of alternating ping-pong cycles across tools (e.g. A ➔ B ➔ A ➔ B). |
|
|
195
|
+
| `maxOscillationRepeats` | `number` | `3` | Maximum cycles of 2-4 step oscillations permitted before loop block. |
|
|
196
|
+
| `payloadBloatGuard` | `boolean` | `true` | Enable truncation and payload guard for oversized tool responses. |
|
|
197
|
+
| `maxToolResultChars` | `number` | `65536` | Maximum allowed character length for tool results before truncating (0 = disabled). |
|
|
198
|
+
| `errorThrashingGuard` | `boolean` | `true` | Enable fail-loop detection and fast-abort on repeated tool errors. |
|
|
199
|
+
| `maxConsecutiveFailures` | `number` | `4` | Maximum consecutive tool errors before error thrashing block is enforced. |
|
|
200
|
+
| `adaptiveSteering` | `boolean` | `true` | Enable smart steering to guide agents toward recovery before hard turn termination. |
|
|
201
|
+
| `targetQuotaGuard` | `boolean` | `true` | Enable target-level per-file and per-resource quota protection. |
|
|
202
|
+
| `maxUnchangedReadsPerTarget` | `number` | `3` | Maximum repeated reads of an unchanged file/resource target before refusal. |
|
|
203
|
+
| `maxReadsPerTarget` | `number` | `6` | Maximum total read operations allowed on a single target per turn. |
|
|
204
|
+
| `maxEditsPerTarget` | `number` | `8` | Maximum edit or write operations allowed on a single target per turn. |
|
|
205
|
+
| `maxTargetAttempts` | `number` | `12` | Maximum total tool operations allowed across all actions for a single target per turn. |
|
|
193
206
|
|
|
194
207
|
---
|
|
195
208
|
|
package/README.ru.md
CHANGED
|
@@ -60,7 +60,7 @@ graph TD
|
|
|
60
60
|
subgraph DSH ["Среда выполнения DeepSeek Harness"]
|
|
61
61
|
Turn["Ход выполнения агента<br/>(Рассуждение LLM и вызовы инструментов)"]
|
|
62
62
|
Stream["Поток генерации ассистента<br/>(text-delta и block-end)"]
|
|
63
|
-
UserStop["Анализ сообщений пользователя<br/>(Стоп-слова: стоп, хватит,
|
|
63
|
+
UserStop["Анализ сообщений пользователя<br/>(Стоп-слова: стоп, хватит, прекрати)"]
|
|
64
64
|
end
|
|
65
65
|
|
|
66
66
|
subgraph LoopGuard ["@goodandready/dsh-agent-loop-guard"]
|
|
@@ -104,7 +104,7 @@ graph TD
|
|
|
104
104
|
|
|
105
105
|
| Код защиты | Условие срабатывания | Лимит по умолчанию | Действие плагина |
|
|
106
106
|
|:---|:---|:---|:---|
|
|
107
|
-
| `LOOP_GUARD_STOP` | Пользователь отправил команду остановки (`стоп`, `хватит`, `прекрати`,
|
|
107
|
+
| `LOOP_GUARD_STOP` | Пользователь отправил команду остановки (`стоп`, `хватит`, `прекрати`, `stop`, `halt`, `cancel`) | Мгновенно | Блокирует вызовы инструментов; требует немедленный текстовый ответ |
|
|
108
108
|
| `LOOP_GUARD_DUPLICATE` | Повторный вызов с идентичными аргументами и неизменным результатом | 1 повтор | Пресекает топтание на месте; требует сменить подход |
|
|
109
109
|
| `LOOP_GUARD_REPEAT` | Череда вызовов инструментов одной группы без изменения состояния | `maxCallsPerRepeatGroup` (5) | Останавливает монотонные повторы |
|
|
110
110
|
| `LOOP_GUARD_LIMIT` | Суммарное число бесплодных попыток за текущий ход | `maxToolAttemptsPerTurn` (64) | Ограничивает общий бюджет холостых действий |
|
|
@@ -131,7 +131,7 @@ graph TD
|
|
|
131
131
|
|
|
132
132
|
### 5. Веб-интерфейс, живая телеметрия и обновление в один клик
|
|
133
133
|
|
|
134
|
-
* **Интегрированная карточка настроек**: нативно встроена во вкладку *«Настройки → Плагины → Настройки плагинов»* (`
|
|
134
|
+
* **Интегрированная карточка настроек**: нативно встроена во вкладку *«Настройки → Плагины → Настройки плагинов»* (`plugins.item` / `plugins.row.config`).
|
|
135
135
|
* **Дизайн-система DSH**: построена строго на системных переменных DSH (`--dsw-alias-*`), доступных связках `<label>`/`<input>` (`htmlFor`/`id`) и нативном шевроне с плавной анимацией без тяжёлых сторонних UI-библиотек.
|
|
136
136
|
* **Телеметрия инцидентов**: живые счётчики заблокированных петель (`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`) с возможностью мгновенного сброса через защищённый маршрут `/api/@goodandready/dsh-agent-loop-guard/telemetry`.
|
|
137
137
|
* **One-Click Updater**: проверка актуальных версий в реестре npm и обновление плагина в один клик через защищённый loopback API (`/api/@goodandready/dsh-agent-loop-guard/update`).
|
|
@@ -188,6 +188,19 @@ dsh-agent-loop-guard:
|
|
|
188
188
|
| `maxAssistantBlockChars` | `number` | `16384` | Максимальный размер текстового блока для хэширования (в байтах). |
|
|
189
189
|
| `pseudoToolCallThreshold` | `number` | `3` | Порог непрерывных ходов с псевдовызовами без реальных инструментов для отмены сессии (0 = отключено). |
|
|
190
190
|
| `pseudoToolCallPatterns` | `array` | `[]` | Пользовательские регулярные выражения или строки для обнаружения псевдовызовов. |
|
|
191
|
+
| `stopPatterns` | `array` | `[]` | Пользовательские регулярные выражения или строки для команд остановки пользователя. |
|
|
192
|
+
| `oscillationDetection` | `boolean` | `true` | Обнаружение осциллирующих циклов инструментов (пинг-понг вроде A ➔ B ➔ A ➔ B). |
|
|
193
|
+
| `maxOscillationRepeats` | `number` | `3` | Максимум повторов цикла осцилляции (длиной 2-4 шага) перед блокировкой. |
|
|
194
|
+
| `payloadBloatGuard` | `boolean` | `true` | Обрезка и защита от раздувания результатов вызова инструментов. |
|
|
195
|
+
| `maxToolResultChars` | `number` | `65536` | Максимум символов в результате инструмента перед безопасным усечением (0 = выкл). |
|
|
196
|
+
| `errorThrashingGuard` | `boolean` | `true` | Защита от серий повторяющихся ошибок инструментов (fail-loop detection). |
|
|
197
|
+
| `maxConsecutiveFailures` | `number` | `4` | Порог непрерывных ошибок инструментов до принудительной остановки. |
|
|
198
|
+
| `adaptiveSteering` | `boolean` | `true` | Умное наставление модели перед жестким прерыванием хода. |
|
|
199
|
+
| `targetQuotaGuard` | `boolean` | `true` | Квоты обращений к файлам и ресурсам (защита от зацикливания на одной цели). |
|
|
200
|
+
| `maxUnchangedReadsPerTarget` | `number` | `3` | Максимум повторных чтений неизмененного файла/ресурса перед блокировкой. |
|
|
201
|
+
| `maxReadsPerTarget` | `number` | `6` | Максимум операций чтения одного целевого файла за ход. |
|
|
202
|
+
| `maxEditsPerTarget` | `number` | `8` | Максимум операций изменения/записи одного целевого файла за ход. |
|
|
203
|
+
| `maxTargetAttempts` | `number` | `12` | Суммарный лимит любых операций над целевым файлом за ход. |
|
|
191
204
|
|
|
192
205
|
---
|
|
193
206
|
|
package/README.zh.md
CHANGED
|
@@ -129,7 +129,7 @@ graph TD
|
|
|
129
129
|
|
|
130
130
|
### 5. 原生 WebUI 设置卡片、实时防护遥测与一键平滑更新
|
|
131
131
|
|
|
132
|
-
* **原生设置面板集成**:直接内嵌于 DSH Web 控制台「设置 ➔ 插件 ➔ 插件设置」卡片列表中(`
|
|
132
|
+
* **原生设置面板集成**:直接内嵌于 DSH Web 控制台「设置 ➔ 插件 ➔ 插件设置」卡片列表中(`plugins.item` / `plugins.row.config`)。
|
|
133
133
|
* **对齐 DSH 设计规范**:完全基于 DSH 标准设计令牌变量(`--dsw-alias-*`)与无障碍标签绑定(`htmlFor`/`id`),搭配轻量级平滑展开 Chevron 图标,零外部重型 UI 库依赖。
|
|
134
134
|
* **实时防护遥测看板**:在设置卡片中直观呈现当前运行时拦截的死循环总数(`LOOP_GUARD_DUPLICATE`, `LOOP_GUARD_REPEAT`, `LOOP_GUARD_LIMIT`, `LOOP_GUARD_OUTPUT`),支持通过 `/api/@goodandready/dsh-agent-loop-guard/telemetry` 安全端点一键重置计数。
|
|
135
135
|
* **一键无缝在线更新**:卡片自动联动 npm 官方源检查最新版本,支持通过经过鉴权的本地环回 API(`/api/@goodandready/dsh-agent-loop-guard/update`)在后台安全完成版本升级。
|
|
@@ -186,6 +186,19 @@ dsh-agent-loop-guard:
|
|
|
186
186
|
| `maxAssistantBlockChars` | `number` | `16384` | 捕获用于段落指纹比对的最大字符数。 |
|
|
187
187
|
| `pseudoToolCallThreshold` | `number` | `3` | 伪工具调用空转拦截阈值(连续回合数,0 表示禁用)。 |
|
|
188
188
|
| `pseudoToolCallPatterns` | `array` | `[]` | 自定义伪工具调用文本检测正则表达式或关键词列表。 |
|
|
189
|
+
| `stopPatterns` | `array` | `[]` | 自定义用户停止指令检测正则表达式或关键词列表。 |
|
|
190
|
+
| `oscillationDetection` | `boolean` | `true` | 是否启用多工具交替循环检测(如 A ➔ B ➔ A ➔ B 乒乓震荡)。 |
|
|
191
|
+
| `maxOscillationRepeats` | `number` | `3` | 触发交替循环拦截的最大重复次数(2-4 步序列)。 |
|
|
192
|
+
| `payloadBloatGuard` | `boolean` | `true` | 超大结果防膨胀保护(自动截断过大输出)。 |
|
|
193
|
+
| `maxToolResultChars` | `number` | `65536` | 工具结果字符上限(超过此长度安全截断头部与尾部,0 表示禁用)。 |
|
|
194
|
+
| `errorThrashingGuard` | `boolean` | `true` | 工具连续报错熔断拦截保护(防止报错死循环)。 |
|
|
195
|
+
| `maxConsecutiveFailures` | `number` | `4` | 触发连续报错熔断的最大失败次数。 |
|
|
196
|
+
| `adaptiveSteering` | `boolean` | `true` | 是否启用智能引导纠正(在硬性中断前给予纠正提示)。 |
|
|
197
|
+
| `targetQuotaGuard` | `boolean` | `true` | 是否启用目标配额守卫(单文件/目标防死循环)。 |
|
|
198
|
+
| `maxUnchangedReadsPerTarget` | `number` | `3` | 单文件内容无变化时的最大允许重复读取次数。 |
|
|
199
|
+
| `maxReadsPerTarget` | `number` | `6` | 单回合针对单个文件的最大读取操作次数。 |
|
|
200
|
+
| `maxEditsPerTarget` | `number` | `8` | 单回合针对单个文件的最大修改/写入操作次数。 |
|
|
201
|
+
| `maxTargetAttempts` | `number` | `12` | 单回合针对单个文件的总操作次数上限。 |
|
|
189
202
|
|
|
190
203
|
---
|
|
191
204
|
|
package/lib/client.js
CHANGED
|
@@ -62,7 +62,7 @@ window.__ModuleLoader__.load({
|
|
|
62
62
|
updateChecking: 'Checking updates…', updateAvailable: 'Update available: v{v}', upToDate: 'Up to date',
|
|
63
63
|
updateNow: 'Update Now', updateViaPluginsPage: 'Update in Plugins page', updating: 'Updating…',
|
|
64
64
|
updateSuccess: 'Updated to v{v}. Restart DSH service to apply changes.', updateFailed: 'Update failed: {msg}', checkUpdateFailed: 'Check failed',
|
|
65
|
-
telemetryTitle: 'Protection Telemetry', telemetryLoadFailed: 'Failed to load telemetry', totalBlocked: 'Loops Prevented',
|
|
65
|
+
telemetryTitle: 'Protection Telemetry', telemetryLoadFailed: 'Failed to load telemetry', totalBlocked: 'Loops Prevented', totalTruncations: 'Truncations',
|
|
66
66
|
steeredCount: 'Smart Steers', lastViolation: 'Last Incident', noViolations: 'No loop violations detected in current runtime.',
|
|
67
67
|
resetStats: 'Reset Stats', statsResetDone: 'Stats reset', statsResetFailed: 'Failed to reset stats',
|
|
68
68
|
presetsTitle: 'Presets', presetStrict: 'Strict', presetBalanced: 'Balanced', presetAutonomous: 'Autonomous Coding',
|
|
@@ -88,7 +88,7 @@ window.__ModuleLoader__.load({
|
|
|
88
88
|
updateChecking: 'Проверка обновлений…', updateAvailable: 'Доступно обновление: v{v}', upToDate: 'Установлена актуальная версия',
|
|
89
89
|
updateNow: 'Обновить сейчас', updateViaPluginsPage: 'Обновите на вкладке плагинов', updating: 'Обновление…',
|
|
90
90
|
updateSuccess: 'Обновлено до v{v}. Перезапустите службу DSH для применения.', updateFailed: 'Ошибка обновления: {msg}', checkUpdateFailed: 'Не удалось проверить',
|
|
91
|
-
telemetryTitle: 'Телеметрия защиты', telemetryLoadFailed: 'Не удалось загрузить телеметрию', totalBlocked: 'Предотвращено циклов',
|
|
91
|
+
telemetryTitle: 'Телеметрия защиты', telemetryLoadFailed: 'Не удалось загрузить телеметрию', totalBlocked: 'Предотвращено циклов', totalTruncations: 'Усечений',
|
|
92
92
|
steeredCount: 'Упреждающих подсказок', lastViolation: 'Последний инцидент', noViolations: 'В текущем сеансе циклов не зафиксировано.',
|
|
93
93
|
resetStats: 'Сбросить статистику', statsResetDone: 'Статистика сброшена', statsResetFailed: 'Не удалось сбросить статистику',
|
|
94
94
|
presetsTitle: 'Профили', presetStrict: 'Строгий', presetBalanced: 'Баланс', presetAutonomous: 'Автономный код',
|
|
@@ -114,7 +114,7 @@ window.__ModuleLoader__.load({
|
|
|
114
114
|
updateChecking: '正在检查更新…', updateAvailable: '发现新版本: v{v}', upToDate: '已是最新版本',
|
|
115
115
|
updateNow: '立即更新', updateViaPluginsPage: '请在插件页面更新', updating: '正在更新…',
|
|
116
116
|
updateSuccess: '已更新至 v{v}。请重启 DSH 服务以生效变更。', updateFailed: '更新失败: {msg}', checkUpdateFailed: '检查更新失败',
|
|
117
|
-
telemetryTitle: '防护运行遥测', telemetryLoadFailed: '获取遥测数据失败', totalBlocked: '已拦截死循环',
|
|
117
|
+
telemetryTitle: '防护运行遥测', telemetryLoadFailed: '获取遥测数据失败', totalBlocked: '已拦截死循环', totalTruncations: '截断次数',
|
|
118
118
|
steeredCount: '自纠正引导次数', lastViolation: '最近拦截事件', noViolations: '当前运行时未检测到死循环违规。',
|
|
119
119
|
resetStats: '重置统计', statsResetDone: '统计已重置', statsResetFailed: '重置统计失败',
|
|
120
120
|
presetsTitle: '灵敏度预设', presetStrict: '严格', presetBalanced: '平衡', presetAutonomous: '自主编程',
|
|
@@ -169,40 +169,58 @@ window.__ModuleLoader__.load({
|
|
|
169
169
|
},
|
|
170
170
|
};
|
|
171
171
|
function IncidentTelemetryPanel({ telemetry, tt, onCopyDump, onResetTelemetry }) {
|
|
172
|
+
const truncCount = telemetry.totalTruncations || (telemetry.byCode && telemetry.byCode.LOOP_GUARD_PAYLOAD_TRUNCATED) || 0;
|
|
173
|
+
const hasActivity = Boolean(telemetry.totalViolations > 0 || telemetry.steeredCount > 0 || truncCount > 0);
|
|
172
174
|
return React.createElement('div', {
|
|
173
175
|
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)' }
|
|
174
176
|
},
|
|
175
177
|
React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
|
|
176
178
|
React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, tt('telemetryTitle')),
|
|
177
179
|
React.createElement('div', { style: { display: 'flex', gap: 6 } },
|
|
178
|
-
telemetry.totalViolations > 0 && React.createElement('button', { className: 'alg-btn-ghost', onClick: onCopyDump }, tt('copyDump')),
|
|
179
|
-
(
|
|
180
|
+
(telemetry.totalViolations > 0 || truncCount > 0) && React.createElement('button', { className: 'alg-btn-ghost', onClick: onCopyDump }, tt('copyDump')),
|
|
181
|
+
(hasActivity || (telemetry.incidents && telemetry.incidents.length > 0)) && React.createElement('button', { className: 'alg-btn-ghost', onClick: onResetTelemetry }, tt('resetStats'))
|
|
180
182
|
)
|
|
181
183
|
),
|
|
182
184
|
React.createElement('div', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
|
|
183
185
|
telemetry.error
|
|
184
|
-
? React.createElement('span', { style: { color: 'var(--dsw-alias-state-error-primary)' } }, telemetry.error)
|
|
185
|
-
:
|
|
186
|
+
? React.createElement('span', { role: 'alert', 'aria-live': 'assertive', style: { color: 'var(--dsw-alias-state-error-primary)' } }, telemetry.error)
|
|
187
|
+
: hasActivity
|
|
186
188
|
? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 6 } },
|
|
187
|
-
React.createElement('div', { style: { display: 'flex', gap: 16 } },
|
|
188
|
-
React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-state-warn-primary)' } }, telemetry.totalViolations)),
|
|
189
|
-
React.createElement('div', null, tt('steeredCount') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-brand-primary)' } }, telemetry.steeredCount || 0))
|
|
189
|
+
React.createElement('div', { style: { display: 'flex', gap: 16, flexWrap: 'wrap' } },
|
|
190
|
+
React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-state-warn-primary)' } }, telemetry.totalViolations || 0)),
|
|
191
|
+
React.createElement('div', null, tt('steeredCount') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-brand-primary)' } }, telemetry.steeredCount || 0)),
|
|
192
|
+
React.createElement('div', null, tt('totalTruncations') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-label-secondary)' } }, truncCount))
|
|
190
193
|
),
|
|
191
194
|
telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
|
|
192
195
|
tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
|
|
193
196
|
),
|
|
194
197
|
telemetry.incidents && telemetry.incidents.length > 0 && React.createElement('div', { style: { marginTop: 6, borderTop: '1px solid var(--dsw-alias-border-l2)', paddingTop: 6 } },
|
|
195
198
|
React.createElement('div', { style: { fontWeight: 500, marginBottom: 4 } }, tt('incidentsTitle')),
|
|
196
|
-
telemetry.incidents.slice(0,
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
199
|
+
telemetry.incidents.slice(0, 12).map((inc, i) => {
|
|
200
|
+
const timeStr = inc.timestamp ? new Date(inc.timestamp).toLocaleTimeString() : '';
|
|
201
|
+
const isSteer = inc.code === 'LOOP_GUARD_STEER';
|
|
202
|
+
const isTrunc = inc.code === 'LOOP_GUARD_PAYLOAD_TRUNCATED';
|
|
203
|
+
const color = isSteer ? 'var(--dsw-alias-brand-primary)' : (isTrunc ? 'var(--dsw-alias-label-secondary)' : 'var(--dsw-alias-state-error-primary)');
|
|
204
|
+
return React.createElement('div', { key: inc.id || i, className: 'alg-incident-row' },
|
|
205
|
+
timeStr ? React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)', minWidth: 54, fontSize: 10 } }, timeStr) : null,
|
|
206
|
+
React.createElement('span', { style: { fontWeight: 500, color } }, inc.code),
|
|
207
|
+
React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)', marginLeft: 'auto' } }, inc.tool)
|
|
208
|
+
);
|
|
209
|
+
})
|
|
200
210
|
)
|
|
201
211
|
)
|
|
202
212
|
: React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
|
|
203
213
|
)
|
|
204
214
|
);
|
|
205
215
|
}
|
|
216
|
+
function resolveLocaleDict(ctx) {
|
|
217
|
+
const snap = typeof ctx?.locale?.getLocale === 'function' ? ctx.locale.getLocale()
|
|
218
|
+
: (typeof ctx?.locale?.getSnapshot === 'function' ? ctx.locale.getSnapshot() : null);
|
|
219
|
+
const loc = typeof snap === 'string' ? snap : (snap?.active || snap?.locale || snap?.id);
|
|
220
|
+
const locStr = String(loc || (typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en')).toLowerCase();
|
|
221
|
+
return locStr.startsWith('zh') ? zh : (locStr.startsWith('ru') ? ru : en);
|
|
222
|
+
}
|
|
223
|
+
|
|
206
224
|
function PluginCard({ ctx: _ctx, t, bare, ...props }) {
|
|
207
225
|
const isBare = Boolean(bare || props?.view === 'page');
|
|
208
226
|
const [expanded, setExpanded] = React.useState(false);
|
|
@@ -230,15 +248,7 @@ window.__ModuleLoader__.load({
|
|
|
230
248
|
if (typeof _ctx?.locale?.subscribe === 'function') return _ctx.locale.subscribe(() => setLocaleTick((c) => c + 1));
|
|
231
249
|
}, []);
|
|
232
250
|
|
|
233
|
-
const
|
|
234
|
-
const snap = typeof _ctx?.locale?.getLocale === 'function' ? _ctx.locale.getLocale()
|
|
235
|
-
: (typeof _ctx?.locale?.getSnapshot === 'function' ? _ctx.locale.getSnapshot() : null);
|
|
236
|
-
const loc = typeof snap === 'string' ? snap : (snap?.active || snap?.locale || snap?.id);
|
|
237
|
-
return loc || (typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en');
|
|
238
|
-
};
|
|
239
|
-
const locStr = String(getActiveLocale()).toLowerCase();
|
|
240
|
-
const currentLang = locStr.startsWith('zh') ? 'zh' : (locStr.startsWith('ru') ? 'ru' : 'en');
|
|
241
|
-
const dict = currentLang === 'zh' ? zh : (currentLang === 'ru' ? ru : en);
|
|
251
|
+
const dict = resolveLocaleDict(_ctx);
|
|
242
252
|
const tt = (k, params) => {
|
|
243
253
|
let str = (typeof t === 'function' ? t(k) : null) || dict[k] || en[k] || k;
|
|
244
254
|
if (params && typeof params === 'object') {
|
|
@@ -460,7 +470,7 @@ window.__ModuleLoader__.load({
|
|
|
460
470
|
}
|
|
461
471
|
}, updateState.checking ? tt('updateChecking') : (updateState.updateAvailable ? tt('updateAvailable', { v: updateState.latestVersion }) : (updateState.currentVersion ? tt('upToDate') : '—')))
|
|
462
472
|
),
|
|
463
|
-
updateState.error && React.createElement('span', { style: { color: 'var(--dsw-alias-state-error-primary)', fontSize: 12 } }, updateState.error)
|
|
473
|
+
updateState.error && React.createElement('span', { role: 'alert', 'aria-live': 'assertive', style: { color: 'var(--dsw-alias-state-error-primary)', fontSize: 12 } }, updateState.error)
|
|
464
474
|
),
|
|
465
475
|
updateState.updateAvailable && (
|
|
466
476
|
(updateState.isDesktop || !updateState.canAutoUpdate)
|
|
@@ -468,7 +478,7 @@ window.__ModuleLoader__.load({
|
|
|
468
478
|
: React.createElement('button', { className: 'alg-btn-updater', onClick: onTriggerUpdate, disabled: updateState.updating }, updateState.updating ? tt('updating') : tt('updateNow'))
|
|
469
479
|
)
|
|
470
480
|
),
|
|
471
|
-
updateState.notice && React.createElement('div', {
|
|
481
|
+
updateState.notice && React.createElement('div', { role: 'status', 'aria-live': 'polite',
|
|
472
482
|
style: { padding: '8px 12px', marginBottom: 12, background: 'color-mix(in srgb, var(--dsw-alias-state-success-primary) 10%, transparent)', color: 'var(--dsw-alias-state-success-primary)', borderRadius: 6, fontSize: 12, border: '1px solid color-mix(in srgb, var(--dsw-alias-state-success-primary) 20%, transparent)' }
|
|
473
483
|
}, updateState.notice),
|
|
474
484
|
|
|
@@ -513,7 +523,7 @@ window.__ModuleLoader__.load({
|
|
|
513
523
|
React.createElement('button', {
|
|
514
524
|
className: 'alg-btn-primary', onClick: onSave, disabled: saving || status !== 'ready',
|
|
515
525
|
}, saving ? tt('saving') : tt('ready')),
|
|
516
|
-
msg && React.createElement('span', { style: { fontSize: 13, color: msg.includes(';') ? 'var(--dsw-alias-state-error-primary)' : 'var(--dsw-alias-state-success-primary)' } }, msg)
|
|
526
|
+
msg && React.createElement('span', { role: 'status', 'aria-live': 'polite', style: { fontSize: 13, color: msg.includes(';') ? 'var(--dsw-alias-state-error-primary)' : 'var(--dsw-alias-state-success-primary)' } }, msg)
|
|
517
527
|
)
|
|
518
528
|
);
|
|
519
529
|
|
|
@@ -523,18 +533,17 @@ window.__ModuleLoader__.load({
|
|
|
523
533
|
|
|
524
534
|
function PluginItem(props) {
|
|
525
535
|
if (props && props.view === 'summary') {
|
|
526
|
-
|
|
536
|
+
const d = resolveLocaleDict(props.ctx);
|
|
537
|
+
return React.createElement('div', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, d.sub || en.sub);
|
|
527
538
|
}
|
|
528
539
|
return React.createElement(PluginCard, { ...props, bare: Boolean(props && (props.bare || props.view === 'page')) });
|
|
529
540
|
}
|
|
530
541
|
exports.inject = ['slots', 'configForms', 'locale'];
|
|
531
542
|
exports.apply = function apply(ctx) {
|
|
532
543
|
if (typeof ctx.locale?.register === 'function') {
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
ctx.locale.register(NS, { en, zh });
|
|
537
|
-
}
|
|
544
|
+
const reg = () => ctx.locale.register(NS, { en, zh, ru });
|
|
545
|
+
if (typeof ctx.effect === 'function') ctx.effect(reg, 'dsh-agent-loop-guard: locale');
|
|
546
|
+
else reg();
|
|
538
547
|
}
|
|
539
548
|
|
|
540
549
|
function registerSlotWhenReady(slotName, registerFn) {
|
|
@@ -542,53 +551,31 @@ window.__ModuleLoader__.load({
|
|
|
542
551
|
if (typeof ctx.slots.inject === 'function') {
|
|
543
552
|
try {
|
|
544
553
|
ctx.slots.inject(slotName, () => {
|
|
545
|
-
try {
|
|
546
|
-
|
|
547
|
-
} catch (err) {
|
|
548
|
-
console.warn('[' + NS + '] Error registering slot ' + slotName + ':', err);
|
|
549
|
-
}
|
|
554
|
+
try { return registerFn(); }
|
|
555
|
+
catch (err) { console.warn('[' + NS + '] Error registering slot ' + slotName + ':', err); }
|
|
550
556
|
});
|
|
551
557
|
return;
|
|
552
|
-
} catch (err) {
|
|
553
|
-
console.warn('[' + NS + '] Failed to inject slot ' + slotName + ':', err);
|
|
554
|
-
}
|
|
558
|
+
} catch (err) { console.warn('[' + NS + '] Failed to inject slot ' + slotName + ':', err); }
|
|
555
559
|
}
|
|
556
560
|
if (typeof ctx.slots.register === 'function') {
|
|
557
|
-
try {
|
|
558
|
-
|
|
559
|
-
} catch (err) {
|
|
560
|
-
console.warn('[' + NS + '] Failed direct registration for ' + slotName + ':', err);
|
|
561
|
-
}
|
|
561
|
+
try { registerFn(); }
|
|
562
|
+
catch (err) { console.warn('[' + NS + '] Failed direct registration for ' + slotName + ':', err); }
|
|
562
563
|
}
|
|
563
564
|
}
|
|
564
565
|
|
|
565
566
|
registerSlotWhenReady('plugins.row.config', () =>
|
|
566
567
|
ctx.slots.register(
|
|
567
|
-
{
|
|
568
|
-
name: 'plugins.row.config',
|
|
569
|
-
key: ROW_CONFIG_KEY,
|
|
570
|
-
order: 10,
|
|
571
|
-
locale: NS,
|
|
572
|
-
inject: () => ({ ctx }),
|
|
573
|
-
},
|
|
568
|
+
{ name: 'plugins.row.config', key: ROW_CONFIG_KEY, order: 10, locale: NS, inject: () => ({ ctx }) },
|
|
574
569
|
(props) => React.createElement(PluginItem, { ...props, ctx: (props && props.ctx) || ctx })
|
|
575
570
|
)
|
|
576
571
|
);
|
|
577
572
|
|
|
578
573
|
registerSlotWhenReady('plugins.item', () =>
|
|
579
574
|
ctx.slots.register(
|
|
580
|
-
{
|
|
581
|
-
name: 'plugins.item',
|
|
582
|
-
id: ROW_ID,
|
|
583
|
-
order: 10,
|
|
584
|
-
label: () => 'Agent Loop Guard',
|
|
585
|
-
locale: NS,
|
|
586
|
-
inject: () => ({ ctx }),
|
|
587
|
-
},
|
|
575
|
+
{ name: 'plugins.item', id: ROW_ID, order: 10, label: () => 'Agent Loop Guard', locale: NS, inject: () => ({ ctx }) },
|
|
588
576
|
(props) => React.createElement(PluginCard, { ...props, ctx: (props && props.ctx) || ctx })
|
|
589
577
|
)
|
|
590
578
|
);
|
|
591
|
-
|
|
592
579
|
};
|
|
593
580
|
return module.exports;
|
|
594
581
|
},
|
package/lib/guard-state.js
CHANGED
|
@@ -33,8 +33,6 @@ import {
|
|
|
33
33
|
export * from './guard-helpers.js';
|
|
34
34
|
export * from './target-quota-guard.js';
|
|
35
35
|
|
|
36
|
-
|
|
37
|
-
|
|
38
36
|
function cleanStringList(list, fallback = []) {
|
|
39
37
|
return Array.isArray(list) ? list.filter((n) => typeof n === 'string' && n.trim() !== '').map((n) => n.trim()) : fallback;
|
|
40
38
|
}
|
|
@@ -80,6 +78,7 @@ export class LoopGuardState {
|
|
|
80
78
|
|
|
81
79
|
this.metrics = {
|
|
82
80
|
totalViolations: 0,
|
|
81
|
+
totalTruncations: 0,
|
|
83
82
|
steeredCount: 0,
|
|
84
83
|
byCode: {
|
|
85
84
|
LOOP_GUARD_STOP: 0, LOOP_GUARD_DUPLICATE: 0, LOOP_GUARD_REPEAT: 0,
|
|
@@ -160,7 +159,11 @@ export class LoopGuardState {
|
|
|
160
159
|
}
|
|
161
160
|
|
|
162
161
|
recordExternalViolation(code, detail, extra = {}) {
|
|
163
|
-
|
|
162
|
+
if (code === 'LOOP_GUARD_PAYLOAD_TRUNCATED') {
|
|
163
|
+
this.metrics.totalTruncations = (this.metrics.totalTruncations || 0) + 1;
|
|
164
|
+
} else {
|
|
165
|
+
this.metrics.totalViolations += 1;
|
|
166
|
+
}
|
|
164
167
|
this.metrics.byCode[code] = (this.metrics.byCode[code] || 0) + 1;
|
|
165
168
|
this.metrics.lastViolation = {
|
|
166
169
|
code,
|
|
@@ -183,6 +186,7 @@ export class LoopGuardState {
|
|
|
183
186
|
|
|
184
187
|
resetTelemetry() {
|
|
185
188
|
this.metrics.totalViolations = 0;
|
|
189
|
+
this.metrics.totalTruncations = 0;
|
|
186
190
|
this.metrics.steeredCount = 0;
|
|
187
191
|
for (const k of Object.keys(this.metrics.byCode)) {
|
|
188
192
|
this.metrics.byCode[k] = 0;
|
|
@@ -389,7 +393,7 @@ export class LoopGuardState {
|
|
|
389
393
|
}
|
|
390
394
|
|
|
391
395
|
state.answerOnly = true;
|
|
392
|
-
state.stopReason =
|
|
396
|
+
if (!state.stopReason) state.stopReason = detail;
|
|
393
397
|
if (!state.blockReason) {
|
|
394
398
|
state.blockReason = code;
|
|
395
399
|
}
|
package/lib/plugin-updater.js
CHANGED
|
@@ -88,6 +88,7 @@ export function isTrustedTelemetryRequest(request, targetCtx = null) {
|
|
|
88
88
|
export function isTrustedUpdateRequest(request, targetCtx = null) {
|
|
89
89
|
if (header(request, UPDATE_HEADER) !== '1') return false;
|
|
90
90
|
const conn = getConnection(targetCtx);
|
|
91
|
+
const remoteAddress = request?.socket?.remoteAddress;
|
|
91
92
|
if (conn && typeof conn.requestRejection === 'function') {
|
|
92
93
|
let rejection;
|
|
93
94
|
try {
|
|
@@ -96,8 +97,10 @@ export function isTrustedUpdateRequest(request, targetCtx = null) {
|
|
|
96
97
|
return false;
|
|
97
98
|
}
|
|
98
99
|
if (rejection !== undefined) return false;
|
|
100
|
+
if (!isLoopback(remoteAddress) && !isPrivateLan(remoteAddress)) return false;
|
|
101
|
+
} else {
|
|
102
|
+
if (!isLoopback(remoteAddress)) return false;
|
|
99
103
|
}
|
|
100
|
-
if (!isLoopback(request?.socket?.remoteAddress)) return false;
|
|
101
104
|
const site = header(request, 'sec-fetch-site');
|
|
102
105
|
if (site !== undefined && site !== 'same-origin') return false;
|
|
103
106
|
const origin = header(request, 'origin');
|
|
@@ -313,7 +316,7 @@ export async function currentVersion(manifestUrl) {
|
|
|
313
316
|
}
|
|
314
317
|
}
|
|
315
318
|
|
|
316
|
-
export async function status(options, target) {
|
|
319
|
+
export async function status(options, target, request = null, targetCtx = null) {
|
|
317
320
|
let current = 'unknown';
|
|
318
321
|
try {
|
|
319
322
|
current = await currentVersion(options.manifestUrl);
|
|
@@ -323,7 +326,21 @@ export async function status(options, target) {
|
|
|
323
326
|
const latest = await latestVersion(options.packageName, options.registry ?? 'https://registry.npmjs.org');
|
|
324
327
|
const validCurrent = current !== 'unknown';
|
|
325
328
|
const isDesktop = Boolean(target.isDesktop);
|
|
326
|
-
|
|
329
|
+
let canAutoUpdate = Boolean(target.cliEntry !== undefined && (!isDesktop || target.desktopCli !== undefined));
|
|
330
|
+
if (canAutoUpdate && request) {
|
|
331
|
+
const conn = getConnection(targetCtx);
|
|
332
|
+
const remote = request?.socket?.remoteAddress;
|
|
333
|
+
if (conn && typeof conn.requestRejection === 'function') {
|
|
334
|
+
try {
|
|
335
|
+
if (conn.requestRejection(request) !== undefined) canAutoUpdate = false;
|
|
336
|
+
if (!isLoopback(remote) && !isPrivateLan(remote)) canAutoUpdate = false;
|
|
337
|
+
} catch {
|
|
338
|
+
canAutoUpdate = false;
|
|
339
|
+
}
|
|
340
|
+
} else if (!isLoopback(remote)) {
|
|
341
|
+
canAutoUpdate = false;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
327
344
|
return {
|
|
328
345
|
packageName: options.packageName,
|
|
329
346
|
currentVersion: current,
|
|
@@ -399,7 +416,7 @@ export function registerPluginUpdater(ctx, options) {
|
|
|
399
416
|
try {
|
|
400
417
|
const target = runtime();
|
|
401
418
|
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
402
|
-
const payload = await status(options, target);
|
|
419
|
+
const payload = await status(options, target, request, ctx);
|
|
403
420
|
response.writeHead(200, {
|
|
404
421
|
'content-type': 'application/json; charset=utf-8',
|
|
405
422
|
'cache-control': 'no-store',
|
|
@@ -422,7 +439,7 @@ export function registerPluginUpdater(ctx, options) {
|
|
|
422
439
|
}
|
|
423
440
|
installing = true;
|
|
424
441
|
try {
|
|
425
|
-
const before = await status(options, target);
|
|
442
|
+
const before = await status(options, target, request, ctx);
|
|
426
443
|
if (before.latestVersion === undefined) {
|
|
427
444
|
json(response, 503, { error: 'The latest version is temporarily unavailable.' });
|
|
428
445
|
return;
|