@goodandready/dsh-agent-loop-guard 0.2.4 → 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.
- package/README.md +25 -2
- package/README.ru.md +197 -44
- package/README.zh.md +195 -44
- package/docs/README.ru.md +26 -2
- package/docs/README.zh.md +26 -2
- package/docs/design/DESIGN.md +94 -0
- package/lib/client.js +286 -68
- package/lib/guard-state.js +101 -8
- package/lib/index.js +77 -8
- package/lib/plugin-updater.js +268 -0
- package/package.json +2 -2
package/lib/guard-state.js
CHANGED
|
@@ -110,17 +110,39 @@ 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
|
+
};
|
|
124
146
|
}
|
|
125
147
|
|
|
126
148
|
updateConfig(config = {}) {
|
|
@@ -128,16 +150,52 @@ export class LoopGuardState {
|
|
|
128
150
|
? config.progressToolNames
|
|
129
151
|
.filter((name) => typeof name === 'string' && name.trim() !== '')
|
|
130
152
|
.map((name) => name.trim())
|
|
131
|
-
:
|
|
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);
|
|
132
159
|
this.config = {
|
|
133
160
|
...this.config,
|
|
134
161
|
...config,
|
|
135
162
|
maxToolAttemptsPerTurn: nonNegativeInteger(config.maxToolAttemptsPerTurn, this.config.maxToolAttemptsPerTurn ?? 64),
|
|
136
163
|
maxProgressToolCallsPerTurn: positiveInteger(config.maxProgressToolCallsPerTurn, this.config.maxProgressToolCallsPerTurn ?? 16),
|
|
137
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),
|
|
138
167
|
blockExactDuplicates: config.blockExactDuplicates !== undefined ? Boolean(config.blockExactDuplicates) : this.config.blockExactDuplicates,
|
|
139
168
|
};
|
|
140
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;
|
|
141
199
|
}
|
|
142
200
|
|
|
143
201
|
agentKey(agent) {
|
|
@@ -210,8 +268,16 @@ export class LoopGuardState {
|
|
|
210
268
|
}
|
|
211
269
|
|
|
212
270
|
violation(state, agent, name, args, callId, code, detail) {
|
|
213
|
-
|
|
214
|
-
|
|
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
|
+
|
|
215
281
|
const summary = safeCallSummary(name, args);
|
|
216
282
|
const event = {
|
|
217
283
|
code,
|
|
@@ -222,11 +288,34 @@ export class LoopGuardState {
|
|
|
222
288
|
attemptsSinceProgress: state.attemptsSinceProgress,
|
|
223
289
|
progressAttemptsSinceProgress: state.progressAttemptsSinceProgress,
|
|
224
290
|
lastProgress: state.lastProgress,
|
|
291
|
+
dryRun: Boolean(this.config.dryRunMode),
|
|
225
292
|
...summary,
|
|
226
293
|
};
|
|
227
294
|
try { this.onViolation?.(event); } catch {}
|
|
228
|
-
|
|
229
|
-
|
|
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}`;
|
|
230
319
|
}
|
|
231
320
|
|
|
232
321
|
denyReason(agent, name, args, callId) {
|
|
@@ -243,8 +332,12 @@ export class LoopGuardState {
|
|
|
243
332
|
const exactGroup = state.exactGroups.get(fingerprint);
|
|
244
333
|
const repeatCount = repeatGroup?.progressEpoch === state.progressEpoch ? repeatGroup.count : 0;
|
|
245
334
|
const exactCount = exactGroup?.progressEpoch === state.progressEpoch ? exactGroup.count : 0;
|
|
246
|
-
|
|
247
|
-
|
|
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) {
|
|
248
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');
|
|
249
342
|
}
|
|
250
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');
|
|
@@ -345,4 +438,4 @@ export class LoopGuardState {
|
|
|
345
438
|
call.released = true;
|
|
346
439
|
this.decrementReservations(state, call);
|
|
347
440
|
}
|
|
348
|
-
}
|
|
441
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -6,6 +6,7 @@ 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
12
|
export const inject = ['tools', 'agents', 'sessions', 'settings'];
|
|
@@ -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,9 +83,11 @@ 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
|
-
|
|
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
|
}
|
|
@@ -90,11 +99,18 @@ export function apply(ctx, config = {}) {
|
|
|
90
99
|
|
|
91
100
|
const syncFrom = (raw) => {
|
|
92
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
|
+
: [];
|
|
93
105
|
return {
|
|
94
106
|
...raw,
|
|
95
107
|
maxToolAttemptsPerTurn: nonNegativeInteger(raw.maxToolAttemptsPerTurn, 64),
|
|
96
108
|
maxProgressToolCallsPerTurn: positiveInteger(raw.maxProgressToolCallsPerTurn, 16),
|
|
97
109
|
maxCallsPerRepeatGroup,
|
|
110
|
+
strictTools,
|
|
111
|
+
strictToolLimit: positiveInteger(raw.strictToolLimit, 3),
|
|
112
|
+
dryRunMode: Boolean(raw.dryRunMode),
|
|
113
|
+
blockExactDuplicates: raw.blockExactDuplicates !== false,
|
|
98
114
|
assistantOutputGuard: raw.assistantOutputGuard !== false,
|
|
99
115
|
maxRepeatedAssistantLines: positiveInteger(raw.maxRepeatedAssistantLines, 5),
|
|
100
116
|
maxRepeatedAssistantBlocks: positiveInteger(raw.maxRepeatedAssistantBlocks, 5),
|
|
@@ -134,6 +150,59 @@ export function apply(ctx, config = {}) {
|
|
|
134
150
|
}
|
|
135
151
|
});
|
|
136
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
|
+
}
|
|
204
|
+
});
|
|
205
|
+
|
|
137
206
|
ctx.on('agent/pre-step', async ({ agent, turn, messages, signal }, next) => {
|
|
138
207
|
const decision = await next();
|
|
139
208
|
if (decision.kind === 'reject' || signal.aborted) return decision;
|
|
@@ -162,10 +231,10 @@ export function apply(ctx, config = {}) {
|
|
|
162
231
|
index: chunk.index,
|
|
163
232
|
text: chunk.text,
|
|
164
233
|
});
|
|
165
|
-
cancelOnOutputHit(ctx, session, assistantState, hit);
|
|
234
|
+
cancelOnOutputHit(ctx, session, assistantState, hit, state);
|
|
166
235
|
} else if (chunk?.type === 'block-end') {
|
|
167
236
|
const hit = assistantState.endBlock(session.id);
|
|
168
|
-
cancelOnOutputHit(ctx, session, assistantState, hit);
|
|
237
|
+
cancelOnOutputHit(ctx, session, assistantState, hit, state);
|
|
169
238
|
}
|
|
170
239
|
return;
|
|
171
240
|
}
|
|
@@ -178,7 +247,7 @@ export function apply(ctx, config = {}) {
|
|
|
178
247
|
index: message?.index ?? 0,
|
|
179
248
|
text: assistantTextFromMessage(message),
|
|
180
249
|
});
|
|
181
|
-
cancelOnOutputHit(ctx, session, assistantState, hit);
|
|
250
|
+
cancelOnOutputHit(ctx, session, assistantState, hit, state);
|
|
182
251
|
return;
|
|
183
252
|
}
|
|
184
253
|
if (event.type === 'user/message') {
|
|
@@ -195,12 +264,12 @@ export function apply(ctx, config = {}) {
|
|
|
195
264
|
}
|
|
196
265
|
if (event.type === 'step/end') {
|
|
197
266
|
const hit = assistantState.endStep(session.id);
|
|
198
|
-
cancelOnOutputHit(ctx, session, assistantState, hit);
|
|
267
|
+
cancelOnOutputHit(ctx, session, assistantState, hit, state);
|
|
199
268
|
return;
|
|
200
269
|
}
|
|
201
270
|
if (event.type === 'turn/end') {
|
|
202
271
|
const hit = assistantState.endTurn(session.id);
|
|
203
|
-
cancelOnOutputHit(ctx, session, assistantState, hit);
|
|
272
|
+
cancelOnOutputHit(ctx, session, assistantState, hit, state);
|
|
204
273
|
return;
|
|
205
274
|
}
|
|
206
275
|
});
|
|
@@ -208,4 +277,4 @@ export function apply(ctx, config = {}) {
|
|
|
208
277
|
}
|
|
209
278
|
|
|
210
279
|
return ctx.tools.guard((execution) => state.denyReason(execution.agent, execution.name, execution.arguments, execution.callId));
|
|
211
|
-
}
|
|
280
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { readFile } from 'node:fs/promises';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { basename, dirname, isAbsolute, resolve } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
7
|
+
|
|
8
|
+
const UPDATE_HEADER = 'x-dsh-plugin-update';
|
|
9
|
+
const UPDATE_TIMEOUT_MS = 10 * 60_000;
|
|
10
|
+
const VERSION_CACHE_MS = 5 * 60_000;
|
|
11
|
+
let latestCache = null;
|
|
12
|
+
|
|
13
|
+
function header(request, name) {
|
|
14
|
+
const value = request.headers?.[name];
|
|
15
|
+
return Array.isArray(value) ? value[0] : value;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function isLoopback(value) {
|
|
19
|
+
const address = value?.toLowerCase().replace(/^\[|\]$/g, '');
|
|
20
|
+
return address === 'localhost' || address === 'localhost.' || address === '::1'
|
|
21
|
+
|| address?.startsWith('127.') === true
|
|
22
|
+
|| address?.startsWith('::ffff:127.') === true;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function isTrustedUpdateRequest(request) {
|
|
26
|
+
if (header(request, UPDATE_HEADER) !== '1') return false;
|
|
27
|
+
if (!isLoopback(request.socket?.remoteAddress)) return false;
|
|
28
|
+
const site = header(request, 'sec-fetch-site');
|
|
29
|
+
if (site !== undefined && site !== 'same-origin') return false;
|
|
30
|
+
const origin = header(request, 'origin');
|
|
31
|
+
const host = header(request, 'host');
|
|
32
|
+
if (origin === undefined || host === undefined) return false;
|
|
33
|
+
try {
|
|
34
|
+
const url = new URL(origin);
|
|
35
|
+
return (url.protocol === 'http:' || url.protocol === 'https:')
|
|
36
|
+
&& isLoopback(url.hostname) && url.host === host;
|
|
37
|
+
} catch {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function validProfileName(value) {
|
|
43
|
+
return typeof value === 'string' && value !== '' && value !== '.' && value !== '..'
|
|
44
|
+
&& !value.includes('/') && !value.includes('\\') && !/[\0-\x1f\x7f]/.test(value);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function profileNameFromArgv(argv) {
|
|
48
|
+
for (let index = 2; index < argv.length; index += 1) {
|
|
49
|
+
if (argv[index] === '--profile') return argv[index + 1];
|
|
50
|
+
if (argv[index]?.startsWith('--profile=')) return argv[index].slice('--profile='.length);
|
|
51
|
+
}
|
|
52
|
+
return argv[2] === 'web' ? 'web' : undefined;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function findDshCliEntry() {
|
|
56
|
+
const value = process.argv[1];
|
|
57
|
+
if (value === undefined || value === '') return undefined;
|
|
58
|
+
const entry = value.startsWith('file:') ? fileURLToPath(value) : resolve(process.cwd(), value);
|
|
59
|
+
if (!existsSync(entry)) return undefined;
|
|
60
|
+
for (let directory = dirname(entry); ; directory = dirname(directory)) {
|
|
61
|
+
const manifestPath = resolve(directory, 'package.json');
|
|
62
|
+
if (existsSync(manifestPath)) {
|
|
63
|
+
try {
|
|
64
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
65
|
+
const bin = typeof manifest.bin === 'string'
|
|
66
|
+
? manifest.bin
|
|
67
|
+
: typeof manifest.bin === 'object' && manifest.bin !== null
|
|
68
|
+
? manifest.bin.dsh
|
|
69
|
+
: undefined;
|
|
70
|
+
if (manifest.name === '@deepseek-ai/dsh' && typeof bin === 'string'
|
|
71
|
+
&& !isAbsolute(bin) && resolve(directory, bin) === resolve(entry)) return entry;
|
|
72
|
+
} catch {
|
|
73
|
+
// Continue searching parent package directories.
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const parent = dirname(directory);
|
|
77
|
+
if (parent === directory) return undefined;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function runtime() {
|
|
82
|
+
const profileDir = resolve(process.env.DSH_PROFILE_DIR
|
|
83
|
+
?? resolve(homedir(), '.dsh', 'profiles', 'web'));
|
|
84
|
+
const selected = profileNameFromArgv(process.argv);
|
|
85
|
+
const profileName = validProfileName(selected)
|
|
86
|
+
? selected
|
|
87
|
+
: validProfileName(basename(profileDir)) ? basename(profileDir) : 'web';
|
|
88
|
+
const cliEntry = findDshCliEntry();
|
|
89
|
+
return cliEntry === undefined ? { profileName, profileDir } : { profileName, profileDir, cliEntry };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function parseSemver(value) {
|
|
93
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value);
|
|
94
|
+
if (match === null) return undefined;
|
|
95
|
+
return {
|
|
96
|
+
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
97
|
+
prerelease: match[4]?.split('.') ?? [],
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function comparePrerelease(left, right) {
|
|
102
|
+
if (left.length === 0 || right.length === 0) return left.length === right.length ? 0 : left.length === 0 ? 1 : -1;
|
|
103
|
+
const length = Math.max(left.length, right.length);
|
|
104
|
+
for (let index = 0; index < length; index += 1) {
|
|
105
|
+
const a = left[index];
|
|
106
|
+
const b = right[index];
|
|
107
|
+
if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1;
|
|
108
|
+
if (a === b) continue;
|
|
109
|
+
const aNumeric = /^\d+$/.test(a);
|
|
110
|
+
const bNumeric = /^\d+$/.test(b);
|
|
111
|
+
if (aNumeric && bNumeric) {
|
|
112
|
+
const aNumber = BigInt(a);
|
|
113
|
+
const bNumber = BigInt(b);
|
|
114
|
+
if (aNumber !== bNumber) return aNumber > bNumber ? 1 : -1;
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
if (aNumeric !== bNumeric) return aNumeric ? -1 : 1;
|
|
118
|
+
return a > b ? 1 : -1;
|
|
119
|
+
}
|
|
120
|
+
return 0;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function isNewerVersion(currentValue, candidateValue) {
|
|
124
|
+
const current = parseSemver(currentValue);
|
|
125
|
+
const candidate = parseSemver(candidateValue);
|
|
126
|
+
if (current === undefined || candidate === undefined) return false;
|
|
127
|
+
for (let index = 0; index < 3; index += 1) {
|
|
128
|
+
if (candidate.core[index] !== current.core[index]) return candidate.core[index] > current.core[index];
|
|
129
|
+
}
|
|
130
|
+
return comparePrerelease(candidate.prerelease, current.prerelease) > 0;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async function latestVersion(packageName, registry) {
|
|
134
|
+
if (latestCache?.packageName === packageName && latestCache.registry === registry && Date.now() < latestCache.expiresAt) {
|
|
135
|
+
return latestCache.version;
|
|
136
|
+
}
|
|
137
|
+
try {
|
|
138
|
+
const response = await fetch(`${registry.replace(/\/$/, '')}/${encodeURIComponent(packageName)}/latest`, {
|
|
139
|
+
signal: AbortSignal.timeout(8_000),
|
|
140
|
+
});
|
|
141
|
+
if (!response.ok) return undefined;
|
|
142
|
+
const value = await response.json();
|
|
143
|
+
if (typeof value?.version !== 'string' || value.version === '') return undefined;
|
|
144
|
+
latestCache = { packageName, registry, version: value.version, expiresAt: Date.now() + VERSION_CACHE_MS };
|
|
145
|
+
return value.version;
|
|
146
|
+
} catch {
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function currentVersion(manifestUrl) {
|
|
152
|
+
const value = JSON.parse(await readFile(manifestUrl, 'utf8'));
|
|
153
|
+
if (typeof value?.version !== 'string' || value.version === '') throw new Error('Cannot read current plugin version.');
|
|
154
|
+
return value.version;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async function status(options, target) {
|
|
158
|
+
const current = await currentVersion(options.manifestUrl);
|
|
159
|
+
const latest = await latestVersion(options.packageName, options.registry ?? 'https://registry.npmjs.org');
|
|
160
|
+
return {
|
|
161
|
+
packageName: options.packageName,
|
|
162
|
+
currentVersion: current,
|
|
163
|
+
...(latest === undefined ? {} : { latestVersion: latest }),
|
|
164
|
+
latestCheckFailed: latest === undefined,
|
|
165
|
+
updateAvailable: latest !== undefined && isNewerVersion(current, latest),
|
|
166
|
+
profileName: target.profileName,
|
|
167
|
+
canAutoUpdate: target.cliEntry !== undefined,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async function installExact(target, packageSpec, options) {
|
|
172
|
+
if (target.cliEntry === undefined) throw new Error('Automatic update is unavailable in this runtime.');
|
|
173
|
+
await new Promise((resolvePromise, reject) => {
|
|
174
|
+
const child = spawn(process.execPath, [
|
|
175
|
+
target.cliEntry, 'plugin', '--profile', target.profileName, 'add',
|
|
176
|
+
'--config.minimumReleaseAge=0', packageSpec,
|
|
177
|
+
`--registry=${options.registry ?? 'https://registry.npmjs.org/'}`,
|
|
178
|
+
], {
|
|
179
|
+
cwd: target.profileDir,
|
|
180
|
+
windowsHide: true,
|
|
181
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
182
|
+
env: { ...process.env, NO_COLOR: '1' },
|
|
183
|
+
});
|
|
184
|
+
let detail = '';
|
|
185
|
+
child.stdout?.on('data', (chunk) => { detail = (detail + String(chunk)).slice(-4_000); });
|
|
186
|
+
child.stderr?.on('data', (chunk) => { detail = (detail + String(chunk)).slice(-4_000); });
|
|
187
|
+
const timer = setTimeout(() => {
|
|
188
|
+
child.kill();
|
|
189
|
+
reject(new Error('Update timed out; use the normal DSH update flow.'));
|
|
190
|
+
}, UPDATE_TIMEOUT_MS);
|
|
191
|
+
child.once('error', (error) => { clearTimeout(timer); reject(error); });
|
|
192
|
+
child.once('exit', (code) => {
|
|
193
|
+
clearTimeout(timer);
|
|
194
|
+
if (code === 0) resolvePromise();
|
|
195
|
+
else reject(new Error(detail.trim() || `Update exited with code ${String(code)}.`));
|
|
196
|
+
});
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function json(response, statusCode, value) {
|
|
201
|
+
response.writeHead(statusCode, {
|
|
202
|
+
'content-type': 'application/json; charset=utf-8',
|
|
203
|
+
'cache-control': 'no-store',
|
|
204
|
+
});
|
|
205
|
+
response.end(JSON.stringify(value));
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export function registerPluginUpdater(ctx, options) {
|
|
209
|
+
let installing = false;
|
|
210
|
+
if (typeof ctx?.webServer?.register !== 'function') {
|
|
211
|
+
ctx?.logger?.warn?.('dsh-agent-loop-guard: webServer service unavailable, updater skipped');
|
|
212
|
+
return () => {};
|
|
213
|
+
}
|
|
214
|
+
return ctx.webServer.register({
|
|
215
|
+
kind: 'exact',
|
|
216
|
+
path: options.endpoint,
|
|
217
|
+
handler: async (request, response) => {
|
|
218
|
+
try {
|
|
219
|
+
const target = runtime();
|
|
220
|
+
if (request.method === 'GET' || request.method === 'HEAD') {
|
|
221
|
+
const payload = await status(options, target);
|
|
222
|
+
response.writeHead(200, {
|
|
223
|
+
'content-type': 'application/json; charset=utf-8',
|
|
224
|
+
'cache-control': 'no-store',
|
|
225
|
+
});
|
|
226
|
+
response.end(request.method === 'HEAD' ? undefined : JSON.stringify(payload));
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (request.method !== 'POST') {
|
|
230
|
+
response.writeHead(405, { allow: 'GET, HEAD, POST' });
|
|
231
|
+
response.end();
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
if (!isTrustedUpdateRequest(request)) {
|
|
235
|
+
json(response, 403, { error: 'Rejected non-local or cross-origin update request.' });
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
if (installing) {
|
|
239
|
+
json(response, 409, { error: 'This plugin is already updating.' });
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
installing = true;
|
|
243
|
+
try {
|
|
244
|
+
const before = await status(options, target);
|
|
245
|
+
if (before.latestVersion === undefined) {
|
|
246
|
+
json(response, 503, { error: 'The latest version is temporarily unavailable.' });
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (!before.updateAvailable) {
|
|
250
|
+
json(response, 200, before);
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
await installExact(target, `${options.packageName}@${before.latestVersion}`, options);
|
|
254
|
+
json(response, 200, {
|
|
255
|
+
...before,
|
|
256
|
+
updatedVersion: before.latestVersion,
|
|
257
|
+
restartRequired: true,
|
|
258
|
+
});
|
|
259
|
+
} finally {
|
|
260
|
+
installing = false;
|
|
261
|
+
}
|
|
262
|
+
} catch (error) {
|
|
263
|
+
ctx?.logger?.warn?.(`dsh-agent-loop-guard: plugin updater failed: ${String(error)}`);
|
|
264
|
+
json(response, 503, { error: 'Plugin update failed; see server logs.' });
|
|
265
|
+
}
|
|
266
|
+
},
|
|
267
|
+
});
|
|
268
|
+
}
|
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.5",
|
|
4
4
|
"description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
@@ -21,7 +21,7 @@
|
|
|
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"
|
|
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"
|
|
25
25
|
},
|
|
26
26
|
"dsh": {
|
|
27
27
|
"bundle": {
|