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

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,19 @@ import {
13
13
  resultFingerprint,
14
14
  safeCallSummary,
15
15
  outcomeFromExecution,
16
+ normalizeErrorSignature,
17
+ GUARD_PRESETS,
18
+ formatSteeringAdvice,
19
+ formatViolationGuidance,
20
+ extractTargetKey,
21
+ classifyToolAction,
22
+ checkTargetQuota,
23
+ recordTargetOutcome,
24
+ decrementReservations,
25
+ handleTargetViolation,
16
26
  } from './guard-helpers.js';
17
27
 
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
- };
28
+ export * from './guard-helpers.js';
34
29
 
35
30
  export class LoopGuardState {
36
31
  constructor(config = {}) {
@@ -62,6 +57,14 @@ export class LoopGuardState {
62
57
  pseudoToolCallPatterns: Array.isArray(config.pseudoToolCallPatterns) ? config.pseudoToolCallPatterns : [],
63
58
  oscillationDetection: config.oscillationDetection !== undefined ? Boolean(config.oscillationDetection) : true,
64
59
  maxOscillationRepeats: positiveInteger(config.maxOscillationRepeats, 3),
60
+ errorThrashingGuard: config.errorThrashingGuard !== undefined ? Boolean(config.errorThrashingGuard) : true,
61
+ maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, 4),
62
+ adaptiveSteering: Boolean(config.adaptiveSteering),
63
+ targetQuotaGuard: config.targetQuotaGuard !== undefined ? Boolean(config.targetQuotaGuard) : true,
64
+ maxUnchangedReadsPerTarget: config.maxUnchangedReadsPerTarget !== undefined ? positiveInteger(config.maxUnchangedReadsPerTarget, 3) : Math.max(3, positiveInteger(config.maxCallsPerRepeatGroup, 5)),
65
+ maxReadsPerTarget: positiveInteger(config.maxReadsPerTarget, 6),
66
+ maxEditsPerTarget: positiveInteger(config.maxEditsPerTarget, 8),
67
+ maxTargetAttempts: positiveInteger(config.maxTargetAttempts, 12),
65
68
  };
66
69
  this.stopPatterns = stopPatterns;
67
70
  this.pseudoPatterns = this.config.pseudoToolCallPatterns;
@@ -72,19 +75,17 @@ export class LoopGuardState {
72
75
  this.byAgent = new Map();
73
76
  this.objectKeys = new WeakMap();
74
77
  this.nextObjectKey = 1;
78
+ this.incidents = [];
75
79
 
76
80
  this.metrics = {
77
81
  totalViolations: 0,
82
+ steeredCount: 0,
78
83
  byCode: {
79
- LOOP_GUARD_STOP: 0,
80
- LOOP_GUARD_DUPLICATE: 0,
81
- LOOP_GUARD_REPEAT: 0,
82
- LOOP_GUARD_LIMIT: 0,
83
- LOOP_GUARD_PROGRESS_LIMIT: 0,
84
- LOOP_GUARD_OUTPUT: 0,
85
- LOOP_GUARD_PSEUDO_TOOL_CALL: 0,
86
- LOOP_GUARD_OSCILLATION: 0,
87
- LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
84
+ LOOP_GUARD_STOP: 0, LOOP_GUARD_DUPLICATE: 0, LOOP_GUARD_REPEAT: 0,
85
+ LOOP_GUARD_LIMIT: 0, LOOP_GUARD_PROGRESS_LIMIT: 0, LOOP_GUARD_OUTPUT: 0,
86
+ LOOP_GUARD_PSEUDO_TOOL_CALL: 0, LOOP_GUARD_OSCILLATION: 0, LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
87
+ LOOP_GUARD_ERROR_THRASHING: 0, LOOP_GUARD_STEER: 0, LOOP_GUARD_TARGET_QUOTA: 0,
88
+ LOOP_GUARD_UNREFRESHED_READ: 0,
88
89
  },
89
90
  lastViolation: null,
90
91
  };
@@ -110,6 +111,14 @@ export class LoopGuardState {
110
111
  strictToolLimit: positiveInteger(config.strictToolLimit, this.config.strictToolLimit ?? 3),
111
112
  dryRunMode: config.dryRunMode !== undefined ? Boolean(config.dryRunMode) : Boolean(this.config.dryRunMode),
112
113
  blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : this.config.blockExactDuplicates,
114
+ errorThrashingGuard: config.errorThrashingGuard !== undefined ? Boolean(config.errorThrashingGuard) : this.config.errorThrashingGuard,
115
+ maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, this.config.maxConsecutiveFailures ?? 4),
116
+ adaptiveSteering: config.adaptiveSteering !== undefined ? Boolean(config.adaptiveSteering) : this.config.adaptiveSteering,
117
+ targetQuotaGuard: config.targetQuotaGuard !== undefined ? Boolean(config.targetQuotaGuard) : this.config.targetQuotaGuard,
118
+ maxUnchangedReadsPerTarget: config.maxUnchangedReadsPerTarget !== undefined ? positiveInteger(config.maxUnchangedReadsPerTarget, 3) : (this.config.maxUnchangedReadsPerTarget ?? 3),
119
+ maxReadsPerTarget: positiveInteger(config.maxReadsPerTarget, this.config.maxReadsPerTarget ?? 6),
120
+ maxEditsPerTarget: positiveInteger(config.maxEditsPerTarget, this.config.maxEditsPerTarget ?? 8),
121
+ maxTargetAttempts: positiveInteger(config.maxTargetAttempts, this.config.maxTargetAttempts ?? 12),
113
122
  };
114
123
  if (Array.isArray(config.stopPatterns)) {
115
124
  this.stopPatterns = config.stopPatterns
@@ -139,6 +148,23 @@ export class LoopGuardState {
139
148
  return hasStopRequest(messages, this.stopPatterns);
140
149
  }
141
150
 
151
+ recordIncident(agent, code, detail, tool = '', state = null) {
152
+ if (!this.incidents) this.incidents = [];
153
+ const chain = state?.recentCallSequence
154
+ ? state.recentCallSequence.slice(-5).map((fp) => fp.split(':', 1)[0])
155
+ : (tool ? [String(tool)] : []);
156
+ this.incidents.push({
157
+ id: 'inc-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6),
158
+ timestamp: Date.now(),
159
+ session: state?.sessionId || this.agentKey(agent),
160
+ code: String(code),
161
+ tool: String(tool || 'system'),
162
+ reason: String(detail || ''),
163
+ chain,
164
+ });
165
+ if (this.incidents.length > 30) this.incidents.shift();
166
+ }
167
+
142
168
  recordExternalViolation(code, detail, extra = {}) {
143
169
  this.metrics.totalViolations += 1;
144
170
  this.metrics.byCode[code] = (this.metrics.byCode[code] || 0) + 1;
@@ -149,6 +175,7 @@ export class LoopGuardState {
149
175
  turn: extra.turn,
150
176
  reason: detail,
151
177
  };
178
+ this.recordIncident(null, code, detail, extra.tool || 'assistant/output', null);
152
179
  }
153
180
 
154
181
  getTelemetry() {
@@ -156,15 +183,18 @@ export class LoopGuardState {
156
183
  ...this.metrics,
157
184
  activeAgents: this.byAgent.size,
158
185
  dryRunMode: Boolean(this.config.dryRunMode),
186
+ incidents: (this.incidents || []).slice(-20).reverse(),
159
187
  };
160
188
  }
161
189
 
162
190
  resetTelemetry() {
163
191
  this.metrics.totalViolations = 0;
192
+ this.metrics.steeredCount = 0;
164
193
  for (const k of Object.keys(this.metrics.byCode)) {
165
194
  this.metrics.byCode[k] = 0;
166
195
  }
167
196
  this.metrics.lastViolation = null;
197
+ this.incidents = [];
168
198
  }
169
199
 
170
200
  disposeSession(sessionId) {
@@ -196,26 +226,14 @@ export class LoopGuardState {
196
226
 
197
227
  emptyState(turn = undefined) {
198
228
  return {
199
- turn,
200
- attemptsSinceProgress: 0,
201
- progressAttemptsSinceProgress: 0,
202
- calls: [],
203
- nextCallKey: 1,
204
- stopRequested: false,
205
- answerOnly: false,
206
- stopReason: '',
207
- blockReason: undefined,
208
- progressEpoch: 0,
209
- repeatGroups: new Map(),
210
- exactGroups: new Map(),
211
- lastResults: new Map(),
212
- lastProgress: undefined,
213
- lastEvidence: undefined,
214
- consecutivePseudoTurns: 0,
215
- turnRealToolCalls: 0,
216
- turnHadPseudoCall: false,
217
- turnAssistantText: '',
218
- recentCallSequence: [],
229
+ turn, attemptsSinceProgress: 0, progressAttemptsSinceProgress: 0, calls: [],
230
+ nextCallKey: 1, stopRequested: false, answerOnly: false, stopReason: '',
231
+ blockReason: undefined, progressEpoch: 0, repeatGroups: new Map(),
232
+ exactGroups: new Map(), lastResults: new Map(), lastProgress: undefined,
233
+ lastEvidence: undefined, consecutivePseudoTurns: 0, turnRealToolCalls: 0,
234
+ turnHadPseudoCall: false, turnAssistantText: '', recentCallSequence: [],
235
+ consecutiveFailures: 0, lastErrorSignature: null, errorRepeatCount: 0,
236
+ steeredCodes: new Set(), targetCallCounts: new Map(), targetReadFingerprints: new Map(),
219
237
  };
220
238
  }
221
239
 
@@ -247,7 +265,6 @@ export class LoopGuardState {
247
265
  return state;
248
266
  }
249
267
 
250
-
251
268
  observeAssistantText(agent, text) {
252
269
  if (!text || typeof text !== 'string') return;
253
270
  const state = this.stateFor(agent);
@@ -274,6 +291,12 @@ export class LoopGuardState {
274
291
  state.answerOnly = false;
275
292
  state.stopReason = '';
276
293
  state.blockReason = undefined;
294
+ state.consecutiveFailures = 0;
295
+ state.lastErrorSignature = null;
296
+ state.errorRepeatCount = 0;
297
+ state.steeredCodes?.clear();
298
+ state.targetCallCounts?.clear();
299
+ state.targetReadFingerprints?.clear();
277
300
  }
278
301
 
279
302
  endTurn(agent, turnData = {}) {
@@ -315,27 +338,23 @@ export class LoopGuardState {
315
338
  }
316
339
 
317
340
  decrementReservations(state, call) {
318
- if (!call || !call.counted || call.committed) return;
319
- state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
320
- if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
321
- if (call.repeatFingerprint) {
322
- const group = state.repeatGroups.get(call.repeatFingerprint);
323
- if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
324
- group.count = Math.max(0, group.count - 1);
325
- }
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
- }
341
+ decrementReservations(state, call);
342
+ }
343
+
344
+ handleViolation(state, agent, name, args, callId, code, detail) {
345
+ if (code === 'LOOP_GUARD_STOP' || state.answerOnly) {
346
+ return this.violation(state, agent, name, args, callId, code, detail);
332
347
  }
333
- if (call.fingerprint) {
334
- const exact = state.exactGroups.get(call.fingerprint);
335
- if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
336
- exact.count = Math.max(0, exact.count - 1);
337
- }
348
+ if (this.config.adaptiveSteering && !state.steeredCodes?.has(code)) {
349
+ if (!state.steeredCodes) state.steeredCodes = new Set();
350
+ state.steeredCodes.add(code);
351
+ this.metrics.steeredCount = (this.metrics.steeredCount || 0) + 1;
352
+ this.recordIncident(agent, 'LOOP_GUARD_STEER', `${code}: ${detail}`, name, state);
353
+
354
+ const advice = formatSteeringAdvice(code, detail, name);
355
+ return `[LOOP_GUARD_STEER] Warning: ${advice} If this pattern continues, tool execution will be terminated for this turn.`;
338
356
  }
357
+ return this.violation(state, agent, name, args, callId, code, detail);
339
358
  }
340
359
 
341
360
  violation(state, agent, name, args, callId, code, detail) {
@@ -348,6 +367,7 @@ export class LoopGuardState {
348
367
  turn: state.turn,
349
368
  reason: detail,
350
369
  };
370
+ this.recordIncident(agent, code, detail, name, state);
351
371
 
352
372
  const summary = safeCallSummary(name, args);
353
373
  const event = {
@@ -378,26 +398,7 @@ export class LoopGuardState {
378
398
  state.blockReason = code;
379
399
  }
380
400
 
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}`;
401
+ return formatViolationGuidance(code, detail, name, this.config);
401
402
  }
402
403
 
403
404
  denyReason(agent, name, args, callId) {
@@ -424,7 +425,7 @@ export class LoopGuardState {
424
425
  const oscillation = detectOscillation(candidateSeq, this.config.maxOscillationRepeats);
425
426
  if (oscillation) {
426
427
  const cycleNames = oscillation.cycle.map((fp) => fp.split(':', 1)[0]);
427
- return this.violation(
428
+ return this.handleViolation(
428
429
  state,
429
430
  agent,
430
431
  name,
@@ -436,13 +437,31 @@ export class LoopGuardState {
436
437
  }
437
438
  }
438
439
 
440
+ if (this.config.errorThrashingGuard && (state.consecutiveFailures >= this.config.maxConsecutiveFailures || (state.errorRepeatCount >= this.config.maxConsecutiveFailures && state.lastErrorSignature))) {
441
+ const sig = state.lastErrorSignature || 'UNKNOWN_ERROR';
442
+ return this.handleViolation(
443
+ state,
444
+ agent,
445
+ name,
446
+ args,
447
+ callId,
448
+ 'LOOP_GUARD_ERROR_THRASHING',
449
+ `tool calls produced ${state.consecutiveFailures} consecutive failures (signature: ${sig}) without productive progress`
450
+ );
451
+ }
452
+
439
453
  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');
454
+ 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
455
  }
442
456
 
443
457
  if (repeatCount >= maxRepeats) {
444
458
  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');
459
+ return this.handleViolation(state, agent, name, args, callId, code, 'near-identical tool call repeated without a new result or state change after ' + repeatCount + ' attempts');
460
+ }
461
+
462
+ if (this.config.targetQuotaGuard) {
463
+ const targetCheck = checkTargetQuota(state, this.config, name, args);
464
+ if (targetCheck) return handleTargetViolation(state, this, agent, name, args, targetCheck);
446
465
  }
447
466
  const isProgressTool = this.progressToolNames.has(String(name));
448
467
  if (isProgressTool) {
@@ -463,11 +482,22 @@ export class LoopGuardState {
463
482
  count: (priorExact?.progressEpoch === state.progressEpoch ? priorExact.count : 0) + 1,
464
483
  progressEpoch: state.progressEpoch,
465
484
  });
485
+ const target = extractTargetKey(name, args);
486
+ const action = classifyToolAction(name);
487
+ if (target) {
488
+ if (!state.targetCallCounts) state.targetCallCounts = new Map();
489
+ const counts = state.targetCallCounts.get(target) || { read: 0, edit: 0, write: 0, delete: 0, default: 0, total: 0 };
490
+ counts[action] = (counts[action] || 0) + 1;
491
+ counts.total += 1;
492
+ state.targetCallCounts.set(target, counts);
493
+ }
466
494
  const call = {
467
495
  id,
468
496
  fingerprint,
469
497
  repeatFingerprint,
470
498
  isProgressTool,
499
+ target,
500
+ action,
471
501
  pending: true,
472
502
  committed: false,
473
503
  released: false,
@@ -506,6 +536,18 @@ export class LoopGuardState {
506
536
  call.resultSeen = true;
507
537
  call.resultFingerprint = outcome.resultFingerprint;
508
538
  call.progressToken = outcome.progressToken;
539
+
540
+ if (!outcome.successful) {
541
+ state.consecutiveFailures = (state.consecutiveFailures || 0) + 1;
542
+ const errorSig = normalizeErrorSignature(outcome.errorValue || execution?.error || maybeResult);
543
+ if (state.lastErrorSignature === errorSig) {
544
+ state.errorRepeatCount = (state.errorRepeatCount || 0) + 1;
545
+ } else {
546
+ state.lastErrorSignature = errorSig;
547
+ state.errorRepeatCount = 1;
548
+ }
549
+ }
550
+
509
551
  const prior = state.lastEvidence;
510
552
  const priorForCall = state.lastResults.get(call.repeatFingerprint);
511
553
  const resultUnchangedForCall = priorForCall !== undefined
@@ -517,12 +559,17 @@ export class LoopGuardState {
517
559
  || prior.resultFingerprint !== outcome.resultFingerprint
518
560
  || prior.progressToken !== outcome.progressToken);
519
561
  call.productive = productive;
562
+ recordTargetOutcome(state, call, outcome, productive);
520
563
  state.lastResults.set(call.repeatFingerprint, outcome);
521
564
  if (productive) {
522
565
  state.lastEvidence = outcome;
523
566
  state.progressEpoch += 1;
524
567
  state.attemptsSinceProgress = 0;
525
568
  state.progressAttemptsSinceProgress = 0;
569
+ state.consecutiveFailures = 0;
570
+ state.lastErrorSignature = null;
571
+ state.errorRepeatCount = 0;
572
+ state.steeredCodes?.clear();
526
573
  state.repeatGroups.clear();
527
574
  state.exactGroups.clear();
528
575
  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,14 @@ 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),
127
+ targetQuotaGuard: Schema.boolean().volatile().default(true),
128
+ maxUnchangedReadsPerTarget: Schema.number().volatile().min(1).default(3),
129
+ maxReadsPerTarget: Schema.number().volatile().min(1).default(6),
130
+ maxEditsPerTarget: Schema.number().volatile().min(1).default(8),
131
+ maxTargetAttempts: Schema.number().volatile().min(1).default(12),
123
132
  });
124
133
 
125
134
  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.1",
4
4
  "description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",