@goodandready/dsh-agent-loop-guard 0.2.24 → 0.2.26

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.26] - 2026-10-20
4
+
5
+ ### Fixed
6
+ - **Tools Result Payload Forwarding (#125, gh-1)**: Fixed tool outcome tracking in `lib/index.js` where `tools/result` event listener only captured the first argument (`execution`), losing the actual result payload passed as the second argument (`result`) by the DSH runtime (`dsh-tools`). Updated `tools/result` to capture `(execution, result)` and forward `{ ...execution, result }` to `state.recordResult()`. Updated `outcomeFromExecution` and `recordResult` in `lib/guard-state.js` to accept `maybeResult` and extract result payload, properly recognizing successful tool executions as productive progress (`productive: true`), advancing `progressEpoch`, and clearing `exactGroups`. Resolves false-positive `LOOP_GUARD_DUPLICATE` blocks on legitimate retries and eliminates catastrophic lockouts into `answerOnly` mode.
7
+
8
+ ## [0.2.25] - 2026-10-19
9
+
10
+ ### Fixed
11
+ - **Stop Command Detection & History Isolation (#120)**: Hardened `hasStopRequest` in `lib/guard-state.js` to inspect only the latest user message (`source.kind === 'user'` or `role === 'user'`), eliminating cross-turn leakage where a past stop command in turn 1 permanently locked tools in subsequent turns. Removed broad keywords `answer` and `回答` from default stop patterns, and introduced `isDefaultStopRequest` to require explicit standalone or imperative stop commands ("stop", "halt", "cancel", "abort", "terminate", "please stop", "停止", "暂停", "取消", "终止", "死循环"), eliminating false-positive blocks on regular user requests ("answer in Russian", "please answer using files", "stop the service and fix it").
12
+ - **Bounded Streaming Output Buffer (#121)**: Bounded `state.pending` buffer in `AssistantOutputGuardState.observeText` to `maxAssistantBlockChars` and parsed newlines incrementally via `indexOf('\n')` instead of `split(/\n/gu)`, preventing unbounded memory growth and O(N^2) CPU stalls during long streaming outputs without line breaks (such as minified JSON or base64 payloads).
13
+ - **Issue Label Deduplication (#122)**: Reassigned affected issues to canonical project labels and cleaned up duplicate labels in Gitea repository.
14
+
3
15
  ## [0.2.24] - 2026-10-15
4
16
 
5
17
  ### Fixed
@@ -177,12 +177,29 @@ export class AssistantOutputGuardState {
177
177
  state.streamedText += text;
178
178
  }
179
179
  state.streamedSkipAvailable = true;
180
- state.pending += text;
181
- const lines = state.pending.split(/\n/gu);
182
- state.pending = lines.pop() ?? '';
183
- for (const line of lines) {
184
- const hit = this.observeLine(session, line);
180
+ let nlIdx = text.indexOf('\n');
181
+ if (nlIdx === -1) {
182
+ state.pending += text;
183
+ if (state.pending.length > this.maxAssistantBlockChars) {
184
+ state.pending = state.pending.slice(-this.maxAssistantBlockChars);
185
+ }
186
+ } else {
187
+ const firstLine = state.pending + text.slice(0, nlIdx);
188
+ state.pending = '';
189
+ const hit = this.observeLine(session, firstLine);
185
190
  if (hit) return hit;
191
+
192
+ let start = nlIdx + 1;
193
+ while ((nlIdx = text.indexOf('\n', start)) !== -1) {
194
+ const line = text.slice(start, nlIdx);
195
+ const hit = this.observeLine(session, line);
196
+ if (hit) return hit;
197
+ start = nlIdx + 1;
198
+ }
199
+ state.pending = text.slice(start);
200
+ if (state.pending.length > this.maxAssistantBlockChars) {
201
+ state.pending = state.pending.slice(-this.maxAssistantBlockChars);
202
+ }
186
203
  }
187
204
  return undefined;
188
205
  }
@@ -1,9 +1,33 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  export const DEFAULT_STOP_PATTERNS = {
3
- en: /(?<![\p{L}\p{N}_-])(?:stop|halt|cancel|abort|terminate|answer(?:\s+now)?)(?![\p{L}\p{N}_-])/iu,
4
- zh: /(?:停止|暂停|取消|终止|回答|死循环)/u,
3
+ en: /(?<![\p{L}\p{N}_-])(?:stop|halt|cancel|abort|terminate)(?![\p{L}\p{N}_-])/iu,
4
+ zh: /(?:停止|暂停|取消|终止|死循环)/u,
5
5
  };
6
6
 
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
+
7
31
  export function compileStopPatterns(customPatterns = []) {
8
32
  if (!Array.isArray(customPatterns)) return [];
9
33
  const compiled = [];
@@ -72,15 +96,23 @@ export function nonNegativeInteger(value, fallback) {
72
96
  export function hasStopRequest(messages, customPatterns = []) {
73
97
  if (!Array.isArray(messages)) return false;
74
98
  const compiledCustom = compileStopPatterns(customPatterns);
75
- return messages.some((message) => {
76
- if (message?.source?.kind !== 'user') return false;
77
- const text = textFrom(message.content);
78
- if (!text) return false;
79
- if (DEFAULT_STOP_PATTERNS.en.test(text) || DEFAULT_STOP_PATTERNS.zh.test(text)) {
80
- return true;
99
+ let lastUserMessage = null;
100
+ for (let i = messages.length - 1; i >= 0; i--) {
101
+ const msg = messages[i];
102
+ if (msg && (msg.source?.kind === 'user' || msg.role === 'user')) {
103
+ lastUserMessage = msg;
104
+ break;
81
105
  }
82
- return compiledCustom.some((regex) => regex.test(text));
83
- });
106
+ }
107
+ if (!lastUserMessage) return false;
108
+
109
+ const text = textFrom(lastUserMessage.content);
110
+ if (!text) return false;
111
+
112
+ if (isDefaultStopRequest(text)) {
113
+ return true;
114
+ }
115
+ return compiledCustom.some((regex) => regex.test(text));
84
116
  }
85
117
 
86
118
  export function callFingerprint(name, args) {
@@ -123,20 +155,30 @@ function hasOwn(object, key) {
123
155
  return object !== null && typeof object === 'object' && Object.prototype.hasOwnProperty.call(object, key);
124
156
  }
125
157
 
126
- function outcomeFromExecution(execution) {
158
+ function outcomeFromExecution(execution, maybeResult = undefined) {
159
+ const result = maybeResult !== undefined ? maybeResult : execution?.result;
127
160
  const data = execution?.data;
128
- const hasResult = hasOwn(execution, 'result') || hasOwn(execution, 'output')
129
- || hasOwn(data, 'result') || hasOwn(data, 'output') || hasOwn(execution, 'error');
161
+ const hasResult = result !== undefined
162
+ || hasOwn(execution, 'result')
163
+ || hasOwn(execution, 'output')
164
+ || hasOwn(data, 'result')
165
+ || hasOwn(data, 'output')
166
+ || hasOwn(execution, 'error')
167
+ || hasOwn(execution, 'content')
168
+ || hasOwn(execution, 'isError');
130
169
  if (!hasResult) return { known: false, successful: false, resultFingerprint: '<unknown>', progressToken: '<unknown>' };
131
- const value = execution?.result ?? execution?.output ?? data?.result ?? data?.output
170
+ const value = result ?? execution?.output ?? data?.result ?? data?.output
132
171
  ?? (hasOwn(execution, 'error') ? { error: execution.error } : undefined);
133
172
  const failed = (execution?.error != null && execution?.error !== false)
173
+ || execution?.isError === true
134
174
  || value?.isError === true
135
175
  || value?.success === false
136
176
  || value?.ok === false
137
177
  || (value?.error != null && value?.error !== false);
138
178
  const explicitProgress = execution?.progressToken ?? execution?.progress ?? execution?.stateVersion
139
- ?? data?.progressToken ?? data?.progress ?? data?.stateVersion;
179
+ ?? data?.progressToken ?? data?.progress ?? data?.stateVersion
180
+ ?? value?.progressToken ?? value?.progress ?? value?.stateVersion
181
+ ?? value?.meta?.progressToken;
140
182
  return {
141
183
  known: true,
142
184
  successful: !failed,
@@ -483,7 +525,7 @@ export class LoopGuardState {
483
525
  }
484
526
  }
485
527
 
486
- recordResult(agent, execution = {}) {
528
+ recordResult(agent, execution = {}, maybeResult = undefined) {
487
529
  const state = this.stateFor(agent);
488
530
  const call = this.findCall(state, execution.callId);
489
531
  if (call === undefined) return { known: false, productive: false };
@@ -492,7 +534,7 @@ export class LoopGuardState {
492
534
  this.decrementReservations(state, call);
493
535
  return { known: false, productive: false };
494
536
  }
495
- const outcome = outcomeFromExecution(execution);
537
+ const outcome = outcomeFromExecution(execution, maybeResult);
496
538
  call.pending = false;
497
539
  call.committed = true;
498
540
  call.resultSeen = true;
package/lib/index.js CHANGED
@@ -302,8 +302,9 @@ export function apply(ctx, config = {}) {
302
302
  return next();
303
303
  });
304
304
 
305
- ctx.on('tools/result', (execution) => {
306
- state.recordResult(execution.agent, execution);
305
+ ctx.on('tools/result', (execution, result) => {
306
+ const payload = result !== undefined ? { ...execution, result } : execution;
307
+ state.recordResult(execution?.agent, payload, result);
307
308
  });
308
309
 
309
310
  ctx.on('session/event', (session, event) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-agent-loop-guard",
3
- "version": "0.2.24",
3
+ "version": "0.2.26",
4
4
  "description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",