@goodandready/dsh-agent-loop-guard 0.3.5 → 0.3.7
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 +15 -0
- package/README.md +4 -2
- package/lib/client.js +13 -28
- package/lib/guard-helpers.js +0 -30
- package/lib/guard-state.js +6 -7
- package/lib/index.js +51 -11
- package/lib/target-quota-guard.js +72 -7
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.3.6] - 2026-11-18
|
|
4
|
+
|
|
5
|
+
### Fixed
|
|
6
|
+
- **Telemetry Redaction Completeness (#156)**: `lastViolation.reason` is now redacted with `redactTelemetryText`, matching incident journal redaction; absolute target paths no longer leak through the telemetry endpoint.
|
|
7
|
+
- **Localization Standard Compliance (#154)**: Removed the in-plugin `ru` dictionary and registration; the client registers exactly `{ en, zh }`. Russian UI is provided by `dsh-russian-lang`, with translation keys tracked there.
|
|
8
|
+
- **Windows Test Portability (#161)**: Symlink assertion skips gracefully when Windows denies symlink creation (`EPERM`/`EACCES`), and case-sensitive target expectations are platform-aware.
|
|
9
|
+
- **Documentation Sync (#160)**: `index.md` names the current release line; DESIGN uses canonical `--dsw-alias-brand-primary` and state tokens; docs-consistency test guards both.
|
|
10
|
+
- **Line Budget Headroom (#164)**: Moved `decrementReservations` into `lib/target-quota-guard.js`, reducing `lib/guard-helpers.js` below 450 lines.
|
|
11
|
+
- **Dead Import Cleanup (#165)**: Removed the remaining unused `GUARD_PRESETS` import from `lib/guard-state.js`.
|
|
12
|
+
- **Windows Packaging Warning (#153)**: `pack-release.mjs` prefers `npm_execpath`, avoiding `shell:true` argument concatenation under `npm run`; `npm run pack:release` remains cross-platform.
|
|
13
|
+
- **Preset Documentation (#159)**: Clarified that `Balanced` is a recommended, stricter-than-default profile; server/client parity remains enforced by `test/presets-parity.test.js`.
|
|
14
|
+
|
|
15
|
+
### Documentation
|
|
16
|
+
- Added `npm ci` and `npm audit --omit=dev --audit-level=high` to the verification workflow; the reviewed lockfile is part of the release gate.
|
|
17
|
+
|
|
3
18
|
## [0.3.5] - 2026-11-18
|
|
4
19
|
|
|
5
20
|
### Fixed
|
package/README.md
CHANGED
|
@@ -48,7 +48,7 @@ When autonomous AI coding agents encounter unexpected tool failures, ambiguous i
|
|
|
48
48
|
5. **Error Thrashing Guard**: Halts runaway failure cycles sharing normalized error signatures (`FS_ENOENT`, `FS_EPERM`, `EXIT_*`, `HTTP_*`, etc.) even when parameters vary.
|
|
49
49
|
6. **Smart Steering**: 2-stage defense injecting actionable self-correction directives (`[LOOP_GUARD_STEER]`) before escalating to hard cancellation.
|
|
50
50
|
7. **Incident Journal & Diagnostic Dump**: Circular telemetry buffer tracking recent incidents with execution chains and 1-click dump copying in Web UI.
|
|
51
|
-
8. **Sensitivity Presets**: 1-click preset selector (`Strict`, `Balanced`, `Autonomous Coding`) for immediate threshold configuration.
|
|
51
|
+
8. **Sensitivity Presets**: 1-click preset selector (`Strict`, `Balanced`, `Autonomous Coding`) for immediate threshold configuration. `Balanced` is a recommended starting profile and is intentionally stricter than the schema defaults.
|
|
52
52
|
9. **Zero Core Modifications**: Implemented purely through Cordis lifecycle hooks (`ctx.tools.guard`, `agent/pre-step`, `tools/execute`, `session/event`).
|
|
53
53
|
|
|
54
54
|
---
|
|
@@ -208,11 +208,13 @@ dsh-agent-loop-guard:
|
|
|
208
208
|
|
|
209
209
|
## 🧪 Testing & Verification
|
|
210
210
|
|
|
211
|
-
|
|
211
|
+
The reviewed `package-lock.json` pins the peer dependency graph used for audit and CI. Use `npm ci` for a clean, lockfile-respecting install:
|
|
212
212
|
|
|
213
213
|
```bash
|
|
214
|
+
npm ci
|
|
214
215
|
npm test
|
|
215
216
|
npm run check
|
|
217
|
+
npm audit --omit=dev --audit-level=high
|
|
216
218
|
```
|
|
217
219
|
|
|
218
220
|
---
|
package/lib/client.js
CHANGED
|
@@ -76,6 +76,7 @@ window.__ModuleLoader__.load({
|
|
|
76
76
|
progressToolNames: 'Progress tool names (comma-separated)', pseudoToolCallThreshold: 'Pseudo tool-call loop threshold (turns, 0 = disabled)',
|
|
77
77
|
oscillationDetection: 'Oscillation loop guard (ping-pong cycles)', maxOscillationRepeats: 'Max oscillation repeats (2-4 step cycles)',
|
|
78
78
|
payloadBloatGuard: 'Payload bloat guard (truncate huge outputs)', maxToolResultChars: 'Max tool result characters (0 = disabled)',
|
|
79
|
+
stopPatterns: 'Stop patterns (user message regexes, comma separated)', pseudoToolCallPatterns: 'Pseudo tool-call patterns (regex, comma separated)',
|
|
79
80
|
errorThrashingGuard: 'Error thrashing guard (fail-loop detection)', maxConsecutiveFailures: 'Max consecutive failures before thrashing block',
|
|
80
81
|
adaptiveSteering: 'Smart steering (guide agent before hard cancel)', targetQuotaGuard: 'Target quota guard (per-file loop protection)',
|
|
81
82
|
maxUnchangedReadsPerTarget: 'Max unchanged reads per target file', maxReadsPerTarget: 'Max reads per target file per turn',
|
|
@@ -83,31 +84,6 @@ window.__ModuleLoader__.load({
|
|
|
83
84
|
saving: 'Saving…', ready: 'Save Settings', saved: 'Saved',
|
|
84
85
|
};
|
|
85
86
|
|
|
86
|
-
const ru = {
|
|
87
|
-
title: 'Agent Loop Guard', sub: 'Защита от бесконечных циклов инструментов и вывода ассистента', version: 'Версия',
|
|
88
|
-
updateChecking: 'Проверка обновлений…', updateAvailable: 'Доступно обновление: v{v}', upToDate: 'Установлена актуальная версия',
|
|
89
|
-
updateNow: 'Обновить сейчас', updateViaPluginsPage: 'Обновите на вкладке плагинов', updating: 'Обновление…',
|
|
90
|
-
updateSuccess: 'Обновлено до v{v}. Перезапустите службу DSH для применения.', updateFailed: 'Ошибка обновления: {msg}', checkUpdateFailed: 'Не удалось проверить',
|
|
91
|
-
telemetryTitle: 'Телеметрия защиты', telemetryLoadFailed: 'Не удалось загрузить телеметрию', totalBlocked: 'Предотвращено циклов', totalTruncations: 'Усечений',
|
|
92
|
-
steeredCount: 'Упреждающих подсказок', lastViolation: 'Последний инцидент', noViolations: 'В текущем сеансе циклов не зафиксировано.',
|
|
93
|
-
resetStats: 'Сбросить статистику', statsResetDone: 'Статистика сброшена', statsResetFailed: 'Не удалось сбросить статистику',
|
|
94
|
-
presetsTitle: 'Профили', presetStrict: 'Строгий', presetBalanced: 'Баланс', presetAutonomous: 'Автономный код',
|
|
95
|
-
presetApplied: 'Применен профиль {name}', copyDump: 'Скопировать дамп диагностики', dumpCopied: 'Дамп скопирован в буфер',
|
|
96
|
-
incidentsTitle: 'Журнал инцидентов (Post-Mortem)', maxToolAttemptsPerTurn: 'Макс. попыток инструментов за ход (0 = выкл)',
|
|
97
|
-
maxProgressToolCallsPerTurn: 'Макс. вызовов инструментов прогресса за ход', maxCallsPerRepeatGroup: 'Макс. повторов в группе',
|
|
98
|
-
strictTools: 'Строгие инструменты (через запятую)', strictToolLimit: 'Лимит строгих инструментов',
|
|
99
|
-
blockExactDuplicates: 'Блокировать точные дубликаты вызовов', dryRunMode: 'Режим аудита (логировать, но не блокировать)',
|
|
100
|
-
assistantOutputGuard: 'Защита от циклов текста ассистента', maxRepeatedAssistantLines: 'Макс. повторов одной строки',
|
|
101
|
-
maxRepeatedAssistantBlocks: 'Макс. повторов блока текста', maxAssistantBlockChars: 'Макс. размер блока текста для проверки',
|
|
102
|
-
progressToolNames: 'Инструменты прогресса (через запятую)', pseudoToolCallThreshold: 'Порог циклов псевдовызовов (ходов, 0 = выкл)',
|
|
103
|
-
oscillationDetection: 'Защита от осцилляций (циклов туда-сюда)', maxOscillationRepeats: 'Макс. повторов цикла осцилляции',
|
|
104
|
-
payloadBloatGuard: 'Защита от раздувания результатов (обрезка)', maxToolResultChars: 'Макс. символов результата (0 = выкл)',
|
|
105
|
-
errorThrashingGuard: 'Защита от серий ошибок инструментов', maxConsecutiveFailures: 'Порог серии ошибок перед блокировкой',
|
|
106
|
-
adaptiveSteering: 'Умное наставление (предупреждать перед отменой)', targetQuotaGuard: 'Квоты обращений к файлам (защита от циклов по целям)',
|
|
107
|
-
maxUnchangedReadsPerTarget: 'Макс. повторных чтений неизмененного файла', maxReadsPerTarget: 'Макс. чтений одного файла за ход',
|
|
108
|
-
maxEditsPerTarget: 'Макс. правок одного файла за ход', maxTargetAttempts: 'Макс. всего операций над файлом за ход',
|
|
109
|
-
saving: 'Сохранение…', ready: 'Сохранить настройки', saved: 'Сохранено',
|
|
110
|
-
};
|
|
111
87
|
|
|
112
88
|
const zh = {
|
|
113
89
|
title: 'Agent Loop Guard', sub: '工具调用与助手输出防死循环熔断限制', version: '版本',
|
|
@@ -128,6 +104,7 @@ window.__ModuleLoader__.load({
|
|
|
128
104
|
progressToolNames: '进度标记工具(逗号分隔)', pseudoToolCallThreshold: '伪工具调用空转拦截阈值(连续回合数,0 表示禁用)',
|
|
129
105
|
oscillationDetection: '交替循环拦截(乒乓震荡检测)', maxOscillationRepeats: '最大交替循环重复次数(2-4 步序列)',
|
|
130
106
|
payloadBloatGuard: '超大结果防膨胀拦截(截断巨大输出)', maxToolResultChars: '工具结果字符上限(0 表示禁用)',
|
|
107
|
+
stopPatterns: '停止词模式(用户消息正则,逗号分隔)', pseudoToolCallPatterns: '伪工具调用模式(正则,逗号分隔)',
|
|
131
108
|
errorThrashingGuard: '工具重复报错拦截(错误循环保护)', maxConsecutiveFailures: '连续报错熔断阈值',
|
|
132
109
|
adaptiveSteering: '智能自纠正(熔断前引导修正)', targetQuotaGuard: '目标配额守卫(单文件/目标防死循环)',
|
|
133
110
|
maxUnchangedReadsPerTarget: '单文件无变化最大重复读取次数', maxReadsPerTarget: '单文件最大读取次数',
|
|
@@ -142,7 +119,7 @@ window.__ModuleLoader__.load({
|
|
|
142
119
|
oscillationDetection: true, maxOscillationRepeats: 3, payloadBloatGuard: true, maxToolResultChars: 65536,
|
|
143
120
|
errorThrashingGuard: true, maxConsecutiveFailures: 4, adaptiveSteering: true,
|
|
144
121
|
targetQuotaGuard: true, maxUnchangedReadsPerTarget: 3, maxReadsPerTarget: 6,
|
|
145
|
-
maxEditsPerTarget: 8, maxTargetAttempts: 12,
|
|
122
|
+
maxEditsPerTarget: 8, maxTargetAttempts: 12, stopPatterns: [], pseudoToolCallPatterns: [],
|
|
146
123
|
};
|
|
147
124
|
|
|
148
125
|
const CLIENT_PRESETS = {
|
|
@@ -218,7 +195,7 @@ window.__ModuleLoader__.load({
|
|
|
218
195
|
: (typeof ctx?.locale?.getSnapshot === 'function' ? ctx.locale.getSnapshot() : null);
|
|
219
196
|
const loc = typeof snap === 'string' ? snap : (snap?.active || snap?.locale || snap?.id);
|
|
220
197
|
const locStr = String(loc || (typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en')).toLowerCase();
|
|
221
|
-
return locStr.startsWith('zh') ? zh :
|
|
198
|
+
return locStr.startsWith('zh') ? zh : en;
|
|
222
199
|
}
|
|
223
200
|
|
|
224
201
|
function PluginCard({ ctx: _ctx, t, bare, ...props }) {
|
|
@@ -276,6 +253,8 @@ window.__ModuleLoader__.load({
|
|
|
276
253
|
...d, ...DEFAULTS, ...vals,
|
|
277
254
|
progressToolNamesText: names.join(', '),
|
|
278
255
|
strictToolsText: strict.join(', '),
|
|
256
|
+
stopPatternsText: (Array.isArray(vals.stopPatterns) ? vals.stopPatterns : DEFAULTS.stopPatterns).join(', '),
|
|
257
|
+
pseudoToolCallPatternsText: (Array.isArray(vals.pseudoToolCallPatterns) ? vals.pseudoToolCallPatterns : DEFAULTS.pseudoToolCallPatterns).join(', '),
|
|
279
258
|
}));
|
|
280
259
|
}
|
|
281
260
|
setStatus('ready');
|
|
@@ -345,6 +324,8 @@ window.__ModuleLoader__.load({
|
|
|
345
324
|
setMsg('');
|
|
346
325
|
const names = draft.progressToolNamesText.split(',').map((s) => s.trim()).filter(Boolean);
|
|
347
326
|
const strictList = draft.strictToolsText.split(',').map((s) => s.trim()).filter(Boolean);
|
|
327
|
+
const stopList = String(draft.stopPatternsText || '').split(/[,\n]/).map((s) => s.trim()).filter(Boolean);
|
|
328
|
+
const pseudoList = String(draft.pseudoToolCallPatternsText || '').split(/[,\n]/).map((s) => s.trim()).filter(Boolean);
|
|
348
329
|
const payload = {
|
|
349
330
|
maxToolAttemptsPerTurn: Number(draft.maxToolAttemptsPerTurn) || 0, maxProgressToolCallsPerTurn: Number(draft.maxProgressToolCallsPerTurn) || 16,
|
|
350
331
|
maxCallsPerRepeatGroup: Number(draft.maxCallsPerRepeatGroup) || 5, strictTools: strictList, strictToolLimit: Number(draft.strictToolLimit) || 3,
|
|
@@ -361,6 +342,8 @@ window.__ModuleLoader__.load({
|
|
|
361
342
|
maxReadsPerTarget: Number(draft.maxReadsPerTarget) || 6,
|
|
362
343
|
maxEditsPerTarget: Number(draft.maxEditsPerTarget) || 8,
|
|
363
344
|
maxTargetAttempts: Number(draft.maxTargetAttempts) || 12,
|
|
345
|
+
stopPatterns: stopList,
|
|
346
|
+
pseudoToolCallPatterns: pseudoList,
|
|
364
347
|
};
|
|
365
348
|
const errs = [];
|
|
366
349
|
for (const [k, v] of Object.entries(payload)) {
|
|
@@ -504,6 +487,8 @@ window.__ModuleLoader__.load({
|
|
|
504
487
|
field('maxAssistantBlockChars', num('maxAssistantBlockChars')),
|
|
505
488
|
field('progressToolNames', str('progressToolNamesText')),
|
|
506
489
|
field('pseudoToolCallThreshold', num('pseudoToolCallThreshold')),
|
|
490
|
+
field('stopPatterns', str('stopPatternsText')),
|
|
491
|
+
field('pseudoToolCallPatterns', str('pseudoToolCallPatternsText')),
|
|
507
492
|
check('oscillationDetection'),
|
|
508
493
|
field('maxOscillationRepeats', num('maxOscillationRepeats')),
|
|
509
494
|
check('payloadBloatGuard'),
|
|
@@ -541,7 +526,7 @@ window.__ModuleLoader__.load({
|
|
|
541
526
|
exports.inject = ['slots', 'configForms', 'locale'];
|
|
542
527
|
exports.apply = function apply(ctx) {
|
|
543
528
|
if (typeof ctx.locale?.register === 'function') {
|
|
544
|
-
const reg = () => ctx.locale.register(NS, { en, zh
|
|
529
|
+
const reg = () => ctx.locale.register(NS, { en, zh });
|
|
545
530
|
if (typeof ctx.effect === 'function') ctx.effect(reg, 'dsh-agent-loop-guard: locale');
|
|
546
531
|
else reg();
|
|
547
532
|
}
|
package/lib/guard-helpers.js
CHANGED
|
@@ -311,36 +311,6 @@ export {
|
|
|
311
311
|
handleTargetViolation,
|
|
312
312
|
} from './target-quota-guard.js';
|
|
313
313
|
|
|
314
|
-
export function decrementReservations(state, call) {
|
|
315
|
-
if (!call || !call.counted || call.committed) return;
|
|
316
|
-
state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
|
|
317
|
-
if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
|
|
318
|
-
if (call.repeatFingerprint) {
|
|
319
|
-
const group = state.repeatGroups.get(call.repeatFingerprint);
|
|
320
|
-
if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
|
|
321
|
-
group.count = Math.max(0, group.count - 1);
|
|
322
|
-
}
|
|
323
|
-
}
|
|
324
|
-
if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
|
|
325
|
-
const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
|
|
326
|
-
if (lastIdx !== -1) {
|
|
327
|
-
state.recentCallSequence.splice(lastIdx, 1);
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
if (call.fingerprint) {
|
|
331
|
-
const exact = state.exactGroups.get(call.fingerprint);
|
|
332
|
-
if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
|
|
333
|
-
exact.count = Math.max(0, exact.count - 1);
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
if (call.target && state.targetCallCounts) {
|
|
337
|
-
const counts = state.targetCallCounts.get(call.target);
|
|
338
|
-
if (counts) {
|
|
339
|
-
if (call.action && counts[call.action] > 0) counts[call.action] -= 1;
|
|
340
|
-
if (counts.total > 0) counts.total -= 1;
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
314
|
|
|
345
315
|
|
|
346
316
|
|
package/lib/guard-state.js
CHANGED
|
@@ -1,23 +1,18 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isDefaultStopRequest,
|
|
3
3
|
detectOscillation,
|
|
4
|
-
DEFAULT_PSEUDO_TOOL_PATTERNS,
|
|
5
4
|
compilePseudoToolPatterns,
|
|
6
5
|
isPseudoToolCallText,
|
|
7
|
-
compileStopPatterns,
|
|
8
6
|
positiveInteger,
|
|
9
7
|
nonNegativeInteger,
|
|
10
8
|
hasStopRequest,
|
|
11
9
|
callFingerprint,
|
|
12
10
|
callRepeatFingerprint,
|
|
13
|
-
resultFingerprint,
|
|
14
11
|
safeCallSummary,
|
|
15
12
|
outcomeFromExecution,
|
|
16
13
|
normalizeErrorSignature,
|
|
17
|
-
GUARD_PRESETS,
|
|
18
14
|
formatSteeringAdvice,
|
|
19
15
|
formatViolationGuidance,
|
|
20
|
-
decrementReservations,
|
|
21
16
|
} from './guard-helpers.js';
|
|
22
17
|
|
|
23
18
|
import {
|
|
@@ -28,6 +23,7 @@ import {
|
|
|
28
23
|
handleTargetViolation,
|
|
29
24
|
maskSessionId,
|
|
30
25
|
redactTelemetryText,
|
|
26
|
+
decrementReservations,
|
|
31
27
|
} from './target-quota-guard.js';
|
|
32
28
|
|
|
33
29
|
export * from './guard-helpers.js';
|
|
@@ -170,7 +166,7 @@ export class LoopGuardState {
|
|
|
170
166
|
tool: extra.tool || 'assistant/output',
|
|
171
167
|
timestamp: Date.now(),
|
|
172
168
|
turn: extra.turn,
|
|
173
|
-
reason: detail,
|
|
169
|
+
reason: redactTelemetryText(detail),
|
|
174
170
|
};
|
|
175
171
|
this.recordIncident(null, code, detail, extra.tool || 'assistant/output', null);
|
|
176
172
|
}
|
|
@@ -178,6 +174,9 @@ export class LoopGuardState {
|
|
|
178
174
|
getTelemetry() {
|
|
179
175
|
return {
|
|
180
176
|
...this.metrics,
|
|
177
|
+
lastViolation: this.metrics.lastViolation
|
|
178
|
+
? { ...this.metrics.lastViolation, reason: redactTelemetryText(this.metrics.lastViolation.reason) }
|
|
179
|
+
: null,
|
|
181
180
|
activeAgents: this.byAgent.size,
|
|
182
181
|
dryRunMode: Boolean(this.config.dryRunMode),
|
|
183
182
|
incidents: (this.incidents || []).slice(-20).reverse(),
|
|
@@ -365,7 +364,7 @@ export class LoopGuardState {
|
|
|
365
364
|
tool: String(name),
|
|
366
365
|
timestamp: Date.now(),
|
|
367
366
|
turn: state.turn,
|
|
368
|
-
reason: detail,
|
|
367
|
+
reason: redactTelemetryText(detail),
|
|
369
368
|
};
|
|
370
369
|
this.recordIncident(agent, code, detail, name, state);
|
|
371
370
|
|
package/lib/index.js
CHANGED
|
@@ -28,6 +28,48 @@ export function truncateText(text, maxChars = 65536, headRatio = 0.7) {
|
|
|
28
28
|
return head + banner + tail;
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
+
const DEEP_TRUNCATE_MAX_DEPTH = 6;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Truncates oversized strings anywhere inside a JSON-like value (#177).
|
|
35
|
+
* Plain objects and arrays are cloned only along the changed path; cycles,
|
|
36
|
+
* non-plain objects (Buffer, Date, class instances) and the depth limit are
|
|
37
|
+
* left untouched.
|
|
38
|
+
*/
|
|
39
|
+
function truncateDeep(value, maxChars, depth = 0, seen = new WeakSet()) {
|
|
40
|
+
if (typeof value === 'string') {
|
|
41
|
+
return value.length > maxChars ? truncateText(value, maxChars) : value;
|
|
42
|
+
}
|
|
43
|
+
if (value === null || typeof value !== 'object' || depth >= DEEP_TRUNCATE_MAX_DEPTH) return value;
|
|
44
|
+
if (seen.has(value)) return value;
|
|
45
|
+
seen.add(value);
|
|
46
|
+
|
|
47
|
+
if (Array.isArray(value)) {
|
|
48
|
+
let clone = null;
|
|
49
|
+
for (let i = 0; i < value.length; i++) {
|
|
50
|
+
const next = truncateDeep(value[i], maxChars, depth + 1, seen);
|
|
51
|
+
if (next !== value[i]) {
|
|
52
|
+
if (!clone) clone = value.slice();
|
|
53
|
+
clone[i] = next;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return clone || value;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const proto = Object.getPrototypeOf(value);
|
|
60
|
+
if (proto !== Object.prototype && proto !== null) return value;
|
|
61
|
+
|
|
62
|
+
let clone = null;
|
|
63
|
+
for (const key of Object.keys(value)) {
|
|
64
|
+
const next = truncateDeep(value[key], maxChars, depth + 1, seen);
|
|
65
|
+
if (next !== value[key]) {
|
|
66
|
+
if (!clone) clone = { ...value };
|
|
67
|
+
clone[key] = next;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return clone || value;
|
|
71
|
+
}
|
|
72
|
+
|
|
31
73
|
export function truncateExecutionResult(result, maxChars, state = null, execution = null) {
|
|
32
74
|
if (!result || typeof result !== 'object' || maxChars <= 0) return result;
|
|
33
75
|
|
|
@@ -39,24 +81,22 @@ export function truncateExecutionResult(result, maxChars, state = null, executio
|
|
|
39
81
|
truncatedValue = truncateText(result.value, maxChars);
|
|
40
82
|
didTruncate = true;
|
|
41
83
|
} else if (result.value !== null && typeof result.value === 'object') {
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
clonedVal[key] = truncateText(result.value[key], maxChars);
|
|
47
|
-
didTruncate = true;
|
|
48
|
-
}
|
|
84
|
+
const deepValue = truncateDeep(result.value, maxChars);
|
|
85
|
+
if (deepValue !== result.value) {
|
|
86
|
+
truncatedValue = deepValue;
|
|
87
|
+
didTruncate = true;
|
|
49
88
|
}
|
|
50
|
-
if (clonedVal) truncatedValue = clonedVal;
|
|
51
89
|
}
|
|
52
90
|
|
|
53
91
|
if (Array.isArray(result.content)) {
|
|
54
92
|
let clonedContent = null;
|
|
55
93
|
for (let i = 0; i < result.content.length; i++) {
|
|
56
94
|
const block = result.content[i];
|
|
57
|
-
if (block
|
|
58
|
-
|
|
59
|
-
|
|
95
|
+
if (!block || typeof block !== 'object') continue;
|
|
96
|
+
const deepBlock = truncateDeep(block, maxChars);
|
|
97
|
+
if (deepBlock !== block) {
|
|
98
|
+
if (!clonedContent) clonedContent = result.content.slice();
|
|
99
|
+
clonedContent[i] = deepBlock;
|
|
60
100
|
didTruncate = true;
|
|
61
101
|
}
|
|
62
102
|
}
|
|
@@ -37,6 +37,35 @@ export function classifyToolAction(name) {
|
|
|
37
37
|
return 'default';
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
+
const REALPATH_CACHE_TTL_MS = 30000;
|
|
41
|
+
const REALPATH_CACHE_MAX = 500;
|
|
42
|
+
const realpathCache = new Map();
|
|
43
|
+
|
|
44
|
+
function readRealpathCache(probe) {
|
|
45
|
+
const hit = realpathCache.get(probe);
|
|
46
|
+
if (!hit) return undefined;
|
|
47
|
+
if (Date.now() - hit.at > REALPATH_CACHE_TTL_MS) {
|
|
48
|
+
realpathCache.delete(probe);
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
return hit.real;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function writeRealpathCache(probe, real) {
|
|
55
|
+
if (realpathCache.size >= REALPATH_CACHE_MAX) realpathCache.clear();
|
|
56
|
+
realpathCache.set(probe, { real, at: Date.now() });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** @internal test hook: current realpath cache size (#175). */
|
|
60
|
+
export function getTargetKeyCacheSize() {
|
|
61
|
+
return realpathCache.size;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @internal test hook: reset the realpath cache (#175). */
|
|
65
|
+
export function clearTargetKeyCache() {
|
|
66
|
+
realpathCache.clear();
|
|
67
|
+
}
|
|
68
|
+
|
|
40
69
|
export function extractTargetKey(name, args) {
|
|
41
70
|
if (!args) return null;
|
|
42
71
|
let raw = null;
|
|
@@ -77,12 +106,17 @@ export function extractTargetKey(name, args) {
|
|
|
77
106
|
|
|
78
107
|
try {
|
|
79
108
|
const probe = path.isAbsolute(normalized) ? normalized : path.resolve(normalized);
|
|
80
|
-
|
|
109
|
+
const cachedReal = readRealpathCache(probe);
|
|
110
|
+
if (cachedReal !== undefined) {
|
|
111
|
+
if (cachedReal) normalized = cachedReal;
|
|
112
|
+
} else if (fs.existsSync(probe)) {
|
|
81
113
|
const stat = fs.lstatSync(probe);
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
114
|
+
let real = null;
|
|
115
|
+
if (stat.isSymbolicLink()) real = fs.realpathSync(probe).replace(/\\/g, '/');
|
|
116
|
+
writeRealpathCache(probe, real);
|
|
117
|
+
if (real) normalized = real;
|
|
118
|
+
} else {
|
|
119
|
+
writeRealpathCache(probe, null);
|
|
86
120
|
}
|
|
87
121
|
} catch {
|
|
88
122
|
// best-effort filesystem check
|
|
@@ -221,7 +255,7 @@ export function handleTargetViolation(state, guard, agent, name, args, check) {
|
|
|
221
255
|
tool: String(name),
|
|
222
256
|
timestamp: Date.now(),
|
|
223
257
|
turn: state.turn,
|
|
224
|
-
reason: check.detail,
|
|
258
|
+
reason: redactTelemetryText(check.detail),
|
|
225
259
|
};
|
|
226
260
|
guard.recordIncident(agent, check.code, check.detail, name, state);
|
|
227
261
|
if (config.dryRunMode) return undefined;
|
|
@@ -241,4 +275,35 @@ export function redactTelemetryText(text) {
|
|
|
241
275
|
sanitized = sanitized.replace(/(?:\/(?:[a-zA-Z0-9._-]+)\/)+(?:[a-zA-Z0-9._-]+\/)*([a-zA-Z0-9._-]+)/g, '.../$1');
|
|
242
276
|
return sanitized;
|
|
243
277
|
}
|
|
244
|
-
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
export function decrementReservations(state, call) {
|
|
281
|
+
if (!call || !call.counted || call.committed) return;
|
|
282
|
+
state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
|
|
283
|
+
if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
|
|
284
|
+
if (call.repeatFingerprint) {
|
|
285
|
+
const group = state.repeatGroups.get(call.repeatFingerprint);
|
|
286
|
+
if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
|
|
287
|
+
group.count = Math.max(0, group.count - 1);
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
|
|
291
|
+
const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
|
|
292
|
+
if (lastIdx !== -1) {
|
|
293
|
+
state.recentCallSequence.splice(lastIdx, 1);
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
if (call.fingerprint) {
|
|
297
|
+
const exact = state.exactGroups.get(call.fingerprint);
|
|
298
|
+
if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
|
|
299
|
+
exact.count = Math.max(0, exact.count - 1);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (call.target && state.targetCallCounts) {
|
|
303
|
+
const counts = state.targetCallCounts.get(call.target);
|
|
304
|
+
if (counts) {
|
|
305
|
+
if (call.action && counts[call.action] > 0) counts[call.action] -= 1;
|
|
306
|
+
if (counts.total > 0) counts.total -= 1;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|