@goodandready/dsh-agent-loop-guard 0.2.26 → 0.2.29

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 CHANGED
@@ -1,5 +1,29 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.29] - 2026-11-12
4
+
5
+ ### Added
6
+ - **Canonical Entry Points & Documentation (#136)**: Added standard project entry files `AGENTS.md` (agent workflow constraints, identity invariants, build commands), `index.md` (project roadmap, architecture, commands, test matrix), and `deploy.sh` (canonical test, identity, and profile installation script). Added `.gitattributes` with `export-ignore` rules, ensuring internal documentation is strictly excluded from npm releases and public GitHub mirrors.
7
+ - **Package Cleanliness & Root Artifact Guard (#137)**: Added `scripts/pack-check.mjs` and `npm run pack:check` script. Enforces that untracked `.tgz` archives cannot reside in the repository root (moved to persistent `~/.dsh/artifacts/`) and validates the strict file size budget (<= 256 KiB) across all packaged files. Added automated unit tests in `test/pack-release.test.js`.
8
+
9
+ ### Fixed
10
+ - **Security Vulnerability Remediations (#138)**: Resolved high-severity vulnerability in `zod` (GHSA-mrhx-c7xc-m3w5) and moderate-severity vulnerability in `fast-uri` (GHSA-w74x-v6f9-j3xg) via explicit `overrides` in `package.json` (`zod >= 4.6.6`, `fast-uri >= 3.1.9`). Cleaned `npm audit --omit=dev` down to 0 vulnerabilities.
11
+ - **Dead Export Removal & Architecture Modularization (#139)**: Removed unused and dead export `DEFAULT_STOP_PATTERNS` from `lib/guard-state.js` in favor of anchored regular expressions `EXPLICIT_STOP_EN` / `EXPLICIT_STOP_ZH` in `isDefaultStopRequest()`. Modularized helper functions, pattern compilers, and fingerprint generators into `lib/guard-helpers.js` with full backward-compatible re-exports, bringing all server files strictly under the 600-line limit and eliminating preflight warnings.
12
+
13
+ ## [0.2.28] - 2026-11-10
14
+
15
+ ### Added
16
+ - **Multi-Tool Oscillation Loop Guard (#130)**: Implemented cycle detection for alternating multi-tool sequences (period $P \in [2, 4]$) repeating $K$ times (default `maxOscillationRepeats = 3`). Prevents runaway ping-pong loops (such as A ➔ B ➔ A ➔ B or A ➔ B ➔ C ➔ A ➔ B ➔ C) when tools repeat cyclical operations without state progression. Triggers `LOOP_GUARD_OSCILLATION` with actionable guidance directing the agent to modify its strategy or provide a direct response. Added `oscillationDetection` (boolean) and `maxOscillationRepeats` (number) settings with `.volatile()` reactivity and UI localization.
17
+ - **Payload Bloat Guard (#131)**: Safeguarded model context window from excessive tool outputs via automatic head/tail truncation for execution results exceeding `maxToolResultChars` (default: 65,536 chars / 64 KB, 0 = disabled). Injects a clear steering banner instructing the agent to use line ranges, grep, head, tail, or save to file instead of dumping entire content. Records `LOOP_GUARD_PAYLOAD_TRUNCATED` in telemetry without failing tool execution. Added `payloadBloatGuard` and `maxToolResultChars` settings with `.volatile()` reactivity and UI controls.
18
+
19
+ ### Fixed
20
+ - **Preflight Empty Catch Elimination (#134)**: Replaced 5 unhandled empty `catch` blocks in `lib/plugin-updater.js` (`findDesktopCliEntry`) and `src/client/50-settings-card.js` with `bestEffort(label, fn, logger)` helper and explicit snapshot sync handling. Ensures clean preflight checks (`FAIL=0`).
21
+
22
+ ## [0.2.27] - 2026-11-01
23
+
24
+ ### Added
25
+ - **Pseudo Tool-Call Runaway Loop Guard (#128, gh-2)**: Implemented fail-closed detection and cancellation for runaway pseudo tool-calls (`LOOP_GUARD_PSEUDO_TOOL_CALL`). When a model gets stuck after a tool failure or hallucination and outputs raw tool-call tags/blocks (e.g. `<invoke name="...">`, `<function_call>`, `<tool_call>`, ```tool_call, `[TOOL_CALL: ...]`) across consecutive turns without triggering real DSH `tool/call` events, the guard monitors turn completions (`turn/end`). If `pseudoToolCallThreshold` (default: 3) consecutive turns complete with pseudo tool-call syntax and 0 real tool executions, the agent is canceled cleanly via `agent.cancel()`. Added `pseudoToolCallThreshold` and `pseudoToolCallPatterns` to Schemastery Config with `.volatile()` reactivity, updated Settings Card with EN/ZH localization, and recorded violations in live telemetry.
26
+
3
27
  ## [0.2.26] - 2026-10-20
4
28
 
5
29
  ### Fixed
package/README.md CHANGED
@@ -107,6 +107,9 @@ When a loop is detected, the guard rejects the call with structured diagnostics
107
107
  | `LOOP_GUARD_LIMIT` | Total non-productive tool attempts since last successful progress | `maxToolAttemptsPerTurn` (64) | Caps turn exploratory budget |
108
108
  | `LOOP_GUARD_PROGRESS_LIMIT` | Successive invocations of progress tools without content changes | `maxProgressToolCallsPerTurn` (16) | Prevents infinite todo-writing loops |
109
109
  | `LOOP_GUARD_OUTPUT` | Assistant generated identical lines or multi-line blocks | `maxRepeatedAssistantLines` (5) | Cancels session cleanly via `agent.cancel()` |
110
+ | `LOOP_GUARD_PSEUDO_TOOL_CALL` | Consecutive completed turns outputting pseudo tool-call syntax (`<invoke>`, etc.) with 0 real tools | `pseudoToolCallThreshold` (3) | Cancels session cleanly via `agent.cancel()` |
111
+ | `LOOP_GUARD_OSCILLATION` | Multi-tool alternating cycle (e.g. A ➔ B ➔ A ➔ B) repeated without state change | `maxOscillationRepeats` (3) | Blocks oscillating loop; provides actionable steering guidance |
112
+ | `LOOP_GUARD_PAYLOAD_TRUNCATED` | Tool execution output exceeded maximum safe result size | `maxToolResultChars` (65536) | Safely truncates oversized payload (head + tail) with steering banner; records in telemetry |
110
113
 
111
114
  ### 3. Assistant Output Stream Guard
112
115
 
@@ -180,6 +183,8 @@ dsh-agent-loop-guard:
180
183
  | `maxRepeatedAssistantLines` | `number` | `5` | Threshold of consecutive identical output lines to trigger session cancellation. |
181
184
  | `maxRepeatedAssistantBlocks` | `number` | `5` | Threshold of repeated multi-line markdown blocks before aborting generation. |
182
185
  | `maxAssistantBlockChars` | `number` | `16384` | Maximum byte length captured for block fingerprinting. |
186
+ | `pseudoToolCallThreshold` | `number` | `3` | Consecutive completed turns with pseudo tool calls and 0 real tools before cancellation (0 = disabled). |
187
+ | `pseudoToolCallPatterns` | `array` | `[]` | Custom regex or string patterns for pseudo tool-call detection. |
183
188
 
184
189
  ---
185
190
 
package/README.ru.md CHANGED
@@ -105,6 +105,9 @@ graph TD
105
105
  | `LOOP_GUARD_LIMIT` | Суммарное число бесплодных попыток за текущий ход | `maxToolAttemptsPerTurn` (64) | Ограничивает общий бюджет холостых действий |
106
106
  | `LOOP_GUARD_PROGRESS_LIMIT` | Повторные вызовы progress-инструментов без реального продвижения | `maxProgressToolCallsPerTurn` (16) | Блокирует бесконечную перезапись todo |
107
107
  | `LOOP_GUARD_OUTPUT` | Модель генерирует одинаковые строки или блоки текста | `maxRepeatedAssistantLines` (5) | Мягко прерывает сессию через `agent.cancel()` |
108
+ | `LOOP_GUARD_PSEUDO_TOOL_CALL` | Зацикливание на выводе псевдовызовов инструментов (`<invoke>` и др.) при 0 реальных вызовов | `pseudoToolCallThreshold` (3) | Чистая отмена сессии через `agent.cancel()` |
109
+ | `LOOP_GUARD_OSCILLATION` | Циклическое чередование инструментов (пинг-понг / осцилляция вида A ➔ B ➔ A ➔ B) без изменения состояния | `maxOscillationRepeats` (3) | Пресекает колебательный цикл; направляет агента сменить стратегию |
110
+ | `LOOP_GUARD_PAYLOAD_TRUNCATED` | Результат работы инструмента превысил лимит допустимого размера | `maxToolResultChars` (65536) | Безопасно усекает аномальный вывод (head + tail) с баннером рекомендаций; фиксирует в телеметрии |
108
111
 
109
112
  ### 3. Предотвращение зацикливания текстового вывода
110
113
 
@@ -178,6 +181,8 @@ dsh-agent-loop-guard:
178
181
  | `maxRepeatedAssistantLines` | `number` | `5` | Порог повторяющихся одинаковых строк текста для прерывания генерации. |
179
182
  | `maxRepeatedAssistantBlocks` | `number` | `5` | Порог повторяющихся многострочных блоков до отмены хода. |
180
183
  | `maxAssistantBlockChars` | `number` | `16384` | Максимальный размер текстового блока для хэширования (в байтах). |
184
+ | `pseudoToolCallThreshold` | `number` | `3` | Порог непрерывных ходов с псевдовызовами без реальных инструментов для отмены сессии (0 = отключено). |
185
+ | `pseudoToolCallPatterns` | `array` | `[]` | Пользовательские регулярные выражения или строки для обнаружения псевдовызовов. |
181
186
 
182
187
  ---
183
188
 
package/README.zh.md CHANGED
@@ -105,6 +105,9 @@ graph TD
105
105
  | `LOOP_GUARD_LIMIT` | 当前回合自上次产出有效进展以来的总无效调用次数超标 | `maxToolAttemptsPerTurn` (64) | 限制单回合探索预算上限 |
106
106
  | `LOOP_GUARD_PROGRESS_LIMIT` | 连续调用进度工具而未产生任何任务变更 | `maxProgressToolCallsPerTurn` (16) | 防止陷入无限修改清单死循环 |
107
107
  | `LOOP_GUARD_OUTPUT` | 智能体在流式输出中重复输出相同单行或完整段落 | `maxRepeatedAssistantLines` (5) | 通过 `agent.cancel()` 安全中断当前输出 |
108
+ | `LOOP_GUARD_PSEUDO_TOOL_CALL` | 连续 completed 回合输出伪工具调用语法(如 `<invoke>`)且 0 次真实工具调用 | `pseudoToolCallThreshold` (3) | 通过 `agent.cancel()` 安全中断当前会话 |
109
+ | `LOOP_GUARD_OSCILLATION` | 多工具交替震荡循环(例如 A ➔ B ➔ A ➔ B 乒乓死循环)且无状态进展 | `maxOscillationRepeats` (3) | 拦截交替空转循环;提示智能体切换策略或直接回答 |
110
+ | `LOOP_GUARD_PAYLOAD_TRUNCATED` | 工具返回结果字符数超出安全阈值 | `maxToolResultChars` (65536) | 安全截断过大输出(保留首尾)并注入引导提示;记录遥测且不中断工具执行 |
108
111
 
109
112
  ### 3. 流式文本防死循环机制
110
113
 
@@ -176,6 +179,8 @@ dsh-agent-loop-guard:
176
179
  | `maxRepeatedAssistantLines` | `number` | `5` | 触发输出中断的连续相同单行阈值。 |
177
180
  | `maxRepeatedAssistantBlocks` | `number` | `5` | 触发输出中断的连续重复段落阈值。 |
178
181
  | `maxAssistantBlockChars` | `number` | `16384` | 捕获用于段落指纹比对的最大字符数。 |
182
+ | `pseudoToolCallThreshold` | `number` | `3` | 伪工具调用空转拦截阈值(连续回合数,0 表示禁用)。 |
183
+ | `pseudoToolCallPatterns` | `array` | `[]` | 自定义伪工具调用文本检测正则表达式或关键词列表。 |
179
184
 
180
185
  ---
181
186
 
package/lib/client.js CHANGED
@@ -124,6 +124,11 @@ window.__ModuleLoader__.load({
124
124
  maxRepeatedAssistantBlocks: 'Max repeated assistant blocks',
125
125
  maxAssistantBlockChars: 'Max assistant block chars',
126
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)',
127
132
  saving: 'Saving…',
128
133
  ready: 'Save Settings',
129
134
  saved: 'Saved',
@@ -162,15 +167,22 @@ window.__ModuleLoader__.load({
162
167
  maxRepeatedAssistantBlocks: '最大段落重复次数',
163
168
  maxAssistantBlockChars: '最大段落判定字符数',
164
169
  progressToolNames: '进度标记工具(逗号分隔)',
170
+ pseudoToolCallThreshold: '伪工具调用空转拦截阈值(连续回合数,0 表示禁用)',
171
+ oscillationDetection: '交替循环拦截(乒乓震荡检测)',
172
+ maxOscillationRepeats: '最大交替循环重复次数(2-4 步序列)',
173
+ payloadBloatGuard: '超大结果防膨胀拦截(截断巨大输出)',
174
+ maxToolResultChars: '工具结果字符上限(0 表示禁用)',
165
175
  saving: '正在保存…',
166
176
  ready: '保存配置',
167
177
  saved: '配置已保存',
168
178
  };
179
+
169
180
  const DEFAULTS = {
170
181
  maxToolAttemptsPerTurn: 64, maxProgressToolCallsPerTurn: 16, progressToolNames: ['todo_write'],
171
182
  maxCallsPerRepeatGroup: 5, strictTools: [], strictToolLimit: 3, blockExactDuplicates: true,
172
183
  dryRunMode: false, assistantOutputGuard: true, maxRepeatedAssistantLines: 5,
173
- maxRepeatedAssistantBlocks: 5, maxAssistantBlockChars: 16384,
184
+ maxRepeatedAssistantBlocks: 5, maxAssistantBlockChars: 16384, pseudoToolCallThreshold: 3,
185
+ oscillationDetection: true, maxOscillationRepeats: 3, payloadBloatGuard: true, maxToolResultChars: 65536,
174
186
  };
175
187
 
176
188
  function PluginCard({ ctx: _ctx, t, bare, ...props }) {
@@ -197,9 +209,7 @@ window.__ModuleLoader__.load({
197
209
 
198
210
  const [, setLocaleTick] = React.useState(0);
199
211
  React.useEffect(() => {
200
- if (typeof _ctx?.locale?.subscribe === 'function') {
201
- return _ctx.locale.subscribe(() => setLocaleTick((c) => c + 1));
202
- }
212
+ if (typeof _ctx?.locale?.subscribe === 'function') return _ctx.locale.subscribe(() => setLocaleTick((c) => c + 1));
203
213
  }, []);
204
214
 
205
215
  const getActiveLocale = () => {
@@ -251,13 +261,10 @@ window.__ModuleLoader__.load({
251
261
  } catch (_) { if (!cancelled) setStatus('unavailable'); }
252
262
 
253
263
  const unsub = typeof scope.subscribe === 'function' ? scope.subscribe(() => {
254
- if (!cancelled && typeof scope.getSnapshot === 'function') { try { syncFromSnapshot(scope.getSnapshot()); } catch (_) {} }
264
+ if (!cancelled && typeof scope.getSnapshot === 'function') { try { syncFromSnapshot(scope.getSnapshot()); } catch (err) { void err; } }
255
265
  }) : null;
256
266
 
257
- return () => {
258
- cancelled = true;
259
- if (typeof unsub === 'function') unsub();
260
- };
267
+ return () => { cancelled = true; if (typeof unsub === 'function') unsub(); };
261
268
  }, [scope]);
262
269
 
263
270
  React.useEffect(() => {
@@ -315,12 +322,12 @@ window.__ModuleLoader__.load({
315
322
  maxCallsPerRepeatGroup: Number(draft.maxCallsPerRepeatGroup) || 5,
316
323
  strictToolLimit: Number(draft.strictToolLimit) || 3,
317
324
  strictTools: strictNames,
318
- blockExactDuplicates: !!draft.blockExactDuplicates,
319
- dryRunMode: !!draft.dryRunMode,
320
- assistantOutputGuard: !!draft.assistantOutputGuard,
321
- maxRepeatedAssistantLines: Number(draft.maxRepeatedAssistantLines) || 5,
322
- maxRepeatedAssistantBlocks: Number(draft.maxRepeatedAssistantBlocks) || 5,
325
+ blockExactDuplicates: !!draft.blockExactDuplicates, dryRunMode: !!draft.dryRunMode, assistantOutputGuard: !!draft.assistantOutputGuard,
326
+ maxRepeatedAssistantLines: Number(draft.maxRepeatedAssistantLines) || 5, maxRepeatedAssistantBlocks: Number(draft.maxRepeatedAssistantBlocks) || 5,
323
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,
324
331
  progressToolNames: names.length ? names : ['todo_write'],
325
332
  };
326
333
  const errs = [];
@@ -488,6 +495,11 @@ window.__ModuleLoader__.load({
488
495
  field('maxRepeatedAssistantBlocks', num('maxRepeatedAssistantBlocks')),
489
496
  field('maxAssistantBlockChars', num('maxAssistantBlockChars')),
490
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')),
491
503
 
492
504
  React.createElement('div', {
493
505
  style: { display: 'flex', alignItems: 'center', gap: 12, paddingTop: 14, borderTop: '1px solid var(--dsw-alias-border-l2)', marginTop: 10 }
@@ -499,21 +511,17 @@ window.__ModuleLoader__.load({
499
511
  )
500
512
  );
501
513
 
502
- if (isBare) {
503
- return React.createElement('div', { className: 'alg-page' }, body);
504
- }
514
+ if (isBare) return React.createElement('div', { className: 'alg-page' }, body);
505
515
  return React.createElement('li', { className: 'alg-card' }, header, expanded && body);
506
516
  }
507
517
 
508
518
  function PluginItem(props) {
509
519
  if (props && props.view === 'summary') {
510
- return React.createElement('div', {
511
- style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 }
512
- }, en.sub);
520
+ return React.createElement('div', { style: { color: 'var(--dsw-alias-label-secondary)', fontSize: 13 } }, en.sub);
513
521
  }
514
- const isBare = Boolean(props && (props.bare || props.view === 'page'));
515
- return React.createElement(PluginCard, { ...props, bare: isBare });
522
+ return React.createElement(PluginCard, { ...props, bare: Boolean(props && (props.bare || props.view === 'page')) });
516
523
  }
524
+
517
525
  exports.inject = ['slots', 'configForms', 'locale'];
518
526
  exports.apply = function apply(ctx) {
519
527
  if (typeof ctx.locale?.register === 'function') {
@@ -0,0 +1,264 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ const EXPLICIT_STOP_EN = /^(?:please\s+)?(?:stop|halt|cancel|abort|terminate)(?:\s+(?:now|please|immediately|execution|calling\s+tools|and\s+answer|and\s+explain))?[.!?]*$/iu;
4
+ const EXPLICIT_STOP_ZH = /^(?:请|检测到)?(?:停止|暂停|取消|终止|死循环)(?:执行|操作|调用|一下|了)?[!。??!]*$/u;
5
+
6
+ export function isDefaultStopRequest(text) {
7
+ if (!text || typeof text !== 'string') return false;
8
+ const trimmed = text.trim();
9
+ if (!trimmed) return false;
10
+
11
+ // Direct single-command match
12
+ if (EXPLICIT_STOP_EN.test(trimmed) || EXPLICIT_STOP_ZH.test(trimmed)) {
13
+ return true;
14
+ }
15
+
16
+ // Multi-sentence / multi-line message: check if any standalone segment/sentence is an explicit stop command
17
+ const segments = trimmed.split(/[\r\n.!?。!?]+/).map((s) => s.trim()).filter(Boolean);
18
+ for (const segment of segments) {
19
+ if (EXPLICIT_STOP_EN.test(segment) || EXPLICIT_STOP_ZH.test(segment)) {
20
+ return true;
21
+ }
22
+ }
23
+
24
+ return false;
25
+ }
26
+
27
+ export function detectOscillation(sequence, maxRepeats = 3, minPeriod = 2, maxPeriod = 4) {
28
+ if (!Array.isArray(sequence)) return null;
29
+ const len = sequence.length;
30
+
31
+ for (let period = minPeriod; period <= maxPeriod; period++) {
32
+ const requiredLength = period * maxRepeats;
33
+ if (len < requiredLength) continue;
34
+
35
+ const sample = sequence.slice(len - period, len);
36
+ const allSame = sample.every((item) => item === sample[0]);
37
+ if (allSame) continue;
38
+
39
+ let isMatch = true;
40
+ for (let rep = 1; rep < maxRepeats; rep++) {
41
+ for (let i = 0; i < period; i++) {
42
+ const expected = sequence[len - period + i];
43
+ const actual = sequence[len - (rep + 1) * period + i];
44
+ if (expected !== actual) {
45
+ isMatch = false;
46
+ break;
47
+ }
48
+ }
49
+ if (!isMatch) break;
50
+ }
51
+
52
+ if (isMatch) {
53
+ return {
54
+ period,
55
+ repeats: maxRepeats,
56
+ cycle: sample,
57
+ };
58
+ }
59
+ }
60
+
61
+ return null;
62
+ }
63
+
64
+ export const DEFAULT_PSEUDO_TOOL_PATTERNS = [
65
+ /<(?:invoke|function_call|tool_call|call:)\b/iu,
66
+ /<\/(?:invoke|function_call|tool_call)>/iu,
67
+ /```(?:tool_call|invoke|function_call)\b/iu,
68
+ /(?:\[TOOL_CALLS?\]|\[(?:TOOL_CALL|CALL):)/iu,
69
+ ];
70
+
71
+ export function compilePseudoToolPatterns(customPatterns = []) {
72
+ if (!Array.isArray(customPatterns)) return [];
73
+ const compiled = [];
74
+ for (const item of customPatterns) {
75
+ if (item instanceof RegExp) {
76
+ compiled.push(item);
77
+ } else if (typeof item === 'string' && item.trim() !== '') {
78
+ try {
79
+ const match = /^\/(.+)\/([a-z]*)$/i.exec(item.trim());
80
+ if (match) {
81
+ compiled.push(new RegExp(match[1], match[2] || 'iu'));
82
+ } else {
83
+ const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, (m) => '\\' + m);
84
+ compiled.push(new RegExp(escaped, 'iu'));
85
+ }
86
+ } catch {
87
+ const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, (m) => '\\' + m);
88
+ compiled.push(new RegExp(escaped, 'iu'));
89
+ }
90
+ }
91
+ }
92
+ return compiled;
93
+ }
94
+
95
+ export function isPseudoToolCallText(text, customPatterns = []) {
96
+ if (!text || typeof text !== 'string') return false;
97
+ for (const regex of DEFAULT_PSEUDO_TOOL_PATTERNS) {
98
+ if (regex.test(text)) return true;
99
+ }
100
+ const compiled = compilePseudoToolPatterns(customPatterns);
101
+ for (const regex of compiled) {
102
+ if (regex.test(text)) return true;
103
+ }
104
+ return false;
105
+ }
106
+
107
+ export function compileStopPatterns(customPatterns = []) {
108
+ if (!Array.isArray(customPatterns)) return [];
109
+ const compiled = [];
110
+ for (const item of customPatterns) {
111
+ if (item instanceof RegExp) {
112
+ compiled.push(item);
113
+ } else if (typeof item === 'string' && item.trim() !== '') {
114
+ const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
115
+ compiled.push(new RegExp(escaped, 'iu'));
116
+ }
117
+ }
118
+ return compiled;
119
+ }
120
+
121
+ const SECRET_KEY_PATTERN = /(?:token|secret|password|authorization|api[-_]?key|cookie)/iu;
122
+
123
+ function stableJson(value) {
124
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
125
+ if (Array.isArray(value)) return '[' + value.map(stableJson).join(',') + ']';
126
+ return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + stableJson(value[key])).join(',') + '}';
127
+ }
128
+
129
+ function normalizedJson(value) {
130
+ if (value === null || typeof value !== 'object') {
131
+ if (typeof value === 'string') return JSON.stringify(value.trim().replace(/\s+/gu, ' '));
132
+ return JSON.stringify(value);
133
+ }
134
+ if (Array.isArray(value)) return '[' + value.map(normalizedJson).join(',') + ']';
135
+ return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + normalizedJson(value[key])).join(',') + '}';
136
+ }
137
+
138
+ function textFrom(value) {
139
+ if (!Array.isArray(value)) return '';
140
+ return value.map((block) => {
141
+ if (block === null || typeof block !== 'object') return '';
142
+ if (typeof block.text === 'string') return block.text;
143
+ if (Array.isArray(block.content)) return textFrom(block.content);
144
+ return '';
145
+ }).join('\n');
146
+ }
147
+
148
+ function safeLogValue(value, depth = 0) {
149
+ if (depth > 3) return '[depth-limit]';
150
+ if (typeof value === 'string') {
151
+ return value.replace(/((?:Bearer|token)\s+)[^\s'"]+/giu, '$1[redacted]')
152
+ .replace(/((?:token|secret|password|authorization|api[-_]?key)=)[^\s&]+/giu, '$1[redacted]')
153
+ .slice(0, 400);
154
+ }
155
+ if (value === null || typeof value !== 'object') return value;
156
+ if (Array.isArray(value)) return value.slice(0, 20).map((item) => safeLogValue(item, depth + 1));
157
+ const output = {};
158
+ for (const [key, item] of Object.entries(value).slice(0, 40)) {
159
+ output[key] = SECRET_KEY_PATTERN.test(key) ? '[redacted]' : safeLogValue(item, depth + 1);
160
+ }
161
+ return output;
162
+ }
163
+
164
+ export function positiveInteger(value, fallback) {
165
+ return Number.isSafeInteger(value) && value >= 1 ? value : fallback;
166
+ }
167
+
168
+ export function nonNegativeInteger(value, fallback) {
169
+ return Number.isSafeInteger(value) && value >= 0 ? value : fallback;
170
+ }
171
+
172
+ export function hasStopRequest(messages, customPatterns = []) {
173
+ if (!Array.isArray(messages)) return false;
174
+ const compiledCustom = compileStopPatterns(customPatterns);
175
+ let lastUserMessage = null;
176
+ for (let i = messages.length - 1; i >= 0; i--) {
177
+ const msg = messages[i];
178
+ if (msg && (msg.source?.kind === 'user' || msg.role === 'user')) {
179
+ lastUserMessage = msg;
180
+ break;
181
+ }
182
+ }
183
+ if (!lastUserMessage) return false;
184
+
185
+ const text = textFrom(lastUserMessage.content);
186
+ if (!text) return false;
187
+
188
+ if (isDefaultStopRequest(text)) {
189
+ return true;
190
+ }
191
+ return compiledCustom.some((regex) => regex.test(text));
192
+ }
193
+
194
+ export function callFingerprint(name, args) {
195
+ try {
196
+ const raw = stableJson(args);
197
+ const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
198
+ return String(name) + ':' + body;
199
+ } catch {
200
+ return String(name) + ':<unserializable>';
201
+ }
202
+ }
203
+
204
+ export function callRepeatFingerprint(name, args) {
205
+ try {
206
+ const raw = normalizedJson(args);
207
+ const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
208
+ return String(name) + ':' + body;
209
+ } catch {
210
+ return String(name) + ':<unserializable>';
211
+ }
212
+ }
213
+
214
+ export function resultFingerprint(value) {
215
+ try {
216
+ const raw = stableJson(value);
217
+ return raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
218
+ } catch {
219
+ return '<unserializable-result>';
220
+ }
221
+ }
222
+
223
+ export function safeCallSummary(name, args) {
224
+ return {
225
+ tool: String(name),
226
+ arguments: safeLogValue(args),
227
+ };
228
+ }
229
+
230
+ function hasOwn(object, key) {
231
+ return object !== null && typeof object === 'object' && Object.prototype.hasOwnProperty.call(object, key);
232
+ }
233
+
234
+ export function outcomeFromExecution(execution, maybeResult = undefined) {
235
+ const result = maybeResult !== undefined ? maybeResult : execution?.result;
236
+ const data = execution?.data;
237
+ const hasResult = result !== undefined
238
+ || hasOwn(execution, 'result')
239
+ || hasOwn(execution, 'output')
240
+ || hasOwn(data, 'result')
241
+ || hasOwn(data, 'output')
242
+ || hasOwn(execution, 'error')
243
+ || hasOwn(execution, 'content')
244
+ || hasOwn(execution, 'isError');
245
+ if (!hasResult) return { known: false, successful: false, resultFingerprint: '<unknown>', progressToken: '<unknown>' };
246
+ const value = result ?? execution?.output ?? data?.result ?? data?.output
247
+ ?? (hasOwn(execution, 'error') ? { error: execution.error } : undefined);
248
+ const failed = (execution?.error != null && execution?.error !== false)
249
+ || execution?.isError === true
250
+ || value?.isError === true
251
+ || value?.success === false
252
+ || value?.ok === false
253
+ || (value?.error != null && value?.error !== false);
254
+ const explicitProgress = execution?.progressToken ?? execution?.progress ?? execution?.stateVersion
255
+ ?? data?.progressToken ?? data?.progress ?? data?.stateVersion
256
+ ?? value?.progressToken ?? value?.progress ?? value?.stateVersion
257
+ ?? value?.meta?.progressToken;
258
+ return {
259
+ known: true,
260
+ successful: !failed,
261
+ resultFingerprint: resultFingerprint(value),
262
+ progressToken: explicitProgress === undefined ? resultFingerprint(value) : resultFingerprint(explicitProgress),
263
+ };
264
+ }
@@ -1,192 +1,37 @@
1
- import { createHash } from 'node:crypto';
2
- export const DEFAULT_STOP_PATTERNS = {
3
- en: /(?<![\p{L}\p{N}_-])(?:stop|halt|cancel|abort|terminate)(?![\p{L}\p{N}_-])/iu,
4
- zh: /(?:停止|暂停|取消|终止|死循环)/u,
1
+ import {
2
+ isDefaultStopRequest,
3
+ detectOscillation,
4
+ DEFAULT_PSEUDO_TOOL_PATTERNS,
5
+ compilePseudoToolPatterns,
6
+ isPseudoToolCallText,
7
+ compileStopPatterns,
8
+ positiveInteger,
9
+ nonNegativeInteger,
10
+ hasStopRequest,
11
+ callFingerprint,
12
+ callRepeatFingerprint,
13
+ resultFingerprint,
14
+ safeCallSummary,
15
+ outcomeFromExecution,
16
+ } from './guard-helpers.js';
17
+
18
+ export {
19
+ isDefaultStopRequest,
20
+ detectOscillation,
21
+ DEFAULT_PSEUDO_TOOL_PATTERNS,
22
+ compilePseudoToolPatterns,
23
+ isPseudoToolCallText,
24
+ compileStopPatterns,
25
+ positiveInteger,
26
+ nonNegativeInteger,
27
+ hasStopRequest,
28
+ callFingerprint,
29
+ callRepeatFingerprint,
30
+ resultFingerprint,
31
+ safeCallSummary,
32
+ outcomeFromExecution,
5
33
  };
6
34
 
7
- const EXPLICIT_STOP_EN = /^(?:please\s+)?(?:stop|halt|cancel|abort|terminate)(?:\s+(?:now|please|immediately|execution|calling\s+tools|and\s+answer|and\s+explain))?[.!?]*$/iu;
8
- const EXPLICIT_STOP_ZH = /^(?:请|检测到)?(?:停止|暂停|取消|终止|死循环)(?:执行|操作|调用|一下|了)?[!。??!]*$/u;
9
-
10
- export function isDefaultStopRequest(text) {
11
- if (!text || typeof text !== 'string') return false;
12
- const trimmed = text.trim();
13
- if (!trimmed) return false;
14
-
15
- // Direct single-command match
16
- if (EXPLICIT_STOP_EN.test(trimmed) || EXPLICIT_STOP_ZH.test(trimmed)) {
17
- return true;
18
- }
19
-
20
- // Multi-sentence / multi-line message: check if any standalone segment/sentence is an explicit stop command
21
- const segments = trimmed.split(/[\r\n.!?。!?]+/).map((s) => s.trim()).filter(Boolean);
22
- for (const segment of segments) {
23
- if (EXPLICIT_STOP_EN.test(segment) || EXPLICIT_STOP_ZH.test(segment)) {
24
- return true;
25
- }
26
- }
27
-
28
- return false;
29
- }
30
-
31
- export function compileStopPatterns(customPatterns = []) {
32
- if (!Array.isArray(customPatterns)) return [];
33
- const compiled = [];
34
- for (const item of customPatterns) {
35
- if (item instanceof RegExp) {
36
- compiled.push(item);
37
- } else if (typeof item === 'string' && item.trim() !== '') {
38
- const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
39
- compiled.push(new RegExp(escaped, 'iu'));
40
- }
41
- }
42
- return compiled;
43
- }
44
-
45
- const SECRET_KEY_PATTERN = /(?:token|secret|password|authorization|api[-_]?key|cookie)/iu;
46
-
47
- function stableJson(value) {
48
- if (value === null || typeof value !== 'object') return JSON.stringify(value);
49
- if (Array.isArray(value)) return '[' + value.map(stableJson).join(',') + ']';
50
- return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + stableJson(value[key])).join(',') + '}';
51
- }
52
-
53
- function normalizedJson(value) {
54
- if (value === null || typeof value !== 'object') {
55
- if (typeof value === 'string') return JSON.stringify(value.trim().replace(/\s+/gu, ' '));
56
- return JSON.stringify(value);
57
- }
58
- if (Array.isArray(value)) return '[' + value.map(normalizedJson).join(',') + ']';
59
- return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + normalizedJson(value[key])).join(',') + '}';
60
- }
61
-
62
- function textFrom(value) {
63
- if (!Array.isArray(value)) return '';
64
- return value.map((block) => {
65
- if (block === null || typeof block !== 'object') return '';
66
- if (typeof block.text === 'string') return block.text;
67
- if (Array.isArray(block.content)) return textFrom(block.content);
68
- return '';
69
- }).join('\n');
70
- }
71
-
72
- function safeLogValue(value, depth = 0) {
73
- if (depth > 3) return '[depth-limit]';
74
- if (typeof value === 'string') {
75
- return value.replace(/((?:Bearer|token)\s+)[^\s'"]+/giu, '$1[redacted]')
76
- .replace(/((?:token|secret|password|authorization|api[-_]?key)=)[^\s&]+/giu, '$1[redacted]')
77
- .slice(0, 400);
78
- }
79
- if (value === null || typeof value !== 'object') return value;
80
- if (Array.isArray(value)) return value.slice(0, 20).map((item) => safeLogValue(item, depth + 1));
81
- const output = {};
82
- for (const [key, item] of Object.entries(value).slice(0, 40)) {
83
- output[key] = SECRET_KEY_PATTERN.test(key) ? '[redacted]' : safeLogValue(item, depth + 1);
84
- }
85
- return output;
86
- }
87
-
88
- export function positiveInteger(value, fallback) {
89
- return Number.isSafeInteger(value) && value >= 1 ? value : fallback;
90
- }
91
-
92
- export function nonNegativeInteger(value, fallback) {
93
- return Number.isSafeInteger(value) && value >= 0 ? value : fallback;
94
- }
95
-
96
- export function hasStopRequest(messages, customPatterns = []) {
97
- if (!Array.isArray(messages)) return false;
98
- const compiledCustom = compileStopPatterns(customPatterns);
99
- let lastUserMessage = null;
100
- for (let i = messages.length - 1; i >= 0; i--) {
101
- const msg = messages[i];
102
- if (msg && (msg.source?.kind === 'user' || msg.role === 'user')) {
103
- lastUserMessage = msg;
104
- break;
105
- }
106
- }
107
- if (!lastUserMessage) return false;
108
-
109
- const text = textFrom(lastUserMessage.content);
110
- if (!text) return false;
111
-
112
- if (isDefaultStopRequest(text)) {
113
- return true;
114
- }
115
- return compiledCustom.some((regex) => regex.test(text));
116
- }
117
-
118
- export function callFingerprint(name, args) {
119
- try {
120
- const raw = stableJson(args);
121
- const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
122
- return String(name) + ':' + body;
123
- } catch {
124
- return String(name) + ':<unserializable>';
125
- }
126
- }
127
-
128
- export function callRepeatFingerprint(name, args) {
129
- try {
130
- const raw = normalizedJson(args);
131
- const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
132
- return String(name) + ':' + body;
133
- } catch {
134
- return String(name) + ':<unserializable>';
135
- }
136
- }
137
-
138
- export function resultFingerprint(value) {
139
- try {
140
- const raw = stableJson(value);
141
- return raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
142
- } catch {
143
- return '<unserializable-result>';
144
- }
145
- }
146
-
147
- export function safeCallSummary(name, args) {
148
- return {
149
- tool: String(name),
150
- arguments: safeLogValue(args),
151
- };
152
- }
153
-
154
- function hasOwn(object, key) {
155
- return object !== null && typeof object === 'object' && Object.prototype.hasOwnProperty.call(object, key);
156
- }
157
-
158
- function outcomeFromExecution(execution, maybeResult = undefined) {
159
- const result = maybeResult !== undefined ? maybeResult : execution?.result;
160
- const data = execution?.data;
161
- const hasResult = result !== undefined
162
- || hasOwn(execution, 'result')
163
- || hasOwn(execution, 'output')
164
- || hasOwn(data, 'result')
165
- || hasOwn(data, 'output')
166
- || hasOwn(execution, 'error')
167
- || hasOwn(execution, 'content')
168
- || hasOwn(execution, 'isError');
169
- if (!hasResult) return { known: false, successful: false, resultFingerprint: '<unknown>', progressToken: '<unknown>' };
170
- const value = result ?? execution?.output ?? data?.result ?? data?.output
171
- ?? (hasOwn(execution, 'error') ? { error: execution.error } : undefined);
172
- const failed = (execution?.error != null && execution?.error !== false)
173
- || execution?.isError === true
174
- || value?.isError === true
175
- || value?.success === false
176
- || value?.ok === false
177
- || (value?.error != null && value?.error !== false);
178
- const explicitProgress = execution?.progressToken ?? execution?.progress ?? execution?.stateVersion
179
- ?? data?.progressToken ?? data?.progress ?? data?.stateVersion
180
- ?? value?.progressToken ?? value?.progress ?? value?.stateVersion
181
- ?? value?.meta?.progressToken;
182
- return {
183
- known: true,
184
- successful: !failed,
185
- resultFingerprint: resultFingerprint(value),
186
- progressToken: explicitProgress === undefined ? resultFingerprint(value) : resultFingerprint(explicitProgress),
187
- };
188
- }
189
-
190
35
  export class LoopGuardState {
191
36
  constructor(config = {}) {
192
37
  const progressToolNames = Array.isArray(config.progressToolNames)
@@ -213,8 +58,13 @@ export class LoopGuardState {
213
58
  dryRunMode: Boolean(config.dryRunMode),
214
59
  blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : true,
215
60
  stopPatterns,
61
+ pseudoToolCallThreshold: nonNegativeInteger(config.pseudoToolCallThreshold, 3),
62
+ pseudoToolCallPatterns: Array.isArray(config.pseudoToolCallPatterns) ? config.pseudoToolCallPatterns : [],
63
+ oscillationDetection: config.oscillationDetection !== undefined ? Boolean(config.oscillationDetection) : true,
64
+ maxOscillationRepeats: positiveInteger(config.maxOscillationRepeats, 3),
216
65
  };
217
66
  this.stopPatterns = stopPatterns;
67
+ this.pseudoPatterns = this.config.pseudoToolCallPatterns;
218
68
  this.logger = config.logger;
219
69
  this.onViolation = typeof config.onViolation === 'function' ? config.onViolation : undefined;
220
70
  this.progressToolNames = new Set(progressToolNames);
@@ -232,6 +82,9 @@ export class LoopGuardState {
232
82
  LOOP_GUARD_LIMIT: 0,
233
83
  LOOP_GUARD_PROGRESS_LIMIT: 0,
234
84
  LOOP_GUARD_OUTPUT: 0,
85
+ LOOP_GUARD_PSEUDO_TOOL_CALL: 0,
86
+ LOOP_GUARD_OSCILLATION: 0,
87
+ LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
235
88
  },
236
89
  lastViolation: null,
237
90
  };
@@ -264,6 +117,19 @@ export class LoopGuardState {
264
117
  .map((name) => name.trim());
265
118
  this.config.stopPatterns = this.stopPatterns;
266
119
  }
120
+ if (config.pseudoToolCallThreshold !== undefined) {
121
+ this.config.pseudoToolCallThreshold = nonNegativeInteger(config.pseudoToolCallThreshold, this.config.pseudoToolCallThreshold ?? 3);
122
+ }
123
+ if (Array.isArray(config.pseudoToolCallPatterns)) {
124
+ this.pseudoPatterns = config.pseudoToolCallPatterns;
125
+ this.config.pseudoToolCallPatterns = this.pseudoPatterns;
126
+ }
127
+ if (config.oscillationDetection !== undefined) {
128
+ this.config.oscillationDetection = Boolean(config.oscillationDetection);
129
+ }
130
+ if (config.maxOscillationRepeats !== undefined) {
131
+ this.config.maxOscillationRepeats = positiveInteger(config.maxOscillationRepeats, this.config.maxOscillationRepeats ?? 3);
132
+ }
267
133
  if (config.logger !== undefined) this.logger = config.logger;
268
134
  this.progressToolNames = new Set(progressToolNames);
269
135
  this.strictTools = new Set(strictTools);
@@ -320,6 +186,11 @@ export class LoopGuardState {
320
186
  }
321
187
  return key;
322
188
  }
189
+ if (typeof agent === 'string') {
190
+ if (agent.startsWith('session:') || agent.startsWith('agent:') || agent.startsWith('object:')) return agent;
191
+ if (this.byAgent.has('session:' + agent)) return 'session:' + agent;
192
+ return 'agent:' + agent;
193
+ }
323
194
  return 'agent:' + String(agent ?? 'unknown');
324
195
  }
325
196
 
@@ -340,6 +211,11 @@ export class LoopGuardState {
340
211
  lastResults: new Map(),
341
212
  lastProgress: undefined,
342
213
  lastEvidence: undefined,
214
+ consecutivePseudoTurns: 0,
215
+ turnRealToolCalls: 0,
216
+ turnHadPseudoCall: false,
217
+ turnAssistantText: '',
218
+ recentCallSequence: [],
343
219
  };
344
220
  }
345
221
 
@@ -347,7 +223,9 @@ export class LoopGuardState {
347
223
  const key = this.agentKey(agent);
348
224
  const prior = this.byAgent.get(key);
349
225
  if (prior === undefined || prior.turn !== turn) {
226
+ const consecutivePseudoTurns = prior ? prior.consecutivePseudoTurns : 0;
350
227
  const next = this.emptyState(turn);
228
+ next.consecutivePseudoTurns = consecutivePseudoTurns;
351
229
  next.stopRequested = Boolean(stopRequested);
352
230
  if (stopRequested) next.blockReason = 'LOOP_GUARD_STOP';
353
231
  this.byAgent.set(key, next);
@@ -369,6 +247,65 @@ export class LoopGuardState {
369
247
  return state;
370
248
  }
371
249
 
250
+
251
+ observeAssistantText(agent, text) {
252
+ if (!text || typeof text !== 'string') return;
253
+ const state = this.stateFor(agent);
254
+ if (state.turnHadPseudoCall) return;
255
+ state.turnAssistantText = (state.turnAssistantText + text).slice(-65536);
256
+ if (isPseudoToolCallText(state.turnAssistantText, this.pseudoPatterns)) {
257
+ state.turnHadPseudoCall = true;
258
+ }
259
+ }
260
+
261
+ markRealToolCall(agent) {
262
+ const state = this.stateFor(agent);
263
+ state.turnRealToolCalls += 1;
264
+ state.consecutivePseudoTurns = 0;
265
+ }
266
+
267
+ resetForUser(agent) {
268
+ const state = this.stateFor(agent);
269
+ state.consecutivePseudoTurns = 0;
270
+ state.turnHadPseudoCall = false;
271
+ state.turnRealToolCalls = 0;
272
+ state.turnAssistantText = '';
273
+ state.recentCallSequence = [];
274
+ state.answerOnly = false;
275
+ state.stopReason = '';
276
+ state.blockReason = undefined;
277
+ }
278
+
279
+ endTurn(agent, turnData = {}) {
280
+ const state = this.stateFor(agent);
281
+ state.turnAssistantText = '';
282
+ if (this.config.pseudoToolCallThreshold <= 0) {
283
+ state.turnHadPseudoCall = false;
284
+ state.turnRealToolCalls = 0;
285
+ return undefined;
286
+ }
287
+
288
+ if (state.turnRealToolCalls === 0 && state.turnHadPseudoCall) {
289
+ state.consecutivePseudoTurns += 1;
290
+ if (state.consecutivePseudoTurns >= this.config.pseudoToolCallThreshold) {
291
+ const detail = `model completed ${state.consecutivePseudoTurns} consecutive turns outputting pseudo tool calls with 0 real tool executions`;
292
+ return {
293
+ hit: true,
294
+ code: 'LOOP_GUARD_PSEUDO_TOOL_CALL',
295
+ reason: `LOOP_GUARD_PSEUDO_TOOL_CALL: ${detail}`,
296
+ count: state.consecutivePseudoTurns,
297
+ detail,
298
+ };
299
+ }
300
+ } else if (state.turnRealToolCalls > 0) {
301
+ state.consecutivePseudoTurns = 0;
302
+ }
303
+
304
+ state.turnHadPseudoCall = false;
305
+ state.turnRealToolCalls = 0;
306
+ return undefined;
307
+ }
308
+
372
309
  findCall(state, callId) {
373
310
  if (typeof callId === 'string' && callId.length > 0) {
374
311
  const exact = state.calls.findLast((call) => call.id === callId && !call.released);
@@ -387,6 +324,12 @@ export class LoopGuardState {
387
324
  group.count = Math.max(0, group.count - 1);
388
325
  }
389
326
  }
327
+ if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
328
+ const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
329
+ if (lastIdx !== -1) {
330
+ state.recentCallSequence.splice(lastIdx, 1);
331
+ }
332
+ }
390
333
  if (call.fingerprint) {
391
334
  const exact = state.exactGroups.get(call.fingerprint);
392
335
  if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
@@ -446,6 +389,10 @@ export class LoopGuardState {
446
389
  guidance += `Progress tool "${name}" repeatedly called without task changes. Stop updating task lists and proceed to execute or respond.`;
447
390
  } else if (code === 'LOOP_GUARD_LIMIT') {
448
391
  guidance += `Turn budget of ${this.config.maxToolAttemptsPerTurn} non-productive attempts exhausted. Cease tool execution and explain current progress or roadblock to the user.`;
392
+ } else if (code === 'LOOP_GUARD_OSCILLATION') {
393
+ guidance += 'Alternating sequence of tools was repeated without progress. Break the cycle: alter your strategy, check prerequisites, or answer directly.';
394
+ } else if (code === 'LOOP_GUARD_PSEUDO_TOOL_CALL') {
395
+ guidance += 'Consecutive turns completed with pseudo tool-call syntax but zero real tool executions. Cease outputting raw <invoke> tags and provide a direct answer, or verify tool syntax.';
449
396
  } else {
450
397
  guidance += 'Cease tool execution and provide a final text response. The next user turn will reset this guard.';
451
398
  }
@@ -472,6 +419,23 @@ export class LoopGuardState {
472
419
  const isStrictTool = this.strictTools.has(String(name));
473
420
  const maxRepeats = isStrictTool ? this.config.strictToolLimit : this.config.maxCallsPerRepeatGroup;
474
421
 
422
+ if (this.config.oscillationDetection) {
423
+ const candidateSeq = [...state.recentCallSequence, repeatFingerprint];
424
+ const oscillation = detectOscillation(candidateSeq, this.config.maxOscillationRepeats);
425
+ if (oscillation) {
426
+ const cycleNames = oscillation.cycle.map((fp) => fp.split(':', 1)[0]);
427
+ return this.violation(
428
+ state,
429
+ agent,
430
+ name,
431
+ args,
432
+ callId,
433
+ 'LOOP_GUARD_OSCILLATION',
434
+ `alternating tool execution cycle [${cycleNames.join(' ➔ ')}] repeated ${oscillation.repeats} times without productive progress`
435
+ );
436
+ }
437
+ }
438
+
475
439
  if (this.config.blockExactDuplicates && exactCount >= 1) {
476
440
  return this.violation(state, agent, name, args, callId, 'LOOP_GUARD_DUPLICATE', 'identical tool call repeated without a new result or state change after ' + exactCount + ' attempts');
477
441
  }
@@ -512,6 +476,8 @@ export class LoopGuardState {
512
476
  };
513
477
  state.calls.push(call);
514
478
  state.attemptsSinceProgress += 1;
479
+ state.recentCallSequence.push(repeatFingerprint);
480
+ if (state.recentCallSequence.length > 32) state.recentCallSequence.shift();
515
481
  if (isProgressTool) state.progressAttemptsSinceProgress += 1;
516
482
  return undefined;
517
483
  }
@@ -559,6 +525,7 @@ export class LoopGuardState {
559
525
  state.progressAttemptsSinceProgress = 0;
560
526
  state.repeatGroups.clear();
561
527
  state.exactGroups.clear();
528
+ state.recentCallSequence = [];
562
529
  state.lastProgress = {
563
530
  callId: call.id,
564
531
  tool: call.fingerprint.split(':', 1)[0],
package/lib/index.js CHANGED
@@ -11,6 +11,73 @@ import { registerPluginUpdater, isTrustedTelemetryRequest } from './plugin-updat
11
11
  export const name = '@goodandready/dsh-agent-loop-guard';
12
12
  export const inject = ['tools', 'agents', 'sessions'];
13
13
 
14
+
15
+ export function truncateText(text, maxChars = 65536, headRatio = 0.7) {
16
+ if (typeof text !== 'string' || text.length <= maxChars || maxChars <= 0) {
17
+ return text;
18
+ }
19
+ const headChars = Math.floor(maxChars * headRatio);
20
+ const tailChars = Math.max(0, maxChars - headChars);
21
+ const totalKb = (text.length / 1024).toFixed(1);
22
+ const limitKb = (maxChars / 1024).toFixed(1);
23
+ const headKb = (headChars / 1024).toFixed(1);
24
+ const tailKb = (tailChars / 1024).toFixed(1);
25
+ const banner = `\n\n... [TRUNCATED: Output size (${totalKb} KB) exceeded limit (${limitKb} KB). Showing first ${headKb} KB and last ${tailKb} KB. Use line ranges, grep, head, tail, or save to file instead of dumping entire content] ...\n\n`;
26
+
27
+ const head = text.slice(0, headChars);
28
+ const tail = tailChars > 0 ? text.slice(-tailChars) : '';
29
+ return head + banner + tail;
30
+ }
31
+
32
+ export function truncateExecutionResult(result, maxChars, state = null, execution = null) {
33
+ if (!result || typeof result !== 'object' || maxChars <= 0) return result;
34
+
35
+ let didTruncate = false;
36
+ let truncatedValue = result.value;
37
+ let truncatedContent = result.content;
38
+
39
+ if (typeof result.value === 'string' && result.value.length > maxChars) {
40
+ truncatedValue = truncateText(result.value, maxChars);
41
+ didTruncate = true;
42
+ } else if (result.value !== null && typeof result.value === 'object') {
43
+ let clonedVal = null;
44
+ for (const key of Object.keys(result.value)) {
45
+ if (typeof result.value[key] === 'string' && result.value[key].length > maxChars) {
46
+ if (!clonedVal) clonedVal = { ...result.value };
47
+ clonedVal[key] = truncateText(result.value[key], maxChars);
48
+ didTruncate = true;
49
+ }
50
+ }
51
+ if (clonedVal) truncatedValue = clonedVal;
52
+ }
53
+
54
+ if (Array.isArray(result.content)) {
55
+ let clonedContent = null;
56
+ for (let i = 0; i < result.content.length; i++) {
57
+ const block = result.content[i];
58
+ if (block && typeof block === 'object' && typeof block.text === 'string' && block.text.length > maxChars) {
59
+ if (!clonedContent) clonedContent = result.content.map((b) => ({ ...b }));
60
+ clonedContent[i].text = truncateText(block.text, maxChars);
61
+ didTruncate = true;
62
+ }
63
+ }
64
+ if (clonedContent) truncatedContent = clonedContent;
65
+ }
66
+
67
+ if (!didTruncate) return result;
68
+
69
+ state?.recordExternalViolation?.('LOOP_GUARD_PAYLOAD_TRUNCATED', `Output truncated (exceeded ${maxChars} chars)`, {
70
+ tool: execution?.name || 'tool',
71
+ turn: state?.turn,
72
+ });
73
+
74
+ return {
75
+ ...result,
76
+ value: truncatedValue,
77
+ content: truncatedContent,
78
+ };
79
+ }
80
+
14
81
  export function isVolatileRef(value) {
15
82
  return value !== null && typeof value === 'object' && !Array.isArray(value) && typeof value.get === 'function';
16
83
  }
@@ -47,6 +114,12 @@ export const Config = Schema.object({
47
114
  maxRepeatedAssistantBlocks: Schema.number().volatile().min(1).default(5),
48
115
  maxAssistantBlockChars: Schema.number().volatile().min(256).default(16_384),
49
116
  stopPatterns: Schema.array(Schema.string()).volatile().default([]),
117
+ pseudoToolCallThreshold: Schema.number().volatile().min(0).default(3),
118
+ pseudoToolCallPatterns: Schema.array(Schema.string()).volatile().default([]),
119
+ oscillationDetection: Schema.boolean().volatile().default(true),
120
+ maxOscillationRepeats: Schema.number().volatile().min(2).default(3),
121
+ payloadBloatGuard: Schema.boolean().volatile().default(true),
122
+ maxToolResultChars: Schema.number().volatile().min(0).default(65_536),
50
123
  });
51
124
 
52
125
  function callIdFromEvent(event) {
@@ -71,6 +144,29 @@ function cancelForOutputLoop(ctx, session, reason) {
71
144
  }
72
145
  }
73
146
 
147
+
148
+ function cancelOnPseudoHit(ctx, session, hit, state = null) {
149
+ if (!hit) return;
150
+ const code = hit.code || 'LOOP_GUARD_PSEUDO_TOOL_CALL';
151
+ const event = {
152
+ code,
153
+ reason: hit.reason,
154
+ session: session.id,
155
+ count: hit.count,
156
+ };
157
+ try {
158
+ ctx.logger?.warn?.('dsh-agent-loop-guard: ' + JSON.stringify(event));
159
+ } catch (error) {
160
+ ctx.logger?.warn?.('dsh-agent-loop-guard: ' + code + ' session=' + session.id);
161
+ }
162
+ try {
163
+ state?.recordExternalViolation?.('LOOP_GUARD_PSEUDO_TOOL_CALL', hit.reason, { tool: 'assistant/output' });
164
+ } catch (error) {
165
+ ctx.logger?.debug?.('dsh-agent-loop-guard: failed to record external violation: ' + (error instanceof Error ? error.message : String(error)));
166
+ }
167
+ cancelForOutputLoop(ctx, session, hit.reason);
168
+ }
169
+
74
170
  function cancelOnOutputHit(ctx, session, assistantState, hit, state = null) {
75
171
  if (!hit || assistantState.hasActiveTool(session.id)) return;
76
172
  const code = String(hit.reason).split(':', 1)[0];
@@ -129,6 +225,9 @@ export function apply(ctx, config = {}) {
129
225
  const stopPatterns = Array.isArray(raw.stopPatterns)
130
226
  ? raw.stopPatterns.filter((t) => typeof t === 'string' && t.trim() !== '').map((t) => t.trim())
131
227
  : [];
228
+ const pseudoToolCallPatterns = Array.isArray(raw.pseudoToolCallPatterns)
229
+ ? raw.pseudoToolCallPatterns.filter((t) => typeof t === 'string' && t.trim() !== '').map((t) => t.trim())
230
+ : [];
132
231
  return {
133
232
  ...raw,
134
233
  maxToolAttemptsPerTurn: nonNegativeInteger(raw.maxToolAttemptsPerTurn, 64),
@@ -143,6 +242,12 @@ export function apply(ctx, config = {}) {
143
242
  maxRepeatedAssistantBlocks: positiveInteger(raw.maxRepeatedAssistantBlocks, 5),
144
243
  maxAssistantBlockChars: positiveInteger(raw.maxAssistantBlockChars, 16_384),
145
244
  stopPatterns,
245
+ pseudoToolCallThreshold: nonNegativeInteger(raw.pseudoToolCallThreshold, 3),
246
+ pseudoToolCallPatterns,
247
+ oscillationDetection: raw.oscillationDetection !== false,
248
+ maxOscillationRepeats: positiveInteger(raw.maxOscillationRepeats, 3),
249
+ payloadBloatGuard: raw.payloadBloatGuard !== false,
250
+ maxToolResultChars: nonNegativeInteger(raw.maxToolResultChars, 65_536),
146
251
  };
147
252
  };
148
253
 
@@ -299,7 +404,10 @@ export function apply(ctx, config = {}) {
299
404
 
300
405
  ctx.on('tools/execute', async (execution, next) => {
301
406
  state.commitCall(execution.agent, execution.callId);
302
- return next();
407
+ state.markRealToolCall(execution.agent);
408
+ const result = await next();
409
+ if (raw.payloadBloatGuard === false || !result || (raw.maxToolResultChars ?? 65_536) <= 0) return result;
410
+ return truncateExecutionResult(result, raw.maxToolResultChars ?? 65_536, state, execution);
303
411
  });
304
412
 
305
413
  ctx.on('tools/result', (execution, result) => {
@@ -308,18 +416,26 @@ export function apply(ctx, config = {}) {
308
416
  });
309
417
 
310
418
  ctx.on('session/event', (session, event) => {
311
- if (raw.assistantOutputGuard === false) return;
419
+ const outputGuardActive = raw.assistantOutputGuard !== false;
420
+ const pseudoGuardActive = (raw.pseudoToolCallThreshold ?? 3) > 0;
421
+ if (!outputGuardActive && !pseudoGuardActive) return;
422
+
312
423
  if (event.type === 'assistant/chunk') {
313
424
  const chunk = event.data?.chunk;
314
425
  if (chunk?.type === 'text-delta') {
315
- const hit = assistantState.observeText(session.id, {
316
- turn: event.data?.turn,
317
- step: event.data?.step,
318
- index: chunk.index,
319
- text: chunk.text,
320
- });
321
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
322
- } else if (chunk?.type === 'block-end') {
426
+ if (pseudoGuardActive && typeof chunk.text === 'string') {
427
+ state.observeAssistantText(session, chunk.text);
428
+ }
429
+ if (outputGuardActive) {
430
+ const hit = assistantState.observeText(session.id, {
431
+ turn: event.data?.turn,
432
+ step: event.data?.step,
433
+ index: chunk.index,
434
+ text: chunk.text,
435
+ });
436
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
437
+ }
438
+ } else if (chunk?.type === 'block-end' && outputGuardActive) {
323
439
  const hit = assistantState.endBlock(session.id);
324
440
  cancelOnOutputHit(ctx, session, assistantState, hit, state);
325
441
  }
@@ -327,36 +443,54 @@ export function apply(ctx, config = {}) {
327
443
  }
328
444
  if (event.type === 'assistant/message') {
329
445
  const message = event.data?.message;
330
- const hit = assistantState.observeMessage(session.id, {
331
- id: message?.id ?? event.seq,
332
- turn: event.data?.turn,
333
- step: event.data?.step,
334
- index: message?.index ?? 0,
335
- text: assistantTextFromMessage(message),
336
- });
337
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
446
+ const text = assistantTextFromMessage(message);
447
+ if (pseudoGuardActive && text) {
448
+ state.observeAssistantText(session, text);
449
+ }
450
+ if (outputGuardActive) {
451
+ const hit = assistantState.observeMessage(session.id, {
452
+ id: message?.id ?? event.seq,
453
+ turn: event.data?.turn,
454
+ step: event.data?.step,
455
+ index: message?.index ?? 0,
456
+ text,
457
+ });
458
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
459
+ }
338
460
  return;
339
461
  }
340
462
  if (event.type === 'user/message') {
341
- assistantState.resetForUser(session.id);
463
+ if (pseudoGuardActive) state.resetForUser(session);
464
+ if (outputGuardActive) assistantState.resetForUser(session.id);
342
465
  return;
343
466
  }
344
467
  if (event.type === 'tool/call') {
345
- assistantState.markToolCall(session.id, callIdFromEvent(event));
468
+ if (pseudoGuardActive) state.markRealToolCall(session);
469
+ if (outputGuardActive) assistantState.markToolCall(session.id, callIdFromEvent(event));
346
470
  return;
347
471
  }
348
472
  if (event.type === 'tool/result') {
349
- assistantState.markToolResult(session.id, callIdFromEvent(event));
473
+ if (outputGuardActive) assistantState.markToolResult(session.id, callIdFromEvent(event));
350
474
  return;
351
475
  }
352
476
  if (event.type === 'step/end') {
353
- const hit = assistantState.endStep(session.id);
354
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
477
+ if (outputGuardActive) {
478
+ const hit = assistantState.endStep(session.id);
479
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
480
+ }
355
481
  return;
356
482
  }
357
483
  if (event.type === 'turn/end') {
358
- const hit = assistantState.endTurn(session.id);
359
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
484
+ if (pseudoGuardActive) {
485
+ const pseudoHit = state.endTurn(session, event.data);
486
+ if (pseudoHit?.hit) {
487
+ cancelOnPseudoHit(ctx, session, pseudoHit, state);
488
+ }
489
+ }
490
+ if (outputGuardActive) {
491
+ const hit = assistantState.endTurn(session.id);
492
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
493
+ }
360
494
  return;
361
495
  }
362
496
  });
@@ -134,7 +134,18 @@ export function isDesktopProfile(profileName, profileDir) {
134
134
  return false;
135
135
  }
136
136
 
137
- export function findDesktopCliEntry() {
137
+ export function bestEffort(label, fn, logger) {
138
+ try {
139
+ return fn();
140
+ } catch (err) {
141
+ if (logger && typeof logger.debug === 'function') {
142
+ logger.debug(`[plugin-updater:bestEffort] ${label}:`, err?.message || err);
143
+ }
144
+ return undefined;
145
+ }
146
+ }
147
+
148
+ export function findDesktopCliEntry(logger) {
138
149
  if (process.env.DSH_DESKTOP_CLI && existsSync(process.env.DSH_DESKTOP_CLI)) {
139
150
  return process.env.DSH_DESKTOP_CLI;
140
151
  }
@@ -145,27 +156,30 @@ export function findDesktopCliEntry() {
145
156
  const pathDirs = pathEnv.split(isWin ? ';' : ':');
146
157
  for (const dir of pathDirs) {
147
158
  if (!dir) continue;
148
- try {
159
+ const hit = bestEffort('probe PATH candidate', () => {
149
160
  const candidate = resolve(dir, cliName);
150
- if (existsSync(candidate)) return candidate;
151
- } catch {}
161
+ return existsSync(candidate) ? candidate : undefined;
162
+ }, logger);
163
+ if (hit) return hit;
152
164
  }
153
165
 
154
166
  if (typeof process.resourcesPath === 'string') {
155
- try {
167
+ const hit = bestEffort('probe resourcesPath candidate', () => {
156
168
  const candidate = resolve(process.resourcesPath, 'runtime', 'cli', 'bin', cliName);
157
- if (existsSync(candidate)) return candidate;
158
- } catch {}
169
+ return existsSync(candidate) ? candidate : undefined;
170
+ }, logger);
171
+ if (hit) return hit;
159
172
  }
160
173
 
161
- try {
174
+ const execHit = bestEffort('probe execDir candidate', () => {
162
175
  const execDir = dirname(process.execPath);
163
176
  const candidate = resolve(execDir, 'resources', 'runtime', 'cli', 'bin', cliName);
164
- if (existsSync(candidate)) return candidate;
165
- } catch {}
177
+ return existsSync(candidate) ? candidate : undefined;
178
+ }, logger);
179
+ if (execHit) return execHit;
166
180
 
167
181
  if (isWin && process.env.LOCALAPPDATA) {
168
- try {
182
+ const hit = bestEffort('probe LOCALAPPDATA candidate', () => {
169
183
  const candidate = resolve(
170
184
  process.env.LOCALAPPDATA,
171
185
  'Programs',
@@ -176,8 +190,9 @@ export function findDesktopCliEntry() {
176
190
  'bin',
177
191
  'dsh.cmd'
178
192
  );
179
- if (existsSync(candidate)) return candidate;
180
- } catch {}
193
+ return existsSync(candidate) ? candidate : undefined;
194
+ }, logger);
195
+ if (hit) return hit;
181
196
  }
182
197
 
183
198
  return undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-agent-loop-guard",
3
- "version": "0.2.26",
3
+ "version": "0.2.29",
4
4
  "description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -21,11 +21,12 @@
21
21
  ],
22
22
  "scripts": {
23
23
  "test": "node --test",
24
- "check": "node --check lib/index.js && node --check lib/guard-state.js && node --check lib/assistant-output-state.js && node --check lib/plugin-updater.js && node --check lib/client.js",
24
+ "check": "node --check lib/index.js && node --check lib/guard-state.js && node --check lib/guard-helpers.js && node --check lib/assistant-output-state.js && node --check lib/plugin-updater.js && node --check lib/client.js && node scripts/pack-check.mjs",
25
25
  "build:client": "node scripts/build-client.mjs",
26
26
  "pretest": "node scripts/build-client.mjs",
27
27
  "clean": "node scripts/clean-pack.mjs",
28
- "pack:release": "node scripts/pack-release.mjs"
28
+ "pack:release": "node scripts/pack-release.mjs",
29
+ "pack:check": "node scripts/pack-check.mjs"
29
30
  },
30
31
  "dsh": {
31
32
  "bundle": {
@@ -56,5 +57,9 @@
56
57
  },
57
58
  "devDependencies": {
58
59
  "@deepseek-ai/schemastery": "^3.18.4"
60
+ },
61
+ "overrides": {
62
+ "zod": "^4.6.6",
63
+ "fast-uri": "^3.1.9"
59
64
  }
60
65
  }