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

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,24 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.28] - 2026-11-10
4
+
5
+ ### Added
6
+ - **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.
7
+ - **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.
8
+
9
+ ### Fixed
10
+ - **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`).
11
+
12
+ ## [0.2.27] - 2026-11-01
13
+
14
+ ### Added
15
+ - **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.
16
+
17
+ ## [0.2.26] - 2026-10-20
18
+
19
+ ### Fixed
20
+ - **Tools Result Payload Forwarding (#125, gh-1)**: Fixed tool outcome tracking in `lib/index.js` where `tools/result` event listener only captured the first argument (`execution`), losing the actual result payload passed as the second argument (`result`) by the DSH runtime (`dsh-tools`). Updated `tools/result` to capture `(execution, result)` and forward `{ ...execution, result }` to `state.recordResult()`. Updated `outcomeFromExecution` and `recordResult` in `lib/guard-state.js` to accept `maybeResult` and extract result payload, properly recognizing successful tool executions as productive progress (`productive: true`), advancing `progressEpoch`, and clearing `exactGroups`. Resolves false-positive `LOOP_GUARD_DUPLICATE` blocks on legitimate retries and eliminates catastrophic lockouts into `answerOnly` mode.
21
+
3
22
  ## [0.2.25] - 2026-10-19
4
23
 
5
24
  ### 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') {
@@ -28,6 +28,88 @@ export function isDefaultStopRequest(text) {
28
28
  return false;
29
29
  }
30
30
 
31
+
32
+
33
+ export function detectOscillation(sequence, maxRepeats = 3, minPeriod = 2, maxPeriod = 4) {
34
+ if (!Array.isArray(sequence)) return null;
35
+ const len = sequence.length;
36
+
37
+ for (let period = minPeriod; period <= maxPeriod; period++) {
38
+ const requiredLength = period * maxRepeats;
39
+ if (len < requiredLength) continue;
40
+
41
+ const sample = sequence.slice(len - period, len);
42
+ const allSame = sample.every((item) => item === sample[0]);
43
+ if (allSame) continue;
44
+
45
+ let isMatch = true;
46
+ for (let rep = 1; rep < maxRepeats; rep++) {
47
+ for (let i = 0; i < period; i++) {
48
+ const expected = sequence[len - period + i];
49
+ const actual = sequence[len - (rep + 1) * period + i];
50
+ if (expected !== actual) {
51
+ isMatch = false;
52
+ break;
53
+ }
54
+ }
55
+ if (!isMatch) break;
56
+ }
57
+
58
+ if (isMatch) {
59
+ return {
60
+ period,
61
+ repeats: maxRepeats,
62
+ cycle: sample,
63
+ };
64
+ }
65
+ }
66
+
67
+ return null;
68
+ }
69
+
70
+ export const DEFAULT_PSEUDO_TOOL_PATTERNS = [
71
+ /<(?:invoke|function_call|tool_call|call:)\b/iu,
72
+ /<\/(?:invoke|function_call|tool_call)>/iu,
73
+ /```(?:tool_call|invoke|function_call)\b/iu,
74
+ /(?:\[TOOL_CALLS?\]|\[(?:TOOL_CALL|CALL):)/iu,
75
+ ];
76
+
77
+ export function compilePseudoToolPatterns(customPatterns = []) {
78
+ if (!Array.isArray(customPatterns)) return [];
79
+ const compiled = [];
80
+ for (const item of customPatterns) {
81
+ if (item instanceof RegExp) {
82
+ compiled.push(item);
83
+ } else if (typeof item === 'string' && item.trim() !== '') {
84
+ try {
85
+ const match = /^\/(.+)\/([a-z]*)$/i.exec(item.trim());
86
+ if (match) {
87
+ compiled.push(new RegExp(match[1], match[2] || 'iu'));
88
+ } else {
89
+ const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, (m) => '\\' + m);
90
+ compiled.push(new RegExp(escaped, 'iu'));
91
+ }
92
+ } catch {
93
+ const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, (m) => '\\' + m);
94
+ compiled.push(new RegExp(escaped, 'iu'));
95
+ }
96
+ }
97
+ }
98
+ return compiled;
99
+ }
100
+
101
+ export function isPseudoToolCallText(text, customPatterns = []) {
102
+ if (!text || typeof text !== 'string') return false;
103
+ for (const regex of DEFAULT_PSEUDO_TOOL_PATTERNS) {
104
+ if (regex.test(text)) return true;
105
+ }
106
+ const compiled = compilePseudoToolPatterns(customPatterns);
107
+ for (const regex of compiled) {
108
+ if (regex.test(text)) return true;
109
+ }
110
+ return false;
111
+ }
112
+
31
113
  export function compileStopPatterns(customPatterns = []) {
32
114
  if (!Array.isArray(customPatterns)) return [];
33
115
  const compiled = [];
@@ -155,20 +237,30 @@ function hasOwn(object, key) {
155
237
  return object !== null && typeof object === 'object' && Object.prototype.hasOwnProperty.call(object, key);
156
238
  }
157
239
 
158
- function outcomeFromExecution(execution) {
240
+ function outcomeFromExecution(execution, maybeResult = undefined) {
241
+ const result = maybeResult !== undefined ? maybeResult : execution?.result;
159
242
  const data = execution?.data;
160
- const hasResult = hasOwn(execution, 'result') || hasOwn(execution, 'output')
161
- || hasOwn(data, 'result') || hasOwn(data, 'output') || hasOwn(execution, 'error');
243
+ const hasResult = result !== undefined
244
+ || hasOwn(execution, 'result')
245
+ || hasOwn(execution, 'output')
246
+ || hasOwn(data, 'result')
247
+ || hasOwn(data, 'output')
248
+ || hasOwn(execution, 'error')
249
+ || hasOwn(execution, 'content')
250
+ || hasOwn(execution, 'isError');
162
251
  if (!hasResult) return { known: false, successful: false, resultFingerprint: '<unknown>', progressToken: '<unknown>' };
163
- const value = execution?.result ?? execution?.output ?? data?.result ?? data?.output
252
+ const value = result ?? execution?.output ?? data?.result ?? data?.output
164
253
  ?? (hasOwn(execution, 'error') ? { error: execution.error } : undefined);
165
254
  const failed = (execution?.error != null && execution?.error !== false)
255
+ || execution?.isError === true
166
256
  || value?.isError === true
167
257
  || value?.success === false
168
258
  || value?.ok === false
169
259
  || (value?.error != null && value?.error !== false);
170
260
  const explicitProgress = execution?.progressToken ?? execution?.progress ?? execution?.stateVersion
171
- ?? data?.progressToken ?? data?.progress ?? data?.stateVersion;
261
+ ?? data?.progressToken ?? data?.progress ?? data?.stateVersion
262
+ ?? value?.progressToken ?? value?.progress ?? value?.stateVersion
263
+ ?? value?.meta?.progressToken;
172
264
  return {
173
265
  known: true,
174
266
  successful: !failed,
@@ -203,8 +295,13 @@ export class LoopGuardState {
203
295
  dryRunMode: Boolean(config.dryRunMode),
204
296
  blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : true,
205
297
  stopPatterns,
298
+ pseudoToolCallThreshold: nonNegativeInteger(config.pseudoToolCallThreshold, 3),
299
+ pseudoToolCallPatterns: Array.isArray(config.pseudoToolCallPatterns) ? config.pseudoToolCallPatterns : [],
300
+ oscillationDetection: config.oscillationDetection !== undefined ? Boolean(config.oscillationDetection) : true,
301
+ maxOscillationRepeats: positiveInteger(config.maxOscillationRepeats, 3),
206
302
  };
207
303
  this.stopPatterns = stopPatterns;
304
+ this.pseudoPatterns = this.config.pseudoToolCallPatterns;
208
305
  this.logger = config.logger;
209
306
  this.onViolation = typeof config.onViolation === 'function' ? config.onViolation : undefined;
210
307
  this.progressToolNames = new Set(progressToolNames);
@@ -222,6 +319,9 @@ export class LoopGuardState {
222
319
  LOOP_GUARD_LIMIT: 0,
223
320
  LOOP_GUARD_PROGRESS_LIMIT: 0,
224
321
  LOOP_GUARD_OUTPUT: 0,
322
+ LOOP_GUARD_PSEUDO_TOOL_CALL: 0,
323
+ LOOP_GUARD_OSCILLATION: 0,
324
+ LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
225
325
  },
226
326
  lastViolation: null,
227
327
  };
@@ -254,6 +354,19 @@ export class LoopGuardState {
254
354
  .map((name) => name.trim());
255
355
  this.config.stopPatterns = this.stopPatterns;
256
356
  }
357
+ if (config.pseudoToolCallThreshold !== undefined) {
358
+ this.config.pseudoToolCallThreshold = nonNegativeInteger(config.pseudoToolCallThreshold, this.config.pseudoToolCallThreshold ?? 3);
359
+ }
360
+ if (Array.isArray(config.pseudoToolCallPatterns)) {
361
+ this.pseudoPatterns = config.pseudoToolCallPatterns;
362
+ this.config.pseudoToolCallPatterns = this.pseudoPatterns;
363
+ }
364
+ if (config.oscillationDetection !== undefined) {
365
+ this.config.oscillationDetection = Boolean(config.oscillationDetection);
366
+ }
367
+ if (config.maxOscillationRepeats !== undefined) {
368
+ this.config.maxOscillationRepeats = positiveInteger(config.maxOscillationRepeats, this.config.maxOscillationRepeats ?? 3);
369
+ }
257
370
  if (config.logger !== undefined) this.logger = config.logger;
258
371
  this.progressToolNames = new Set(progressToolNames);
259
372
  this.strictTools = new Set(strictTools);
@@ -310,6 +423,11 @@ export class LoopGuardState {
310
423
  }
311
424
  return key;
312
425
  }
426
+ if (typeof agent === 'string') {
427
+ if (agent.startsWith('session:') || agent.startsWith('agent:') || agent.startsWith('object:')) return agent;
428
+ if (this.byAgent.has('session:' + agent)) return 'session:' + agent;
429
+ return 'agent:' + agent;
430
+ }
313
431
  return 'agent:' + String(agent ?? 'unknown');
314
432
  }
315
433
 
@@ -330,6 +448,11 @@ export class LoopGuardState {
330
448
  lastResults: new Map(),
331
449
  lastProgress: undefined,
332
450
  lastEvidence: undefined,
451
+ consecutivePseudoTurns: 0,
452
+ turnRealToolCalls: 0,
453
+ turnHadPseudoCall: false,
454
+ turnAssistantText: '',
455
+ recentCallSequence: [],
333
456
  };
334
457
  }
335
458
 
@@ -337,7 +460,9 @@ export class LoopGuardState {
337
460
  const key = this.agentKey(agent);
338
461
  const prior = this.byAgent.get(key);
339
462
  if (prior === undefined || prior.turn !== turn) {
463
+ const consecutivePseudoTurns = prior ? prior.consecutivePseudoTurns : 0;
340
464
  const next = this.emptyState(turn);
465
+ next.consecutivePseudoTurns = consecutivePseudoTurns;
341
466
  next.stopRequested = Boolean(stopRequested);
342
467
  if (stopRequested) next.blockReason = 'LOOP_GUARD_STOP';
343
468
  this.byAgent.set(key, next);
@@ -359,6 +484,65 @@ export class LoopGuardState {
359
484
  return state;
360
485
  }
361
486
 
487
+
488
+ observeAssistantText(agent, text) {
489
+ if (!text || typeof text !== 'string') return;
490
+ const state = this.stateFor(agent);
491
+ if (state.turnHadPseudoCall) return;
492
+ state.turnAssistantText = (state.turnAssistantText + text).slice(-65536);
493
+ if (isPseudoToolCallText(state.turnAssistantText, this.pseudoPatterns)) {
494
+ state.turnHadPseudoCall = true;
495
+ }
496
+ }
497
+
498
+ markRealToolCall(agent) {
499
+ const state = this.stateFor(agent);
500
+ state.turnRealToolCalls += 1;
501
+ state.consecutivePseudoTurns = 0;
502
+ }
503
+
504
+ resetForUser(agent) {
505
+ const state = this.stateFor(agent);
506
+ state.consecutivePseudoTurns = 0;
507
+ state.turnHadPseudoCall = false;
508
+ state.turnRealToolCalls = 0;
509
+ state.turnAssistantText = '';
510
+ state.recentCallSequence = [];
511
+ state.answerOnly = false;
512
+ state.stopReason = '';
513
+ state.blockReason = undefined;
514
+ }
515
+
516
+ endTurn(agent, turnData = {}) {
517
+ const state = this.stateFor(agent);
518
+ state.turnAssistantText = '';
519
+ if (this.config.pseudoToolCallThreshold <= 0) {
520
+ state.turnHadPseudoCall = false;
521
+ state.turnRealToolCalls = 0;
522
+ return undefined;
523
+ }
524
+
525
+ if (state.turnRealToolCalls === 0 && state.turnHadPseudoCall) {
526
+ state.consecutivePseudoTurns += 1;
527
+ if (state.consecutivePseudoTurns >= this.config.pseudoToolCallThreshold) {
528
+ const detail = `model completed ${state.consecutivePseudoTurns} consecutive turns outputting pseudo tool calls with 0 real tool executions`;
529
+ return {
530
+ hit: true,
531
+ code: 'LOOP_GUARD_PSEUDO_TOOL_CALL',
532
+ reason: `LOOP_GUARD_PSEUDO_TOOL_CALL: ${detail}`,
533
+ count: state.consecutivePseudoTurns,
534
+ detail,
535
+ };
536
+ }
537
+ } else if (state.turnRealToolCalls > 0) {
538
+ state.consecutivePseudoTurns = 0;
539
+ }
540
+
541
+ state.turnHadPseudoCall = false;
542
+ state.turnRealToolCalls = 0;
543
+ return undefined;
544
+ }
545
+
362
546
  findCall(state, callId) {
363
547
  if (typeof callId === 'string' && callId.length > 0) {
364
548
  const exact = state.calls.findLast((call) => call.id === callId && !call.released);
@@ -377,6 +561,12 @@ export class LoopGuardState {
377
561
  group.count = Math.max(0, group.count - 1);
378
562
  }
379
563
  }
564
+ if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
565
+ const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
566
+ if (lastIdx !== -1) {
567
+ state.recentCallSequence.splice(lastIdx, 1);
568
+ }
569
+ }
380
570
  if (call.fingerprint) {
381
571
  const exact = state.exactGroups.get(call.fingerprint);
382
572
  if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
@@ -436,6 +626,10 @@ export class LoopGuardState {
436
626
  guidance += `Progress tool "${name}" repeatedly called without task changes. Stop updating task lists and proceed to execute or respond.`;
437
627
  } else if (code === 'LOOP_GUARD_LIMIT') {
438
628
  guidance += `Turn budget of ${this.config.maxToolAttemptsPerTurn} non-productive attempts exhausted. Cease tool execution and explain current progress or roadblock to the user.`;
629
+ } else if (code === 'LOOP_GUARD_OSCILLATION') {
630
+ guidance += 'Alternating sequence of tools was repeated without progress. Break the cycle: alter your strategy, check prerequisites, or answer directly.';
631
+ } else if (code === 'LOOP_GUARD_PSEUDO_TOOL_CALL') {
632
+ 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.';
439
633
  } else {
440
634
  guidance += 'Cease tool execution and provide a final text response. The next user turn will reset this guard.';
441
635
  }
@@ -462,6 +656,23 @@ export class LoopGuardState {
462
656
  const isStrictTool = this.strictTools.has(String(name));
463
657
  const maxRepeats = isStrictTool ? this.config.strictToolLimit : this.config.maxCallsPerRepeatGroup;
464
658
 
659
+ if (this.config.oscillationDetection) {
660
+ const candidateSeq = [...state.recentCallSequence, repeatFingerprint];
661
+ const oscillation = detectOscillation(candidateSeq, this.config.maxOscillationRepeats);
662
+ if (oscillation) {
663
+ const cycleNames = oscillation.cycle.map((fp) => fp.split(':', 1)[0]);
664
+ return this.violation(
665
+ state,
666
+ agent,
667
+ name,
668
+ args,
669
+ callId,
670
+ 'LOOP_GUARD_OSCILLATION',
671
+ `alternating tool execution cycle [${cycleNames.join(' ➔ ')}] repeated ${oscillation.repeats} times without productive progress`
672
+ );
673
+ }
674
+ }
675
+
465
676
  if (this.config.blockExactDuplicates && exactCount >= 1) {
466
677
  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');
467
678
  }
@@ -502,6 +713,8 @@ export class LoopGuardState {
502
713
  };
503
714
  state.calls.push(call);
504
715
  state.attemptsSinceProgress += 1;
716
+ state.recentCallSequence.push(repeatFingerprint);
717
+ if (state.recentCallSequence.length > 32) state.recentCallSequence.shift();
505
718
  if (isProgressTool) state.progressAttemptsSinceProgress += 1;
506
719
  return undefined;
507
720
  }
@@ -515,7 +728,7 @@ export class LoopGuardState {
515
728
  }
516
729
  }
517
730
 
518
- recordResult(agent, execution = {}) {
731
+ recordResult(agent, execution = {}, maybeResult = undefined) {
519
732
  const state = this.stateFor(agent);
520
733
  const call = this.findCall(state, execution.callId);
521
734
  if (call === undefined) return { known: false, productive: false };
@@ -524,7 +737,7 @@ export class LoopGuardState {
524
737
  this.decrementReservations(state, call);
525
738
  return { known: false, productive: false };
526
739
  }
527
- const outcome = outcomeFromExecution(execution);
740
+ const outcome = outcomeFromExecution(execution, maybeResult);
528
741
  call.pending = false;
529
742
  call.committed = true;
530
743
  call.resultSeen = true;
@@ -549,6 +762,7 @@ export class LoopGuardState {
549
762
  state.progressAttemptsSinceProgress = 0;
550
763
  state.repeatGroups.clear();
551
764
  state.exactGroups.clear();
765
+ state.recentCallSequence = [];
552
766
  state.lastProgress = {
553
767
  callId: call.id,
554
768
  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,26 +404,38 @@ 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
- ctx.on('tools/result', (execution) => {
306
- state.recordResult(execution.agent, execution);
413
+ ctx.on('tools/result', (execution, result) => {
414
+ const payload = result !== undefined ? { ...execution, result } : execution;
415
+ state.recordResult(execution?.agent, payload, result);
307
416
  });
308
417
 
309
418
  ctx.on('session/event', (session, event) => {
310
- if (raw.assistantOutputGuard === false) return;
419
+ const outputGuardActive = raw.assistantOutputGuard !== false;
420
+ const pseudoGuardActive = (raw.pseudoToolCallThreshold ?? 3) > 0;
421
+ if (!outputGuardActive && !pseudoGuardActive) return;
422
+
311
423
  if (event.type === 'assistant/chunk') {
312
424
  const chunk = event.data?.chunk;
313
425
  if (chunk?.type === 'text-delta') {
314
- const hit = assistantState.observeText(session.id, {
315
- turn: event.data?.turn,
316
- step: event.data?.step,
317
- index: chunk.index,
318
- text: chunk.text,
319
- });
320
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
321
- } 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) {
322
439
  const hit = assistantState.endBlock(session.id);
323
440
  cancelOnOutputHit(ctx, session, assistantState, hit, state);
324
441
  }
@@ -326,36 +443,54 @@ export function apply(ctx, config = {}) {
326
443
  }
327
444
  if (event.type === 'assistant/message') {
328
445
  const message = event.data?.message;
329
- const hit = assistantState.observeMessage(session.id, {
330
- id: message?.id ?? event.seq,
331
- turn: event.data?.turn,
332
- step: event.data?.step,
333
- index: message?.index ?? 0,
334
- text: assistantTextFromMessage(message),
335
- });
336
- 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
+ }
337
460
  return;
338
461
  }
339
462
  if (event.type === 'user/message') {
340
- assistantState.resetForUser(session.id);
463
+ if (pseudoGuardActive) state.resetForUser(session);
464
+ if (outputGuardActive) assistantState.resetForUser(session.id);
341
465
  return;
342
466
  }
343
467
  if (event.type === 'tool/call') {
344
- assistantState.markToolCall(session.id, callIdFromEvent(event));
468
+ if (pseudoGuardActive) state.markRealToolCall(session);
469
+ if (outputGuardActive) assistantState.markToolCall(session.id, callIdFromEvent(event));
345
470
  return;
346
471
  }
347
472
  if (event.type === 'tool/result') {
348
- assistantState.markToolResult(session.id, callIdFromEvent(event));
473
+ if (outputGuardActive) assistantState.markToolResult(session.id, callIdFromEvent(event));
349
474
  return;
350
475
  }
351
476
  if (event.type === 'step/end') {
352
- const hit = assistantState.endStep(session.id);
353
- cancelOnOutputHit(ctx, session, assistantState, hit, state);
477
+ if (outputGuardActive) {
478
+ const hit = assistantState.endStep(session.id);
479
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
480
+ }
354
481
  return;
355
482
  }
356
483
  if (event.type === 'turn/end') {
357
- const hit = assistantState.endTurn(session.id);
358
- 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
+ }
359
494
  return;
360
495
  }
361
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.25",
3
+ "version": "0.2.28",
4
4
  "description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",