@goodandready/dsh-agent-loop-guard 0.2.28 → 0.3.0

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/lib/client.js CHANGED
@@ -19,509 +19,468 @@ window.__ModuleLoader__.load({
19
19
  } catch (err) {
20
20
  console.warn?.('[dsh-agent-loop-guard] primitives unavailable, using SVG fallback:', err?.message || String(err));
21
21
  }
22
- const CSS_STYLES = `
23
- .alg-page { width: 100%; min-width: 0; }
24
- .alg-card {
25
- border: 1px solid var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-3);
26
- border-radius: 12px; list-style: none; margin-bottom: 12px; overflow: hidden;
27
- transition: border-color 0.15s ease;
28
- }
29
- .alg-card:hover { border-color: var(--dsw-alias-border-l1, var(--dsw-alias-border-l2)); }
30
- .alg-header-btn {
31
- appearance: none; width: 100%; font: inherit; color: inherit; text-align: left;
32
- cursor: pointer; background: transparent; border: 0; border-radius: 12px;
33
- display: flex; align-items: center; gap: 12px; padding: 14px 16px;
34
- transition: background 0.15s ease;
35
- }
36
- .alg-header-btn:hover { background: var(--dsw-alias-interactive-bg-hover); }
37
- .alg-chevron {
38
- margin-left: auto; color: var(--dsw-alias-label-tertiary);
39
- display: flex; align-items: center; justify-content: center;
40
- transition: transform 0.2s ease;
41
- }
42
- .alg-chevron.expanded { transform: rotate(180deg); }
43
- .alg-body { padding: 0 16px 16px; border-top: 1px solid var(--dsw-alias-border-l2); }
44
- .alg-field { display: flex; flex-direction: column; gap: 6px; padding: 10px 0; }
45
- .alg-field label { font-size: 13px; color: var(--dsw-alias-label-secondary); cursor: pointer; }
46
- .alg-input {
47
- height: 34px; border: 1px solid var(--dsw-alias-border-l2);
48
- background: var(--dsw-alias-bg-layer-3); color: var(--dsw-alias-label-primary);
49
- border-radius: 8px; padding: 0 12px; font-size: 13px; outline: none;
50
- transition: border-color 0.15s ease;
51
- }
52
- .alg-input:focus { border-color: var(--dsw-alias-brand-primary); }
53
- .alg-checkbox-label {
54
- display: flex; align-items: center; gap: 8px; font-size: 13px;
55
- color: var(--dsw-alias-label-primary); cursor: pointer; padding: 6px 0;
56
- }
57
- .alg-btn-primary {
58
- appearance: none; font: inherit; cursor: pointer; border: 0; border-radius: 8px;
59
- padding: 6px 16px; font-size: 13px; font-weight: 500;
60
- background: var(--dsw-alias-brand-primary); color: var(--dsw-alias-label-primary-inverted, var(--dsw-alias-bg-layer-3));
61
- transition: opacity 0.15s ease;
62
- }
63
- .alg-btn-primary:hover:not(:disabled) { opacity: 0.9; }
64
- .alg-btn-primary:disabled { opacity: 0.5; cursor: default; }
65
- .alg-btn-updater {
66
- appearance: none; font: inherit; cursor: pointer; border: 0; border-radius: 6px;
67
- padding: 4px 10px; font-size: 12px; font-weight: 500;
68
- background: var(--dsw-alias-brand-primary); color: var(--dsw-alias-label-primary-inverted, var(--dsw-alias-bg-layer-3));
69
- transition: opacity 0.15s ease;
70
- }
71
- .alg-btn-updater:hover:not(:disabled) { opacity: 0.9; }
72
- .alg-btn-updater:disabled { opacity: 0.6; cursor: default; }
73
- .alg-btn-ghost {
74
- background: transparent; border: 1px solid var(--dsw-alias-border-l2);
75
- color: var(--dsw-alias-label-tertiary); border-radius: 4px; padding: 2px 8px;
76
- font-size: 11px; cursor: pointer; transition: color 0.15s ease, border-color 0.15s ease;
77
- }
78
- .alg-btn-ghost:hover {
79
- color: var(--dsw-alias-label-primary);
80
- border-color: var(--dsw-alias-label-secondary);
81
- }
82
- `;
83
-
84
- if (typeof document !== 'undefined') {
85
- const styleId = 'dsh-agent-loop-guard-styles';
86
- if (!document.getElementById(styleId)) {
87
- const style = document.createElement('style');
88
- style.id = styleId;
89
- style.setAttribute('data-dsh-plugin', '@goodandready/dsh-agent-loop-guard');
90
- style.textContent = CSS_STYLES;
91
- document.head.appendChild(style);
92
- }
93
- }
94
- const en = {
95
- title: 'Agent Loop Guard',
96
- sub: 'Fail-closed tool-call and assistant-output loop limits',
97
- version: 'Version',
98
- updateChecking: 'Checking updates…',
99
- updateAvailable: 'Update available: v{v}',
100
- upToDate: 'Up to date',
101
- updateNow: 'Update Now',
102
- updateViaPluginsPage: 'Update in Plugins page',
103
- updating: 'Updating…',
104
- updateSuccess: 'Updated to v{v}. Restart DSH service to apply changes.',
105
- updateFailed: 'Update failed: {msg}',
106
- checkUpdateFailed: 'Check failed',
107
- telemetryTitle: 'Protection Telemetry',
108
- telemetryLoadFailed: 'Failed to load telemetry',
109
- totalBlocked: 'Loops Prevented',
110
- lastViolation: 'Last Incident',
111
- noViolations: 'No loop violations detected in current runtime.',
112
- resetStats: 'Reset Stats',
113
- statsResetDone: 'Stats reset',
114
- statsResetFailed: 'Failed to reset stats',
115
- maxToolAttemptsPerTurn: 'Max tool attempts per turn (0 = disabled)',
116
- maxProgressToolCallsPerTurn: 'Max progress tool calls per turn',
117
- maxCallsPerRepeatGroup: 'Max calls per repeat group',
118
- strictTools: 'Strict tools (comma-separated, lower limit)',
119
- strictToolLimit: 'Strict tools limit',
120
- blockExactDuplicates: 'Block exact duplicate tool calls',
121
- dryRunMode: 'Dry-run / Audit mode (log only, do not reject)',
122
- assistantOutputGuard: 'Assistant output guard',
123
- maxRepeatedAssistantLines: 'Max repeated assistant lines',
124
- maxRepeatedAssistantBlocks: 'Max repeated assistant blocks',
125
- maxAssistantBlockChars: 'Max assistant block chars',
126
- progressToolNames: 'Progress tool names (comma-separated)',
127
- pseudoToolCallThreshold: 'Pseudo tool-call loop threshold (turns, 0 = disabled)',
128
- oscillationDetection: 'Oscillation loop guard (ping-pong cycles)',
129
- maxOscillationRepeats: 'Max oscillation repeats (2-4 step cycles)',
130
- payloadBloatGuard: 'Payload bloat guard (truncate huge outputs)',
131
- maxToolResultChars: 'Max tool result characters (0 = disabled)',
132
- saving: 'Saving…',
133
- ready: 'Save Settings',
134
- saved: 'Saved',
135
- };
136
-
137
- const zh = {
138
- title: 'Agent Loop Guard',
139
- sub: '工具调用与助手输出防死循环熔断限制',
140
- version: '版本',
141
- updateChecking: '正在检查更新…',
142
- updateAvailable: '发现新版本: v{v}',
143
- upToDate: '已是最新版本',
144
- updateNow: '立即更新',
145
- updateViaPluginsPage: '请在插件页面更新',
146
- updating: '正在更新…',
147
- updateSuccess: '已更新至 v{v}。请重启 DSH 服务以生效变更。',
148
- updateFailed: '更新失败: {msg}',
149
- checkUpdateFailed: '检查更新失败',
150
- telemetryTitle: '防护运行遥测',
151
- telemetryLoadFailed: '获取遥测数据失败',
152
- totalBlocked: '已拦截死循环',
153
- lastViolation: '最近拦截事件',
154
- noViolations: '当前运行时未检测到死循环违规。',
155
- resetStats: '重置统计',
156
- statsResetDone: '统计已重置',
157
- statsResetFailed: '重置统计失败',
158
- maxToolAttemptsPerTurn: '单回合最大工具尝试次数(0 表示禁用)',
159
- maxProgressToolCallsPerTurn: '单回合最大进度工具调用次数',
160
- maxCallsPerRepeatGroup: '同组工具最大重复调用次数',
161
- strictTools: '严格限制工具(逗号分隔,触发更低阈值)',
162
- strictToolLimit: '严格工具调用上限',
163
- blockExactDuplicates: '立即拦截完全相同的重复工具调用',
164
- dryRunMode: '审计模拟模式(仅记录日志,不实际拦截)',
165
- assistantOutputGuard: '助手文本输出防循环守卫',
166
- maxRepeatedAssistantLines: '最大单行重复次数',
167
- maxRepeatedAssistantBlocks: '最大段落重复次数',
168
- maxAssistantBlockChars: '最大段落判定字符数',
169
- progressToolNames: '进度标记工具(逗号分隔)',
170
- pseudoToolCallThreshold: '伪工具调用空转拦截阈值(连续回合数,0 表示禁用)',
171
- oscillationDetection: '交替循环拦截(乒乓震荡检测)',
172
- maxOscillationRepeats: '最大交替循环重复次数(2-4 步序列)',
173
- payloadBloatGuard: '超大结果防膨胀拦截(截断巨大输出)',
174
- maxToolResultChars: '工具结果字符上限(0 表示禁用)',
175
- saving: '正在保存…',
176
- ready: '保存配置',
177
- saved: '配置已保存',
178
- };
179
-
180
- const DEFAULTS = {
181
- maxToolAttemptsPerTurn: 64, maxProgressToolCallsPerTurn: 16, progressToolNames: ['todo_write'],
182
- maxCallsPerRepeatGroup: 5, strictTools: [], strictToolLimit: 3, blockExactDuplicates: true,
183
- dryRunMode: false, assistantOutputGuard: true, maxRepeatedAssistantLines: 5,
184
- maxRepeatedAssistantBlocks: 5, maxAssistantBlockChars: 16384, pseudoToolCallThreshold: 3,
185
- oscillationDetection: true, maxOscillationRepeats: 3, payloadBloatGuard: true, maxToolResultChars: 65536,
186
- };
187
-
188
- function PluginCard({ ctx: _ctx, t, bare, ...props }) {
189
- const isBare = Boolean(bare || props?.view === 'page');
190
- const [expanded, setExpanded] = React.useState(false);
191
- const isExpanded = Boolean(isBare || expanded);
192
- const [draft, setDraft] = React.useState({ ...DEFAULTS, progressToolNamesText: 'todo_write', strictToolsText: '' });
193
- const [status, setStatus] = React.useState('loading');
194
- const [saving, setSaving] = React.useState(false);
195
- const [msg, setMsg] = React.useState('');
196
-
197
- const [updateState, setUpdateState] = React.useState({
198
- checking: false, updateAvailable: false, currentVersion: '', latestVersion: '',
199
- updating: false, notice: '', error: '', canAutoUpdate: true, isDesktop: false,
200
- });
201
-
202
- const [telemetry, setTelemetry] = React.useState({ totalViolations: 0, byCode: {}, lastViolation: null });
203
-
204
- const scopeRef = React.useRef(null);
205
- if (!scopeRef.current && _ctx && _ctx.configForms) {
206
- try { scopeRef.current = _ctx.configForms.get(NS); } catch (e) { scopeRef.current = null; }
207
- }
208
- const scope = scopeRef.current;
209
-
210
- const [, setLocaleTick] = React.useState(0);
211
- React.useEffect(() => {
212
- if (typeof _ctx?.locale?.subscribe === 'function') return _ctx.locale.subscribe(() => setLocaleTick((c) => c + 1));
213
- }, []);
214
-
215
- const getActiveLocale = () => {
216
- const snap = typeof _ctx?.locale?.getLocale === 'function'
217
- ? _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
- if (loc) return loc;
221
- return typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en';
222
- };
223
- const currentLang = String(getActiveLocale()).toLowerCase().startsWith('zh') ? 'zh' : 'en';
224
- const dict = currentLang === 'zh' ? zh : en;
225
- const tt = (k, params) => {
226
- let str = (typeof t === 'function' ? t(k) : null) || dict[k] || en[k] || k;
227
- if (params && typeof params === 'object') {
228
- for (const [pk, pv] of Object.entries(params)) {
229
- str = str.replace(new RegExp('\\{' + pk + '\\}', 'g'), String(pv));
230
- }
231
- }
232
- return str;
233
- };
234
-
235
- React.useEffect(() => {
236
- if (!scope) { setStatus('unavailable'); return; }
237
- let cancelled = false;
238
- const syncFromSnapshot = (snap) => {
239
- if (!snap || typeof snap !== 'object') return;
240
- if ('status' in snap) {
241
- if (snap.status === 'loading') { setStatus('loading'); return; }
242
- if (snap.status === 'unavailable') { setStatus('unavailable'); return; }
243
- }
244
- const vals = snap.value !== undefined ? snap.value : (snap.values !== undefined ? snap.values : snap);
245
- if (vals && typeof vals === 'object') {
246
- const names = Array.isArray(vals.progressToolNames) ? vals.progressToolNames : DEFAULTS.progressToolNames;
247
- const strict = Array.isArray(vals.strictTools) ? vals.strictTools : DEFAULTS.strictTools;
248
- setDraft((d) => ({
249
- ...d, ...DEFAULTS, ...vals,
250
- progressToolNamesText: names.join(', '),
251
- strictToolsText: strict.join(', '),
252
- }));
253
- }
254
- setStatus('ready');
255
- };
256
-
257
- try {
258
- if (typeof scope.getSnapshot === 'function') syncFromSnapshot(scope.getSnapshot());
259
- else if (typeof scope.get === 'function') Promise.resolve(scope.get()).then((s) => { if (!cancelled) syncFromSnapshot(s); }).catch(() => { if (!cancelled) setStatus('unavailable'); });
260
- else setStatus('unavailable');
261
- } catch (_) { if (!cancelled) setStatus('unavailable'); }
262
-
263
- const unsub = typeof scope.subscribe === 'function' ? scope.subscribe(() => {
264
- if (!cancelled && typeof scope.getSnapshot === 'function') { try { syncFromSnapshot(scope.getSnapshot()); } catch (err) { void err; } }
265
- }) : null;
266
-
267
- return () => { cancelled = true; if (typeof unsub === 'function') unsub(); };
268
- }, [scope]);
269
-
270
- React.useEffect(() => {
271
- if (!isExpanded) return;
272
- let cancelled = false;
273
-
274
- (async () => {
275
- setUpdateState((s) => ({ ...s, checking: true, error: '', notice: '' }));
276
- try {
277
- const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/update');
278
- if (!res.ok) throw new Error('HTTP ' + res.status);
279
- const data = await res.json();
280
- if (cancelled) return;
281
- setUpdateState((s) => ({
282
- ...s, checking: false, currentVersion: data.currentVersion || '',
283
- latestVersion: data.latestVersion || '', updateAvailable: !!data.updateAvailable,
284
- canAutoUpdate: data.canAutoUpdate !== false, isDesktop: !!data.isDesktop,
285
- }));
286
- } catch (err) {
287
- if (cancelled) return;
288
- setUpdateState((s) => ({ ...s, checking: false, error: tt('checkUpdateFailed') }));
289
- }
290
- })();
291
-
292
- (async () => {
293
- try {
294
- const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry');
295
- if (!res.ok) throw new Error('HTTP ' + res.status);
296
- const data = await res.json();
297
- if (cancelled) return;
298
- setTelemetry({
299
- totalViolations: Number(data.totalViolations) || 0,
300
- byCode: data.byCode || {},
301
- lastViolation: data.lastViolation || null,
302
- error: null,
303
- });
304
- } catch (err) {
305
- if (cancelled) return;
306
- setTelemetry((t) => ({ ...t, error: tt('telemetryLoadFailed') }));
307
- }
308
- })();
309
-
310
- return () => { cancelled = true; };
311
- }, [isExpanded]);
312
-
313
- async function onSave() {
314
- if (!scope) { setMsg('Settings unavailable'); return; }
315
- setSaving(true); setMsg('');
316
- const names = String(draft.progressToolNamesText || '').split(',').map((s) => s.trim()).filter(Boolean);
317
- const strictNames = String(draft.strictToolsText || '').split(',').map((s) => s.trim()).filter(Boolean);
318
- const maxToolAttempts = Number(draft.maxToolAttemptsPerTurn);
319
- const payload = {
320
- maxToolAttemptsPerTurn: Number.isFinite(maxToolAttempts) && maxToolAttempts >= 0 ? maxToolAttempts : 64,
321
- maxProgressToolCallsPerTurn: Number(draft.maxProgressToolCallsPerTurn) || 16,
322
- maxCallsPerRepeatGroup: Number(draft.maxCallsPerRepeatGroup) || 5,
323
- strictToolLimit: Number(draft.strictToolLimit) || 3,
324
- strictTools: strictNames,
325
- blockExactDuplicates: !!draft.blockExactDuplicates, dryRunMode: !!draft.dryRunMode, assistantOutputGuard: !!draft.assistantOutputGuard,
326
- maxRepeatedAssistantLines: Number(draft.maxRepeatedAssistantLines) || 5, maxRepeatedAssistantBlocks: Number(draft.maxRepeatedAssistantBlocks) || 5,
327
- maxAssistantBlockChars: Number(draft.maxAssistantBlockChars) || 16384,
328
- pseudoToolCallThreshold: Number.isFinite(Number(draft.pseudoToolCallThreshold)) && Number(draft.pseudoToolCallThreshold) >= 0 ? Number(draft.pseudoToolCallThreshold) : 3,
329
- oscillationDetection: draft.oscillationDetection !== false, maxOscillationRepeats: Number(draft.maxOscillationRepeats) || 3,
330
- payloadBloatGuard: draft.payloadBloatGuard !== false, maxToolResultChars: Number.isFinite(Number(draft.maxToolResultChars)) && Number(draft.maxToolResultChars) >= 0 ? Number(draft.maxToolResultChars) : 65536,
331
- progressToolNames: names.length ? names : ['todo_write'],
332
- };
333
- const errs = [];
334
- for (const [k, v] of Object.entries(payload)) {
335
- try { await scope.set(k, v); } catch (e) { errs.push(k + ': ' + (e && e.message || String(e))); }
336
- }
337
- setSaving(false);
338
- setMsg(errs.length ? errs.join('; ') : tt('saved'));
339
- }
340
-
341
- async function onTriggerUpdate() {
342
- if (updateState.updating) return;
343
- setUpdateState((s) => ({ ...s, updating: true, error: '', notice: '' }));
344
- try {
345
- const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/update', {
346
- method: 'POST',
347
- headers: { 'x-dsh-plugin-update': '1' },
348
- });
349
- const data = await res.json();
350
- if (!res.ok || data.error) throw new Error(data.error || 'Update failed with HTTP ' + res.status);
351
- setUpdateState((s) => ({
352
- ...s, updating: false, updateAvailable: false,
353
- currentVersion: data.updatedVersion || s.latestVersion,
354
- notice: tt('updateSuccess', { v: data.updatedVersion || s.latestVersion }),
355
- }));
356
- } catch (err) {
357
- setUpdateState((s) => ({ ...s, updating: false, error: tt('updateFailed', { msg: err.message || String(err) }) }));
358
- }
359
- }
360
-
361
- async function onResetTelemetry() {
362
- try {
363
- const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry', {
364
- method: 'POST',
365
- headers: { 'x-dsh-loop-guard': '1' },
366
- });
367
- if (!res.ok) throw new Error('HTTP ' + res.status);
368
- setTelemetry({ totalViolations: 0, byCode: {}, lastViolation: null, error: null });
369
- setMsg(tt('statsResetDone'));
370
- } catch (err) {
371
- setMsg(tt('statsResetFailed'));
372
- }
373
- }
374
-
375
- const renderChevron = () => {
376
- if (PrimitivesChevron) {
377
- return React.createElement(PrimitivesChevron, {
378
- className: 'alg-chevron' + (expanded ? ' expanded' : ''),
379
- style: { width: 14, height: 14, color: 'inherit' }
380
- });
381
- }
382
- return React.createElement('svg', {
383
- className: 'alg-chevron' + (expanded ? ' expanded' : ''),
384
- width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none',
385
- stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
386
- style: { flexShrink: 0 }
387
- }, React.createElement('polyline', { points: '6 9 12 15 18 9' }));
388
- };
389
-
390
- const field = (key, input) => {
391
- const id = 'alg-' + key;
392
- const linkedInput = React.isValidElement && React.isValidElement(input)
393
- ? React.cloneElement(input, { id })
394
- : input;
395
- return React.createElement('div', { className: 'alg-field' },
396
- React.createElement('label', { htmlFor: id }, tt(key)),
397
- linkedInput
398
- );
399
- };
400
-
401
- const num = (key) => React.createElement('input', {
402
- type: 'number', className: 'alg-input', value: draft[key],
403
- onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
404
- });
405
-
406
- const str = (key) => React.createElement('input', {
407
- type: 'text', className: 'alg-input', value: draft[key],
408
- onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
409
- });
410
-
411
- const check = (key) => React.createElement('label', { className: 'alg-checkbox-label' },
412
- React.createElement('input', {
413
- type: 'checkbox', checked: !!draft[key],
414
- onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.checked }))
415
- }),
416
- tt(key)
417
- );
418
-
419
- const header = React.createElement('button', {
420
- className: 'alg-header-btn',
421
- onClick: () => setExpanded(!expanded),
422
- 'aria-expanded': expanded,
423
- },
424
- React.createElement('span', { style: { display: 'flex', flexDirection: 'column' } },
425
- React.createElement('span', { style: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 } },
426
- tt('title'),
427
- React.createElement('span', { style: { fontSize: 11, fontWeight: 500, padding: '2px 6px', borderRadius: 6, background: 'color-mix(in srgb, var(--dsw-alias-brand-primary) 15%, transparent)', color: 'var(--dsw-alias-brand-primary)' } }, updateState.currentVersion ? 'v' + updateState.currentVersion : (updateState.checking ? '…' : '—'))
428
- ),
429
- React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, tt('sub'))
430
- ),
431
- renderChevron()
432
- );
433
-
434
- const body = React.createElement('div', { className: 'alg-body' },
435
- React.createElement('div', {
436
- style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: '1px solid var(--dsw-alias-border-l2)' }
437
- },
438
- React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 2 } },
439
- React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
440
- React.createElement('span', { style: { fontSize: 13, fontWeight: 500, color: 'var(--dsw-alias-label-primary)' } },
441
- tt('version') + ': ' + (updateState.currentVersion ? 'v' + updateState.currentVersion : '—')
442
- ),
443
- React.createElement('span', {
444
- style: {
445
- fontSize: 11, padding: '1px 6px', borderRadius: 4,
446
- background: updateState.updateAvailable ? 'color-mix(in srgb, var(--dsw-alias-brand-primary) 15%, transparent)' : 'color-mix(in srgb, var(--dsw-alias-state-success-primary) 15%, transparent)',
447
- color: updateState.updateAvailable ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-state-success-primary)',
448
- }
449
- }, updateState.checking ? tt('updateChecking') : (updateState.updateAvailable ? tt('updateAvailable', { v: updateState.latestVersion }) : (updateState.currentVersion ? tt('upToDate') : '—')))
450
- ),
451
- updateState.error && React.createElement('span', { style: { color: 'var(--dsw-alias-state-error-primary)', fontSize: 12 } }, updateState.error)
452
- ),
453
- updateState.updateAvailable && (
454
- (updateState.isDesktop || !updateState.canAutoUpdate)
455
- ? React.createElement('span', { className: 'alg-updater-hint', style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, tt('updateViaPluginsPage'))
456
- : React.createElement('button', { className: 'alg-btn-updater', onClick: onTriggerUpdate, disabled: updateState.updating }, updateState.updating ? tt('updating') : tt('updateNow'))
457
- )
458
- ),
459
- updateState.notice && React.createElement('div', {
460
- 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)' }
461
- }, updateState.notice),
462
-
463
- React.createElement('div', {
464
- 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)' }
465
- },
466
- React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
467
- React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, tt('telemetryTitle')),
468
- telemetry.totalViolations > 0 && React.createElement('button', {
469
- className: 'alg-btn-ghost', onClick: onResetTelemetry,
470
- }, tt('resetStats'))
471
- ),
472
- React.createElement('div', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
473
- telemetry.error
474
- ? React.createElement('span', { style: { color: 'var(--dsw-alias-state-error-primary)' } }, telemetry.error)
475
- : telemetry.totalViolations > 0
476
- ? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
477
- React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-state-warn-primary)' } }, telemetry.totalViolations)),
478
- telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
479
- tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
480
- )
481
- )
482
- : React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
483
- )
484
- ),
485
-
486
- field('maxToolAttemptsPerTurn', num('maxToolAttemptsPerTurn')),
487
- field('maxProgressToolCallsPerTurn', num('maxProgressToolCallsPerTurn')),
488
- field('maxCallsPerRepeatGroup', num('maxCallsPerRepeatGroup')),
489
- field('strictTools', str('strictToolsText')),
490
- field('strictToolLimit', num('strictToolLimit')),
491
- check('blockExactDuplicates'),
492
- check('dryRunMode'),
493
- check('assistantOutputGuard'),
494
- field('maxRepeatedAssistantLines', num('maxRepeatedAssistantLines')),
495
- field('maxRepeatedAssistantBlocks', num('maxRepeatedAssistantBlocks')),
496
- field('maxAssistantBlockChars', num('maxAssistantBlockChars')),
497
- field('progressToolNames', str('progressToolNamesText')),
498
- field('pseudoToolCallThreshold', num('pseudoToolCallThreshold')),
499
- check('oscillationDetection'),
500
- field('maxOscillationRepeats', num('maxOscillationRepeats')),
501
- check('payloadBloatGuard'),
502
- field('maxToolResultChars', num('maxToolResultChars')),
503
-
504
- React.createElement('div', {
505
- style: { display: 'flex', alignItems: 'center', gap: 12, paddingTop: 14, borderTop: '1px solid var(--dsw-alias-border-l2)', marginTop: 10 }
506
- },
507
- React.createElement('button', {
508
- className: 'alg-btn-primary', onClick: onSave, disabled: saving || status !== 'ready',
509
- }, saving ? tt('saving') : tt('ready')),
510
- msg && React.createElement('span', { style: { fontSize: 13, color: msg === tt('saved') || msg === tt('statsResetDone') ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-state-error-primary)' } }, msg)
511
- )
512
- );
513
-
514
- if (isBare) return React.createElement('div', { className: 'alg-page' }, body);
515
- return React.createElement('li', { className: 'alg-card' }, header, expanded && body);
516
- }
517
-
518
- function PluginItem(props) {
519
- if (props && props.view === 'summary') {
520
- return React.createElement('div', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, en.sub);
521
- }
522
- return React.createElement(PluginCard, { ...props, bare: Boolean(props && (props.bare || props.view === 'page')) });
523
- }
524
-
22
+ const CSS_STYLES = `
23
+ .alg-page { width: 100%; min-width: 0; }
24
+ .alg-card { border: 1px solid var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-3); border-radius: 12px; list-style: none; margin-bottom: 12px; overflow: hidden; transition: border-color 0.15s ease; }
25
+ .alg-card:hover { border-color: var(--dsw-alias-border-l1, var(--dsw-alias-border-l2)); }
26
+ .alg-header-btn { appearance: none; width: 100%; font: inherit; color: inherit; text-align: left; cursor: pointer; background: transparent; border: 0; border-radius: 12px; display: flex; align-items: center; gap: 12px; padding: 14px 16px; transition: background 0.15s ease; }
27
+ .alg-header-btn:hover { background: var(--dsw-alias-interactive-bg-hover); }
28
+ .alg-chevron { margin-left: auto; color: var(--dsw-alias-label-tertiary); display: flex; align-items: center; justify-content: center; transition: transform 0.2s ease; }
29
+ .alg-chevron.expanded { transform: rotate(180deg); }
30
+ .alg-body { padding: 0 16px 16px; border-top: 1px solid var(--dsw-alias-border-l2); }
31
+ .alg-field { display: flex; flex-direction: column; gap: 6px; padding: 8px 0; }
32
+ .alg-field label { font-size: 13px; color: var(--dsw-alias-label-secondary); cursor: pointer; }
33
+ .alg-input { height: 34px; border: 1px solid var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-3); color: var(--dsw-alias-label-primary); border-radius: 8px; padding: 0 12px; font-size: 13px; outline: none; transition: border-color 0.15s ease; }
34
+ .alg-input:focus { border-color: var(--dsw-alias-brand-primary); }
35
+ .alg-checkbox-label { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--dsw-alias-label-primary); cursor: pointer; padding: 5px 0; }
36
+ .alg-btn-primary { appearance: none; font: inherit; cursor: pointer; border: 0; border-radius: 8px; padding: 6px 16px; font-size: 13px; font-weight: 500; background: var(--dsw-alias-brand-primary); color: var(--dsw-alias-label-primary-inverted, var(--dsw-alias-bg-layer-3)); transition: opacity 0.15s ease; }
37
+ .alg-btn-primary:hover:not(:disabled) { opacity: 0.9; }
38
+ .alg-btn-primary:disabled { opacity: 0.5; cursor: default; }
39
+ .alg-btn-updater { appearance: none; font: inherit; cursor: pointer; border: 0; border-radius: 6px; padding: 4px 10px; font-size: 12px; font-weight: 500; background: var(--dsw-alias-brand-primary); color: var(--dsw-alias-label-primary-inverted, var(--dsw-alias-bg-layer-3)); transition: opacity 0.15s ease; }
40
+ .alg-btn-updater:hover:not(:disabled) { opacity: 0.9; }
41
+ .alg-btn-updater:disabled { opacity: 0.6; cursor: default; }
42
+ .alg-btn-ghost { background: transparent; border: 1px solid var(--dsw-alias-border-l2); color: var(--dsw-alias-label-tertiary); border-radius: 4px; padding: 2px 8px; font-size: 11px; cursor: pointer; transition: color 0.15s ease, border-color 0.15s ease; }
43
+ .alg-btn-ghost:hover { color: var(--dsw-alias-label-primary); border-color: var(--dsw-alias-label-secondary); }
44
+ .alg-presets { display: flex; align-items: center; gap: 8px; padding: 10px 0; border-bottom: 1px solid var(--dsw-alias-border-l2); margin-bottom: 8px; flex-wrap: wrap; }
45
+ .alg-btn-preset { appearance: none; font: inherit; cursor: pointer; border: 1px solid var(--dsw-alias-border-l2); border-radius: 6px; padding: 3px 10px; font-size: 12px; background: var(--dsw-alias-bg-layer-3); color: var(--dsw-alias-label-secondary); transition: all 0.15s ease; }
46
+ .alg-btn-preset:hover { border-color: var(--dsw-alias-brand-primary); color: var(--dsw-alias-label-primary); }
47
+ .alg-incident-row { display: flex; align-items: center; justify-content: space-between; padding: 3px 0; border-bottom: 1px solid color-mix(in srgb, var(--dsw-alias-border-l2) 40%, transparent); font-size: 11px; }
48
+ `;
49
+
50
+ if (typeof document !== 'undefined') {
51
+ const styleId = 'dsh-agent-loop-guard-styles';
52
+ if (!document.getElementById(styleId)) {
53
+ const style = document.createElement('style');
54
+ style.id = styleId;
55
+ style.setAttribute('data-dsh-plugin', '@goodandready/dsh-agent-loop-guard');
56
+ style.textContent = CSS_STYLES;
57
+ document.head.appendChild(style);
58
+ }
59
+ }
60
+ const en = {
61
+ title: 'Agent Loop Guard', sub: 'Fail-closed tool-call and assistant-output loop limits',
62
+ version: 'Version', updateChecking: 'Checking updates…', updateAvailable: 'Update available: v{v}',
63
+ upToDate: 'Up to date', updateNow: 'Update Now', updateViaPluginsPage: 'Update in Plugins page',
64
+ updating: 'Updating…', updateSuccess: 'Updated to v{v}. Restart DSH service to apply changes.',
65
+ updateFailed: 'Update failed: {msg}', checkUpdateFailed: 'Check failed',
66
+ telemetryTitle: 'Protection Telemetry', telemetryLoadFailed: 'Failed to load telemetry',
67
+ totalBlocked: 'Loops Prevented', steeredCount: 'Smart Steers', lastViolation: 'Last Incident',
68
+ noViolations: 'No loop violations detected in current runtime.', resetStats: 'Reset Stats',
69
+ statsResetDone: 'Stats reset', statsResetFailed: 'Failed to reset stats',
70
+ presetsTitle: 'Presets', presetStrict: 'Strict', presetBalanced: 'Balanced', presetAutonomous: 'Autonomous Coding',
71
+ presetApplied: 'Preset {name} applied to form', copyDump: 'Copy Diagnostic Dump', dumpCopied: 'Diagnostic dump copied to clipboard',
72
+ maxToolAttemptsPerTurn: 'Max tool attempts per turn (0 = disabled)', maxProgressToolCallsPerTurn: 'Max progress tool calls per turn',
73
+ maxCallsPerRepeatGroup: 'Max calls per repeat group', strictTools: 'Strict tools (comma-separated, lower limit)',
74
+ strictToolLimit: 'Strict tools limit', blockExactDuplicates: 'Block exact duplicate tool calls',
75
+ dryRunMode: 'Dry-run / Audit mode (log only, do not reject)', assistantOutputGuard: 'Assistant output guard',
76
+ maxRepeatedAssistantLines: 'Max repeated assistant lines', maxRepeatedAssistantBlocks: 'Max repeated assistant blocks',
77
+ maxAssistantBlockChars: 'Max assistant block chars', progressToolNames: 'Progress tool names (comma-separated)',
78
+ pseudoToolCallThreshold: 'Pseudo tool-call loop threshold (turns, 0 = disabled)', oscillationDetection: 'Oscillation loop guard (ping-pong cycles)',
79
+ maxOscillationRepeats: 'Max oscillation repeats (2-4 step cycles)', payloadBloatGuard: 'Payload bloat guard (truncate huge outputs)',
80
+ maxToolResultChars: 'Max tool result characters (0 = disabled)', errorThrashingGuard: 'Error thrashing guard (fail-loop detection)',
81
+ maxConsecutiveFailures: 'Max consecutive failures before thrashing block', adaptiveSteering: 'Smart steering (guide agent before hard cancel)',
82
+ saving: 'Saving…', ready: 'Save Settings', saved: 'Saved',
83
+ };
84
+
85
+ const zh = {
86
+ title: 'Agent Loop Guard', sub: '工具调用与助手输出防死循环熔断限制',
87
+ version: '版本', updateChecking: '正在检查更新…', updateAvailable: '发现新版本: v{v}',
88
+ upToDate: '已是最新版本', updateNow: '立即更新', updateViaPluginsPage: '请在插件页面更新',
89
+ updating: '正在更新…', updateSuccess: '已更新至 v{v}。请重启 DSH 服务以生效变更。',
90
+ updateFailed: '更新失败: {msg}', checkUpdateFailed: '检查更新失败',
91
+ telemetryTitle: '防护运行遥测', telemetryLoadFailed: '获取遥测数据失败',
92
+ totalBlocked: '已拦截死循环', steeredCount: '自纠正引导次数', lastViolation: '最近拦截事件',
93
+ noViolations: '当前运行时未检测到死循环违规。', resetStats: '重置统计',
94
+ statsResetDone: '统计已重置', statsResetFailed: '重置统计失败',
95
+ presetsTitle: '灵敏度预设', presetStrict: '严格', presetBalanced: '平衡', presetAutonomous: '自主编程',
96
+ presetApplied: '已应用预设: {name}', copyDump: '复制诊断数据', dumpCopied: '诊断数据已复制到剪贴板',
97
+ maxToolAttemptsPerTurn: '单回合最大工具尝试次数(0 表示禁用)', maxProgressToolCallsPerTurn: '单回合最大进度工具调用次数',
98
+ maxCallsPerRepeatGroup: '同组工具最大重复调用次数', strictTools: '严格限制工具(逗号分隔,触发更低阈值)',
99
+ strictToolLimit: '严格工具调用上限', blockExactDuplicates: '立即拦截完全相同的重复工具调用',
100
+ dryRunMode: '审计模拟模式(仅记录日志,不实际拦截)', assistantOutputGuard: '助手文本输出防循环守卫',
101
+ maxRepeatedAssistantLines: '最大单行重复次数', maxRepeatedAssistantBlocks: '最大段落重复次数',
102
+ maxAssistantBlockChars: '最大段落判定字符数', progressToolNames: '进度标记工具(逗号分隔)',
103
+ pseudoToolCallThreshold: '伪工具调用空转拦截阈值(连续回合数,0 表示禁用)', oscillationDetection: '交替循环拦截(乒乓震荡检测)',
104
+ maxOscillationRepeats: '最大交替循环重复次数(2-4 步序列)', payloadBloatGuard: '超大结果防膨胀拦截(截断巨大输出)',
105
+ maxToolResultChars: '工具结果字符上限(0 表示禁用)', errorThrashingGuard: '工具重复报错拦截(错误循环保护)',
106
+ maxConsecutiveFailures: '连续报错熔断阈值', adaptiveSteering: '智能自纠正(熔断前引导修正)',
107
+ saving: '正在保存…', ready: '保存配置', saved: '配置已保存',
108
+ };
109
+ const DEFAULTS = {
110
+ maxToolAttemptsPerTurn: 64, maxProgressToolCallsPerTurn: 16, progressToolNames: ['todo_write'],
111
+ maxCallsPerRepeatGroup: 5, strictTools: [], strictToolLimit: 3, blockExactDuplicates: true,
112
+ dryRunMode: false, assistantOutputGuard: true, maxRepeatedAssistantLines: 5,
113
+ maxRepeatedAssistantBlocks: 5, maxAssistantBlockChars: 16384, pseudoToolCallThreshold: 3,
114
+ oscillationDetection: true, maxOscillationRepeats: 3, payloadBloatGuard: true, maxToolResultChars: 65536,
115
+ errorThrashingGuard: true, maxConsecutiveFailures: 4, adaptiveSteering: true,
116
+ };
117
+
118
+ const CLIENT_PRESETS = {
119
+ strict: {
120
+ maxToolAttemptsPerTurn: 10, maxProgressToolCallsPerTurn: 3, maxCallsPerRepeatGroup: 2,
121
+ strictToolLimit: 1, blockExactDuplicates: true, oscillationDetection: true, maxOscillationRepeats: 2,
122
+ errorThrashingGuard: true, maxConsecutiveFailures: 3, payloadBloatGuard: true, maxToolResultChars: 32768,
123
+ pseudoToolCallThreshold: 2, adaptiveSteering: true,
124
+ },
125
+ balanced: {
126
+ maxToolAttemptsPerTurn: 16, maxProgressToolCallsPerTurn: 6, maxCallsPerRepeatGroup: 3,
127
+ strictToolLimit: 2, blockExactDuplicates: true, oscillationDetection: true, maxOscillationRepeats: 3,
128
+ errorThrashingGuard: true, maxConsecutiveFailures: 4, payloadBloatGuard: true, maxToolResultChars: 65536,
129
+ pseudoToolCallThreshold: 3, adaptiveSteering: true,
130
+ },
131
+ autonomous: {
132
+ maxToolAttemptsPerTurn: 32, maxProgressToolCallsPerTurn: 12, maxCallsPerRepeatGroup: 5,
133
+ strictToolLimit: 3, blockExactDuplicates: true, oscillationDetection: true, maxOscillationRepeats: 4,
134
+ errorThrashingGuard: true, maxConsecutiveFailures: 6, payloadBloatGuard: true, maxToolResultChars: 131072,
135
+ pseudoToolCallThreshold: 4, adaptiveSteering: true,
136
+ },
137
+ };
138
+ function PluginCard({ ctx: _ctx, t, bare, ...props }) {
139
+ const isBare = Boolean(bare || props?.view === 'page');
140
+ const [expanded, setExpanded] = React.useState(false);
141
+ const isExpanded = Boolean(isBare || expanded);
142
+ const [draft, setDraft] = React.useState({ ...DEFAULTS, progressToolNamesText: 'todo_write', strictToolsText: '' });
143
+ const [status, setStatus] = React.useState('loading');
144
+ const [saving, setSaving] = React.useState(false);
145
+ const [msg, setMsg] = React.useState('');
146
+
147
+ const [updateState, setUpdateState] = React.useState({
148
+ checking: false, updateAvailable: false, currentVersion: '', latestVersion: '',
149
+ updating: false, notice: '', error: '', canAutoUpdate: true, isDesktop: false,
150
+ });
151
+
152
+ const [telemetry, setTelemetry] = React.useState({ totalViolations: 0, steeredCount: 0, byCode: {}, lastViolation: null, incidents: [] });
153
+
154
+ const scopeRef = React.useRef(null);
155
+ if (!scopeRef.current && _ctx && _ctx.configForms) {
156
+ try { scopeRef.current = _ctx.configForms.get(NS); } catch (e) { scopeRef.current = null; }
157
+ }
158
+ const scope = scopeRef.current;
159
+
160
+ const [, setLocaleTick] = React.useState(0);
161
+ React.useEffect(() => {
162
+ if (typeof _ctx?.locale?.subscribe === 'function') return _ctx.locale.subscribe(() => setLocaleTick((c) => c + 1));
163
+ }, []);
164
+
165
+ const getActiveLocale = () => {
166
+ const snap = typeof _ctx?.locale?.getLocale === 'function' ? _ctx.locale.getLocale()
167
+ : (typeof _ctx?.locale?.getSnapshot === 'function' ? _ctx.locale.getSnapshot() : null);
168
+ const loc = typeof snap === 'string' ? snap : (snap?.active || snap?.locale || snap?.id);
169
+ return loc || (typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en');
170
+ };
171
+ const currentLang = String(getActiveLocale()).toLowerCase().startsWith('zh') ? 'zh' : 'en';
172
+ const dict = currentLang === 'zh' ? zh : en;
173
+ const tt = (k, params) => {
174
+ let str = (typeof t === 'function' ? t(k) : null) || dict[k] || en[k] || k;
175
+ if (params && typeof params === 'object') {
176
+ for (const [pk, pv] of Object.entries(params)) {
177
+ str = str.replace(new RegExp('\\{' + pk + '\\}', 'g'), String(pv));
178
+ }
179
+ }
180
+ return str;
181
+ };
182
+
183
+ React.useEffect(() => {
184
+ if (!scope) { setStatus('unavailable'); return; }
185
+ let cancelled = false;
186
+ const syncFromSnapshot = (snap) => {
187
+ if (!snap || typeof snap !== 'object') return;
188
+ if ('status' in snap) {
189
+ if (snap.status === 'loading') { setStatus('loading'); return; }
190
+ if (snap.status === 'unavailable') { setStatus('unavailable'); return; }
191
+ }
192
+ const vals = snap.value !== undefined ? snap.value : (snap.values !== undefined ? snap.values : snap);
193
+ if (vals && typeof vals === 'object') {
194
+ const names = Array.isArray(vals.progressToolNames) ? vals.progressToolNames : DEFAULTS.progressToolNames;
195
+ const strict = Array.isArray(vals.strictTools) ? vals.strictTools : DEFAULTS.strictTools;
196
+ setDraft((d) => ({
197
+ ...d, ...DEFAULTS, ...vals,
198
+ progressToolNamesText: names.join(', '),
199
+ strictToolsText: strict.join(', '),
200
+ }));
201
+ }
202
+ setStatus('ready');
203
+ };
204
+
205
+ try {
206
+ if (typeof scope.getSnapshot === 'function') syncFromSnapshot(scope.getSnapshot());
207
+ else if (typeof scope.get === 'function') Promise.resolve(scope.get()).then((s) => { if (!cancelled) syncFromSnapshot(s); }).catch(() => { if (!cancelled) setStatus('unavailable'); });
208
+ else setStatus('unavailable');
209
+ } catch (_) { if (!cancelled) setStatus('unavailable'); }
210
+
211
+ const unsub = typeof scope.subscribe === 'function' ? scope.subscribe(() => {
212
+ if (!cancelled && typeof scope.getSnapshot === 'function') { try { syncFromSnapshot(scope.getSnapshot()); } catch (err) { void err; } }
213
+ }) : null;
214
+
215
+ return () => { cancelled = true; if (typeof unsub === 'function') unsub(); };
216
+ }, [scope]);
217
+
218
+ React.useEffect(() => {
219
+ if (!isExpanded) return;
220
+ let cancelled = false;
221
+
222
+ (async () => {
223
+ try {
224
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/update');
225
+ if (!res.ok) throw new Error('HTTP ' + res.status);
226
+ const data = await res.json();
227
+ if (cancelled) return;
228
+ setUpdateState((s) => ({
229
+ ...s, checking: false, updateAvailable: Boolean(data.updateAvailable),
230
+ currentVersion: data.currentVersion || '', latestVersion: data.latestVersion || '',
231
+ updating: false, notice: '', error: '',
232
+ canAutoUpdate: data.canAutoUpdate !== false, isDesktop: !!data.isDesktop,
233
+ }));
234
+ } catch (err) {
235
+ if (cancelled) return;
236
+ setUpdateState((s) => ({ ...s, checking: false, error: tt('checkUpdateFailed') }));
237
+ }
238
+ })();
239
+
240
+ (async () => {
241
+ try {
242
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry');
243
+ if (!res.ok) throw new Error('HTTP ' + res.status);
244
+ const data = await res.json();
245
+ if (cancelled) return;
246
+ setTelemetry({
247
+ totalViolations: Number(data.totalViolations) || 0,
248
+ steeredCount: Number(data.steeredCount) || 0,
249
+ byCode: data.byCode || {},
250
+ lastViolation: data.lastViolation || null,
251
+ incidents: Array.isArray(data.incidents) ? data.incidents : [],
252
+ error: null,
253
+ });
254
+ } catch (err) {
255
+ if (cancelled) return;
256
+ setTelemetry((t) => ({ ...t, error: tt('telemetryLoadFailed') }));
257
+ }
258
+ })();
259
+
260
+ return () => { cancelled = true; };
261
+ }, [isExpanded]);
262
+
263
+ async function onSave() {
264
+ if (!scope || saving) return;
265
+ setSaving(true);
266
+ setMsg('');
267
+ const names = draft.progressToolNamesText.split(',').map((s) => s.trim()).filter(Boolean);
268
+ const strictList = draft.strictToolsText.split(',').map((s) => s.trim()).filter(Boolean);
269
+ const payload = {
270
+ maxToolAttemptsPerTurn: Number(draft.maxToolAttemptsPerTurn) || 0, maxProgressToolCallsPerTurn: Number(draft.maxProgressToolCallsPerTurn) || 16,
271
+ maxCallsPerRepeatGroup: Number(draft.maxCallsPerRepeatGroup) || 5, strictTools: strictList, strictToolLimit: Number(draft.strictToolLimit) || 3,
272
+ blockExactDuplicates: draft.blockExactDuplicates !== false, dryRunMode: Boolean(draft.dryRunMode),
273
+ assistantOutputGuard: draft.assistantOutputGuard !== false, maxRepeatedAssistantLines: Number(draft.maxRepeatedAssistantLines) || 5,
274
+ maxRepeatedAssistantBlocks: Number(draft.maxRepeatedAssistantBlocks) || 5, maxAssistantBlockChars: Number(draft.maxAssistantBlockChars) || 16384,
275
+ pseudoToolCallThreshold: Number.isFinite(Number(draft.pseudoToolCallThreshold)) ? Number(draft.pseudoToolCallThreshold) : 3,
276
+ oscillationDetection: draft.oscillationDetection !== false, maxOscillationRepeats: Number(draft.maxOscillationRepeats) || 3,
277
+ payloadBloatGuard: draft.payloadBloatGuard !== false, progressToolNames: names.length ? names : ['todo_write'],
278
+ maxToolResultChars: Number.isFinite(Number(draft.maxToolResultChars)) && Number(draft.maxToolResultChars) >= 0 ? Number(draft.maxToolResultChars) : 65536,
279
+ errorThrashingGuard: draft.errorThrashingGuard !== false, maxConsecutiveFailures: Number(draft.maxConsecutiveFailures) || 4,
280
+ adaptiveSteering: draft.adaptiveSteering !== false,
281
+ };
282
+ const errs = [];
283
+ for (const [k, v] of Object.entries(payload)) {
284
+ try { await scope.set(k, v); } catch (e) { errs.push(k + ': ' + (e && e.message || String(e))); }
285
+ }
286
+ setSaving(false);
287
+ setMsg(errs.length ? errs.join('; ') : tt('saved'));
288
+ }
289
+
290
+ function applyPreset(name) {
291
+ if (!CLIENT_PRESETS[name]) return;
292
+ setDraft((d) => ({ ...d, ...CLIENT_PRESETS[name] }));
293
+ setMsg(tt('presetApplied', { name: tt('preset' + name.charAt(0).toUpperCase() + name.slice(1)) }));
294
+ }
295
+
296
+ function onCopyDump() {
297
+ try {
298
+ if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) navigator.clipboard.writeText(JSON.stringify(telemetry, null, 2));
299
+ setMsg(tt('dumpCopied'));
300
+ } catch (e) { setMsg(String(e)); }
301
+ }
302
+
303
+ async function onTriggerUpdate() {
304
+ if (updateState.updating) return;
305
+ setUpdateState((s) => ({ ...s, updating: true, error: '', notice: '' }));
306
+ try {
307
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/update', {
308
+ method: 'POST', headers: { 'x-dsh-plugin-update': '1' },
309
+ });
310
+ const data = await res.json();
311
+ if (!res.ok || data.error) throw new Error(data.error || 'HTTP ' + res.status);
312
+ setUpdateState((s) => ({
313
+ ...s, updating: false, updateAvailable: false,
314
+ currentVersion: data.updatedVersion || s.latestVersion,
315
+ notice: tt('updateSuccess', { v: data.updatedVersion || s.latestVersion }),
316
+ }));
317
+ } catch (err) { setUpdateState((s) => ({ ...s, updating: false, error: tt('updateFailed', { msg: err.message || String(err) }) })); }
318
+ }
319
+
320
+ async function onResetTelemetry() {
321
+ try {
322
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry', {
323
+ method: 'POST', headers: { 'x-dsh-loop-guard': '1' },
324
+ });
325
+ if (!res.ok) throw new Error('HTTP ' + res.status);
326
+ setTelemetry({ totalViolations: 0, steeredCount: 0, byCode: {}, lastViolation: null, incidents: [], error: null });
327
+ setMsg(tt('statsResetDone'));
328
+ } catch (err) { setMsg(tt('statsResetFailed')); }
329
+ }
330
+
331
+ const renderChevron = () => {
332
+ if (PrimitivesChevron) {
333
+ return React.createElement(PrimitivesChevron, {
334
+ className: 'alg-chevron' + (expanded ? ' expanded' : ''),
335
+ style: { width: 14, height: 14, color: 'inherit' }
336
+ });
337
+ }
338
+ return React.createElement('svg', {
339
+ className: 'alg-chevron' + (expanded ? ' expanded' : ''),
340
+ width: 14, height: 14, viewBox: '0 0 24 24', fill: 'none',
341
+ stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round',
342
+ style: { flexShrink: 0 }
343
+ }, React.createElement('polyline', { points: '6 9 12 15 18 9' }));
344
+ };
345
+
346
+ const field = (key, input) => {
347
+ const id = 'alg-' + key;
348
+ const linkedInput = React.isValidElement && React.isValidElement(input)
349
+ ? React.cloneElement(input, { id }) : input;
350
+ return React.createElement('div', { key, className: 'alg-field' },
351
+ React.createElement('label', { htmlFor: id }, tt(key)),
352
+ linkedInput
353
+ );
354
+ };
355
+
356
+ const num = (k) => React.createElement('input', { type: 'number', className: 'alg-input', value: draft[k], onChange: (e) => setDraft((d) => ({ ...d, [k]: e.target.value })) });
357
+ const str = (k) => React.createElement('input', { type: 'text', className: 'alg-input', value: draft[k], onChange: (e) => setDraft((d) => ({ ...d, [k]: e.target.value })) });
358
+ const check = (k) => React.createElement('label', { key: k, className: 'alg-checkbox-label' }, React.createElement('input', { type: 'checkbox', checked: !!draft[k], onChange: (e) => setDraft((d) => ({ ...d, [k]: e.target.checked })) }), tt(k));
359
+
360
+ const header = React.createElement('button', {
361
+ className: 'alg-header-btn', onClick: () => setExpanded(!expanded), 'aria-expanded': expanded,
362
+ },
363
+ React.createElement('span', { style: { display: 'flex', flexDirection: 'column' } },
364
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 } },
365
+ tt('title'),
366
+ React.createElement('span', { style: { fontSize: 11, fontWeight: 500, padding: '2px 6px', borderRadius: 6, background: 'color-mix(in srgb, var(--dsw-alias-brand-primary) 15%, transparent)', color: 'var(--dsw-alias-brand-primary)' } }, updateState.currentVersion ? 'v' + updateState.currentVersion : (updateState.checking ? '…' : '—'))
367
+ ),
368
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, tt('sub'))
369
+ ),
370
+ renderChevron()
371
+ );
372
+
373
+ const body = React.createElement('div', { className: 'alg-body' },
374
+ React.createElement('div', {
375
+ style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '12px 0', borderBottom: '1px solid var(--dsw-alias-border-l2)' }
376
+ },
377
+ React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 2 } },
378
+ React.createElement('div', { style: { display: 'flex', alignItems: 'center', gap: 8 } },
379
+ React.createElement('span', { style: { fontSize: 13, fontWeight: 500, color: 'var(--dsw-alias-label-primary)' } },
380
+ tt('version') + ': ' + (updateState.currentVersion ? 'v' + updateState.currentVersion : '—')
381
+ ),
382
+ React.createElement('span', {
383
+ style: {
384
+ fontSize: 11, padding: '1px 6px', borderRadius: 4,
385
+ background: updateState.updateAvailable ? 'color-mix(in srgb, var(--dsw-alias-brand-primary) 15%, transparent)' : 'color-mix(in srgb, var(--dsw-alias-state-success-primary) 15%, transparent)',
386
+ color: updateState.updateAvailable ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-state-success-primary)',
387
+ }
388
+ }, updateState.checking ? tt('updateChecking') : (updateState.updateAvailable ? tt('updateAvailable', { v: updateState.latestVersion }) : (updateState.currentVersion ? tt('upToDate') : '—')))
389
+ ),
390
+ updateState.error && React.createElement('span', { style: { color: 'var(--dsw-alias-state-error-primary)', fontSize: 12 } }, updateState.error)
391
+ ),
392
+ updateState.updateAvailable && (
393
+ (updateState.isDesktop || !updateState.canAutoUpdate)
394
+ ? React.createElement('span', { className: 'alg-updater-hint', style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, tt('updateViaPluginsPage'))
395
+ : React.createElement('button', { className: 'alg-btn-updater', onClick: onTriggerUpdate, disabled: updateState.updating }, updateState.updating ? tt('updating') : tt('updateNow'))
396
+ )
397
+ ),
398
+ updateState.notice && React.createElement('div', {
399
+ 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)' }
400
+ }, updateState.notice),
401
+
402
+ React.createElement('div', { className: 'alg-presets' },
403
+ React.createElement('span', { style: { fontSize: 12, fontWeight: 500, color: 'var(--dsw-alias-label-secondary)', marginRight: 4 } }, tt('presetsTitle') + ':'),
404
+ React.createElement('button', { type: 'button', className: 'alg-btn-preset', onClick: () => applyPreset('strict') }, tt('presetStrict')),
405
+ React.createElement('button', { type: 'button', className: 'alg-btn-preset', onClick: () => applyPreset('balanced') }, tt('presetBalanced')),
406
+ React.createElement('button', { type: 'button', className: 'alg-btn-preset', onClick: () => applyPreset('autonomous') }, tt('presetAutonomous'))
407
+ ),
408
+
409
+ React.createElement('div', {
410
+ 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)' }
411
+ },
412
+ React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
413
+ React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, tt('telemetryTitle')),
414
+ React.createElement('div', { style: { display: 'flex', gap: 6 } },
415
+ telemetry.totalViolations > 0 && React.createElement('button', { className: 'alg-btn-ghost', onClick: onCopyDump }, tt('copyDump')),
416
+ (telemetry.totalViolations > 0 || (telemetry.incidents && telemetry.incidents.length > 0)) && React.createElement('button', { className: 'alg-btn-ghost', onClick: onResetTelemetry }, tt('resetStats'))
417
+ )
418
+ ),
419
+ React.createElement('div', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
420
+ telemetry.error
421
+ ? React.createElement('span', { style: { color: 'var(--dsw-alias-state-error-primary)' } }, telemetry.error)
422
+ : (telemetry.totalViolations > 0 || telemetry.steeredCount > 0)
423
+ ? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 6 } },
424
+ React.createElement('div', { style: { display: 'flex', gap: 16 } },
425
+ React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-state-warn-primary)' } }, telemetry.totalViolations)),
426
+ React.createElement('div', null, tt('steeredCount') + ': ', React.createElement('strong', { style: { color: 'var(--dsw-alias-brand-primary)' } }, telemetry.steeredCount || 0))
427
+ ),
428
+ telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
429
+ tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
430
+ ),
431
+ telemetry.incidents && telemetry.incidents.length > 0 && React.createElement('div', { style: { marginTop: 6, borderTop: '1px solid var(--dsw-alias-border-l2)', paddingTop: 6 } },
432
+ React.createElement('div', { style: { fontWeight: 500, marginBottom: 4 } }, tt('incidentsTitle')),
433
+ telemetry.incidents.slice(0, 4).map((inc, i) => React.createElement('div', { key: inc.id || i, className: 'alg-incident-row' },
434
+ React.createElement('span', { style: { fontWeight: 500, color: inc.code === 'LOOP_GUARD_STEER' ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-state-error-primary)' } }, inc.code),
435
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, inc.tool)
436
+ ))
437
+ )
438
+ )
439
+ : React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
440
+ )
441
+ ),
442
+
443
+ field('maxToolAttemptsPerTurn', num('maxToolAttemptsPerTurn')),
444
+ field('maxProgressToolCallsPerTurn', num('maxProgressToolCallsPerTurn')),
445
+ field('maxCallsPerRepeatGroup', num('maxCallsPerRepeatGroup')),
446
+ field('strictTools', str('strictToolsText')),
447
+ field('strictToolLimit', num('strictToolLimit')),
448
+ check('blockExactDuplicates'),
449
+ check('dryRunMode'),
450
+ check('assistantOutputGuard'),
451
+ field('maxRepeatedAssistantLines', num('maxRepeatedAssistantLines')),
452
+ field('maxRepeatedAssistantBlocks', num('maxRepeatedAssistantBlocks')),
453
+ field('maxAssistantBlockChars', num('maxAssistantBlockChars')),
454
+ field('progressToolNames', str('progressToolNamesText')),
455
+ field('pseudoToolCallThreshold', num('pseudoToolCallThreshold')),
456
+ check('oscillationDetection'),
457
+ field('maxOscillationRepeats', num('maxOscillationRepeats')),
458
+ check('payloadBloatGuard'),
459
+ field('maxToolResultChars', num('maxToolResultChars')),
460
+ check('errorThrashingGuard'),
461
+ field('maxConsecutiveFailures', num('maxConsecutiveFailures')),
462
+ check('adaptiveSteering'),
463
+
464
+ React.createElement('div', {
465
+ style: { display: 'flex', alignItems: 'center', gap: 12, paddingTop: 14, borderTop: '1px solid var(--dsw-alias-border-l2)', marginTop: 10 }
466
+ },
467
+ React.createElement('button', {
468
+ className: 'alg-btn-primary', onClick: onSave, disabled: saving || status !== 'ready',
469
+ }, saving ? tt('saving') : tt('ready')),
470
+ msg && React.createElement('span', { style: { fontSize: 13, color: msg.includes(';') ? 'var(--dsw-alias-state-error-primary)' : 'var(--dsw-alias-state-success-primary)' } }, msg)
471
+ )
472
+ );
473
+
474
+ if (isBare) return React.createElement('div', { className: 'alg-page' }, body);
475
+ return React.createElement('li', { className: 'alg-card' }, header, expanded && body);
476
+ }
477
+
478
+ function PluginItem(props) {
479
+ if (props && props.view === 'summary') {
480
+ return React.createElement('div', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, en.sub);
481
+ }
482
+ return React.createElement(PluginCard, { ...props, bare: Boolean(props && (props.bare || props.view === 'page')) });
483
+ }
525
484
  exports.inject = ['slots', 'configForms', 'locale'];
526
485
  exports.apply = function apply(ctx) {
527
486
  if (typeof ctx.locale?.register === 'function') {