@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.
@@ -0,0 +1,380 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ const EXPLICIT_STOP_EN = /^(?:please\s+)?(?:stop|halt|cancel|abort|terminate)(?:\s+(?:now|please|immediately|execution|calling\s+tools|and\s+answer|and\s+explain))?[.!?]*$/iu;
4
+ const EXPLICIT_STOP_ZH = /^(?:请|检测到)?(?:停止|暂停|取消|终止|死循环)(?:执行|操作|调用|一下|了)?[!。??!]*$/u;
5
+
6
+ export function isDefaultStopRequest(text) {
7
+ if (!text || typeof text !== 'string') return false;
8
+ const trimmed = text.trim();
9
+ if (!trimmed) return false;
10
+
11
+ if (EXPLICIT_STOP_EN.test(trimmed) || EXPLICIT_STOP_ZH.test(trimmed)) {
12
+ return true;
13
+ }
14
+
15
+ const segments = trimmed.split(/[\r\n.!?。!?]+/).map((s) => s.trim()).filter(Boolean);
16
+ for (const segment of segments) {
17
+ if (EXPLICIT_STOP_EN.test(segment) || EXPLICIT_STOP_ZH.test(segment)) {
18
+ return true;
19
+ }
20
+ }
21
+
22
+ return false;
23
+ }
24
+
25
+ export function detectOscillation(sequence, maxRepeats = 3, minPeriod = 2, maxPeriod = 4) {
26
+ if (!Array.isArray(sequence)) return null;
27
+ const len = sequence.length;
28
+
29
+ for (let period = minPeriod; period <= maxPeriod; period++) {
30
+ const requiredLength = period * maxRepeats;
31
+ if (len < requiredLength) continue;
32
+
33
+ const sample = sequence.slice(len - period, len);
34
+ const allSame = sample.every((item) => item === sample[0]);
35
+ if (allSame) continue;
36
+
37
+ let isMatch = true;
38
+ for (let rep = 1; rep < maxRepeats; rep++) {
39
+ for (let i = 0; i < period; i++) {
40
+ const expected = sequence[len - period + i];
41
+ const actual = sequence[len - (rep + 1) * period + i];
42
+ if (expected !== actual) {
43
+ isMatch = false;
44
+ break;
45
+ }
46
+ }
47
+ if (!isMatch) break;
48
+ }
49
+
50
+ if (isMatch) {
51
+ return {
52
+ period,
53
+ repeats: maxRepeats,
54
+ cycle: sample,
55
+ };
56
+ }
57
+ }
58
+
59
+ return null;
60
+ }
61
+
62
+ export const DEFAULT_PSEUDO_TOOL_PATTERNS = [
63
+ /<(?:invoke|function_call|tool_call|call:)\b/iu,
64
+ /<\/(?:invoke|function_call|tool_call)>/iu,
65
+ /```(?:tool_call|invoke|function_call)\b/iu,
66
+ /(?:\[TOOL_CALLS?\]|\[(?:TOOL_CALL|CALL):)/iu,
67
+ ];
68
+
69
+ export function compilePseudoToolPatterns(customPatterns = []) {
70
+ if (!Array.isArray(customPatterns)) return [];
71
+ const compiled = [];
72
+ for (const item of customPatterns) {
73
+ if (item instanceof RegExp) {
74
+ compiled.push(item);
75
+ } else if (typeof item === 'string' && item.trim() !== '') {
76
+ try {
77
+ const match = /^\/(.+)\/([a-z]*)$/i.exec(item.trim());
78
+ if (match) {
79
+ compiled.push(new RegExp(match[1], match[2] || 'iu'));
80
+ } else {
81
+ const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, (m) => '\\' + m);
82
+ compiled.push(new RegExp(escaped, 'iu'));
83
+ }
84
+ } catch {
85
+ const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, (m) => '\\' + m);
86
+ compiled.push(new RegExp(escaped, 'iu'));
87
+ }
88
+ }
89
+ }
90
+ return compiled;
91
+ }
92
+
93
+ export function isPseudoToolCallText(text, customPatterns = []) {
94
+ if (!text || typeof text !== 'string') return false;
95
+ for (const regex of DEFAULT_PSEUDO_TOOL_PATTERNS) {
96
+ if (regex.test(text)) return true;
97
+ }
98
+ const compiled = compilePseudoToolPatterns(customPatterns);
99
+ for (const regex of compiled) {
100
+ if (regex.test(text)) return true;
101
+ }
102
+ return false;
103
+ }
104
+
105
+ export function compileStopPatterns(customPatterns = []) {
106
+ if (!Array.isArray(customPatterns)) return [];
107
+ const compiled = [];
108
+ for (const item of customPatterns) {
109
+ if (item instanceof RegExp) {
110
+ compiled.push(item);
111
+ } else if (typeof item === 'string' && item.trim() !== '') {
112
+ const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
113
+ compiled.push(new RegExp(escaped, 'iu'));
114
+ }
115
+ }
116
+ return compiled;
117
+ }
118
+
119
+ const SECRET_KEY_PATTERN = /(?:token|secret|password|authorization|api[-_]?key|cookie)/iu;
120
+
121
+ function stableJson(value) {
122
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
123
+ if (Array.isArray(value)) return '[' + value.map(stableJson).join(',') + ']';
124
+ return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + stableJson(value[key])).join(',') + '}';
125
+ }
126
+
127
+ function normalizedJson(value) {
128
+ if (value === null || typeof value !== 'object') {
129
+ if (typeof value === 'string') return JSON.stringify(value.trim().replace(/\s+/gu, ' '));
130
+ return JSON.stringify(value);
131
+ }
132
+ if (Array.isArray(value)) return '[' + value.map(normalizedJson).join(',') + ']';
133
+ return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + normalizedJson(value[key])).join(',') + '}';
134
+ }
135
+
136
+ function textFrom(value) {
137
+ if (!Array.isArray(value)) return '';
138
+ return value.map((block) => {
139
+ if (block === null || typeof block !== 'object') return '';
140
+ if (typeof block.text === 'string') return block.text;
141
+ if (Array.isArray(block.content)) return textFrom(block.content);
142
+ return '';
143
+ }).join('\n');
144
+ }
145
+
146
+ function safeLogValue(value, depth = 0) {
147
+ if (depth > 3) return '[depth-limit]';
148
+ if (typeof value === 'string') {
149
+ return value.replace(/((?:Bearer|token)\s+)[^\s'"]+/giu, '$1[redacted]')
150
+ .replace(/((?:token|secret|password|authorization|api[-_]?key)=)[^\s&]+/giu, '$1[redacted]')
151
+ .slice(0, 400);
152
+ }
153
+ if (value === null || typeof value !== 'object') return value;
154
+ if (Array.isArray(value)) return value.slice(0, 20).map((item) => safeLogValue(item, depth + 1));
155
+ const output = {};
156
+ for (const [key, item] of Object.entries(value).slice(0, 40)) {
157
+ output[key] = SECRET_KEY_PATTERN.test(key) ? '[redacted]' : safeLogValue(item, depth + 1);
158
+ }
159
+ return output;
160
+ }
161
+
162
+ export function positiveInteger(value, fallback) {
163
+ return Number.isSafeInteger(value) && value >= 1 ? value : fallback;
164
+ }
165
+
166
+ export function nonNegativeInteger(value, fallback) {
167
+ return Number.isSafeInteger(value) && value >= 0 ? value : fallback;
168
+ }
169
+
170
+ export function hasStopRequest(messages, customPatterns = []) {
171
+ if (!Array.isArray(messages)) return false;
172
+ const compiledCustom = compileStopPatterns(customPatterns);
173
+ let lastUserMessage = null;
174
+ for (let i = messages.length - 1; i >= 0; i--) {
175
+ const msg = messages[i];
176
+ if (msg && (msg.source?.kind === 'user' || msg.role === 'user')) {
177
+ lastUserMessage = msg;
178
+ break;
179
+ }
180
+ }
181
+ if (!lastUserMessage) return false;
182
+
183
+ const text = textFrom(lastUserMessage.content);
184
+ if (!text) return false;
185
+
186
+ if (isDefaultStopRequest(text)) {
187
+ return true;
188
+ }
189
+ return compiledCustom.some((regex) => regex.test(text));
190
+ }
191
+
192
+ export function callFingerprint(name, args) {
193
+ try {
194
+ const raw = stableJson(args);
195
+ const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
196
+ return String(name) + ':' + body;
197
+ } catch {
198
+ return String(name) + ':<unserializable>';
199
+ }
200
+ }
201
+
202
+ export function callRepeatFingerprint(name, args) {
203
+ try {
204
+ const raw = normalizedJson(args);
205
+ const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
206
+ return String(name) + ':' + body;
207
+ } catch {
208
+ return String(name) + ':<unserializable>';
209
+ }
210
+ }
211
+
212
+ export function resultFingerprint(value) {
213
+ try {
214
+ const raw = stableJson(value);
215
+ return raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
216
+ } catch {
217
+ return '<unserializable-result>';
218
+ }
219
+ }
220
+
221
+ export function safeCallSummary(name, args) {
222
+ return {
223
+ tool: String(name),
224
+ arguments: safeLogValue(args),
225
+ };
226
+ }
227
+
228
+ function hasOwn(object, key) {
229
+ return object !== null && typeof object === 'object' && Object.prototype.hasOwnProperty.call(object, key);
230
+ }
231
+
232
+ export function outcomeFromExecution(execution, maybeResult = undefined) {
233
+ const result = maybeResult !== undefined ? maybeResult : execution?.result;
234
+ const data = execution?.data;
235
+ const hasResult = result !== undefined
236
+ || hasOwn(execution, 'result')
237
+ || hasOwn(execution, 'output')
238
+ || hasOwn(data, 'result')
239
+ || hasOwn(data, 'output')
240
+ || hasOwn(execution, 'error')
241
+ || hasOwn(execution, 'content')
242
+ || hasOwn(execution, 'isError');
243
+ if (!hasResult) return { known: false, successful: false, resultFingerprint: '<unknown>', progressToken: '<unknown>' };
244
+ const value = result ?? execution?.output ?? data?.result ?? data?.output
245
+ ?? (hasOwn(execution, 'error') ? { error: execution.error } : undefined);
246
+ const failed = (execution?.error != null && execution?.error !== false)
247
+ || execution?.isError === true
248
+ || value?.isError === true
249
+ || value?.success === false
250
+ || value?.ok === false
251
+ || (value?.error != null && value?.error !== false);
252
+ const explicitProgress = execution?.progressToken ?? execution?.progress ?? execution?.stateVersion
253
+ ?? data?.progressToken ?? data?.progress ?? data?.stateVersion
254
+ ?? value?.progressToken ?? value?.progress ?? value?.stateVersion
255
+ ?? value?.meta?.progressToken;
256
+ return {
257
+ known: true,
258
+ successful: !failed,
259
+ errorValue: failed ? (execution?.error ?? value?.error ?? value) : undefined,
260
+ resultFingerprint: resultFingerprint(value),
261
+ progressToken: explicitProgress === undefined ? resultFingerprint(value) : resultFingerprint(explicitProgress),
262
+ };
263
+ }
264
+
265
+ export function normalizeErrorSignature(error) {
266
+ if (!error) return 'UNKNOWN_ERROR';
267
+ const text = typeof error === 'string'
268
+ ? error
269
+ : (error.message || error.error || error.name || (typeof error === 'object' ? JSON.stringify(error) : String(error)));
270
+ if (!text || typeof text !== 'string') return 'UNKNOWN_ERROR';
271
+
272
+ const exitMatch = /exit(?:ed)? with code (\d+)|exit code (\d+)/i.exec(text);
273
+ if (exitMatch) return `EXIT_${exitMatch[1] || exitMatch[2]}`;
274
+
275
+ if (/ENOENT|no such file or directory/i.test(text)) return 'FS_ENOENT';
276
+ if (/EACCES|EPERM|permission denied/i.test(text)) return 'FS_EPERM';
277
+ if (/ENOSPC|no space left/i.test(text)) return 'FS_ENOSPC';
278
+ if (/ETIMEDOUT|timed out|timeout/i.test(text)) return 'TIMEOUT';
279
+ if (/ECONNREFUSED|connection refused/i.test(text)) return 'CONN_REFUSED';
280
+ if (/\b404\b|not found/i.test(text)) return 'HTTP_404';
281
+ if (/\b(?:401|403)\b|unauthorized|forbidden/i.test(text)) return 'HTTP_AUTH';
282
+ if (/\b(?:500|502|503)\b|internal server error/i.test(text)) return 'HTTP_SERVER';
283
+
284
+ const sanitized = text
285
+ .replace(/(?:\/[a-zA-Z0-9._-]+)+/g, '<path>')
286
+ .replace(/(?:[A-Za-z]:\\[a-zA-Z0-9._-]+)+/g, '<path>')
287
+ .replace(/\b\d+\b/g, '<n>')
288
+ .replace(/\s+/g, ' ')
289
+ .trim()
290
+ .slice(0, 50);
291
+ return sanitized.length > 0 ? sanitized : 'GENERIC_ERROR';
292
+ }
293
+ export const GUARD_PRESETS = {
294
+ strict: {
295
+ name: 'strict',
296
+ maxToolAttemptsPerTurn: 10,
297
+ maxProgressToolCallsPerTurn: 3,
298
+ maxCallsPerRepeatGroup: 2,
299
+ strictToolLimit: 1,
300
+ blockExactDuplicates: true,
301
+ oscillationDetection: true,
302
+ maxOscillationRepeats: 2,
303
+ errorThrashingGuard: true,
304
+ maxConsecutiveFailures: 3,
305
+ payloadBloatGuard: true,
306
+ maxToolResultChars: 32_768,
307
+ pseudoToolCallThreshold: 2,
308
+ adaptiveSteering: true,
309
+ },
310
+ balanced: {
311
+ name: 'balanced',
312
+ maxToolAttemptsPerTurn: 16,
313
+ maxProgressToolCallsPerTurn: 6,
314
+ maxCallsPerRepeatGroup: 3,
315
+ strictToolLimit: 2,
316
+ blockExactDuplicates: true,
317
+ oscillationDetection: true,
318
+ maxOscillationRepeats: 3,
319
+ errorThrashingGuard: true,
320
+ maxConsecutiveFailures: 4,
321
+ payloadBloatGuard: true,
322
+ maxToolResultChars: 65_536,
323
+ pseudoToolCallThreshold: 3,
324
+ adaptiveSteering: true,
325
+ },
326
+ autonomous: {
327
+ name: 'autonomous',
328
+ maxToolAttemptsPerTurn: 32,
329
+ maxProgressToolCallsPerTurn: 12,
330
+ maxCallsPerRepeatGroup: 5,
331
+ strictToolLimit: 3,
332
+ blockExactDuplicates: true,
333
+ oscillationDetection: true,
334
+ maxOscillationRepeats: 4,
335
+ errorThrashingGuard: true,
336
+ maxConsecutiveFailures: 6,
337
+ payloadBloatGuard: true,
338
+ maxToolResultChars: 131_072,
339
+ pseudoToolCallThreshold: 4,
340
+ adaptiveSteering: true,
341
+ },
342
+ };
343
+
344
+ export function formatSteeringAdvice(code, detail, name) {
345
+ if (code === 'LOOP_GUARD_DUPLICATE' || code === 'LOOP_GUARD_REPEAT') {
346
+ return `Tool "${name}" is repeating previous calls without producing new state. You MUST modify parameters or choose an alternative tool now.`;
347
+ }
348
+ if (code === 'LOOP_GUARD_OSCILLATION') {
349
+ return `Alternating tool cycle was detected (${detail}). Break the loop immediately by changing strategy or reviewing prerequisites.`;
350
+ }
351
+ if (code === 'LOOP_GUARD_ERROR_THRASHING') {
352
+ return `Repeated tool calls resulted in identical failures (${detail}). Stop repeating the failing action and diagnose the root cause or explain the roadblock.`;
353
+ }
354
+ return `Potential loop condition detected (${detail}). Adjust your action or explain your plan.`;
355
+ }
356
+
357
+ export function formatViolationGuidance(code, detail, name, config) {
358
+ let guidance = 'ACTION REQUIRED: ';
359
+ if (code === 'LOOP_GUARD_STOP') {
360
+ guidance += 'User requested stop. Do NOT invoke further tools. Synthesize your final answer in plain text.';
361
+ } else if (code === 'LOOP_GUARD_DUPLICATE') {
362
+ 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.`;
363
+ } else if (code === 'LOOP_GUARD_REPEAT') {
364
+ guidance += `Tool "${name}" reached repetition limit without progress. Switch to an alternative exploration approach or answer directly.`;
365
+ } else if (code === 'LOOP_GUARD_PROGRESS_LIMIT') {
366
+ guidance += `Progress tool "${name}" repeatedly called without task changes. Stop updating task lists and proceed to execute or respond.`;
367
+ } else if (code === 'LOOP_GUARD_LIMIT') {
368
+ guidance += `Turn budget of ${config?.maxToolAttemptsPerTurn ?? 64} non-productive attempts exhausted. Cease tool execution and explain current progress or roadblock to the user.`;
369
+ } else if (code === 'LOOP_GUARD_OSCILLATION') {
370
+ guidance += 'Alternating sequence of tools was repeated without progress. Break the cycle: alter your strategy, check prerequisites, or answer directly.';
371
+ } else if (code === 'LOOP_GUARD_PSEUDO_TOOL_CALL') {
372
+ 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
+ } else if (code === 'LOOP_GUARD_ERROR_THRASHING') {
374
+ 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.';
375
+ } else {
376
+ guidance += 'Cease tool execution and provide a final text response. The next user turn will reset this guard.';
377
+ }
378
+ return `[${code}] ${detail}. No productive progress was observed; provide the final text answer now. ${guidance}`;
379
+ }
380
+