@goodandready/dsh-agent-loop-guard 0.2.28 → 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.
- package/CHANGELOG.md +19 -0
- package/README.md +5 -1
- package/README.ru.md +5 -1
- package/README.zh.md +5 -1
- package/lib/client.js +462 -503
- package/lib/guard-helpers.js +380 -0
- package/lib/guard-state.js +111 -294
- package/lib/index.js +4 -0
- package/package.json +8 -3
package/lib/guard-state.js
CHANGED
|
@@ -1,273 +1,25 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
if (EXPLICIT_STOP_EN.test(segment) || EXPLICIT_STOP_ZH.test(segment)) {
|
|
24
|
-
return true;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
return false;
|
|
29
|
-
}
|
|
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
|
-
|
|
113
|
-
export function compileStopPatterns(customPatterns = []) {
|
|
114
|
-
if (!Array.isArray(customPatterns)) return [];
|
|
115
|
-
const compiled = [];
|
|
116
|
-
for (const item of customPatterns) {
|
|
117
|
-
if (item instanceof RegExp) {
|
|
118
|
-
compiled.push(item);
|
|
119
|
-
} else if (typeof item === 'string' && item.trim() !== '') {
|
|
120
|
-
const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
121
|
-
compiled.push(new RegExp(escaped, 'iu'));
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
return compiled;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
const SECRET_KEY_PATTERN = /(?:token|secret|password|authorization|api[-_]?key|cookie)/iu;
|
|
128
|
-
|
|
129
|
-
function stableJson(value) {
|
|
130
|
-
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
131
|
-
if (Array.isArray(value)) return '[' + value.map(stableJson).join(',') + ']';
|
|
132
|
-
return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + stableJson(value[key])).join(',') + '}';
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
function normalizedJson(value) {
|
|
136
|
-
if (value === null || typeof value !== 'object') {
|
|
137
|
-
if (typeof value === 'string') return JSON.stringify(value.trim().replace(/\s+/gu, ' '));
|
|
138
|
-
return JSON.stringify(value);
|
|
139
|
-
}
|
|
140
|
-
if (Array.isArray(value)) return '[' + value.map(normalizedJson).join(',') + ']';
|
|
141
|
-
return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + normalizedJson(value[key])).join(',') + '}';
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
function textFrom(value) {
|
|
145
|
-
if (!Array.isArray(value)) return '';
|
|
146
|
-
return value.map((block) => {
|
|
147
|
-
if (block === null || typeof block !== 'object') return '';
|
|
148
|
-
if (typeof block.text === 'string') return block.text;
|
|
149
|
-
if (Array.isArray(block.content)) return textFrom(block.content);
|
|
150
|
-
return '';
|
|
151
|
-
}).join('\n');
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
function safeLogValue(value, depth = 0) {
|
|
155
|
-
if (depth > 3) return '[depth-limit]';
|
|
156
|
-
if (typeof value === 'string') {
|
|
157
|
-
return value.replace(/((?:Bearer|token)\s+)[^\s'"]+/giu, '$1[redacted]')
|
|
158
|
-
.replace(/((?:token|secret|password|authorization|api[-_]?key)=)[^\s&]+/giu, '$1[redacted]')
|
|
159
|
-
.slice(0, 400);
|
|
160
|
-
}
|
|
161
|
-
if (value === null || typeof value !== 'object') return value;
|
|
162
|
-
if (Array.isArray(value)) return value.slice(0, 20).map((item) => safeLogValue(item, depth + 1));
|
|
163
|
-
const output = {};
|
|
164
|
-
for (const [key, item] of Object.entries(value).slice(0, 40)) {
|
|
165
|
-
output[key] = SECRET_KEY_PATTERN.test(key) ? '[redacted]' : safeLogValue(item, depth + 1);
|
|
166
|
-
}
|
|
167
|
-
return output;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
export function positiveInteger(value, fallback) {
|
|
171
|
-
return Number.isSafeInteger(value) && value >= 1 ? value : fallback;
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
export function nonNegativeInteger(value, fallback) {
|
|
175
|
-
return Number.isSafeInteger(value) && value >= 0 ? value : fallback;
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
export function hasStopRequest(messages, customPatterns = []) {
|
|
179
|
-
if (!Array.isArray(messages)) return false;
|
|
180
|
-
const compiledCustom = compileStopPatterns(customPatterns);
|
|
181
|
-
let lastUserMessage = null;
|
|
182
|
-
for (let i = messages.length - 1; i >= 0; i--) {
|
|
183
|
-
const msg = messages[i];
|
|
184
|
-
if (msg && (msg.source?.kind === 'user' || msg.role === 'user')) {
|
|
185
|
-
lastUserMessage = msg;
|
|
186
|
-
break;
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
if (!lastUserMessage) return false;
|
|
190
|
-
|
|
191
|
-
const text = textFrom(lastUserMessage.content);
|
|
192
|
-
if (!text) return false;
|
|
193
|
-
|
|
194
|
-
if (isDefaultStopRequest(text)) {
|
|
195
|
-
return true;
|
|
196
|
-
}
|
|
197
|
-
return compiledCustom.some((regex) => regex.test(text));
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
export function callFingerprint(name, args) {
|
|
201
|
-
try {
|
|
202
|
-
const raw = stableJson(args);
|
|
203
|
-
const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
|
|
204
|
-
return String(name) + ':' + body;
|
|
205
|
-
} catch {
|
|
206
|
-
return String(name) + ':<unserializable>';
|
|
207
|
-
}
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
export function callRepeatFingerprint(name, args) {
|
|
211
|
-
try {
|
|
212
|
-
const raw = normalizedJson(args);
|
|
213
|
-
const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
|
|
214
|
-
return String(name) + ':' + body;
|
|
215
|
-
} catch {
|
|
216
|
-
return String(name) + ':<unserializable>';
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
export function resultFingerprint(value) {
|
|
221
|
-
try {
|
|
222
|
-
const raw = stableJson(value);
|
|
223
|
-
return raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
|
|
224
|
-
} catch {
|
|
225
|
-
return '<unserializable-result>';
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
export function safeCallSummary(name, args) {
|
|
230
|
-
return {
|
|
231
|
-
tool: String(name),
|
|
232
|
-
arguments: safeLogValue(args),
|
|
233
|
-
};
|
|
234
|
-
}
|
|
235
|
-
|
|
236
|
-
function hasOwn(object, key) {
|
|
237
|
-
return object !== null && typeof object === 'object' && Object.prototype.hasOwnProperty.call(object, key);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
function outcomeFromExecution(execution, maybeResult = undefined) {
|
|
241
|
-
const result = maybeResult !== undefined ? maybeResult : execution?.result;
|
|
242
|
-
const data = execution?.data;
|
|
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');
|
|
251
|
-
if (!hasResult) return { known: false, successful: false, resultFingerprint: '<unknown>', progressToken: '<unknown>' };
|
|
252
|
-
const value = result ?? execution?.output ?? data?.result ?? data?.output
|
|
253
|
-
?? (hasOwn(execution, 'error') ? { error: execution.error } : undefined);
|
|
254
|
-
const failed = (execution?.error != null && execution?.error !== false)
|
|
255
|
-
|| execution?.isError === true
|
|
256
|
-
|| value?.isError === true
|
|
257
|
-
|| value?.success === false
|
|
258
|
-
|| value?.ok === false
|
|
259
|
-
|| (value?.error != null && value?.error !== false);
|
|
260
|
-
const explicitProgress = execution?.progressToken ?? execution?.progress ?? execution?.stateVersion
|
|
261
|
-
?? data?.progressToken ?? data?.progress ?? data?.stateVersion
|
|
262
|
-
?? value?.progressToken ?? value?.progress ?? value?.stateVersion
|
|
263
|
-
?? value?.meta?.progressToken;
|
|
264
|
-
return {
|
|
265
|
-
known: true,
|
|
266
|
-
successful: !failed,
|
|
267
|
-
resultFingerprint: resultFingerprint(value),
|
|
268
|
-
progressToken: explicitProgress === undefined ? resultFingerprint(value) : resultFingerprint(explicitProgress),
|
|
269
|
-
};
|
|
270
|
-
}
|
|
1
|
+
import {
|
|
2
|
+
isDefaultStopRequest,
|
|
3
|
+
detectOscillation,
|
|
4
|
+
DEFAULT_PSEUDO_TOOL_PATTERNS,
|
|
5
|
+
compilePseudoToolPatterns,
|
|
6
|
+
isPseudoToolCallText,
|
|
7
|
+
compileStopPatterns,
|
|
8
|
+
positiveInteger,
|
|
9
|
+
nonNegativeInteger,
|
|
10
|
+
hasStopRequest,
|
|
11
|
+
callFingerprint,
|
|
12
|
+
callRepeatFingerprint,
|
|
13
|
+
resultFingerprint,
|
|
14
|
+
safeCallSummary,
|
|
15
|
+
outcomeFromExecution,
|
|
16
|
+
normalizeErrorSignature,
|
|
17
|
+
GUARD_PRESETS,
|
|
18
|
+
formatSteeringAdvice,
|
|
19
|
+
formatViolationGuidance,
|
|
20
|
+
} from './guard-helpers.js';
|
|
21
|
+
|
|
22
|
+
export * from './guard-helpers.js';
|
|
271
23
|
|
|
272
24
|
export class LoopGuardState {
|
|
273
25
|
constructor(config = {}) {
|
|
@@ -299,6 +51,9 @@ export class LoopGuardState {
|
|
|
299
51
|
pseudoToolCallPatterns: Array.isArray(config.pseudoToolCallPatterns) ? config.pseudoToolCallPatterns : [],
|
|
300
52
|
oscillationDetection: config.oscillationDetection !== undefined ? Boolean(config.oscillationDetection) : true,
|
|
301
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),
|
|
302
57
|
};
|
|
303
58
|
this.stopPatterns = stopPatterns;
|
|
304
59
|
this.pseudoPatterns = this.config.pseudoToolCallPatterns;
|
|
@@ -309,9 +64,11 @@ export class LoopGuardState {
|
|
|
309
64
|
this.byAgent = new Map();
|
|
310
65
|
this.objectKeys = new WeakMap();
|
|
311
66
|
this.nextObjectKey = 1;
|
|
67
|
+
this.incidents = [];
|
|
312
68
|
|
|
313
69
|
this.metrics = {
|
|
314
70
|
totalViolations: 0,
|
|
71
|
+
steeredCount: 0,
|
|
315
72
|
byCode: {
|
|
316
73
|
LOOP_GUARD_STOP: 0,
|
|
317
74
|
LOOP_GUARD_DUPLICATE: 0,
|
|
@@ -322,6 +79,8 @@ export class LoopGuardState {
|
|
|
322
79
|
LOOP_GUARD_PSEUDO_TOOL_CALL: 0,
|
|
323
80
|
LOOP_GUARD_OSCILLATION: 0,
|
|
324
81
|
LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
|
|
82
|
+
LOOP_GUARD_ERROR_THRASHING: 0,
|
|
83
|
+
LOOP_GUARD_STEER: 0,
|
|
325
84
|
},
|
|
326
85
|
lastViolation: null,
|
|
327
86
|
};
|
|
@@ -347,6 +106,9 @@ export class LoopGuardState {
|
|
|
347
106
|
strictToolLimit: positiveInteger(config.strictToolLimit, this.config.strictToolLimit ?? 3),
|
|
348
107
|
dryRunMode: config.dryRunMode !== undefined ? Boolean(config.dryRunMode) : Boolean(this.config.dryRunMode),
|
|
349
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,
|
|
350
112
|
};
|
|
351
113
|
if (Array.isArray(config.stopPatterns)) {
|
|
352
114
|
this.stopPatterns = config.stopPatterns
|
|
@@ -376,6 +138,23 @@ export class LoopGuardState {
|
|
|
376
138
|
return hasStopRequest(messages, this.stopPatterns);
|
|
377
139
|
}
|
|
378
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
|
+
|
|
379
158
|
recordExternalViolation(code, detail, extra = {}) {
|
|
380
159
|
this.metrics.totalViolations += 1;
|
|
381
160
|
this.metrics.byCode[code] = (this.metrics.byCode[code] || 0) + 1;
|
|
@@ -386,6 +165,7 @@ export class LoopGuardState {
|
|
|
386
165
|
turn: extra.turn,
|
|
387
166
|
reason: detail,
|
|
388
167
|
};
|
|
168
|
+
this.recordIncident(null, code, detail, extra.tool || 'assistant/output', null);
|
|
389
169
|
}
|
|
390
170
|
|
|
391
171
|
getTelemetry() {
|
|
@@ -393,15 +173,18 @@ export class LoopGuardState {
|
|
|
393
173
|
...this.metrics,
|
|
394
174
|
activeAgents: this.byAgent.size,
|
|
395
175
|
dryRunMode: Boolean(this.config.dryRunMode),
|
|
176
|
+
incidents: (this.incidents || []).slice(-20).reverse(),
|
|
396
177
|
};
|
|
397
178
|
}
|
|
398
179
|
|
|
399
180
|
resetTelemetry() {
|
|
400
181
|
this.metrics.totalViolations = 0;
|
|
182
|
+
this.metrics.steeredCount = 0;
|
|
401
183
|
for (const k of Object.keys(this.metrics.byCode)) {
|
|
402
184
|
this.metrics.byCode[k] = 0;
|
|
403
185
|
}
|
|
404
186
|
this.metrics.lastViolation = null;
|
|
187
|
+
this.incidents = [];
|
|
405
188
|
}
|
|
406
189
|
|
|
407
190
|
disposeSession(sessionId) {
|
|
@@ -453,6 +236,10 @@ export class LoopGuardState {
|
|
|
453
236
|
turnHadPseudoCall: false,
|
|
454
237
|
turnAssistantText: '',
|
|
455
238
|
recentCallSequence: [],
|
|
239
|
+
consecutiveFailures: 0,
|
|
240
|
+
lastErrorSignature: null,
|
|
241
|
+
errorRepeatCount: 0,
|
|
242
|
+
steeredCodes: new Set(),
|
|
456
243
|
};
|
|
457
244
|
}
|
|
458
245
|
|
|
@@ -484,7 +271,6 @@ export class LoopGuardState {
|
|
|
484
271
|
return state;
|
|
485
272
|
}
|
|
486
273
|
|
|
487
|
-
|
|
488
274
|
observeAssistantText(agent, text) {
|
|
489
275
|
if (!text || typeof text !== 'string') return;
|
|
490
276
|
const state = this.stateFor(agent);
|
|
@@ -511,6 +297,10 @@ export class LoopGuardState {
|
|
|
511
297
|
state.answerOnly = false;
|
|
512
298
|
state.stopReason = '';
|
|
513
299
|
state.blockReason = undefined;
|
|
300
|
+
state.consecutiveFailures = 0;
|
|
301
|
+
state.lastErrorSignature = null;
|
|
302
|
+
state.errorRepeatCount = 0;
|
|
303
|
+
state.steeredCodes?.clear();
|
|
514
304
|
}
|
|
515
305
|
|
|
516
306
|
endTurn(agent, turnData = {}) {
|
|
@@ -575,6 +365,22 @@ export class LoopGuardState {
|
|
|
575
365
|
}
|
|
576
366
|
}
|
|
577
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
|
+
|
|
578
384
|
violation(state, agent, name, args, callId, code, detail) {
|
|
579
385
|
this.metrics.totalViolations += 1;
|
|
580
386
|
this.metrics.byCode[code] = (this.metrics.byCode[code] || 0) + 1;
|
|
@@ -585,6 +391,7 @@ export class LoopGuardState {
|
|
|
585
391
|
turn: state.turn,
|
|
586
392
|
reason: detail,
|
|
587
393
|
};
|
|
394
|
+
this.recordIncident(agent, code, detail, name, state);
|
|
588
395
|
|
|
589
396
|
const summary = safeCallSummary(name, args);
|
|
590
397
|
const event = {
|
|
@@ -615,26 +422,7 @@ export class LoopGuardState {
|
|
|
615
422
|
state.blockReason = code;
|
|
616
423
|
}
|
|
617
424
|
|
|
618
|
-
|
|
619
|
-
if (code === 'LOOP_GUARD_STOP') {
|
|
620
|
-
guidance += 'User requested stop. Do NOT invoke further tools. Synthesize your final answer in plain text.';
|
|
621
|
-
} else if (code === 'LOOP_GUARD_DUPLICATE') {
|
|
622
|
-
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.`;
|
|
623
|
-
} else if (code === 'LOOP_GUARD_REPEAT') {
|
|
624
|
-
guidance += `Tool "${name}" reached repetition limit without progress. Switch to an alternative exploration approach or answer directly.`;
|
|
625
|
-
} else if (code === 'LOOP_GUARD_PROGRESS_LIMIT') {
|
|
626
|
-
guidance += `Progress tool "${name}" repeatedly called without task changes. Stop updating task lists and proceed to execute or respond.`;
|
|
627
|
-
} else if (code === 'LOOP_GUARD_LIMIT') {
|
|
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.';
|
|
633
|
-
} else {
|
|
634
|
-
guidance += 'Cease tool execution and provide a final text response. The next user turn will reset this guard.';
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
return `[${code}] ${detail}. No productive progress was observed; provide the final text answer now. ${guidance}`;
|
|
425
|
+
return formatViolationGuidance(code, detail, name, this.config);
|
|
638
426
|
}
|
|
639
427
|
|
|
640
428
|
denyReason(agent, name, args, callId) {
|
|
@@ -661,7 +449,7 @@ export class LoopGuardState {
|
|
|
661
449
|
const oscillation = detectOscillation(candidateSeq, this.config.maxOscillationRepeats);
|
|
662
450
|
if (oscillation) {
|
|
663
451
|
const cycleNames = oscillation.cycle.map((fp) => fp.split(':', 1)[0]);
|
|
664
|
-
return this.
|
|
452
|
+
return this.handleViolation(
|
|
665
453
|
state,
|
|
666
454
|
agent,
|
|
667
455
|
name,
|
|
@@ -673,13 +461,26 @@ export class LoopGuardState {
|
|
|
673
461
|
}
|
|
674
462
|
}
|
|
675
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
|
+
|
|
676
477
|
if (this.config.blockExactDuplicates && exactCount >= 1) {
|
|
677
|
-
return this.
|
|
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');
|
|
678
479
|
}
|
|
679
480
|
|
|
680
481
|
if (repeatCount >= maxRepeats) {
|
|
681
482
|
const code = (this.config.blockExactDuplicates && exactCount >= maxRepeats) ? 'LOOP_GUARD_DUPLICATE' : 'LOOP_GUARD_REPEAT';
|
|
682
|
-
return this.
|
|
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');
|
|
683
484
|
}
|
|
684
485
|
const isProgressTool = this.progressToolNames.has(String(name));
|
|
685
486
|
if (isProgressTool) {
|
|
@@ -743,6 +544,18 @@ export class LoopGuardState {
|
|
|
743
544
|
call.resultSeen = true;
|
|
744
545
|
call.resultFingerprint = outcome.resultFingerprint;
|
|
745
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
|
+
|
|
746
559
|
const prior = state.lastEvidence;
|
|
747
560
|
const priorForCall = state.lastResults.get(call.repeatFingerprint);
|
|
748
561
|
const resultUnchangedForCall = priorForCall !== undefined
|
|
@@ -760,6 +573,10 @@ export class LoopGuardState {
|
|
|
760
573
|
state.progressEpoch += 1;
|
|
761
574
|
state.attemptsSinceProgress = 0;
|
|
762
575
|
state.progressAttemptsSinceProgress = 0;
|
|
576
|
+
state.consecutiveFailures = 0;
|
|
577
|
+
state.lastErrorSignature = null;
|
|
578
|
+
state.errorRepeatCount = 0;
|
|
579
|
+
state.steeredCodes?.clear();
|
|
763
580
|
state.repeatGroups.clear();
|
|
764
581
|
state.exactGroups.clear();
|
|
765
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.
|
|
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",
|
|
@@ -21,11 +21,12 @@
|
|
|
21
21
|
],
|
|
22
22
|
"scripts": {
|
|
23
23
|
"test": "node --test",
|
|
24
|
-
"check": "node --check lib/index.js && node --check lib/guard-state.js && node --check lib/assistant-output-state.js && node --check lib/plugin-updater.js && node --check lib/client.js",
|
|
24
|
+
"check": "node --check lib/index.js && node --check lib/guard-state.js && node --check lib/guard-helpers.js && node --check lib/assistant-output-state.js && node --check lib/plugin-updater.js && node --check lib/client.js && node scripts/pack-check.mjs",
|
|
25
25
|
"build:client": "node scripts/build-client.mjs",
|
|
26
26
|
"pretest": "node scripts/build-client.mjs",
|
|
27
27
|
"clean": "node scripts/clean-pack.mjs",
|
|
28
|
-
"pack:release": "node scripts/pack-release.mjs"
|
|
28
|
+
"pack:release": "node scripts/pack-release.mjs",
|
|
29
|
+
"pack:check": "node scripts/pack-check.mjs"
|
|
29
30
|
},
|
|
30
31
|
"dsh": {
|
|
31
32
|
"bundle": {
|
|
@@ -56,5 +57,9 @@
|
|
|
56
57
|
},
|
|
57
58
|
"devDependencies": {
|
|
58
59
|
"@deepseek-ai/schemastery": "^3.18.4"
|
|
60
|
+
},
|
|
61
|
+
"overrides": {
|
|
62
|
+
"zod": "^4.6.6",
|
|
63
|
+
"fast-uri": "^3.1.9"
|
|
59
64
|
}
|
|
60
65
|
}
|