@goodandready/dsh-agent-loop-guard 0.2.3 → 0.2.5

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.
@@ -88,11 +88,11 @@ function outcomeFromExecution(execution) {
88
88
  if (!hasResult) return { known: false, successful: false, resultFingerprint: '<unknown>', progressToken: '<unknown>' };
89
89
  const value = execution?.result ?? execution?.output ?? data?.result ?? data?.output
90
90
  ?? (hasOwn(execution, 'error') ? { error: execution.error } : undefined);
91
- const failed = execution?.error !== undefined
91
+ const failed = (execution?.error != null && execution?.error !== false)
92
92
  || value?.isError === true
93
93
  || value?.success === false
94
94
  || value?.ok === false
95
- || value?.error !== undefined;
95
+ || (value?.error != null && value?.error !== false);
96
96
  const explicitProgress = execution?.progressToken ?? execution?.progress ?? execution?.stateVersion
97
97
  ?? data?.progressToken ?? data?.progress ?? data?.stateVersion;
98
98
  return {
@@ -110,17 +110,92 @@ export class LoopGuardState {
110
110
  .filter((name) => typeof name === 'string' && name.trim() !== '')
111
111
  .map((name) => name.trim())
112
112
  : ['todo_write'];
113
+ const strictTools = Array.isArray(config.strictTools)
114
+ ? config.strictTools
115
+ .filter((name) => typeof name === 'string' && name.trim() !== '')
116
+ .map((name) => name.trim())
117
+ : [];
113
118
  this.config = {
114
119
  ...config,
115
120
  maxToolAttemptsPerTurn: nonNegativeInteger(config.maxToolAttemptsPerTurn, 64),
116
121
  maxProgressToolCallsPerTurn: positiveInteger(config.maxProgressToolCallsPerTurn, 16),
117
122
  maxCallsPerRepeatGroup: positiveInteger(config.maxCallsPerRepeatGroup, 5),
123
+ strictToolLimit: positiveInteger(config.strictToolLimit, 3),
124
+ dryRunMode: Boolean(config.dryRunMode),
125
+ blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : true,
118
126
  };
119
127
  this.onViolation = typeof config.onViolation === 'function' ? config.onViolation : undefined;
120
128
  this.progressToolNames = new Set(progressToolNames);
129
+ this.strictTools = new Set(strictTools);
121
130
  this.byAgent = new Map();
122
131
  this.objectKeys = new WeakMap();
123
132
  this.nextObjectKey = 1;
133
+
134
+ this.metrics = {
135
+ totalViolations: 0,
136
+ byCode: {
137
+ LOOP_GUARD_STOP: 0,
138
+ LOOP_GUARD_DUPLICATE: 0,
139
+ LOOP_GUARD_REPEAT: 0,
140
+ LOOP_GUARD_LIMIT: 0,
141
+ LOOP_GUARD_PROGRESS_LIMIT: 0,
142
+ LOOP_GUARD_OUTPUT: 0,
143
+ },
144
+ lastViolation: null,
145
+ };
146
+ }
147
+
148
+ updateConfig(config = {}) {
149
+ const progressToolNames = Array.isArray(config.progressToolNames)
150
+ ? config.progressToolNames
151
+ .filter((name) => typeof name === 'string' && name.trim() !== '')
152
+ .map((name) => name.trim())
153
+ : Array.from(this.progressToolNames);
154
+ const strictTools = Array.isArray(config.strictTools)
155
+ ? config.strictTools
156
+ .filter((name) => typeof name === 'string' && name.trim() !== '')
157
+ .map((name) => name.trim())
158
+ : Array.from(this.strictTools);
159
+ this.config = {
160
+ ...this.config,
161
+ ...config,
162
+ maxToolAttemptsPerTurn: nonNegativeInteger(config.maxToolAttemptsPerTurn, this.config.maxToolAttemptsPerTurn ?? 64),
163
+ maxProgressToolCallsPerTurn: positiveInteger(config.maxProgressToolCallsPerTurn, this.config.maxProgressToolCallsPerTurn ?? 16),
164
+ maxCallsPerRepeatGroup: positiveInteger(config.maxCallsPerRepeatGroup ?? config.maxCallsPerToolPerTurn, this.config.maxCallsPerRepeatGroup ?? 5),
165
+ strictToolLimit: positiveInteger(config.strictToolLimit, this.config.strictToolLimit ?? 3),
166
+ dryRunMode: config.dryRunMode !== undefined ? Boolean(config.dryRunMode) : Boolean(this.config.dryRunMode),
167
+ blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : this.config.blockExactDuplicates,
168
+ };
169
+ this.progressToolNames = new Set(progressToolNames);
170
+ this.strictTools = new Set(strictTools);
171
+ }
172
+
173
+ recordExternalViolation(code, detail, extra = {}) {
174
+ this.metrics.totalViolations += 1;
175
+ this.metrics.byCode[code] = (this.metrics.byCode[code] || 0) + 1;
176
+ this.metrics.lastViolation = {
177
+ code,
178
+ tool: extra.tool || 'assistant/output',
179
+ timestamp: Date.now(),
180
+ turn: extra.turn,
181
+ reason: detail,
182
+ };
183
+ }
184
+
185
+ getTelemetry() {
186
+ return {
187
+ ...this.metrics,
188
+ activeAgents: this.byAgent.size,
189
+ dryRunMode: Boolean(this.config.dryRunMode),
190
+ };
191
+ }
192
+
193
+ resetTelemetry() {
194
+ this.metrics.totalViolations = 0;
195
+ for (const k of Object.keys(this.metrics.byCode)) {
196
+ this.metrics.byCode[k] = 0;
197
+ }
198
+ this.metrics.lastViolation = null;
124
199
  }
125
200
 
126
201
  agentKey(agent) {
@@ -193,8 +268,16 @@ export class LoopGuardState {
193
268
  }
194
269
 
195
270
  violation(state, agent, name, args, callId, code, detail) {
196
- state.answerOnly = true;
197
- state.stopReason = code + ': ' + detail;
271
+ this.metrics.totalViolations += 1;
272
+ this.metrics.byCode[code] = (this.metrics.byCode[code] || 0) + 1;
273
+ this.metrics.lastViolation = {
274
+ code,
275
+ tool: String(name),
276
+ timestamp: Date.now(),
277
+ turn: state.turn,
278
+ reason: detail,
279
+ };
280
+
198
281
  const summary = safeCallSummary(name, args);
199
282
  const event = {
200
283
  code,
@@ -205,11 +288,34 @@ export class LoopGuardState {
205
288
  attemptsSinceProgress: state.attemptsSinceProgress,
206
289
  progressAttemptsSinceProgress: state.progressAttemptsSinceProgress,
207
290
  lastProgress: state.lastProgress,
291
+ dryRun: Boolean(this.config.dryRunMode),
208
292
  ...summary,
209
293
  };
210
294
  try { this.onViolation?.(event); } catch {}
211
- return code + ': ' + detail
212
- + ' No productive progress was observed; provide the final text answer now. The next turn resets this guard.';
295
+
296
+ if (this.config.dryRunMode) {
297
+ return undefined;
298
+ }
299
+
300
+ state.answerOnly = true;
301
+ state.stopReason = code + ': ' + detail;
302
+
303
+ let guidance = 'ACTION REQUIRED: ';
304
+ if (code === 'LOOP_GUARD_STOP') {
305
+ guidance += 'User requested stop. Do NOT invoke further tools. Synthesize your final answer in plain text.';
306
+ } else if (code === 'LOOP_GUARD_DUPLICATE') {
307
+ 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.`;
308
+ } else if (code === 'LOOP_GUARD_REPEAT') {
309
+ guidance += `Tool "${name}" reached repetition limit without progress. Switch to an alternative exploration approach or answer directly.`;
310
+ } else if (code === 'LOOP_GUARD_PROGRESS_LIMIT') {
311
+ guidance += `Progress tool "${name}" repeatedly called without task changes. Stop updating task lists and proceed to execute or respond.`;
312
+ } else if (code === 'LOOP_GUARD_LIMIT') {
313
+ guidance += `Turn budget of ${this.config.maxToolAttemptsPerTurn} non-productive attempts exhausted. Cease tool execution and explain current progress or roadblock to the user.`;
314
+ } else {
315
+ guidance += 'Cease tool execution and provide a final text response. The next user turn will reset this guard.';
316
+ }
317
+
318
+ return `[${code}] ${detail}. No productive progress was observed; provide the final text answer now. ${guidance}`;
213
319
  }
214
320
 
215
321
  denyReason(agent, name, args, callId) {
@@ -226,8 +332,12 @@ export class LoopGuardState {
226
332
  const exactGroup = state.exactGroups.get(fingerprint);
227
333
  const repeatCount = repeatGroup?.progressEpoch === state.progressEpoch ? repeatGroup.count : 0;
228
334
  const exactCount = exactGroup?.progressEpoch === state.progressEpoch ? exactGroup.count : 0;
229
- if (repeatCount >= this.config.maxCallsPerRepeatGroup) {
230
- if (this.config.blockExactDuplicates && exactCount >= this.config.maxCallsPerRepeatGroup) {
335
+
336
+ const isStrictTool = this.strictTools.has(String(name));
337
+ const maxRepeats = isStrictTool ? this.config.strictToolLimit : this.config.maxCallsPerRepeatGroup;
338
+
339
+ if (repeatCount >= maxRepeats) {
340
+ if (this.config.blockExactDuplicates && exactCount >= maxRepeats) {
231
341
  return this.violation(state, agent, name, args, callId, 'LOOP_GUARD_DUPLICATE', 'identical tool call repeated without a new result or state change after ' + repeatCount + ' attempts');
232
342
  }
233
343
  return this.violation(state, agent, name, args, callId, 'LOOP_GUARD_REPEAT', 'near-identical tool call repeated without a new result or state change after ' + repeatCount + ' attempts');
@@ -293,7 +403,12 @@ export class LoopGuardState {
293
403
  call.resultFingerprint = outcome.resultFingerprint;
294
404
  call.progressToken = outcome.progressToken;
295
405
  const prior = state.lastEvidence;
406
+ const priorForCall = state.lastResults.get(call.repeatFingerprint);
407
+ const resultUnchangedForCall = priorForCall !== undefined
408
+ && priorForCall.resultFingerprint === outcome.resultFingerprint
409
+ && priorForCall.progressToken === outcome.progressToken;
296
410
  const productive = outcome.known && outcome.successful
411
+ && !resultUnchangedForCall
297
412
  && (prior === undefined
298
413
  || prior.resultFingerprint !== outcome.resultFingerprint
299
414
  || prior.progressToken !== outcome.progressToken);
@@ -323,4 +438,4 @@ export class LoopGuardState {
323
438
  call.released = true;
324
439
  this.decrementReservations(state, call);
325
440
  }
326
- }
441
+ }
package/lib/index.js CHANGED
@@ -6,9 +6,10 @@ import {
6
6
  positiveInteger,
7
7
  } from './guard-state.js';
8
8
  import { AssistantOutputGuardState, assistantTextFromMessage } from './assistant-output-state.js';
9
+ import { registerPluginUpdater } from './plugin-updater.js';
9
10
 
10
11
  export const name = '@goodandready/dsh-agent-loop-guard';
11
- export const inject = ['tools', 'agents', 'sessions'];
12
+ export const inject = ['tools', 'agents', 'sessions', 'settings'];
12
13
 
13
14
  export const Config = Schema.object({
14
15
  maxToolAttemptsPerTurn: Schema.number().min(0).default(64),
@@ -16,7 +17,10 @@ export const Config = Schema.object({
16
17
  progressToolNames: Schema.array(Schema.string()).default(['todo_write']),
17
18
  maxCallsPerRepeatGroup: Schema.number().min(1).default(5),
18
19
  maxCallsPerToolPerTurn: Schema.number().min(1).default(5),
20
+ strictTools: Schema.array(Schema.string()).default([]),
21
+ strictToolLimit: Schema.number().min(1).default(3),
19
22
  blockExactDuplicates: Schema.boolean().default(true),
23
+ dryRunMode: Schema.boolean().default(false),
20
24
  assistantOutputGuard: Schema.boolean().default(true),
21
25
  maxRepeatedAssistantLines: Schema.number().min(1).default(5),
22
26
  maxRepeatedAssistantBlocks: Schema.number().min(1).default(5),
@@ -45,7 +49,7 @@ function cancelForOutputLoop(ctx, session, reason) {
45
49
  }
46
50
  }
47
51
 
48
- function cancelOnOutputHit(ctx, session, assistantState, hit) {
52
+ function cancelOnOutputHit(ctx, session, assistantState, hit, state = null) {
49
53
  if (!hit || assistantState.hasActiveTool(session.id)) return;
50
54
  const code = String(hit.reason).split(':', 1)[0];
51
55
  const event = {
@@ -61,6 +65,9 @@ function cancelOnOutputHit(ctx, session, assistantState, hit) {
61
65
  } catch (error) {
62
66
  ctx.logger?.warn?.('dsh-agent-loop-guard: ' + code + ' session=' + session.id);
63
67
  }
68
+ try {
69
+ state?.recordExternalViolation?.('LOOP_GUARD_OUTPUT', hit.reason, { tool: 'assistant/output' });
70
+ } catch {}
64
71
  cancelForOutputLoop(ctx, session, hit.reason);
65
72
  }
66
73
 
@@ -76,28 +83,124 @@ function logGuardViolation(ctx, event) {
76
83
  attemptsSinceProgress: event.attemptsSinceProgress,
77
84
  progressAttemptsSinceProgress: event.progressAttemptsSinceProgress,
78
85
  lastProgress: event.lastProgress,
86
+ dryRun: event.dryRun,
79
87
  };
80
88
  try {
81
- ctx.logger?.warn?.('dsh-agent-loop-guard: ' + event.code + ' ' + JSON.stringify(safeEvent));
89
+ const prefix = event.dryRun ? 'dsh-agent-loop-guard [DRY-RUN]: ' : 'dsh-agent-loop-guard: ';
90
+ ctx.logger?.warn?.(prefix + event.code + ' ' + JSON.stringify(safeEvent));
82
91
  } catch (error) {
83
92
  ctx.logger?.warn?.('dsh-agent-loop-guard: ' + event.code + ' (structured log unavailable)');
84
93
  }
85
94
  }
86
95
 
87
96
  export function apply(ctx, config = {}) {
88
- const raw = Config(config) ?? {};
89
- const maxCallsPerRepeatGroup = positiveInteger(raw.maxCallsPerRepeatGroup ?? raw.maxCallsPerToolPerTurn, 5);
97
+ const NS = name;
98
+ let getConfig = () => Config(config) ?? {};
99
+
100
+ const syncFrom = (raw) => {
101
+ const maxCallsPerRepeatGroup = positiveInteger(raw.maxCallsPerRepeatGroup ?? raw.maxCallsPerToolPerTurn, 5);
102
+ const strictTools = Array.isArray(raw.strictTools)
103
+ ? raw.strictTools.filter((t) => typeof t === 'string' && t.trim() !== '').map((t) => t.trim())
104
+ : [];
105
+ return {
106
+ ...raw,
107
+ maxToolAttemptsPerTurn: nonNegativeInteger(raw.maxToolAttemptsPerTurn, 64),
108
+ maxProgressToolCallsPerTurn: positiveInteger(raw.maxProgressToolCallsPerTurn, 16),
109
+ maxCallsPerRepeatGroup,
110
+ strictTools,
111
+ strictToolLimit: positiveInteger(raw.strictToolLimit, 3),
112
+ dryRunMode: Boolean(raw.dryRunMode),
113
+ blockExactDuplicates: raw.blockExactDuplicates !== false,
114
+ assistantOutputGuard: raw.assistantOutputGuard !== false,
115
+ maxRepeatedAssistantLines: positiveInteger(raw.maxRepeatedAssistantLines, 5),
116
+ maxRepeatedAssistantBlocks: positiveInteger(raw.maxRepeatedAssistantBlocks, 5),
117
+ maxAssistantBlockChars: positiveInteger(raw.maxAssistantBlockChars, 16_384),
118
+ };
119
+ };
120
+
121
+ let raw = syncFrom(getConfig());
90
122
  const state = new LoopGuardState({
91
123
  ...raw,
92
- maxToolAttemptsPerTurn: nonNegativeInteger(raw.maxToolAttemptsPerTurn, 64),
93
- maxProgressToolCallsPerTurn: positiveInteger(raw.maxProgressToolCallsPerTurn, 16),
94
- maxCallsPerRepeatGroup,
95
124
  onViolation: (event) => logGuardViolation(ctx, event),
96
125
  });
97
126
  const assistantState = new AssistantOutputGuardState({
98
- maxRepeatedAssistantLines: positiveInteger(raw.maxRepeatedAssistantLines, 5),
99
- maxRepeatedAssistantBlocks: positiveInteger(raw.maxRepeatedAssistantBlocks, 5),
100
- maxAssistantBlockChars: positiveInteger(raw.maxAssistantBlockChars, 16_384),
127
+ maxRepeatedAssistantLines: raw.maxRepeatedAssistantLines,
128
+ maxRepeatedAssistantBlocks: raw.maxRepeatedAssistantBlocks,
129
+ maxAssistantBlockChars: raw.maxAssistantBlockChars,
130
+ });
131
+
132
+ const applyLiveConfig = () => {
133
+ raw = syncFrom(getConfig());
134
+ state.updateConfig(raw);
135
+ if (typeof assistantState.updateConfig === 'function') assistantState.updateConfig(raw);
136
+ };
137
+
138
+ ctx.inject(['settings'], (sctx) => {
139
+ const scope = sctx.settings.register(NS, Config, { base: config });
140
+ getConfig = () => Config(scope.get() ?? config) ?? {};
141
+ applyLiveConfig();
142
+ try {
143
+ if (typeof scope.watch === 'function') {
144
+ sctx.effect(() => scope.watch(() => applyLiveConfig()));
145
+ } else if (typeof scope.subscribe === 'function') {
146
+ sctx.effect(() => scope.subscribe(() => applyLiveConfig()));
147
+ }
148
+ } catch (error) {
149
+ ctx.logger?.warn?.('dsh-agent-loop-guard: settings watch failed: ' + (error instanceof Error ? error.message : String(error)));
150
+ }
151
+ });
152
+
153
+ // Mount updater and telemetry routes when webServer is available
154
+ ctx.inject(['webServer'], (wctx) => {
155
+ try {
156
+ const mountUpdater = () => registerPluginUpdater(wctx, {
157
+ endpoint: '/api/@goodandready/dsh-agent-loop-guard/update',
158
+ packageName: name,
159
+ manifestUrl: new URL('../package.json', import.meta.url),
160
+ });
161
+ if (typeof wctx.effect === 'function') {
162
+ wctx.effect(mountUpdater, 'dsh-agent-loop-guard: updater');
163
+ } else {
164
+ mountUpdater();
165
+ }
166
+
167
+ const mountTelemetry = () => {
168
+ if (typeof wctx.webServer?.register !== 'function') return () => {};
169
+ return wctx.webServer.register({
170
+ kind: 'exact',
171
+ path: '/api/@goodandready/dsh-agent-loop-guard/telemetry',
172
+ handler: async (request, response) => {
173
+ if (request.method === 'GET' || request.method === 'HEAD') {
174
+ const data = state.getTelemetry();
175
+ response.writeHead(200, {
176
+ 'content-type': 'application/json; charset=utf-8',
177
+ 'cache-control': 'no-store',
178
+ });
179
+ response.end(request.method === 'HEAD' ? undefined : JSON.stringify(data));
180
+ return;
181
+ }
182
+ if (request.method === 'POST') {
183
+ state.resetTelemetry();
184
+ response.writeHead(200, {
185
+ 'content-type': 'application/json; charset=utf-8',
186
+ 'cache-control': 'no-store',
187
+ });
188
+ response.end(JSON.stringify({ ok: true, reset: true }));
189
+ return;
190
+ }
191
+ response.writeHead(405, { allow: 'GET, HEAD, POST' });
192
+ response.end();
193
+ },
194
+ });
195
+ };
196
+ if (typeof wctx.effect === 'function') {
197
+ wctx.effect(mountTelemetry, 'dsh-agent-loop-guard: telemetry');
198
+ } else {
199
+ mountTelemetry();
200
+ }
201
+ } catch (error) {
202
+ ctx.logger?.warn?.('dsh-agent-loop-guard: webServer routes registration error: ' + (error instanceof Error ? error.message : String(error)));
203
+ }
101
204
  });
102
205
 
103
206
  ctx.on('agent/pre-step', async ({ agent, turn, messages, signal }, next) => {
@@ -116,8 +219,9 @@ export function apply(ctx, config = {}) {
116
219
  state.recordResult(execution.agent, execution);
117
220
  });
118
221
 
119
- if (raw.assistantOutputGuard !== false) {
222
+ if (true) {
120
223
  ctx.on('session/event', (session, event) => {
224
+ if (raw.assistantOutputGuard === false) return;
121
225
  if (event.type === 'assistant/chunk') {
122
226
  const chunk = event.data?.chunk;
123
227
  if (chunk?.type === 'text-delta') {
@@ -127,10 +231,10 @@ export function apply(ctx, config = {}) {
127
231
  index: chunk.index,
128
232
  text: chunk.text,
129
233
  });
130
- cancelOnOutputHit(ctx, session, assistantState, hit);
234
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
131
235
  } else if (chunk?.type === 'block-end') {
132
236
  const hit = assistantState.endBlock(session.id);
133
- cancelOnOutputHit(ctx, session, assistantState, hit);
237
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
134
238
  }
135
239
  return;
136
240
  }
@@ -143,7 +247,7 @@ export function apply(ctx, config = {}) {
143
247
  index: message?.index ?? 0,
144
248
  text: assistantTextFromMessage(message),
145
249
  });
146
- cancelOnOutputHit(ctx, session, assistantState, hit);
250
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
147
251
  return;
148
252
  }
149
253
  if (event.type === 'user/message') {
@@ -160,12 +264,12 @@ export function apply(ctx, config = {}) {
160
264
  }
161
265
  if (event.type === 'step/end') {
162
266
  const hit = assistantState.endStep(session.id);
163
- cancelOnOutputHit(ctx, session, assistantState, hit);
267
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
164
268
  return;
165
269
  }
166
270
  if (event.type === 'turn/end') {
167
271
  const hit = assistantState.endTurn(session.id);
168
- cancelOnOutputHit(ctx, session, assistantState, hit);
272
+ cancelOnOutputHit(ctx, session, assistantState, hit, state);
169
273
  return;
170
274
  }
171
275
  });
@@ -173,4 +277,4 @@ export function apply(ctx, config = {}) {
173
277
  }
174
278
 
175
279
  return ctx.tools.guard((execution) => state.denyReason(execution.agent, execution.name, execution.arguments, execution.callId));
176
- }
280
+ }