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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -13,24 +13,13 @@ import {
13
13
  resultFingerprint,
14
14
  safeCallSummary,
15
15
  outcomeFromExecution,
16
+ normalizeErrorSignature,
17
+ GUARD_PRESETS,
18
+ formatSteeringAdvice,
19
+ formatViolationGuidance,
16
20
  } from './guard-helpers.js';
17
21
 
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,
33
- };
22
+ export * from './guard-helpers.js';
34
23
 
35
24
  export class LoopGuardState {
36
25
  constructor(config = {}) {
@@ -62,6 +51,9 @@ export class LoopGuardState {
62
51
  pseudoToolCallPatterns: Array.isArray(config.pseudoToolCallPatterns) ? config.pseudoToolCallPatterns : [],
63
52
  oscillationDetection: config.oscillationDetection !== undefined ? Boolean(config.oscillationDetection) : true,
64
53
  maxOscillationRepeats: positiveInteger(config.maxOscillationRepeats, 3),
54
+ errorThrashingGuard: config.errorThrashingGuard !== undefined ? Boolean(config.errorThrashingGuard) : true,
55
+ maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, 4),
56
+ adaptiveSteering: Boolean(config.adaptiveSteering),
65
57
  };
66
58
  this.stopPatterns = stopPatterns;
67
59
  this.pseudoPatterns = this.config.pseudoToolCallPatterns;
@@ -72,9 +64,11 @@ export class LoopGuardState {
72
64
  this.byAgent = new Map();
73
65
  this.objectKeys = new WeakMap();
74
66
  this.nextObjectKey = 1;
67
+ this.incidents = [];
75
68
 
76
69
  this.metrics = {
77
70
  totalViolations: 0,
71
+ steeredCount: 0,
78
72
  byCode: {
79
73
  LOOP_GUARD_STOP: 0,
80
74
  LOOP_GUARD_DUPLICATE: 0,
@@ -85,6 +79,8 @@ export class LoopGuardState {
85
79
  LOOP_GUARD_PSEUDO_TOOL_CALL: 0,
86
80
  LOOP_GUARD_OSCILLATION: 0,
87
81
  LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
82
+ LOOP_GUARD_ERROR_THRASHING: 0,
83
+ LOOP_GUARD_STEER: 0,
88
84
  },
89
85
  lastViolation: null,
90
86
  };
@@ -110,6 +106,9 @@ export class LoopGuardState {
110
106
  strictToolLimit: positiveInteger(config.strictToolLimit, this.config.strictToolLimit ?? 3),
111
107
  dryRunMode: config.dryRunMode !== undefined ? Boolean(config.dryRunMode) : Boolean(this.config.dryRunMode),
112
108
  blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : this.config.blockExactDuplicates,
109
+ errorThrashingGuard: config.errorThrashingGuard !== undefined ? Boolean(config.errorThrashingGuard) : this.config.errorThrashingGuard,
110
+ maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, this.config.maxConsecutiveFailures ?? 4),
111
+ adaptiveSteering: config.adaptiveSteering !== undefined ? Boolean(config.adaptiveSteering) : this.config.adaptiveSteering,
113
112
  };
114
113
  if (Array.isArray(config.stopPatterns)) {
115
114
  this.stopPatterns = config.stopPatterns
@@ -139,6 +138,23 @@ export class LoopGuardState {
139
138
  return hasStopRequest(messages, this.stopPatterns);
140
139
  }
141
140
 
141
+ recordIncident(agent, code, detail, tool = '', state = null) {
142
+ if (!this.incidents) this.incidents = [];
143
+ const chain = state?.recentCallSequence
144
+ ? state.recentCallSequence.slice(-5).map((fp) => fp.split(':', 1)[0])
145
+ : (tool ? [String(tool)] : []);
146
+ this.incidents.push({
147
+ id: 'inc-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6),
148
+ timestamp: Date.now(),
149
+ session: state?.sessionId || this.agentKey(agent),
150
+ code: String(code),
151
+ tool: String(tool || 'system'),
152
+ reason: String(detail || ''),
153
+ chain,
154
+ });
155
+ if (this.incidents.length > 30) this.incidents.shift();
156
+ }
157
+
142
158
  recordExternalViolation(code, detail, extra = {}) {
143
159
  this.metrics.totalViolations += 1;
144
160
  this.metrics.byCode[code] = (this.metrics.byCode[code] || 0) + 1;
@@ -149,6 +165,7 @@ export class LoopGuardState {
149
165
  turn: extra.turn,
150
166
  reason: detail,
151
167
  };
168
+ this.recordIncident(null, code, detail, extra.tool || 'assistant/output', null);
152
169
  }
153
170
 
154
171
  getTelemetry() {
@@ -156,15 +173,18 @@ export class LoopGuardState {
156
173
  ...this.metrics,
157
174
  activeAgents: this.byAgent.size,
158
175
  dryRunMode: Boolean(this.config.dryRunMode),
176
+ incidents: (this.incidents || []).slice(-20).reverse(),
159
177
  };
160
178
  }
161
179
 
162
180
  resetTelemetry() {
163
181
  this.metrics.totalViolations = 0;
182
+ this.metrics.steeredCount = 0;
164
183
  for (const k of Object.keys(this.metrics.byCode)) {
165
184
  this.metrics.byCode[k] = 0;
166
185
  }
167
186
  this.metrics.lastViolation = null;
187
+ this.incidents = [];
168
188
  }
169
189
 
170
190
  disposeSession(sessionId) {
@@ -216,6 +236,10 @@ export class LoopGuardState {
216
236
  turnHadPseudoCall: false,
217
237
  turnAssistantText: '',
218
238
  recentCallSequence: [],
239
+ consecutiveFailures: 0,
240
+ lastErrorSignature: null,
241
+ errorRepeatCount: 0,
242
+ steeredCodes: new Set(),
219
243
  };
220
244
  }
221
245
 
@@ -247,7 +271,6 @@ export class LoopGuardState {
247
271
  return state;
248
272
  }
249
273
 
250
-
251
274
  observeAssistantText(agent, text) {
252
275
  if (!text || typeof text !== 'string') return;
253
276
  const state = this.stateFor(agent);
@@ -274,6 +297,10 @@ export class LoopGuardState {
274
297
  state.answerOnly = false;
275
298
  state.stopReason = '';
276
299
  state.blockReason = undefined;
300
+ state.consecutiveFailures = 0;
301
+ state.lastErrorSignature = null;
302
+ state.errorRepeatCount = 0;
303
+ state.steeredCodes?.clear();
277
304
  }
278
305
 
279
306
  endTurn(agent, turnData = {}) {
@@ -338,6 +365,22 @@ export class LoopGuardState {
338
365
  }
339
366
  }
340
367
 
368
+ handleViolation(state, agent, name, args, callId, code, detail) {
369
+ if (code === 'LOOP_GUARD_STOP' || state.answerOnly) {
370
+ return this.violation(state, agent, name, args, callId, code, detail);
371
+ }
372
+ if (this.config.adaptiveSteering && !state.steeredCodes?.has(code)) {
373
+ if (!state.steeredCodes) state.steeredCodes = new Set();
374
+ state.steeredCodes.add(code);
375
+ this.metrics.steeredCount = (this.metrics.steeredCount || 0) + 1;
376
+ this.recordIncident(agent, 'LOOP_GUARD_STEER', `${code}: ${detail}`, name, state);
377
+
378
+ const advice = formatSteeringAdvice(code, detail, name);
379
+ return `[LOOP_GUARD_STEER] Warning: ${advice} If this pattern continues, tool execution will be terminated for this turn.`;
380
+ }
381
+ return this.violation(state, agent, name, args, callId, code, detail);
382
+ }
383
+
341
384
  violation(state, agent, name, args, callId, code, detail) {
342
385
  this.metrics.totalViolations += 1;
343
386
  this.metrics.byCode[code] = (this.metrics.byCode[code] || 0) + 1;
@@ -348,6 +391,7 @@ export class LoopGuardState {
348
391
  turn: state.turn,
349
392
  reason: detail,
350
393
  };
394
+ this.recordIncident(agent, code, detail, name, state);
351
395
 
352
396
  const summary = safeCallSummary(name, args);
353
397
  const event = {
@@ -378,26 +422,7 @@ export class LoopGuardState {
378
422
  state.blockReason = code;
379
423
  }
380
424
 
381
- let guidance = 'ACTION REQUIRED: ';
382
- if (code === 'LOOP_GUARD_STOP') {
383
- guidance += 'User requested stop. Do NOT invoke further tools. Synthesize your final answer in plain text.';
384
- } else if (code === 'LOOP_GUARD_DUPLICATE') {
385
- guidance += `Tool "${name}" was called with identical arguments without producing new results. Stop repeating this action. Analyze the previous output, alter your parameters, try a different tool, or synthesize a direct textual answer.`;
386
- } else if (code === 'LOOP_GUARD_REPEAT') {
387
- guidance += `Tool "${name}" reached repetition limit without progress. Switch to an alternative exploration approach or answer directly.`;
388
- } else if (code === 'LOOP_GUARD_PROGRESS_LIMIT') {
389
- guidance += `Progress tool "${name}" repeatedly called without task changes. Stop updating task lists and proceed to execute or respond.`;
390
- } else if (code === 'LOOP_GUARD_LIMIT') {
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.';
396
- } else {
397
- guidance += 'Cease tool execution and provide a final text response. The next user turn will reset this guard.';
398
- }
399
-
400
- return `[${code}] ${detail}. No productive progress was observed; provide the final text answer now. ${guidance}`;
425
+ return formatViolationGuidance(code, detail, name, this.config);
401
426
  }
402
427
 
403
428
  denyReason(agent, name, args, callId) {
@@ -424,7 +449,7 @@ export class LoopGuardState {
424
449
  const oscillation = detectOscillation(candidateSeq, this.config.maxOscillationRepeats);
425
450
  if (oscillation) {
426
451
  const cycleNames = oscillation.cycle.map((fp) => fp.split(':', 1)[0]);
427
- return this.violation(
452
+ return this.handleViolation(
428
453
  state,
429
454
  agent,
430
455
  name,
@@ -436,13 +461,26 @@ export class LoopGuardState {
436
461
  }
437
462
  }
438
463
 
464
+ if (this.config.errorThrashingGuard && (state.consecutiveFailures >= this.config.maxConsecutiveFailures || (state.errorRepeatCount >= this.config.maxConsecutiveFailures && state.lastErrorSignature))) {
465
+ const sig = state.lastErrorSignature || 'UNKNOWN_ERROR';
466
+ return this.handleViolation(
467
+ state,
468
+ agent,
469
+ name,
470
+ args,
471
+ callId,
472
+ 'LOOP_GUARD_ERROR_THRASHING',
473
+ `tool calls produced ${state.consecutiveFailures} consecutive failures (signature: ${sig}) without productive progress`
474
+ );
475
+ }
476
+
439
477
  if (this.config.blockExactDuplicates && exactCount >= 1) {
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');
478
+ return this.handleViolation(state, agent, name, args, callId, 'LOOP_GUARD_DUPLICATE', 'identical tool call repeated without a new result or state change after ' + exactCount + ' attempts');
441
479
  }
442
480
 
443
481
  if (repeatCount >= maxRepeats) {
444
482
  const code = (this.config.blockExactDuplicates && exactCount >= maxRepeats) ? 'LOOP_GUARD_DUPLICATE' : 'LOOP_GUARD_REPEAT';
445
- return this.violation(state, agent, name, args, callId, code, 'near-identical tool call repeated without a new result or state change after ' + repeatCount + ' attempts');
483
+ return this.handleViolation(state, agent, name, args, callId, code, 'near-identical tool call repeated without a new result or state change after ' + repeatCount + ' attempts');
446
484
  }
447
485
  const isProgressTool = this.progressToolNames.has(String(name));
448
486
  if (isProgressTool) {
@@ -506,6 +544,18 @@ export class LoopGuardState {
506
544
  call.resultSeen = true;
507
545
  call.resultFingerprint = outcome.resultFingerprint;
508
546
  call.progressToken = outcome.progressToken;
547
+
548
+ if (!outcome.successful) {
549
+ state.consecutiveFailures = (state.consecutiveFailures || 0) + 1;
550
+ const errorSig = normalizeErrorSignature(outcome.errorValue || execution?.error || maybeResult);
551
+ if (state.lastErrorSignature === errorSig) {
552
+ state.errorRepeatCount = (state.errorRepeatCount || 0) + 1;
553
+ } else {
554
+ state.lastErrorSignature = errorSig;
555
+ state.errorRepeatCount = 1;
556
+ }
557
+ }
558
+
509
559
  const prior = state.lastEvidence;
510
560
  const priorForCall = state.lastResults.get(call.repeatFingerprint);
511
561
  const resultUnchangedForCall = priorForCall !== undefined
@@ -523,6 +573,10 @@ export class LoopGuardState {
523
573
  state.progressEpoch += 1;
524
574
  state.attemptsSinceProgress = 0;
525
575
  state.progressAttemptsSinceProgress = 0;
576
+ state.consecutiveFailures = 0;
577
+ state.lastErrorSignature = null;
578
+ state.errorRepeatCount = 0;
579
+ state.steeredCodes?.clear();
526
580
  state.repeatGroups.clear();
527
581
  state.exactGroups.clear();
528
582
  state.recentCallSequence = [];
package/lib/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import Schema from '@deepseek-ai/schemastery';
2
2
  import {
3
3
  LoopGuardState,
4
+ GUARD_PRESETS,
4
5
  hasStopRequest,
5
6
  nonNegativeInteger,
6
7
  positiveInteger,
@@ -120,6 +121,9 @@ export const Config = Schema.object({
120
121
  maxOscillationRepeats: Schema.number().volatile().min(2).default(3),
121
122
  payloadBloatGuard: Schema.boolean().volatile().default(true),
122
123
  maxToolResultChars: Schema.number().volatile().min(0).default(65_536),
124
+ errorThrashingGuard: Schema.boolean().volatile().default(true),
125
+ maxConsecutiveFailures: Schema.number().volatile().min(2).default(4),
126
+ adaptiveSteering: Schema.boolean().volatile().default(true),
123
127
  });
124
128
 
125
129
  function callIdFromEvent(event) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-agent-loop-guard",
3
- "version": "0.2.29",
3
+ "version": "0.3.0",
4
4
  "description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",