@goodandready/dsh-agent-loop-guard 0.2.28 → 0.2.29
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/lib/guard-helpers.js +264 -0
- package/lib/guard-state.js +32 -269
- package/package.json +8 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.2.29] - 2026-11-12
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- **Canonical Entry Points & Documentation (#136)**: Added standard project entry files `AGENTS.md` (agent workflow constraints, identity invariants, build commands), `index.md` (project roadmap, architecture, commands, test matrix), and `deploy.sh` (canonical test, identity, and profile installation script). Added `.gitattributes` with `export-ignore` rules, ensuring internal documentation is strictly excluded from npm releases and public GitHub mirrors.
|
|
7
|
+
- **Package Cleanliness & Root Artifact Guard (#137)**: Added `scripts/pack-check.mjs` and `npm run pack:check` script. Enforces that untracked `.tgz` archives cannot reside in the repository root (moved to persistent `~/.dsh/artifacts/`) and validates the strict file size budget (<= 256 KiB) across all packaged files. Added automated unit tests in `test/pack-release.test.js`.
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
- **Security Vulnerability Remediations (#138)**: Resolved high-severity vulnerability in `zod` (GHSA-mrhx-c7xc-m3w5) and moderate-severity vulnerability in `fast-uri` (GHSA-w74x-v6f9-j3xg) via explicit `overrides` in `package.json` (`zod >= 4.6.6`, `fast-uri >= 3.1.9`). Cleaned `npm audit --omit=dev` down to 0 vulnerabilities.
|
|
11
|
+
- **Dead Export Removal & Architecture Modularization (#139)**: Removed unused and dead export `DEFAULT_STOP_PATTERNS` from `lib/guard-state.js` in favor of anchored regular expressions `EXPLICIT_STOP_EN` / `EXPLICIT_STOP_ZH` in `isDefaultStopRequest()`. Modularized helper functions, pattern compilers, and fingerprint generators into `lib/guard-helpers.js` with full backward-compatible re-exports, bringing all server files strictly under the 600-line limit and eliminating preflight warnings.
|
|
12
|
+
|
|
3
13
|
## [0.2.28] - 2026-11-10
|
|
4
14
|
|
|
5
15
|
### Added
|
|
@@ -0,0 +1,264 @@
|
|
|
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
|
+
// Direct single-command match
|
|
12
|
+
if (EXPLICIT_STOP_EN.test(trimmed) || EXPLICIT_STOP_ZH.test(trimmed)) {
|
|
13
|
+
return true;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// Multi-sentence / multi-line message: check if any standalone segment/sentence is an explicit stop command
|
|
17
|
+
const segments = trimmed.split(/[\r\n.!?。!?]+/).map((s) => s.trim()).filter(Boolean);
|
|
18
|
+
for (const segment of segments) {
|
|
19
|
+
if (EXPLICIT_STOP_EN.test(segment) || EXPLICIT_STOP_ZH.test(segment)) {
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function detectOscillation(sequence, maxRepeats = 3, minPeriod = 2, maxPeriod = 4) {
|
|
28
|
+
if (!Array.isArray(sequence)) return null;
|
|
29
|
+
const len = sequence.length;
|
|
30
|
+
|
|
31
|
+
for (let period = minPeriod; period <= maxPeriod; period++) {
|
|
32
|
+
const requiredLength = period * maxRepeats;
|
|
33
|
+
if (len < requiredLength) continue;
|
|
34
|
+
|
|
35
|
+
const sample = sequence.slice(len - period, len);
|
|
36
|
+
const allSame = sample.every((item) => item === sample[0]);
|
|
37
|
+
if (allSame) continue;
|
|
38
|
+
|
|
39
|
+
let isMatch = true;
|
|
40
|
+
for (let rep = 1; rep < maxRepeats; rep++) {
|
|
41
|
+
for (let i = 0; i < period; i++) {
|
|
42
|
+
const expected = sequence[len - period + i];
|
|
43
|
+
const actual = sequence[len - (rep + 1) * period + i];
|
|
44
|
+
if (expected !== actual) {
|
|
45
|
+
isMatch = false;
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (!isMatch) break;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (isMatch) {
|
|
53
|
+
return {
|
|
54
|
+
period,
|
|
55
|
+
repeats: maxRepeats,
|
|
56
|
+
cycle: sample,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const DEFAULT_PSEUDO_TOOL_PATTERNS = [
|
|
65
|
+
/<(?:invoke|function_call|tool_call|call:)\b/iu,
|
|
66
|
+
/<\/(?:invoke|function_call|tool_call)>/iu,
|
|
67
|
+
/```(?:tool_call|invoke|function_call)\b/iu,
|
|
68
|
+
/(?:\[TOOL_CALLS?\]|\[(?:TOOL_CALL|CALL):)/iu,
|
|
69
|
+
];
|
|
70
|
+
|
|
71
|
+
export function compilePseudoToolPatterns(customPatterns = []) {
|
|
72
|
+
if (!Array.isArray(customPatterns)) return [];
|
|
73
|
+
const compiled = [];
|
|
74
|
+
for (const item of customPatterns) {
|
|
75
|
+
if (item instanceof RegExp) {
|
|
76
|
+
compiled.push(item);
|
|
77
|
+
} else if (typeof item === 'string' && item.trim() !== '') {
|
|
78
|
+
try {
|
|
79
|
+
const match = /^\/(.+)\/([a-z]*)$/i.exec(item.trim());
|
|
80
|
+
if (match) {
|
|
81
|
+
compiled.push(new RegExp(match[1], match[2] || 'iu'));
|
|
82
|
+
} else {
|
|
83
|
+
const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, (m) => '\\' + m);
|
|
84
|
+
compiled.push(new RegExp(escaped, 'iu'));
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, (m) => '\\' + m);
|
|
88
|
+
compiled.push(new RegExp(escaped, 'iu'));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return compiled;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function isPseudoToolCallText(text, customPatterns = []) {
|
|
96
|
+
if (!text || typeof text !== 'string') return false;
|
|
97
|
+
for (const regex of DEFAULT_PSEUDO_TOOL_PATTERNS) {
|
|
98
|
+
if (regex.test(text)) return true;
|
|
99
|
+
}
|
|
100
|
+
const compiled = compilePseudoToolPatterns(customPatterns);
|
|
101
|
+
for (const regex of compiled) {
|
|
102
|
+
if (regex.test(text)) return true;
|
|
103
|
+
}
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function compileStopPatterns(customPatterns = []) {
|
|
108
|
+
if (!Array.isArray(customPatterns)) return [];
|
|
109
|
+
const compiled = [];
|
|
110
|
+
for (const item of customPatterns) {
|
|
111
|
+
if (item instanceof RegExp) {
|
|
112
|
+
compiled.push(item);
|
|
113
|
+
} else if (typeof item === 'string' && item.trim() !== '') {
|
|
114
|
+
const escaped = item.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
115
|
+
compiled.push(new RegExp(escaped, 'iu'));
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return compiled;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const SECRET_KEY_PATTERN = /(?:token|secret|password|authorization|api[-_]?key|cookie)/iu;
|
|
122
|
+
|
|
123
|
+
function stableJson(value) {
|
|
124
|
+
if (value === null || typeof value !== 'object') return JSON.stringify(value);
|
|
125
|
+
if (Array.isArray(value)) return '[' + value.map(stableJson).join(',') + ']';
|
|
126
|
+
return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + stableJson(value[key])).join(',') + '}';
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function normalizedJson(value) {
|
|
130
|
+
if (value === null || typeof value !== 'object') {
|
|
131
|
+
if (typeof value === 'string') return JSON.stringify(value.trim().replace(/\s+/gu, ' '));
|
|
132
|
+
return JSON.stringify(value);
|
|
133
|
+
}
|
|
134
|
+
if (Array.isArray(value)) return '[' + value.map(normalizedJson).join(',') + ']';
|
|
135
|
+
return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + normalizedJson(value[key])).join(',') + '}';
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function textFrom(value) {
|
|
139
|
+
if (!Array.isArray(value)) return '';
|
|
140
|
+
return value.map((block) => {
|
|
141
|
+
if (block === null || typeof block !== 'object') return '';
|
|
142
|
+
if (typeof block.text === 'string') return block.text;
|
|
143
|
+
if (Array.isArray(block.content)) return textFrom(block.content);
|
|
144
|
+
return '';
|
|
145
|
+
}).join('\n');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function safeLogValue(value, depth = 0) {
|
|
149
|
+
if (depth > 3) return '[depth-limit]';
|
|
150
|
+
if (typeof value === 'string') {
|
|
151
|
+
return value.replace(/((?:Bearer|token)\s+)[^\s'"]+/giu, '$1[redacted]')
|
|
152
|
+
.replace(/((?:token|secret|password|authorization|api[-_]?key)=)[^\s&]+/giu, '$1[redacted]')
|
|
153
|
+
.slice(0, 400);
|
|
154
|
+
}
|
|
155
|
+
if (value === null || typeof value !== 'object') return value;
|
|
156
|
+
if (Array.isArray(value)) return value.slice(0, 20).map((item) => safeLogValue(item, depth + 1));
|
|
157
|
+
const output = {};
|
|
158
|
+
for (const [key, item] of Object.entries(value).slice(0, 40)) {
|
|
159
|
+
output[key] = SECRET_KEY_PATTERN.test(key) ? '[redacted]' : safeLogValue(item, depth + 1);
|
|
160
|
+
}
|
|
161
|
+
return output;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function positiveInteger(value, fallback) {
|
|
165
|
+
return Number.isSafeInteger(value) && value >= 1 ? value : fallback;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function nonNegativeInteger(value, fallback) {
|
|
169
|
+
return Number.isSafeInteger(value) && value >= 0 ? value : fallback;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function hasStopRequest(messages, customPatterns = []) {
|
|
173
|
+
if (!Array.isArray(messages)) return false;
|
|
174
|
+
const compiledCustom = compileStopPatterns(customPatterns);
|
|
175
|
+
let lastUserMessage = null;
|
|
176
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
177
|
+
const msg = messages[i];
|
|
178
|
+
if (msg && (msg.source?.kind === 'user' || msg.role === 'user')) {
|
|
179
|
+
lastUserMessage = msg;
|
|
180
|
+
break;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (!lastUserMessage) return false;
|
|
184
|
+
|
|
185
|
+
const text = textFrom(lastUserMessage.content);
|
|
186
|
+
if (!text) return false;
|
|
187
|
+
|
|
188
|
+
if (isDefaultStopRequest(text)) {
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
return compiledCustom.some((regex) => regex.test(text));
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export function callFingerprint(name, args) {
|
|
195
|
+
try {
|
|
196
|
+
const raw = stableJson(args);
|
|
197
|
+
const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
|
|
198
|
+
return String(name) + ':' + body;
|
|
199
|
+
} catch {
|
|
200
|
+
return String(name) + ':<unserializable>';
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export function callRepeatFingerprint(name, args) {
|
|
205
|
+
try {
|
|
206
|
+
const raw = normalizedJson(args);
|
|
207
|
+
const body = raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
|
|
208
|
+
return String(name) + ':' + body;
|
|
209
|
+
} catch {
|
|
210
|
+
return String(name) + ':<unserializable>';
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function resultFingerprint(value) {
|
|
215
|
+
try {
|
|
216
|
+
const raw = stableJson(value);
|
|
217
|
+
return raw.length > 256 ? 'sha256:' + createHash('sha256').update(raw).digest('hex') : raw;
|
|
218
|
+
} catch {
|
|
219
|
+
return '<unserializable-result>';
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export function safeCallSummary(name, args) {
|
|
224
|
+
return {
|
|
225
|
+
tool: String(name),
|
|
226
|
+
arguments: safeLogValue(args),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function hasOwn(object, key) {
|
|
231
|
+
return object !== null && typeof object === 'object' && Object.prototype.hasOwnProperty.call(object, key);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
export function outcomeFromExecution(execution, maybeResult = undefined) {
|
|
235
|
+
const result = maybeResult !== undefined ? maybeResult : execution?.result;
|
|
236
|
+
const data = execution?.data;
|
|
237
|
+
const hasResult = result !== undefined
|
|
238
|
+
|| hasOwn(execution, 'result')
|
|
239
|
+
|| hasOwn(execution, 'output')
|
|
240
|
+
|| hasOwn(data, 'result')
|
|
241
|
+
|| hasOwn(data, 'output')
|
|
242
|
+
|| hasOwn(execution, 'error')
|
|
243
|
+
|| hasOwn(execution, 'content')
|
|
244
|
+
|| hasOwn(execution, 'isError');
|
|
245
|
+
if (!hasResult) return { known: false, successful: false, resultFingerprint: '<unknown>', progressToken: '<unknown>' };
|
|
246
|
+
const value = result ?? execution?.output ?? data?.result ?? data?.output
|
|
247
|
+
?? (hasOwn(execution, 'error') ? { error: execution.error } : undefined);
|
|
248
|
+
const failed = (execution?.error != null && execution?.error !== false)
|
|
249
|
+
|| execution?.isError === true
|
|
250
|
+
|| value?.isError === true
|
|
251
|
+
|| value?.success === false
|
|
252
|
+
|| value?.ok === false
|
|
253
|
+
|| (value?.error != null && value?.error !== false);
|
|
254
|
+
const explicitProgress = execution?.progressToken ?? execution?.progress ?? execution?.stateVersion
|
|
255
|
+
?? data?.progressToken ?? data?.progress ?? data?.stateVersion
|
|
256
|
+
?? value?.progressToken ?? value?.progress ?? value?.stateVersion
|
|
257
|
+
?? value?.meta?.progressToken;
|
|
258
|
+
return {
|
|
259
|
+
known: true,
|
|
260
|
+
successful: !failed,
|
|
261
|
+
resultFingerprint: resultFingerprint(value),
|
|
262
|
+
progressToken: explicitProgress === undefined ? resultFingerprint(value) : resultFingerprint(explicitProgress),
|
|
263
|
+
};
|
|
264
|
+
}
|
package/lib/guard-state.js
CHANGED
|
@@ -1,274 +1,37 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
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
|
+
} from './guard-helpers.js';
|
|
17
|
+
|
|
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,
|
|
5
33
|
};
|
|
6
34
|
|
|
7
|
-
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;
|
|
8
|
-
const EXPLICIT_STOP_ZH = /^(?:请|检测到)?(?:停止|暂停|取消|终止|死循环)(?:执行|操作|调用|一下|了)?[!。??!]*$/u;
|
|
9
|
-
|
|
10
|
-
export function isDefaultStopRequest(text) {
|
|
11
|
-
if (!text || typeof text !== 'string') return false;
|
|
12
|
-
const trimmed = text.trim();
|
|
13
|
-
if (!trimmed) return false;
|
|
14
|
-
|
|
15
|
-
// Direct single-command match
|
|
16
|
-
if (EXPLICIT_STOP_EN.test(trimmed) || EXPLICIT_STOP_ZH.test(trimmed)) {
|
|
17
|
-
return true;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// Multi-sentence / multi-line message: check if any standalone segment/sentence is an explicit stop command
|
|
21
|
-
const segments = trimmed.split(/[\r\n.!?。!?]+/).map((s) => s.trim()).filter(Boolean);
|
|
22
|
-
for (const segment of segments) {
|
|
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
|
-
}
|
|
271
|
-
|
|
272
35
|
export class LoopGuardState {
|
|
273
36
|
constructor(config = {}) {
|
|
274
37
|
const progressToolNames = Array.isArray(config.progressToolNames)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodandready/dsh-agent-loop-guard",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.29",
|
|
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
|
}
|