@goodandready/dsh-agent-loop-guard 0.2.7 → 0.2.8

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
@@ -7,6 +7,152 @@ window.__ModuleLoader__.load({
7
7
  const React = require('react');
8
8
  const NS = '@goodandready/dsh-agent-loop-guard';
9
9
 
10
+ let PrimitivesChevron = null;
11
+ try {
12
+ const prim = require('@deepseek-ai/dsh-client-ui-primitives');
13
+ if (prim && (prim.IconChevronDownOutline14 || prim.IconChevronDown || prim.IconChevronDown16)) {
14
+ PrimitivesChevron = prim.IconChevronDownOutline14 || prim.IconChevronDown || prim.IconChevronDown16;
15
+ }
16
+ } catch {}
17
+
18
+ const CSS_STYLES = `
19
+ .alg-card {
20
+ border: 1px solid var(--dsw-alias-border-l2);
21
+ background: var(--dsw-alias-bg-layer-3);
22
+ border-radius: 12px;
23
+ list-style: none;
24
+ margin-bottom: 12px;
25
+ overflow: hidden;
26
+ transition: border-color 0.15s ease;
27
+ }
28
+ .alg-card:hover {
29
+ border-color: var(--dsw-alias-border-l1, var(--dsw-alias-border-l2));
30
+ }
31
+ .alg-header-btn {
32
+ appearance: none;
33
+ width: 100%;
34
+ font: inherit;
35
+ color: inherit;
36
+ text-align: left;
37
+ cursor: pointer;
38
+ background: transparent;
39
+ border: 0;
40
+ border-radius: 12px;
41
+ display: flex;
42
+ align-items: center;
43
+ gap: 12px;
44
+ padding: 14px 16px;
45
+ transition: background 0.15s ease;
46
+ }
47
+ .alg-header-btn:hover {
48
+ background: var(--dsw-alias-bg-layer-hover, rgba(255, 255, 255, 0.03));
49
+ }
50
+ .alg-chevron {
51
+ margin-left: auto;
52
+ color: var(--dsw-alias-label-tertiary);
53
+ display: flex;
54
+ align-items: center;
55
+ justify-content: center;
56
+ transition: transform 0.2s ease;
57
+ }
58
+ .alg-chevron.expanded {
59
+ transform: rotate(180deg);
60
+ }
61
+ .alg-body {
62
+ padding: 0 16px 16px;
63
+ border-top: 1px solid var(--dsw-alias-border-l2);
64
+ }
65
+ .alg-field {
66
+ display: flex;
67
+ flex-direction: column;
68
+ gap: 6px;
69
+ padding: 10px 0;
70
+ }
71
+ .alg-field label {
72
+ font-size: 13px;
73
+ color: var(--dsw-alias-label-secondary);
74
+ cursor: pointer;
75
+ }
76
+ .alg-input {
77
+ height: 34px;
78
+ border: 1px solid var(--dsw-alias-border-l2);
79
+ background: var(--dsw-alias-bg-layer-3);
80
+ color: var(--dsw-alias-label-primary);
81
+ border-radius: 8px;
82
+ padding: 0 12px;
83
+ font-size: 13px;
84
+ outline: none;
85
+ transition: border-color 0.15s ease;
86
+ }
87
+ .alg-input:focus {
88
+ border-color: var(--dsw-alias-accent-primary, #3b82f6);
89
+ }
90
+ .alg-checkbox-label {
91
+ display: flex;
92
+ align-items: center;
93
+ gap: 8px;
94
+ font-size: 13px;
95
+ color: var(--dsw-alias-label-primary);
96
+ cursor: pointer;
97
+ padding: 6px 0;
98
+ }
99
+ .alg-btn-primary {
100
+ height: 34px;
101
+ padding: 0 18px;
102
+ border: 0;
103
+ border-radius: 8px;
104
+ background: var(--dsw-alias-accent-primary, #3b82f6);
105
+ color: #fff;
106
+ font-size: 13px;
107
+ font-weight: 600;
108
+ cursor: pointer;
109
+ transition: opacity 0.15s ease;
110
+ }
111
+ .alg-btn-primary:disabled {
112
+ opacity: 0.6;
113
+ cursor: default;
114
+ }
115
+ .alg-btn-updater {
116
+ padding: 6px 14px;
117
+ border-radius: 6px;
118
+ background: var(--dsw-alias-accent-primary, #3b82f6);
119
+ color: #fff;
120
+ border: 0;
121
+ font-size: 12px;
122
+ font-weight: 600;
123
+ cursor: pointer;
124
+ }
125
+ .alg-btn-updater:disabled {
126
+ opacity: 0.6;
127
+ cursor: default;
128
+ }
129
+ .alg-btn-ghost {
130
+ background: transparent;
131
+ border: 1px solid var(--dsw-alias-border-l2);
132
+ color: var(--dsw-alias-label-tertiary);
133
+ border-radius: 4px;
134
+ padding: 2px 8px;
135
+ font-size: 11px;
136
+ cursor: pointer;
137
+ transition: color 0.15s ease, border-color 0.15s ease;
138
+ }
139
+ .alg-btn-ghost:hover {
140
+ color: var(--dsw-alias-label-primary);
141
+ border-color: var(--dsw-alias-label-secondary);
142
+ }
143
+ `;
144
+
145
+ if (typeof document !== 'undefined') {
146
+ const styleId = 'dsh-agent-loop-guard-styles';
147
+ if (!document.getElementById(styleId)) {
148
+ const style = document.createElement('style');
149
+ style.id = styleId;
150
+ style.setAttribute('data-dsh-plugin', '@goodandready/dsh-agent-loop-guard');
151
+ style.textContent = CSS_STYLES;
152
+ document.head.appendChild(style);
153
+ }
154
+ }
155
+
10
156
  const en = {
11
157
  title: 'Agent Loop Guard',
12
158
  sub: 'Fail-closed tool-call and assistant-output loop limits',
@@ -20,11 +166,13 @@ window.__ModuleLoader__.load({
20
166
  updateFailed: 'Update failed: {msg}',
21
167
  checkUpdateFailed: 'Check failed',
22
168
  telemetryTitle: 'Protection Telemetry',
169
+ telemetryLoadFailed: 'Failed to load telemetry',
23
170
  totalBlocked: 'Loops Prevented',
24
171
  lastViolation: 'Last Incident',
25
172
  noViolations: 'No loop violations detected in current runtime.',
26
173
  resetStats: 'Reset Stats',
27
174
  statsResetDone: 'Stats reset',
175
+ statsResetFailed: 'Failed to reset stats',
28
176
  maxToolAttemptsPerTurn: 'Max tool attempts per turn (0 = disabled)',
29
177
  maxProgressToolCallsPerTurn: 'Max progress tool calls per turn',
30
178
  maxCallsPerRepeatGroup: 'Max calls per repeat group',
@@ -55,11 +203,13 @@ window.__ModuleLoader__.load({
55
203
  updateFailed: '更新失败: {msg}',
56
204
  checkUpdateFailed: '检查更新失败',
57
205
  telemetryTitle: '防护运行遥测',
206
+ telemetryLoadFailed: '获取遥测数据失败',
58
207
  totalBlocked: '已拦截死循环',
59
208
  lastViolation: '最近拦截事件',
60
209
  noViolations: '当前运行时未检测到死循环违规。',
61
210
  resetStats: '重置统计',
62
211
  statsResetDone: '统计已重置',
212
+ statsResetFailed: '重置统计失败',
63
213
  maxToolAttemptsPerTurn: '单回合最大工具尝试次数(0 表示禁用)',
64
214
  maxProgressToolCallsPerTurn: '单回合最大进度工具调用次数',
65
215
  maxCallsPerRepeatGroup: '同组工具最大重复调用次数',
@@ -107,7 +257,7 @@ window.__ModuleLoader__.load({
107
257
  const [updateState, setUpdateState] = React.useState({
108
258
  checking: false,
109
259
  updateAvailable: false,
110
- currentVersion: '0.2.5',
260
+ currentVersion: '',
111
261
  latestVersion: '',
112
262
  updating: false,
113
263
  notice: '',
@@ -127,7 +277,22 @@ window.__ModuleLoader__.load({
127
277
  }
128
278
  const scope = scopeRef.current;
129
279
 
130
- const currentLang = (_ctx?.locale?.get?.() || navigator.language || 'en').startsWith('zh') ? 'zh' : 'en';
280
+ const [, setLocaleTick] = React.useState(0);
281
+ React.useEffect(() => {
282
+ if (typeof _ctx?.locale?.subscribe === 'function') {
283
+ return _ctx.locale.subscribe(() => setLocaleTick((c) => c + 1));
284
+ }
285
+ }, []);
286
+
287
+ const getActiveLocale = () => {
288
+ const snap = typeof _ctx?.locale?.getLocale === 'function'
289
+ ? _ctx.locale.getLocale()
290
+ : (typeof _ctx?.locale?.getSnapshot === 'function' ? _ctx.locale.getSnapshot() : null);
291
+ const loc = typeof snap === 'string' ? snap : (snap?.locale || snap?.id);
292
+ if (loc) return loc;
293
+ return typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en';
294
+ };
295
+ const currentLang = String(getActiveLocale()).toLowerCase().startsWith('zh') ? 'zh' : 'en';
131
296
  const dict = currentLang === 'zh' ? zh : en;
132
297
  const tt = (k, params) => {
133
298
  let str = (typeof t === 'function' ? t(k) : null) || dict[k] || en[k] || k;
@@ -187,7 +352,7 @@ window.__ModuleLoader__.load({
187
352
  setUpdateState((s) => ({
188
353
  ...s,
189
354
  checking: false,
190
- currentVersion: data.currentVersion || '0.2.5',
355
+ currentVersion: data.currentVersion || '',
191
356
  latestVersion: data.latestVersion || '',
192
357
  updateAvailable: !!data.updateAvailable,
193
358
  }));
@@ -201,11 +366,19 @@ window.__ModuleLoader__.load({
201
366
  (async () => {
202
367
  try {
203
368
  const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry');
204
- if (!res.ok) return;
369
+ if (!res.ok) throw new Error('HTTP ' + res.status);
205
370
  const data = await res.json();
206
371
  if (cancelled) return;
207
- setTelemetry(data);
208
- } catch {}
372
+ setTelemetry({
373
+ totalViolations: Number(data.totalViolations) || 0,
374
+ byCode: data.byCode || {},
375
+ lastViolation: data.lastViolation || null,
376
+ error: null,
377
+ });
378
+ } catch (err) {
379
+ if (cancelled) return;
380
+ setTelemetry((t) => ({ ...t, error: tt('telemetryLoadFailed') }));
381
+ }
209
382
  })();
210
383
 
211
384
  return () => { cancelled = true; };
@@ -275,33 +448,65 @@ window.__ModuleLoader__.load({
275
448
 
276
449
  async function onResetTelemetry() {
277
450
  try {
278
- await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry', { method: 'POST' });
279
- setTelemetry({ totalViolations: 0, byCode: {}, lastViolation: null });
451
+ const res = await fetch('/api/@goodandready/dsh-agent-loop-guard/telemetry', {
452
+ method: 'POST',
453
+ headers: { 'x-dsh-loop-guard': '1' },
454
+ });
455
+ if (!res.ok) throw new Error('HTTP ' + res.status);
456
+ setTelemetry({ totalViolations: 0, byCode: {}, lastViolation: null, error: null });
280
457
  setMsg(tt('statsResetDone'));
281
- } catch {}
458
+ } catch (err) {
459
+ setMsg(tt('statsResetFailed'));
460
+ }
282
461
  }
283
462
 
284
- const field = (key, input) => React.createElement('div', {
285
- className: 'alg-field',
286
- style: { display: 'flex', flexDirection: 'column', gap: 6, padding: '10px 0' }
287
- },
288
- React.createElement('label', { style: { fontSize: 13, color: 'var(--dsw-alias-label-secondary)' } }, tt(key)),
289
- input
290
- );
463
+ const renderChevron = () => {
464
+ if (PrimitivesChevron) {
465
+ return React.createElement(PrimitivesChevron, {
466
+ className: 'alg-chevron' + (expanded ? ' expanded' : ''),
467
+ style: { width: 14, height: 14, color: 'inherit' }
468
+ });
469
+ }
470
+ return React.createElement('svg', {
471
+ className: 'alg-chevron' + (expanded ? ' expanded' : ''),
472
+ width: 14,
473
+ height: 14,
474
+ viewBox: '0 0 24 24',
475
+ fill: 'none',
476
+ stroke: 'currentColor',
477
+ strokeWidth: 2,
478
+ strokeLinecap: 'round',
479
+ strokeLinejoin: 'round',
480
+ style: { flexShrink: 0 }
481
+ }, React.createElement('polyline', { points: '6 9 12 15 18 9' }));
482
+ };
483
+
484
+ const field = (key, input) => {
485
+ const id = 'alg-' + key;
486
+ const linkedInput = React.isValidElement && React.isValidElement(input)
487
+ ? React.cloneElement(input, { id })
488
+ : input;
489
+ return React.createElement('div', { className: 'alg-field' },
490
+ React.createElement('label', { htmlFor: id }, tt(key)),
491
+ linkedInput
492
+ );
493
+ };
291
494
 
292
495
  const num = (key) => React.createElement('input', {
293
- type: 'number', value: draft[key],
496
+ type: 'number',
497
+ className: 'alg-input',
498
+ value: draft[key],
294
499
  onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
295
- style: { height: 34, border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', color: 'var(--dsw-alias-label-primary)', borderRadius: 8, padding: '0 12px', fontSize: 13 }
296
500
  });
297
501
 
298
502
  const str = (key) => React.createElement('input', {
299
- type: 'text', value: draft[key],
503
+ type: 'text',
504
+ className: 'alg-input',
505
+ value: draft[key],
300
506
  onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.value })),
301
- style: { height: 34, border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', color: 'var(--dsw-alias-label-primary)', borderRadius: 8, padding: '0 12px', fontSize: 13 }
302
507
  });
303
508
 
304
- const check = (key) => React.createElement('label', { style: { display: 'flex', alignItems: 'center', gap: 8, fontSize: 13, color: 'var(--dsw-alias-label-primary)', cursor: 'pointer', padding: '6px 0' } },
509
+ const check = (key) => React.createElement('label', { className: 'alg-checkbox-label' },
305
510
  React.createElement('input', {
306
511
  type: 'checkbox', checked: !!draft[key],
307
512
  onChange: (e) => setDraft((d) => ({ ...d, [key]: e.target.checked }))
@@ -311,45 +516,43 @@ window.__ModuleLoader__.load({
311
516
 
312
517
  return React.createElement('li', {
313
518
  className: 'alg-card',
314
- style: { border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-layer-3)', borderRadius: 12, listStyle: 'none', marginBottom: 12 }
315
519
  },
316
520
  React.createElement('button', {
521
+ className: 'alg-header-btn',
317
522
  onClick: () => setExpanded(!expanded),
318
523
  'aria-expanded': expanded,
319
- style: { appearance: 'none', width: '100%', font: 'inherit', color: 'inherit', textAlign: 'left', cursor: 'pointer', background: '0 0', border: 0, borderRadius: 12, display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px' }
320
524
  },
321
525
  React.createElement('span', { style: { display: 'flex', flexDirection: 'column' } },
322
526
  React.createElement('span', { style: { color: 'var(--dsw-alias-label-primary)', fontSize: 15, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 8 } },
323
- '🛑 ' + tt('title'),
324
- React.createElement('span', { style: { fontSize: 11, fontWeight: 500, padding: '2px 6px', borderRadius: 6, background: 'rgba(59,130,246,0.15)', color: 'var(--dsw-alias-accent-primary, #3b82f6)' } }, 'v' + updateState.currentVersion)
527
+ tt('title'),
528
+ React.createElement('span', { style: { fontSize: 11, fontWeight: 500, padding: '2px 6px', borderRadius: 6, background: 'rgba(59,130,246,0.15)', color: 'var(--dsw-alias-accent-primary, #3b82f6)' } }, updateState.currentVersion ? 'v' + updateState.currentVersion : (updateState.checking ? '…' : '—'))
325
529
  ),
326
530
  React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, tt('sub'))
327
531
  ),
328
- React.createElement('span', { style: { marginLeft: 'auto', color: 'var(--dsw-alias-label-tertiary)' } }, expanded ? '▲' : '▼')
532
+ renderChevron()
329
533
  ),
330
534
  expanded && React.createElement('div', {
331
535
  className: 'alg-body',
332
- style: { padding: '0 16px 16px', borderTop: '1px solid var(--dsw-alias-border-l2)' }
333
536
  },
334
537
  // Section: One-Click Updater
335
538
  React.createElement('div', {
336
539
  style: { padding: '12px 14px', margin: '14px 0', background: 'rgba(255,255,255,0.03)', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', flexWrap: 'wrap', gap: 8 }
337
540
  },
338
541
  React.createElement('div', { style: { fontSize: 13, display: 'flex', alignItems: 'center', gap: 8 } },
339
- React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)' } }, tt('version') + ': ' + updateState.currentVersion),
542
+ React.createElement('span', { style: { color: 'var(--dsw-alias-label-secondary)' } }, tt('version') + ': ' + (updateState.currentVersion || (updateState.checking ? '…' : '—'))),
340
543
  updateState.checking && React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)', fontSize: 12 } }, tt('updateChecking')),
341
544
  !updateState.checking && updateState.updateAvailable && React.createElement('span', { style: { color: '#f59e0b', fontWeight: 600, fontSize: 12 } }, tt('updateAvailable', { v: updateState.latestVersion })),
342
545
  !updateState.checking && !updateState.updateAvailable && !updateState.error && React.createElement('span', { style: { color: '#10b981', fontSize: 12 } }, '✓ ' + tt('upToDate')),
343
- updateState.error && React.createElement('span', { style: { color: '#ef4444', fontSize: 12 } }, updateState.error)
546
+ updateState.error && React.createElement('span', { style: { color: 'var(--dsw-alias-status-danger, #ef4444)', fontSize: 12 } }, updateState.error)
344
547
  ),
345
548
  updateState.updateAvailable && React.createElement('button', {
549
+ className: 'alg-btn-updater',
346
550
  onClick: onTriggerUpdate,
347
551
  disabled: updateState.updating,
348
- style: { padding: '6px 14px', borderRadius: 6, background: 'var(--dsw-alias-accent-primary, #3b82f6)', color: '#fff', border: 0, fontSize: 12, fontWeight: 600, cursor: updateState.updating ? 'default' : 'pointer' }
349
552
  }, updateState.updating ? tt('updating') : tt('updateNow'))
350
553
  ),
351
554
  updateState.notice && React.createElement('div', {
352
- style: { padding: '8px 12px', marginBottom: 12, background: 'rgba(16,185,129,0.1)', color: '#10b981', borderRadius: 6, fontSize: 12, border: '1px solid rgba(16,185,129,0.2)' }
555
+ style: { padding: '8px 12px', marginBottom: 12, background: 'rgba(16,185,129,0.1)', color: 'var(--dsw-alias-status-success, #10b981)', borderRadius: 6, fontSize: 12, border: '1px solid rgba(16,185,129,0.2)' }
353
556
  }, updateState.notice),
354
557
 
355
558
  // Section: Protection Telemetry
@@ -357,21 +560,23 @@ window.__ModuleLoader__.load({
357
560
  style: { padding: '12px 14px', margin: '14px 0', background: 'rgba(255,255,255,0.02)', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)' }
358
561
  },
359
562
  React.createElement('div', { style: { display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 } },
360
- React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, '📊 ' + tt('telemetryTitle')),
563
+ React.createElement('span', { style: { fontSize: 13, fontWeight: 600, color: 'var(--dsw-alias-label-primary)' } }, tt('telemetryTitle')),
361
564
  telemetry.totalViolations > 0 && React.createElement('button', {
565
+ className: 'alg-btn-ghost',
362
566
  onClick: onResetTelemetry,
363
- style: { background: 'transparent', border: '1px solid var(--dsw-alias-border-l2)', color: 'var(--dsw-alias-label-tertiary)', borderRadius: 4, padding: '2px 8px', fontSize: 11, cursor: 'pointer' }
364
567
  }, tt('resetStats'))
365
568
  ),
366
569
  React.createElement('div', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } },
367
- telemetry.totalViolations > 0
368
- ? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
369
- React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: '#f59e0b' } }, telemetry.totalViolations)),
370
- telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
371
- tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
570
+ telemetry.error
571
+ ? React.createElement('span', { style: { color: 'var(--dsw-alias-status-danger, #ef4444)' } }, telemetry.error)
572
+ : telemetry.totalViolations > 0
573
+ ? React.createElement('div', { style: { display: 'flex', flexDirection: 'column', gap: 4 } },
574
+ React.createElement('div', null, tt('totalBlocked') + ': ', React.createElement('strong', { style: { color: '#f59e0b' } }, telemetry.totalViolations)),
575
+ telemetry.lastViolation && React.createElement('div', { style: { color: 'var(--dsw-alias-label-tertiary)' } },
576
+ tt('lastViolation') + ': ' + telemetry.lastViolation.code + ' (' + telemetry.lastViolation.tool + ')'
577
+ )
372
578
  )
373
- )
374
- : React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
579
+ : React.createElement('span', { style: { color: 'var(--dsw-alias-label-tertiary)' } }, tt('noViolations'))
375
580
  )
376
581
  ),
377
582
 
@@ -394,11 +599,11 @@ window.__ModuleLoader__.load({
394
599
  style: { display: 'flex', alignItems: 'center', gap: 12, paddingTop: 14, borderTop: '1px solid var(--dsw-alias-border-l2)', marginTop: 10 }
395
600
  },
396
601
  React.createElement('button', {
602
+ className: 'alg-btn-primary',
397
603
  onClick: onSave,
398
604
  disabled: saving || status !== 'ready',
399
- style: { height: 34, padding: '0 18px', border: 0, borderRadius: 8, background: 'var(--dsw-alias-accent-primary, #3b82f6)', color: '#fff', fontSize: 13, fontWeight: 600, cursor: saving ? 'default' : 'pointer' }
400
605
  }, saving ? tt('saving') : tt('ready')),
401
- msg && React.createElement('span', { style: { fontSize: 13, color: msg === tt('saved') || msg === tt('statsResetDone') ? '#10b981' : '#f87171' } }, msg)
606
+ msg && React.createElement('span', { style: { fontSize: 13, color: msg === tt('saved') || msg === tt('statsResetDone') ? 'var(--dsw-alias-status-success, #10b981)' : 'var(--dsw-alias-status-danger, #ef4444)' } }, msg)
402
607
  )
403
608
  )
404
609
  );
@@ -407,7 +612,11 @@ window.__ModuleLoader__.load({
407
612
  exports.inject = ['slots', 'settingsScope', 'locale'];
408
613
  exports.apply = function apply(ctx) {
409
614
  if (typeof ctx.locale?.register === 'function') {
410
- try { ctx.locale.register(NS, { en, zh }); } catch {}
615
+ if (typeof ctx.effect === 'function') {
616
+ ctx.effect(() => ctx.locale.register(NS, { en, zh }), 'dsh-agent-loop-guard: locale');
617
+ } else {
618
+ ctx.locale.register(NS, { en, zh });
619
+ }
411
620
  }
412
621
 
413
622
  function registerSlotWhenReady(slotName, registerFn) {
@@ -1,4 +1,4 @@
1
- const STOP_REQUEST_PATTERN = /(?:\b(?:stop|halt|cancel|answer(?:\s+now)?)\b|останов(?:ись|ить)|прекрати|хватит|ответь|петл[яиюе])/iu;
1
+ const STOP_REQUEST_PATTERN = /(?:\b(?:stop|halt|cancel|answer(?:\s+now)?)\b|(?<![\p{L}\p{N}_-])стоп(?![\p{L}\p{N}_-])|останов(?:ись|ить)|прекрати|хватит|ответь|петл[яиюе])/iu;
2
2
  const SECRET_KEY_PATTERN = /(?:token|secret|password|authorization|api[-_]?key|cookie)/iu;
3
3
 
4
4
  function stableJson(value) {
@@ -124,6 +124,7 @@ export class LoopGuardState {
124
124
  dryRunMode: Boolean(config.dryRunMode),
125
125
  blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : true,
126
126
  };
127
+ this.logger = config.logger;
127
128
  this.onViolation = typeof config.onViolation === 'function' ? config.onViolation : undefined;
128
129
  this.progressToolNames = new Set(progressToolNames);
129
130
  this.strictTools = new Set(strictTools);
@@ -166,6 +167,7 @@ export class LoopGuardState {
166
167
  dryRunMode: config.dryRunMode !== undefined ? Boolean(config.dryRunMode) : Boolean(this.config.dryRunMode),
167
168
  blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : this.config.blockExactDuplicates,
168
169
  };
170
+ if (config.logger !== undefined) this.logger = config.logger;
169
171
  this.progressToolNames = new Set(progressToolNames);
170
172
  this.strictTools = new Set(strictTools);
171
173
  }
@@ -291,7 +293,11 @@ export class LoopGuardState {
291
293
  dryRun: Boolean(this.config.dryRunMode),
292
294
  ...summary,
293
295
  };
294
- try { this.onViolation?.(event); } catch {}
296
+ try {
297
+ this.onViolation?.(event);
298
+ } catch (error) {
299
+ this.logger?.debug?.('dsh-agent-loop-guard: onViolation callback failed: ' + (error instanceof Error ? error.message : String(error)));
300
+ }
295
301
 
296
302
  if (this.config.dryRunMode) {
297
303
  return undefined;
@@ -430,12 +436,4 @@ export class LoopGuardState {
430
436
  }
431
437
  return { known: outcome.known, productive };
432
438
  }
433
-
434
- releaseCall(agent, callId) {
435
- const state = this.stateFor(agent);
436
- const call = this.findCall(state, callId);
437
- if (call === undefined) return;
438
- call.released = true;
439
- this.decrementReservations(state, call);
440
- }
441
439
  }
package/lib/index.js CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  positiveInteger,
7
7
  } from './guard-state.js';
8
8
  import { AssistantOutputGuardState, assistantTextFromMessage } from './assistant-output-state.js';
9
- import { registerPluginUpdater } from './plugin-updater.js';
9
+ import { registerPluginUpdater, isTrustedTelemetryRequest } from './plugin-updater.js';
10
10
 
11
11
  export const name = '@goodandready/dsh-agent-loop-guard';
12
12
  export const inject = ['tools', 'agents', 'sessions', 'settings'];
@@ -16,7 +16,7 @@ export const Config = Schema.object({
16
16
  maxProgressToolCallsPerTurn: Schema.number().min(1).default(16),
17
17
  progressToolNames: Schema.array(Schema.string()).default(['todo_write']),
18
18
  maxCallsPerRepeatGroup: Schema.number().min(1).default(5),
19
- maxCallsPerToolPerTurn: Schema.number().min(1).default(5),
19
+ maxCallsPerToolPerTurn: Schema.number().min(1).default(5).description('Deprecated: legacy alias for maxCallsPerRepeatGroup'),
20
20
  strictTools: Schema.array(Schema.string()).default([]),
21
21
  strictToolLimit: Schema.number().min(1).default(3),
22
22
  blockExactDuplicates: Schema.boolean().default(true),
@@ -67,7 +67,9 @@ function cancelOnOutputHit(ctx, session, assistantState, hit, state = null) {
67
67
  }
68
68
  try {
69
69
  state?.recordExternalViolation?.('LOOP_GUARD_OUTPUT', hit.reason, { tool: 'assistant/output' });
70
- } catch {}
70
+ } catch (error) {
71
+ ctx.logger?.debug?.('dsh-agent-loop-guard: failed to record external violation: ' + (error instanceof Error ? error.message : String(error)));
72
+ }
71
73
  cancelForOutputLoop(ctx, session, hit.reason);
72
74
  }
73
75
 
@@ -121,6 +123,7 @@ export function apply(ctx, config = {}) {
121
123
  let raw = syncFrom(getConfig());
122
124
  const state = new LoopGuardState({
123
125
  ...raw,
126
+ logger: ctx.logger,
124
127
  onViolation: (event) => logGuardViolation(ctx, event),
125
128
  });
126
129
  const assistantState = new AssistantOutputGuardState({
@@ -131,7 +134,7 @@ export function apply(ctx, config = {}) {
131
134
 
132
135
  const applyLiveConfig = () => {
133
136
  raw = syncFrom(getConfig());
134
- state.updateConfig(raw);
137
+ state.updateConfig({ ...raw, logger: ctx.logger });
135
138
  if (typeof assistantState.updateConfig === 'function') assistantState.updateConfig(raw);
136
139
  };
137
140
 
@@ -170,6 +173,14 @@ export function apply(ctx, config = {}) {
170
173
  kind: 'exact',
171
174
  path: '/api/@goodandready/dsh-agent-loop-guard/telemetry',
172
175
  handler: async (request, response) => {
176
+ if (!isTrustedTelemetryRequest(request)) {
177
+ response.writeHead(403, {
178
+ 'content-type': 'application/json; charset=utf-8',
179
+ 'cache-control': 'no-store',
180
+ });
181
+ response.end(JSON.stringify({ error: 'Rejected non-local or cross-origin telemetry request.' }));
182
+ return;
183
+ }
173
184
  if (request.method === 'GET' || request.method === 'HEAD') {
174
185
  const data = state.getTelemetry();
175
186
  response.writeHead(200, {
@@ -219,62 +230,60 @@ export function apply(ctx, config = {}) {
219
230
  state.recordResult(execution.agent, execution);
220
231
  });
221
232
 
222
- if (true) {
223
- ctx.on('session/event', (session, event) => {
224
- if (raw.assistantOutputGuard === false) return;
225
- if (event.type === 'assistant/chunk') {
226
- const chunk = event.data?.chunk;
227
- if (chunk?.type === 'text-delta') {
228
- const hit = assistantState.observeText(session.id, {
229
- turn: event.data?.turn,
230
- step: event.data?.step,
231
- index: chunk.index,
232
- text: chunk.text,
233
- });
234
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
235
- } else if (chunk?.type === 'block-end') {
236
- const hit = assistantState.endBlock(session.id);
237
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
238
- }
239
- return;
240
- }
241
- if (event.type === 'assistant/message') {
242
- const message = event.data?.message;
243
- const hit = assistantState.observeMessage(session.id, {
244
- id: message?.id ?? event.seq,
233
+ ctx.on('session/event', (session, event) => {
234
+ if (raw.assistantOutputGuard === false) return;
235
+ if (event.type === 'assistant/chunk') {
236
+ const chunk = event.data?.chunk;
237
+ if (chunk?.type === 'text-delta') {
238
+ const hit = assistantState.observeText(session.id, {
245
239
  turn: event.data?.turn,
246
240
  step: event.data?.step,
247
- index: message?.index ?? 0,
248
- text: assistantTextFromMessage(message),
241
+ index: chunk.index,
242
+ text: chunk.text,
249
243
  });
250
244
  cancelOnOutputHit(ctx, session, assistantState, hit, state);
251
- return;
252
- }
253
- if (event.type === 'user/message') {
254
- assistantState.resetForUser(session.id);
255
- return;
256
- }
257
- if (event.type === 'tool/call') {
258
- assistantState.markToolCall(session.id, callIdFromEvent(event));
259
- return;
260
- }
261
- if (event.type === 'tool/result') {
262
- assistantState.markToolResult(session.id, callIdFromEvent(event));
263
- return;
264
- }
265
- if (event.type === 'step/end') {
266
- const hit = assistantState.endStep(session.id);
267
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
268
- return;
269
- }
270
- if (event.type === 'turn/end') {
271
- const hit = assistantState.endTurn(session.id);
245
+ } else if (chunk?.type === 'block-end') {
246
+ const hit = assistantState.endBlock(session.id);
272
247
  cancelOnOutputHit(ctx, session, assistantState, hit, state);
273
- return;
274
248
  }
275
- });
276
- ctx.on('session/disposed', (session) => assistantState.dispose(session.id));
277
- }
249
+ return;
250
+ }
251
+ if (event.type === 'assistant/message') {
252
+ const message = event.data?.message;
253
+ const hit = assistantState.observeMessage(session.id, {
254
+ id: message?.id ?? event.seq,
255
+ turn: event.data?.turn,
256
+ step: event.data?.step,
257
+ index: message?.index ?? 0,
258
+ text: assistantTextFromMessage(message),
259
+ });
260
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
261
+ return;
262
+ }
263
+ if (event.type === 'user/message') {
264
+ assistantState.resetForUser(session.id);
265
+ return;
266
+ }
267
+ if (event.type === 'tool/call') {
268
+ assistantState.markToolCall(session.id, callIdFromEvent(event));
269
+ return;
270
+ }
271
+ if (event.type === 'tool/result') {
272
+ assistantState.markToolResult(session.id, callIdFromEvent(event));
273
+ return;
274
+ }
275
+ if (event.type === 'step/end') {
276
+ const hit = assistantState.endStep(session.id);
277
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
278
+ return;
279
+ }
280
+ if (event.type === 'turn/end') {
281
+ const hit = assistantState.endTurn(session.id);
282
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
283
+ return;
284
+ }
285
+ });
286
+ ctx.on('session/disposed', (session) => assistantState.dispose(session.id));
278
287
 
279
288
  return ctx.tools.guard((execution) => state.denyReason(execution.agent, execution.name, execution.arguments, execution.callId));
280
289
  }