@goodandready/dsh-agent-loop-guard 0.3.0 → 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.
- package/CHANGELOG.md +10 -0
- package/README.md +6 -5
- package/README.ru.md +6 -5
- package/README.zh.md +6 -5
- package/lib/client.js +470 -424
- package/lib/guard-helpers.js +214 -0
- package/lib/guard-state.js +49 -56
- package/lib/index.js +5 -0
- package/package.json +1 -1
package/lib/guard-helpers.js
CHANGED
|
@@ -290,6 +290,195 @@ export function normalizeErrorSignature(error) {
|
|
|
290
290
|
.slice(0, 50);
|
|
291
291
|
return sanitized.length > 0 ? sanitized : 'GENERIC_ERROR';
|
|
292
292
|
}
|
|
293
|
+
|
|
294
|
+
export function extractTargetKey(name, args) {
|
|
295
|
+
if (!args) return null;
|
|
296
|
+
let raw = null;
|
|
297
|
+
if (typeof args === 'string') {
|
|
298
|
+
raw = args;
|
|
299
|
+
} else if (typeof args === 'object') {
|
|
300
|
+
raw = args.path ?? args.file ?? args.filePath ?? args.target ?? args.filename
|
|
301
|
+
?? args.uri ?? args.dest ?? args.destination ?? args.src ?? args.source
|
|
302
|
+
?? args.params?.path ?? args.params?.file;
|
|
303
|
+
}
|
|
304
|
+
if (!raw || typeof raw !== 'string') return null;
|
|
305
|
+
const trimmed = raw.trim();
|
|
306
|
+
if (!trimmed) return null;
|
|
307
|
+
|
|
308
|
+
let normalized = trimmed.replace(/\\/g, '/');
|
|
309
|
+
if (normalized.startsWith('file://')) {
|
|
310
|
+
normalized = normalized.slice(7);
|
|
311
|
+
}
|
|
312
|
+
normalized = normalized.replace(/\/{2,}/g, '/');
|
|
313
|
+
while (normalized.startsWith('./')) {
|
|
314
|
+
normalized = normalized.slice(2);
|
|
315
|
+
}
|
|
316
|
+
normalized = normalized.replace(/\/\.\//g, '/');
|
|
317
|
+
if (normalized.length > 1 && normalized.endsWith('/')) {
|
|
318
|
+
normalized = normalized.slice(0, -1);
|
|
319
|
+
}
|
|
320
|
+
return normalized.toLowerCase();
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
export function classifyToolAction(name) {
|
|
324
|
+
if (!name || typeof name !== 'string') return 'default';
|
|
325
|
+
const lower = name.toLowerCase();
|
|
326
|
+
if (lower.includes('read') || lower.includes('view') || lower.includes('cat') || lower.includes('inspect') || lower.includes('fetch')) {
|
|
327
|
+
return 'read';
|
|
328
|
+
}
|
|
329
|
+
if (lower.includes('edit') || lower.includes('patch') || lower.includes('replace') || lower.includes('modify')) {
|
|
330
|
+
return 'edit';
|
|
331
|
+
}
|
|
332
|
+
if (lower.includes('write') || lower.includes('create') || lower.includes('save') || lower.includes('append')) {
|
|
333
|
+
return 'write';
|
|
334
|
+
}
|
|
335
|
+
if (lower.includes('delete') || lower.includes('remove') || lower.includes('unlink') || lower.includes('rm')) {
|
|
336
|
+
return 'delete';
|
|
337
|
+
}
|
|
338
|
+
return 'default';
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export function checkTargetQuota(state, config, name, args) {
|
|
342
|
+
if (!config.targetQuotaGuard) return undefined;
|
|
343
|
+
const target = extractTargetKey(name, args);
|
|
344
|
+
if (!target) return undefined;
|
|
345
|
+
|
|
346
|
+
const action = classifyToolAction(name);
|
|
347
|
+
const counts = state.targetCallCounts?.get(target) || { read: 0, edit: 0, write: 0, delete: 0, default: 0, total: 0 };
|
|
348
|
+
|
|
349
|
+
if (action === 'read' && state.targetReadFingerprints) {
|
|
350
|
+
const readInfo = state.targetReadFingerprints.get(target);
|
|
351
|
+
const maxUnchanged = config.maxUnchangedReadsPerTarget ?? 3;
|
|
352
|
+
if (readInfo && readInfo.unchangedReReads >= maxUnchanged) {
|
|
353
|
+
return {
|
|
354
|
+
code: 'LOOP_GUARD_UNREFRESHED_READ',
|
|
355
|
+
detail: `Target "${target}" has been read ${readInfo.unchangedReReads + 1} times without content changes. File content is already in context. Do not re-read unchanged files; proceed to process or edit, or answer the user directly.`,
|
|
356
|
+
target,
|
|
357
|
+
action,
|
|
358
|
+
nonLatching: true,
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
const maxReads = config.maxReadsPerTarget ?? 6;
|
|
364
|
+
if (action === 'read' && counts.read >= maxReads) {
|
|
365
|
+
return {
|
|
366
|
+
code: 'LOOP_GUARD_TARGET_QUOTA',
|
|
367
|
+
detail: `Read quota (${maxReads}) exceeded for target "${target}". Cease reading this file and proceed with alternative actions or summarize findings.`,
|
|
368
|
+
target,
|
|
369
|
+
action,
|
|
370
|
+
nonLatching: true,
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const maxEdits = config.maxEditsPerTarget ?? 8;
|
|
375
|
+
if ((action === 'edit' || action === 'write') && (counts.edit + counts.write) >= maxEdits) {
|
|
376
|
+
return {
|
|
377
|
+
code: 'LOOP_GUARD_TARGET_QUOTA',
|
|
378
|
+
detail: `Modification quota (${maxEdits}) exceeded for target "${target}". Repeated modifications suggest an unproductive repair loop; diagnose root cause or explain roadblock.`,
|
|
379
|
+
target,
|
|
380
|
+
action,
|
|
381
|
+
nonLatching: true,
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const maxTotal = config.maxTargetAttempts ?? 12;
|
|
386
|
+
if (counts.total >= maxTotal) {
|
|
387
|
+
return {
|
|
388
|
+
code: 'LOOP_GUARD_TARGET_QUOTA',
|
|
389
|
+
detail: `Total operation quota (${maxTotal}) exceeded for target "${target}".`,
|
|
390
|
+
target,
|
|
391
|
+
action,
|
|
392
|
+
nonLatching: true,
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
return undefined;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
export function recordTargetOutcome(state, call, outcome, productive = false) {
|
|
400
|
+
if (!call?.target) return;
|
|
401
|
+
const target = call.target;
|
|
402
|
+
const action = call.action;
|
|
403
|
+
|
|
404
|
+
if (productive) {
|
|
405
|
+
const counts = state.targetCallCounts?.get(target);
|
|
406
|
+
if (counts) {
|
|
407
|
+
counts.read = 0; counts.edit = 0; counts.write = 0; counts.delete = 0; counts.default = 0; counts.total = 0;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
if (action === 'read') {
|
|
412
|
+
if (!state.targetReadFingerprints) state.targetReadFingerprints = new Map();
|
|
413
|
+
const current = state.targetReadFingerprints.get(target);
|
|
414
|
+
const fp = outcome.resultFingerprint;
|
|
415
|
+
if (current && current.lastFingerprint === fp && outcome.successful) {
|
|
416
|
+
current.unchangedReReads = (current.unchangedReReads || 0) + 1;
|
|
417
|
+
} else {
|
|
418
|
+
state.targetReadFingerprints.set(target, {
|
|
419
|
+
lastFingerprint: fp,
|
|
420
|
+
unchangedReReads: 0,
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
} else if ((action === 'edit' || action === 'write') && outcome.successful) {
|
|
424
|
+
if (state.targetReadFingerprints?.has(target)) {
|
|
425
|
+
state.targetReadFingerprints.delete(target);
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export function decrementReservations(state, call) {
|
|
431
|
+
if (!call || !call.counted || call.committed) return;
|
|
432
|
+
state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
|
|
433
|
+
if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
|
|
434
|
+
if (call.repeatFingerprint) {
|
|
435
|
+
const group = state.repeatGroups.get(call.repeatFingerprint);
|
|
436
|
+
if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
|
|
437
|
+
group.count = Math.max(0, group.count - 1);
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
|
|
441
|
+
const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
|
|
442
|
+
if (lastIdx !== -1) {
|
|
443
|
+
state.recentCallSequence.splice(lastIdx, 1);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
if (call.fingerprint) {
|
|
447
|
+
const exact = state.exactGroups.get(call.fingerprint);
|
|
448
|
+
if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
|
|
449
|
+
exact.count = Math.max(0, exact.count - 1);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (call.target && state.targetCallCounts) {
|
|
453
|
+
const counts = state.targetCallCounts.get(call.target);
|
|
454
|
+
if (counts) {
|
|
455
|
+
if (call.action && counts[call.action] > 0) counts[call.action] -= 1;
|
|
456
|
+
if (counts.total > 0) counts.total -= 1;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
export function handleTargetViolation(state, guard, agent, name, args, check) {
|
|
463
|
+
const config = guard.config;
|
|
464
|
+
if (config.adaptiveSteering && !state.steeredCodes?.has(check.code)) {
|
|
465
|
+
if (!state.steeredCodes) state.steeredCodes = new Set();
|
|
466
|
+
state.steeredCodes.add(check.code);
|
|
467
|
+
guard.metrics.steeredCount = (guard.metrics.steeredCount || 0) + 1;
|
|
468
|
+
guard.recordIncident(agent, 'LOOP_GUARD_STEER', `${check.code}: ${check.detail}`, name, state);
|
|
469
|
+
const advice = formatSteeringAdvice(check.code, check.detail, name);
|
|
470
|
+
return `[LOOP_GUARD_STEER] Warning: ${advice} If this pattern continues, tool execution will be terminated for this turn.`;
|
|
471
|
+
}
|
|
472
|
+
guard.metrics.totalViolations += 1;
|
|
473
|
+
guard.metrics.byCode[check.code] = (guard.metrics.byCode[check.code] || 0) + 1;
|
|
474
|
+
guard.metrics.lastViolation = {
|
|
475
|
+
code: check.code, tool: String(name), timestamp: Date.now(), turn: state.turn, reason: check.detail,
|
|
476
|
+
};
|
|
477
|
+
guard.recordIncident(agent, check.code, check.detail, name, state);
|
|
478
|
+
if (config.dryRunMode) return undefined;
|
|
479
|
+
return `[${check.code}] ${check.detail}`;
|
|
480
|
+
}
|
|
481
|
+
|
|
293
482
|
export const GUARD_PRESETS = {
|
|
294
483
|
strict: {
|
|
295
484
|
name: 'strict',
|
|
@@ -306,6 +495,11 @@ export const GUARD_PRESETS = {
|
|
|
306
495
|
maxToolResultChars: 32_768,
|
|
307
496
|
pseudoToolCallThreshold: 2,
|
|
308
497
|
adaptiveSteering: true,
|
|
498
|
+
targetQuotaGuard: true,
|
|
499
|
+
maxUnchangedReadsPerTarget: 2,
|
|
500
|
+
maxReadsPerTarget: 4,
|
|
501
|
+
maxEditsPerTarget: 5,
|
|
502
|
+
maxTargetAttempts: 8,
|
|
309
503
|
},
|
|
310
504
|
balanced: {
|
|
311
505
|
name: 'balanced',
|
|
@@ -322,6 +516,11 @@ export const GUARD_PRESETS = {
|
|
|
322
516
|
maxToolResultChars: 65_536,
|
|
323
517
|
pseudoToolCallThreshold: 3,
|
|
324
518
|
adaptiveSteering: true,
|
|
519
|
+
targetQuotaGuard: true,
|
|
520
|
+
maxUnchangedReadsPerTarget: 3,
|
|
521
|
+
maxReadsPerTarget: 6,
|
|
522
|
+
maxEditsPerTarget: 8,
|
|
523
|
+
maxTargetAttempts: 12,
|
|
325
524
|
},
|
|
326
525
|
autonomous: {
|
|
327
526
|
name: 'autonomous',
|
|
@@ -338,6 +537,11 @@ export const GUARD_PRESETS = {
|
|
|
338
537
|
maxToolResultChars: 131_072,
|
|
339
538
|
pseudoToolCallThreshold: 4,
|
|
340
539
|
adaptiveSteering: true,
|
|
540
|
+
targetQuotaGuard: true,
|
|
541
|
+
maxUnchangedReadsPerTarget: 5,
|
|
542
|
+
maxReadsPerTarget: 10,
|
|
543
|
+
maxEditsPerTarget: 12,
|
|
544
|
+
maxTargetAttempts: 20,
|
|
341
545
|
},
|
|
342
546
|
};
|
|
343
547
|
|
|
@@ -351,6 +555,12 @@ export function formatSteeringAdvice(code, detail, name) {
|
|
|
351
555
|
if (code === 'LOOP_GUARD_ERROR_THRASHING') {
|
|
352
556
|
return `Repeated tool calls resulted in identical failures (${detail}). Stop repeating the failing action and diagnose the root cause or explain the roadblock.`;
|
|
353
557
|
}
|
|
558
|
+
if (code === 'LOOP_GUARD_UNREFRESHED_READ') {
|
|
559
|
+
return `Target has been repeatedly read without changes (${detail}). The file content is already in your context. Proceed to edit, run checks, or provide an answer.`;
|
|
560
|
+
}
|
|
561
|
+
if (code === 'LOOP_GUARD_TARGET_QUOTA') {
|
|
562
|
+
return `Operations on this target reached quota limit (${detail}). Shift focus to other files or summarize findings.`;
|
|
563
|
+
}
|
|
354
564
|
return `Potential loop condition detected (${detail}). Adjust your action or explain your plan.`;
|
|
355
565
|
}
|
|
356
566
|
|
|
@@ -372,6 +582,10 @@ export function formatViolationGuidance(code, detail, name, config) {
|
|
|
372
582
|
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.';
|
|
373
583
|
} else if (code === 'LOOP_GUARD_ERROR_THRASHING') {
|
|
374
584
|
guidance += 'Repeated tool executions resulted in identical errors without state progression. Stop re-trying the failing operation. Investigate the failure reason, check file existence/permissions, or report the roadblock to the user.';
|
|
585
|
+
} else if (code === 'LOOP_GUARD_UNREFRESHED_READ') {
|
|
586
|
+
guidance += 'Target was read repeatedly without content changes. File contents are already in context. Do NOT re-read unchanged files; execute next steps or answer directly.';
|
|
587
|
+
} else if (code === 'LOOP_GUARD_TARGET_QUOTA') {
|
|
588
|
+
guidance += 'Target quota limit reached. Cease repeated operations on this specific target and work on other tasks or answer directly.';
|
|
375
589
|
} else {
|
|
376
590
|
guidance += 'Cease tool execution and provide a final text response. The next user turn will reset this guard.';
|
|
377
591
|
}
|
package/lib/guard-state.js
CHANGED
|
@@ -17,6 +17,12 @@ import {
|
|
|
17
17
|
GUARD_PRESETS,
|
|
18
18
|
formatSteeringAdvice,
|
|
19
19
|
formatViolationGuidance,
|
|
20
|
+
extractTargetKey,
|
|
21
|
+
classifyToolAction,
|
|
22
|
+
checkTargetQuota,
|
|
23
|
+
recordTargetOutcome,
|
|
24
|
+
decrementReservations,
|
|
25
|
+
handleTargetViolation,
|
|
20
26
|
} from './guard-helpers.js';
|
|
21
27
|
|
|
22
28
|
export * from './guard-helpers.js';
|
|
@@ -54,6 +60,11 @@ export class LoopGuardState {
|
|
|
54
60
|
errorThrashingGuard: config.errorThrashingGuard !== undefined ? Boolean(config.errorThrashingGuard) : true,
|
|
55
61
|
maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, 4),
|
|
56
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),
|
|
57
68
|
};
|
|
58
69
|
this.stopPatterns = stopPatterns;
|
|
59
70
|
this.pseudoPatterns = this.config.pseudoToolCallPatterns;
|
|
@@ -70,17 +81,11 @@ export class LoopGuardState {
|
|
|
70
81
|
totalViolations: 0,
|
|
71
82
|
steeredCount: 0,
|
|
72
83
|
byCode: {
|
|
73
|
-
LOOP_GUARD_STOP: 0,
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
LOOP_GUARD_OUTPUT: 0,
|
|
79
|
-
LOOP_GUARD_PSEUDO_TOOL_CALL: 0,
|
|
80
|
-
LOOP_GUARD_OSCILLATION: 0,
|
|
81
|
-
LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
|
|
82
|
-
LOOP_GUARD_ERROR_THRASHING: 0,
|
|
83
|
-
LOOP_GUARD_STEER: 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,
|
|
84
89
|
},
|
|
85
90
|
lastViolation: null,
|
|
86
91
|
};
|
|
@@ -109,6 +114,11 @@ export class LoopGuardState {
|
|
|
109
114
|
errorThrashingGuard: config.errorThrashingGuard !== undefined ? Boolean(config.errorThrashingGuard) : this.config.errorThrashingGuard,
|
|
110
115
|
maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, this.config.maxConsecutiveFailures ?? 4),
|
|
111
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),
|
|
112
122
|
};
|
|
113
123
|
if (Array.isArray(config.stopPatterns)) {
|
|
114
124
|
this.stopPatterns = config.stopPatterns
|
|
@@ -216,30 +226,14 @@ export class LoopGuardState {
|
|
|
216
226
|
|
|
217
227
|
emptyState(turn = undefined) {
|
|
218
228
|
return {
|
|
219
|
-
turn,
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
blockReason: undefined,
|
|
228
|
-
progressEpoch: 0,
|
|
229
|
-
repeatGroups: new Map(),
|
|
230
|
-
exactGroups: new Map(),
|
|
231
|
-
lastResults: new Map(),
|
|
232
|
-
lastProgress: undefined,
|
|
233
|
-
lastEvidence: undefined,
|
|
234
|
-
consecutivePseudoTurns: 0,
|
|
235
|
-
turnRealToolCalls: 0,
|
|
236
|
-
turnHadPseudoCall: false,
|
|
237
|
-
turnAssistantText: '',
|
|
238
|
-
recentCallSequence: [],
|
|
239
|
-
consecutiveFailures: 0,
|
|
240
|
-
lastErrorSignature: null,
|
|
241
|
-
errorRepeatCount: 0,
|
|
242
|
-
steeredCodes: new Set(),
|
|
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(),
|
|
243
237
|
};
|
|
244
238
|
}
|
|
245
239
|
|
|
@@ -301,6 +295,8 @@ export class LoopGuardState {
|
|
|
301
295
|
state.lastErrorSignature = null;
|
|
302
296
|
state.errorRepeatCount = 0;
|
|
303
297
|
state.steeredCodes?.clear();
|
|
298
|
+
state.targetCallCounts?.clear();
|
|
299
|
+
state.targetReadFingerprints?.clear();
|
|
304
300
|
}
|
|
305
301
|
|
|
306
302
|
endTurn(agent, turnData = {}) {
|
|
@@ -342,27 +338,7 @@ export class LoopGuardState {
|
|
|
342
338
|
}
|
|
343
339
|
|
|
344
340
|
decrementReservations(state, call) {
|
|
345
|
-
|
|
346
|
-
state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
|
|
347
|
-
if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
|
|
348
|
-
if (call.repeatFingerprint) {
|
|
349
|
-
const group = state.repeatGroups.get(call.repeatFingerprint);
|
|
350
|
-
if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
|
|
351
|
-
group.count = Math.max(0, group.count - 1);
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
|
|
355
|
-
const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
|
|
356
|
-
if (lastIdx !== -1) {
|
|
357
|
-
state.recentCallSequence.splice(lastIdx, 1);
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
if (call.fingerprint) {
|
|
361
|
-
const exact = state.exactGroups.get(call.fingerprint);
|
|
362
|
-
if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
|
|
363
|
-
exact.count = Math.max(0, exact.count - 1);
|
|
364
|
-
}
|
|
365
|
-
}
|
|
341
|
+
decrementReservations(state, call);
|
|
366
342
|
}
|
|
367
343
|
|
|
368
344
|
handleViolation(state, agent, name, args, callId, code, detail) {
|
|
@@ -482,6 +458,11 @@ export class LoopGuardState {
|
|
|
482
458
|
const code = (this.config.blockExactDuplicates && exactCount >= maxRepeats) ? 'LOOP_GUARD_DUPLICATE' : 'LOOP_GUARD_REPEAT';
|
|
483
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');
|
|
484
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);
|
|
465
|
+
}
|
|
485
466
|
const isProgressTool = this.progressToolNames.has(String(name));
|
|
486
467
|
if (isProgressTool) {
|
|
487
468
|
if (state.progressAttemptsSinceProgress >= this.config.maxProgressToolCallsPerTurn) {
|
|
@@ -501,11 +482,22 @@ export class LoopGuardState {
|
|
|
501
482
|
count: (priorExact?.progressEpoch === state.progressEpoch ? priorExact.count : 0) + 1,
|
|
502
483
|
progressEpoch: state.progressEpoch,
|
|
503
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
|
+
}
|
|
504
494
|
const call = {
|
|
505
495
|
id,
|
|
506
496
|
fingerprint,
|
|
507
497
|
repeatFingerprint,
|
|
508
498
|
isProgressTool,
|
|
499
|
+
target,
|
|
500
|
+
action,
|
|
509
501
|
pending: true,
|
|
510
502
|
committed: false,
|
|
511
503
|
released: false,
|
|
@@ -567,6 +559,7 @@ export class LoopGuardState {
|
|
|
567
559
|
|| prior.resultFingerprint !== outcome.resultFingerprint
|
|
568
560
|
|| prior.progressToken !== outcome.progressToken);
|
|
569
561
|
call.productive = productive;
|
|
562
|
+
recordTargetOutcome(state, call, outcome, productive);
|
|
570
563
|
state.lastResults.set(call.repeatFingerprint, outcome);
|
|
571
564
|
if (productive) {
|
|
572
565
|
state.lastEvidence = outcome;
|
package/lib/index.js
CHANGED
|
@@ -124,6 +124,11 @@ export const Config = Schema.object({
|
|
|
124
124
|
errorThrashingGuard: Schema.boolean().volatile().default(true),
|
|
125
125
|
maxConsecutiveFailures: Schema.number().volatile().min(2).default(4),
|
|
126
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),
|
|
127
132
|
});
|
|
128
133
|
|
|
129
134
|
function callIdFromEvent(event) {
|