@lmzhen/dsh-evolution-review 0.58.0 → 0.59.0
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 +6 -5
- package/lib/index.js +777 -33
- package/lib/types/index.d.ts +5 -0
- package/lib/types/review-executor.d.ts +28 -1
- package/lib/types/review-limiter.d.ts +23 -0
- package/lib/types/review-ptc-channel.d.ts +43 -0
- package/lib/types/review-tool-channel.d.ts +34 -0
- package/lib/types/review-write-locks.d.ts +35 -0
- package/package.json +7 -7
package/lib/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { llmPort, settingsPort, toolsPort } from "@lmzhen/dsh-evolution-adapter/ports";
|
|
2
2
|
import z from "@deepseek-ai/schemastery";
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { BlockAssembler, SessionId, createToolResultMessage, createUserMessage } from "@lmzhen/dsh-evolution-adapter/values";
|
|
5
|
-
import { DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, MAX_TIMER_DELAY_MS, PROMPT_BUNDLE, advanceReview, clampOnce, classifySessionEvent, clearReviewChannel, liveBool, markReviewChannel, paramRowId, pickWithPolicy, readDispatchSignal, recordReviewRead, reviewPrompt, sessionAudited, sessionTurnSignals, sweepReviewChannelSessions, unwrapLive, userSetKeys, verifyPromptBundle, withReviewContext } from "@lmzhen/dsh-evolution-core";
|
|
4
|
+
import { BlockAssembler, SessionId, createToolResultMessage, createUserMessage, defineTool } from "@lmzhen/dsh-evolution-adapter/values";
|
|
5
|
+
import { DEFAULT_REVIEW_MEMORY_INTERVAL, DEFAULT_REVIEW_SKILL_INTERVAL, DEFAULT_REVIEW_TIMEOUT_MS, DEFAULT_SKILL_REVIEW_COMPLETION_MIN_TOOL_CALLS, DEFAULT_SKILL_REVIEW_TRIGGER, DEFAULT_SUBSTANTIVE_MIN_AGENT_CHARS, DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS, DEFAULT_SUBSTANTIVE_MIN_USER_CHARS, INJECT_COMPLETION_SKILL_REVIEW_PROMPT, MAX_TIMER_DELAY_MS, PROMPT_BUNDLE, advanceReview, clampOnce, classifySessionEvent, clearReviewChannel, currentReviewContext, liveBool, markReviewChannel, paramRowId, pickWithPolicy, readDispatchSignal, recordReviewRead, reviewPrompt, sessionAudited, sessionTurnSignals, sweepReviewChannelSessions, unwrapLive, userSetKeys, verifyPromptBundle, withReviewContext } from "@lmzhen/dsh-evolution-core";
|
|
6
|
+
import { createReviewChildAgent } from "@lmzhen/dsh-evolution-adapter/review-child";
|
|
6
7
|
import { assertSkillsRootAliasRetired, filterUnreadSkillOps } from "@lmzhen/dsh-evolution-core/skills";
|
|
7
8
|
//#region lib/types/review-executor.js
|
|
8
9
|
/**
|
|
@@ -14,6 +15,98 @@ import { assertSkillsRootAliasRetired, filterUnreadSkillOps } from "@lmzhen/dsh-
|
|
|
14
15
|
*
|
|
15
16
|
* @module @lmzhen/dsh-evolution-review/review-executor
|
|
16
17
|
*/
|
|
18
|
+
/** The only terminal tool call in an aux review. */
|
|
19
|
+
const REVIEW_DONE_TOOL_NAME = "review_done";
|
|
20
|
+
/** Tool that lets the model wait for a resource lock before re-reading. */
|
|
21
|
+
const REVIEW_WAIT_TOOL_NAME = "review_wait";
|
|
22
|
+
const REVIEW_WAIT_TOOL = {
|
|
23
|
+
name: REVIEW_WAIT_TOOL_NAME,
|
|
24
|
+
description: "Wait for a resource lock to clear. Call only after a write reports a lock/resource conflict; re-read after it returns.",
|
|
25
|
+
parameters: {
|
|
26
|
+
type: "object",
|
|
27
|
+
properties: {
|
|
28
|
+
resource: { type: "string" },
|
|
29
|
+
timeoutMs: { type: "number" }
|
|
30
|
+
},
|
|
31
|
+
required: ["resource", "timeoutMs"]
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
const REVIEW_DONE_TOOL = {
|
|
35
|
+
name: REVIEW_DONE_TOOL_NAME,
|
|
36
|
+
description: "Signal that this review is complete. Call it alone, only after all memory/skill edits for this review are finished.",
|
|
37
|
+
parameters: {
|
|
38
|
+
type: "object",
|
|
39
|
+
properties: {
|
|
40
|
+
summary: { type: "string" },
|
|
41
|
+
memoryChanged: { type: "boolean" },
|
|
42
|
+
skillsChanged: {
|
|
43
|
+
type: "array",
|
|
44
|
+
items: { type: "string" }
|
|
45
|
+
},
|
|
46
|
+
unresolved: {
|
|
47
|
+
type: "array",
|
|
48
|
+
items: { type: "string" }
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
required: [
|
|
52
|
+
"summary",
|
|
53
|
+
"memoryChanged",
|
|
54
|
+
"skillsChanged",
|
|
55
|
+
"unresolved"
|
|
56
|
+
]
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
function parseReviewReport(raw) {
|
|
60
|
+
try {
|
|
61
|
+
const parsed = JSON.parse(raw);
|
|
62
|
+
if (parsed === null || typeof parsed !== "object") return void 0;
|
|
63
|
+
const value = parsed;
|
|
64
|
+
if (typeof value.summary !== "string" || typeof value.memoryChanged !== "boolean") return void 0;
|
|
65
|
+
if (!Array.isArray(value.skillsChanged) || !value.skillsChanged.every((item) => typeof item === "string")) return void 0;
|
|
66
|
+
if (!Array.isArray(value.unresolved) || !value.unresolved.every((item) => typeof item === "string")) return void 0;
|
|
67
|
+
return {
|
|
68
|
+
summary: value.summary,
|
|
69
|
+
memoryChanged: value.memoryChanged,
|
|
70
|
+
skillsChanged: value.skillsChanged,
|
|
71
|
+
unresolved: value.unresolved
|
|
72
|
+
};
|
|
73
|
+
} catch {
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function parseWaitRequest(raw) {
|
|
78
|
+
try {
|
|
79
|
+
const parsed = JSON.parse(raw);
|
|
80
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
81
|
+
const value = parsed;
|
|
82
|
+
const timeoutMs = typeof value.timeoutMs === "number" && Number.isFinite(value.timeoutMs) ? Math.max(1, Math.min(value.timeoutMs, 6e4)) : 1e3;
|
|
83
|
+
return {
|
|
84
|
+
...typeof value.resource === "string" ? { resource: value.resource } : {},
|
|
85
|
+
timeoutMs
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
} catch {}
|
|
89
|
+
return { timeoutMs: 1e3 };
|
|
90
|
+
}
|
|
91
|
+
async function waitForReview(timeoutMs, signal) {
|
|
92
|
+
if (signal.aborted) throw new Error("review_wait aborted");
|
|
93
|
+
await new Promise((resolve) => setTimeout(resolve, timeoutMs));
|
|
94
|
+
signal.throwIfAborted();
|
|
95
|
+
}
|
|
96
|
+
function writeResource(call) {
|
|
97
|
+
if (call.name !== "skill_manage" && call.name !== "memory") return void 0;
|
|
98
|
+
try {
|
|
99
|
+
const parsed = JSON.parse(call.arguments);
|
|
100
|
+
if (parsed !== null && typeof parsed === "object") {
|
|
101
|
+
const value = parsed;
|
|
102
|
+
const name = typeof value.name === "string" ? value.name : void 0;
|
|
103
|
+
const target = typeof value.target === "string" ? value.target : void 0;
|
|
104
|
+
if (call.name === "skill_manage") return "skill:" + (name ?? "<unnamed>");
|
|
105
|
+
return "memory:" + (target ?? "default");
|
|
106
|
+
}
|
|
107
|
+
} catch {}
|
|
108
|
+
return call.name === "skill_manage" ? "skill:<unnamed>" : "memory:default";
|
|
109
|
+
}
|
|
17
110
|
var ReviewModelError = class extends Error {
|
|
18
111
|
code;
|
|
19
112
|
constructor(message, code) {
|
|
@@ -68,6 +161,7 @@ async function runReview(input) {
|
|
|
68
161
|
const header = parent.session.requestHeader();
|
|
69
162
|
if (header === void 0) throw new Error("review requires the parent request header");
|
|
70
163
|
const beforeSeq = parent.session.seq;
|
|
164
|
+
const toolHistory = input.channel?.mode === "ptc" ? parent.session.toolHistory?.() : void 0;
|
|
71
165
|
const messages = [...parent.session.deriveMessages(), createUserMessage({
|
|
72
166
|
content: [{
|
|
73
167
|
type: "text",
|
|
@@ -75,13 +169,18 @@ async function runReview(input) {
|
|
|
75
169
|
}],
|
|
76
170
|
source: { kind: "evolution-review" }
|
|
77
171
|
})];
|
|
78
|
-
const toolHistory = parent.session.toolHistory();
|
|
79
172
|
const maxRounds = input.maxRounds ?? 4;
|
|
173
|
+
const maxToolCalls = input.maxToolCalls ?? 50;
|
|
80
174
|
const actions = [];
|
|
81
175
|
let finalText = "";
|
|
82
176
|
let usage;
|
|
83
177
|
let requests = 0;
|
|
84
178
|
let toolCalls = 0;
|
|
179
|
+
let done = false;
|
|
180
|
+
let hitRoundLimit = false;
|
|
181
|
+
let partialReason;
|
|
182
|
+
let report;
|
|
183
|
+
let waitCount = 0;
|
|
85
184
|
markReview();
|
|
86
185
|
try {
|
|
87
186
|
for (let round = 0; round < maxRounds; round += 1) {
|
|
@@ -94,7 +193,7 @@ async function runReview(input) {
|
|
|
94
193
|
...header.config.temperature === void 0 ? {} : { temperature: header.config.temperature },
|
|
95
194
|
...header.config.maxTokens === void 0 ? {} : { maxTokens: header.config.maxTokens },
|
|
96
195
|
messages,
|
|
97
|
-
...header.tools
|
|
196
|
+
tools: [...input.channel?.visibleTools ?? header.tools ?? [], ...input.channel?.mode === "ptc" ? [] : [REVIEW_WAIT_TOOL, REVIEW_DONE_TOOL]],
|
|
98
197
|
...toolHistory === void 0 ? {} : { toolHistory },
|
|
99
198
|
signal
|
|
100
199
|
}, signal);
|
|
@@ -116,19 +215,137 @@ async function runReview(input) {
|
|
|
116
215
|
if (text !== "") finalText = text;
|
|
117
216
|
const calls = assistant.content.filter((block) => block.type === "tool-call");
|
|
118
217
|
if (calls.length === 0) break;
|
|
218
|
+
const waitCalls = input.channel?.mode === "ptc" ? [] : calls.filter((call) => call.name === REVIEW_WAIT_TOOL_NAME);
|
|
219
|
+
if (waitCalls.length > 0) {
|
|
220
|
+
if (calls.length !== 1) {
|
|
221
|
+
partialReason = "review_wait must be the only tool call in its batch";
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
toolCalls += 1;
|
|
225
|
+
waitCount += 1;
|
|
226
|
+
const parsed = parseWaitRequest(waitCalls[0].arguments);
|
|
227
|
+
const released = parsed.resource !== void 0 && input.writeLocks !== void 0 ? await input.writeLocks.wait(parsed.resource, parsed.timeoutMs, signal) : await waitForReview(parsed.timeoutMs, signal);
|
|
228
|
+
actions.push({
|
|
229
|
+
type: "tool",
|
|
230
|
+
action: REVIEW_WAIT_TOOL_NAME,
|
|
231
|
+
target: parsed.resource ?? "resource",
|
|
232
|
+
status: released === false ? "error" : "ok"
|
|
233
|
+
});
|
|
234
|
+
messages.push(assistant);
|
|
235
|
+
messages.push(createToolResultMessage({
|
|
236
|
+
callId: waitCalls[0].id,
|
|
237
|
+
content: [{
|
|
238
|
+
type: "text",
|
|
239
|
+
text: released === false ? "review_wait timed out" : "review_wait released"
|
|
240
|
+
}],
|
|
241
|
+
isError: released === false
|
|
242
|
+
}));
|
|
243
|
+
if (released === false) {
|
|
244
|
+
partialReason = "lock-wait-exhausted";
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
if (toolCalls >= maxToolCalls) {
|
|
248
|
+
partialReason = "max tool calls reached before review_done";
|
|
249
|
+
break;
|
|
250
|
+
}
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
const doneCalls = input.channel?.mode === "ptc" ? [] : calls.filter((call) => call.name === REVIEW_DONE_TOOL_NAME);
|
|
254
|
+
if (doneCalls.length > 0) {
|
|
255
|
+
toolCalls += calls.length;
|
|
256
|
+
if (calls.length !== 1) {
|
|
257
|
+
partialReason = "review_done must be the only tool call in its batch";
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
const parsed = parseReviewReport(doneCalls[0].arguments);
|
|
261
|
+
if (parsed === void 0) {
|
|
262
|
+
partialReason = "review_done report is invalid";
|
|
263
|
+
break;
|
|
264
|
+
}
|
|
265
|
+
report = parsed;
|
|
266
|
+
done = true;
|
|
267
|
+
actions.push({
|
|
268
|
+
type: "tool",
|
|
269
|
+
action: REVIEW_DONE_TOOL_NAME,
|
|
270
|
+
target: "review",
|
|
271
|
+
status: "ok"
|
|
272
|
+
});
|
|
273
|
+
break;
|
|
274
|
+
}
|
|
119
275
|
messages.push(assistant);
|
|
120
|
-
const
|
|
121
|
-
const
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
276
|
+
const allowedNames = input.channel === void 0 ? toolAllow : new Set(input.channel.visibleTools.map((tool) => tool.name));
|
|
277
|
+
const allowedCalls = calls.filter((call) => allowedNames.has(call.name));
|
|
278
|
+
const releases = [];
|
|
279
|
+
const held = /* @__PURE__ */ new Set();
|
|
280
|
+
const busy = /* @__PURE__ */ new Map();
|
|
281
|
+
const runnable = [];
|
|
282
|
+
for (const call of allowedCalls) {
|
|
283
|
+
const resource = writeResource(call);
|
|
284
|
+
if (resource === void 0 || input.writeLocks === void 0) {
|
|
285
|
+
runnable.push(call);
|
|
286
|
+
continue;
|
|
287
|
+
}
|
|
288
|
+
if (held.has(resource)) {
|
|
289
|
+
runnable.push(call);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const release = input.writeLocks.tryAcquire(resource, input.owner ?? "review");
|
|
293
|
+
if (release === void 0) {
|
|
294
|
+
busy.set(call.id, resource);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
held.add(resource);
|
|
298
|
+
releases.push(release);
|
|
299
|
+
runnable.push(call);
|
|
300
|
+
}
|
|
301
|
+
let batch;
|
|
302
|
+
try {
|
|
303
|
+
batch = runnable.length === 0 ? { results: [] } : input.channel === void 0 ? await tools.execute({
|
|
304
|
+
calls: runnable,
|
|
305
|
+
signal,
|
|
306
|
+
agent: parent
|
|
307
|
+
}) : await input.channel.execute(runnable, signal);
|
|
308
|
+
} finally {
|
|
309
|
+
for (const release of releases) release();
|
|
310
|
+
}
|
|
311
|
+
const channelCompletion = input.channel?.completion?.();
|
|
312
|
+
if (channelCompletion?.done === true && channelCompletion.report !== void 0) {
|
|
313
|
+
report = channelCompletion.report;
|
|
314
|
+
done = true;
|
|
315
|
+
toolCalls += calls.length;
|
|
316
|
+
if (channelCompletion.waitCount !== void 0) waitCount = channelCompletion.waitCount;
|
|
317
|
+
actions.push({
|
|
318
|
+
type: "tool",
|
|
319
|
+
action: REVIEW_DONE_TOOL_NAME,
|
|
320
|
+
target: "review",
|
|
321
|
+
status: "ok"
|
|
322
|
+
});
|
|
323
|
+
break;
|
|
324
|
+
}
|
|
126
325
|
const byCall = new Map(batch.results.map((item) => [item.callId, item]));
|
|
127
|
-
const
|
|
326
|
+
const allowedLabel = [...allowedNames].sort().join(", ");
|
|
128
327
|
for (const call of calls) {
|
|
129
328
|
const item = byCall.get(call.id);
|
|
329
|
+
const busyResource = busy.get(call.id);
|
|
330
|
+
if (busyResource !== void 0) {
|
|
331
|
+
actions.push({
|
|
332
|
+
type: actionType(call.name),
|
|
333
|
+
action: call.name,
|
|
334
|
+
target: toolTarget(call.name, call.arguments),
|
|
335
|
+
status: "error"
|
|
336
|
+
});
|
|
337
|
+
messages.push(createToolResultMessage({
|
|
338
|
+
callId: call.id,
|
|
339
|
+
content: [{
|
|
340
|
+
type: "text",
|
|
341
|
+
text: "resource-busy: " + busyResource + "; call review_wait, then re-read the target and retry"
|
|
342
|
+
}],
|
|
343
|
+
isError: true
|
|
344
|
+
}));
|
|
345
|
+
continue;
|
|
346
|
+
}
|
|
130
347
|
if (item === void 0) {
|
|
131
|
-
if (
|
|
348
|
+
if (allowedNames.has(call.name)) throw new Error("review tool result has no matching call");
|
|
132
349
|
actions.push({
|
|
133
350
|
type: actionType(call.name),
|
|
134
351
|
action: call.name,
|
|
@@ -139,7 +356,7 @@ async function runReview(input) {
|
|
|
139
356
|
callId: call.id,
|
|
140
357
|
content: [{
|
|
141
358
|
type: "text",
|
|
142
|
-
text: `review tool not allowed: ${call.name}; PTC is unavailable in auxiliary review. Use these parent-visible tools directly: ${
|
|
359
|
+
text: `review tool not allowed: ${call.name}; PTC is unavailable in auxiliary review. Use these parent-visible tools directly: ${allowedLabel}`
|
|
143
360
|
}],
|
|
144
361
|
isError: true
|
|
145
362
|
}));
|
|
@@ -162,20 +379,415 @@ async function runReview(input) {
|
|
|
162
379
|
}));
|
|
163
380
|
}
|
|
164
381
|
toolCalls += calls.length;
|
|
382
|
+
if (toolCalls >= maxToolCalls) {
|
|
383
|
+
partialReason = "max tool calls reached before review_done";
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
if (round === maxRounds - 1) hitRoundLimit = true;
|
|
165
387
|
if (parent.session.seq !== beforeSeq) throw new ReviewPartialFailure("review tool mutated the parent Session", actions);
|
|
166
388
|
}
|
|
167
389
|
} finally {
|
|
168
390
|
clearReview();
|
|
169
391
|
}
|
|
170
392
|
if (parent.session.seq !== beforeSeq) throw new ReviewPartialFailure("review mutated the parent Session", actions);
|
|
393
|
+
if (!done && partialReason === void 0) partialReason = "missing review_done";
|
|
394
|
+
if (hitRoundLimit) partialReason = "max review rounds reached before review_done";
|
|
171
395
|
return {
|
|
172
396
|
finalText,
|
|
173
397
|
actions,
|
|
174
398
|
...usage === void 0 ? {} : { usage },
|
|
175
399
|
requests,
|
|
176
|
-
toolCalls
|
|
400
|
+
toolCalls,
|
|
401
|
+
done,
|
|
402
|
+
hitRoundLimit,
|
|
403
|
+
waitCount,
|
|
404
|
+
...report === void 0 ? {} : { report },
|
|
405
|
+
...partialReason === void 0 ? {} : { partialReason }
|
|
177
406
|
};
|
|
178
407
|
}
|
|
408
|
+
//#endregion
|
|
409
|
+
//#region lib/types/review-tool-channel.js
|
|
410
|
+
/** Native transport: the frozen parent header's direct tools plus the live tools service. */
|
|
411
|
+
function nativeReviewToolChannel(parent, toolAllow, tools, executionAgent = parent) {
|
|
412
|
+
const header = parent.session.requestHeader();
|
|
413
|
+
const blocked = (call) => ({
|
|
414
|
+
callId: call.id,
|
|
415
|
+
result: {
|
|
416
|
+
content: [{
|
|
417
|
+
type: "text",
|
|
418
|
+
text: "Tool \"" + call.name + "\" is not available in this background review; use the review tools or finish with review_done."
|
|
419
|
+
}],
|
|
420
|
+
isError: true
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
return {
|
|
424
|
+
mode: "native",
|
|
425
|
+
visibleTools: header?.tools ?? [],
|
|
426
|
+
instruction: "Use only the review tools in this catalog (skill_manage, memory, skill, skill_search, read, glob, grep). Any other tool call is rejected before execution.",
|
|
427
|
+
async execute(calls, signal) {
|
|
428
|
+
const runnable = calls.filter((call) => toolAllow.has(call.name));
|
|
429
|
+
if (runnable.length === 0) return { results: calls.map(blocked) };
|
|
430
|
+
const executed = await tools.execute({
|
|
431
|
+
calls: runnable,
|
|
432
|
+
signal,
|
|
433
|
+
agent: executionAgent
|
|
434
|
+
});
|
|
435
|
+
const byId = new Map(executed.results.map((result) => [result.callId, result]));
|
|
436
|
+
return { results: calls.map((call) => byId.get(call.id) ?? blocked(call)) };
|
|
437
|
+
}
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
//#endregion
|
|
441
|
+
//#region lib/types/review-ptc-channel.js
|
|
442
|
+
/**
|
|
443
|
+
* PTC review tool channel.
|
|
444
|
+
*
|
|
445
|
+
* PTC runs tools through `run_code`; its nested dispatch appends to
|
|
446
|
+
* `exec.agent.session`. The review executor therefore passes a detached child
|
|
447
|
+
* agent created by `@lmzhen/dsh-evolution-adapter/review-child`.
|
|
448
|
+
*
|
|
449
|
+
* The review completion tools (`review_done`, `review_wait`) are registered
|
|
450
|
+
* ONCE per plugin instance by {@link PtcReviewToolHost}. Their `when` guard only
|
|
451
|
+
* admits them while one of the host's review tasks is executing, and their
|
|
452
|
+
* handlers resolve the control record from the active review context. This
|
|
453
|
+
* avoids duplicate global registrations when two PTC reviews run at once.
|
|
454
|
+
*
|
|
455
|
+
* @module @lmzhen/dsh-evolution-review/review-ptc-channel
|
|
456
|
+
*/
|
|
457
|
+
/** Keep PTC's in-program SDK to the review allowlist instead of the parent preset's full tool set. */
|
|
458
|
+
function filterToolSet(full, allowed) {
|
|
459
|
+
if (full === null || typeof full !== "object" || typeof full.view !== "function") return /* @__PURE__ */ new Map();
|
|
460
|
+
const view = full.view.bind(full);
|
|
461
|
+
return {
|
|
462
|
+
view(scope) {
|
|
463
|
+
const source = view(scope);
|
|
464
|
+
if (source === null || typeof source.entries !== "function") return /* @__PURE__ */ new Map();
|
|
465
|
+
const out = /* @__PURE__ */ new Map();
|
|
466
|
+
for (const [name, definition] of source.entries()) if (allowed.has(name)) out.set(name, definition);
|
|
467
|
+
return out;
|
|
468
|
+
},
|
|
469
|
+
...typeof full.dispose === "function" ? { dispose: () => full.dispose() } : {}
|
|
470
|
+
};
|
|
471
|
+
}
|
|
472
|
+
const PTC_INSTRUCTION = "You are reviewing in PTC mode. Write one or more run_code programs that call the available review tools. When the review is complete, call tools.review_done as the only review action of that program. A precise no-op is still completed: always finish with tools.review_done instead of stopping without it. If a write reports resource-busy, call tools.review_wait and then re-read before retrying.";
|
|
473
|
+
function asObject(value) {
|
|
474
|
+
return value !== null && typeof value === "object" ? value : void 0;
|
|
475
|
+
}
|
|
476
|
+
function controlFor(controls, exec) {
|
|
477
|
+
const reviewId = currentReviewContext()?.reviewId;
|
|
478
|
+
if (reviewId !== void 0 && controls.has(reviewId)) return controls.get(reviewId);
|
|
479
|
+
const sessionId = exec?.agent?.session?.id;
|
|
480
|
+
const text = typeof sessionId === "string" ? sessionId : String(sessionId ?? "");
|
|
481
|
+
for (const [taskId, control] of controls) if (text.startsWith("review-child:" + taskId + ":")) return control;
|
|
482
|
+
}
|
|
483
|
+
function reviewDefinitions(controls, locks) {
|
|
484
|
+
return [defineTool({
|
|
485
|
+
name: REVIEW_DONE_TOOL_NAME,
|
|
486
|
+
description: "Finish the review. Must be the only review action in its program.",
|
|
487
|
+
parameters: {
|
|
488
|
+
summary: {
|
|
489
|
+
type: "string",
|
|
490
|
+
required: true
|
|
491
|
+
},
|
|
492
|
+
memoryChanged: {
|
|
493
|
+
type: "boolean",
|
|
494
|
+
required: true
|
|
495
|
+
},
|
|
496
|
+
skillsChanged: {
|
|
497
|
+
type: "array",
|
|
498
|
+
items: { type: "string" },
|
|
499
|
+
required: true
|
|
500
|
+
},
|
|
501
|
+
unresolved: {
|
|
502
|
+
type: "array",
|
|
503
|
+
items: { type: "string" },
|
|
504
|
+
required: true
|
|
505
|
+
}
|
|
506
|
+
},
|
|
507
|
+
output: {
|
|
508
|
+
schema: {
|
|
509
|
+
type: "object",
|
|
510
|
+
additionalProperties: false,
|
|
511
|
+
properties: { ok: {
|
|
512
|
+
type: "boolean",
|
|
513
|
+
required: true
|
|
514
|
+
} }
|
|
515
|
+
},
|
|
516
|
+
render: () => [{
|
|
517
|
+
type: "text",
|
|
518
|
+
text: "review_done accepted"
|
|
519
|
+
}]
|
|
520
|
+
},
|
|
521
|
+
async execute(args, exec) {
|
|
522
|
+
const raw = asObject(args);
|
|
523
|
+
if (raw === void 0) return { ok: false };
|
|
524
|
+
const parsed = parseReviewReport(JSON.stringify(raw));
|
|
525
|
+
const control = controlFor(controls, exec);
|
|
526
|
+
if (parsed === void 0 || control === void 0) return { ok: false };
|
|
527
|
+
control.report = parsed;
|
|
528
|
+
control.done = true;
|
|
529
|
+
return { ok: true };
|
|
530
|
+
}
|
|
531
|
+
}), defineTool({
|
|
532
|
+
name: REVIEW_WAIT_TOOL_NAME,
|
|
533
|
+
description: "Wait for a review resource lock after resource-busy; re-read before retrying.",
|
|
534
|
+
parameters: {
|
|
535
|
+
resource: {
|
|
536
|
+
type: "string",
|
|
537
|
+
required: true
|
|
538
|
+
},
|
|
539
|
+
timeoutMs: { type: "number" }
|
|
540
|
+
},
|
|
541
|
+
output: {
|
|
542
|
+
schema: {
|
|
543
|
+
type: "object",
|
|
544
|
+
additionalProperties: false,
|
|
545
|
+
properties: { ok: {
|
|
546
|
+
type: "boolean",
|
|
547
|
+
required: true
|
|
548
|
+
} }
|
|
549
|
+
},
|
|
550
|
+
render: (_args, value) => [{
|
|
551
|
+
type: "text",
|
|
552
|
+
text: value.ok ? "review_wait released" : "review_wait timed out"
|
|
553
|
+
}]
|
|
554
|
+
},
|
|
555
|
+
async execute(args, exec) {
|
|
556
|
+
const raw = asObject(args);
|
|
557
|
+
const resource = typeof raw?.resource === "string" ? raw.resource : "";
|
|
558
|
+
const timeoutMs = typeof raw?.timeoutMs === "number" && Number.isFinite(raw.timeoutMs) ? raw.timeoutMs : 1e3;
|
|
559
|
+
const control = controlFor(controls, exec);
|
|
560
|
+
if (control === void 0) return { ok: false };
|
|
561
|
+
control.waitCount += 1;
|
|
562
|
+
if (resource === "") return { ok: true };
|
|
563
|
+
return { ok: await locks.wait(resource, timeoutMs, exec.signal) };
|
|
564
|
+
}
|
|
565
|
+
})];
|
|
566
|
+
}
|
|
567
|
+
/**
|
|
568
|
+
* One shared registration surface for all PTC review channels in this plugin
|
|
569
|
+
* instance. Construct once, `register()` once, then `channel()` per task.
|
|
570
|
+
*/
|
|
571
|
+
var PtcReviewToolHost = class {
|
|
572
|
+
tools;
|
|
573
|
+
locks;
|
|
574
|
+
controls = /* @__PURE__ */ new Map();
|
|
575
|
+
active = /* @__PURE__ */ new Set();
|
|
576
|
+
disposers = [];
|
|
577
|
+
registered = false;
|
|
578
|
+
constructor(tools, locks) {
|
|
579
|
+
this.tools = tools;
|
|
580
|
+
this.locks = locks;
|
|
581
|
+
}
|
|
582
|
+
/** Register the review-only tools once; idempotent. */
|
|
583
|
+
register() {
|
|
584
|
+
if (this.registered) return;
|
|
585
|
+
this.registered = true;
|
|
586
|
+
this.disposers = reviewDefinitions(this.controls, this.locks).map((definition) => this.tools.register(definition, { when: () => {
|
|
587
|
+
const reviewId = currentReviewContext()?.reviewId;
|
|
588
|
+
return reviewId !== void 0 && this.active.has(reviewId);
|
|
589
|
+
} }));
|
|
590
|
+
}
|
|
591
|
+
/** Build one task channel over the shared registration. */
|
|
592
|
+
channel(taskId, parentHeaderTools, childAgent, modelSelection, allowedTools) {
|
|
593
|
+
this.register();
|
|
594
|
+
const control = {
|
|
595
|
+
done: false,
|
|
596
|
+
waitCount: 0
|
|
597
|
+
};
|
|
598
|
+
this.controls.set(taskId, control);
|
|
599
|
+
const host = this;
|
|
600
|
+
return {
|
|
601
|
+
mode: "ptc",
|
|
602
|
+
visibleTools: parentHeaderTools,
|
|
603
|
+
instruction: PTC_INSTRUCTION,
|
|
604
|
+
control,
|
|
605
|
+
completion: () => control.done && control.report !== void 0 ? {
|
|
606
|
+
done: true,
|
|
607
|
+
report: control.report,
|
|
608
|
+
waitCount: control.waitCount
|
|
609
|
+
} : void 0,
|
|
610
|
+
async execute(calls, signal) {
|
|
611
|
+
host.active.add(taskId);
|
|
612
|
+
try {
|
|
613
|
+
if (host.tools.execute === void 0) throw new Error("PTC review channel requires tools.execute");
|
|
614
|
+
if (host.tools.resolve === void 0) throw new Error("PTC review channel requires tools.resolve for the review allowlist");
|
|
615
|
+
const toolSet = filterToolSet(await host.tools.resolve({
|
|
616
|
+
agent: childAgent,
|
|
617
|
+
modelSelection,
|
|
618
|
+
signal
|
|
619
|
+
}), allowedTools);
|
|
620
|
+
return await host.tools.execute({
|
|
621
|
+
calls,
|
|
622
|
+
signal,
|
|
623
|
+
agent: childAgent,
|
|
624
|
+
...toolSet === void 0 ? {} : { toolSet }
|
|
625
|
+
});
|
|
626
|
+
} finally {
|
|
627
|
+
host.active.delete(taskId);
|
|
628
|
+
}
|
|
629
|
+
},
|
|
630
|
+
dispose() {
|
|
631
|
+
host.active.delete(taskId);
|
|
632
|
+
host.controls.delete(taskId);
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
/** Remove the global registrations; used when the plugin fiber unloads. */
|
|
637
|
+
dispose() {
|
|
638
|
+
for (const dispose of this.disposers.reverse()) dispose();
|
|
639
|
+
this.disposers = [];
|
|
640
|
+
this.controls.clear();
|
|
641
|
+
this.active.clear();
|
|
642
|
+
this.registered = false;
|
|
643
|
+
}
|
|
644
|
+
};
|
|
645
|
+
//#endregion
|
|
646
|
+
//#region lib/types/review-write-locks.js
|
|
647
|
+
/**
|
|
648
|
+
* Process-local review write locks.
|
|
649
|
+
*
|
|
650
|
+
* The SkillLibrary's per-directory lock + CAS is the final correctness layer.
|
|
651
|
+
* This small registry gives the review model the *recoverable* state it needs:
|
|
652
|
+
* a second review writing the same skill/memory resource gets a `resource-busy`
|
|
653
|
+
* tool result instead of racing silently, and `review_wait` can wait for the
|
|
654
|
+
* holder to release before the model re-reads and retries.
|
|
655
|
+
*
|
|
656
|
+
* It is intentionally not durable and does not coordinate foreground writers or
|
|
657
|
+
* other processes; those keep their existing HomeFence/CAS guarantees.
|
|
658
|
+
*
|
|
659
|
+
* @module @lmzhen/dsh-evolution-review/review-write-locks
|
|
660
|
+
*/
|
|
661
|
+
/** One process-local holder per resource plus its waiters. */
|
|
662
|
+
var ReviewWriteLocks = class {
|
|
663
|
+
closed = false;
|
|
664
|
+
holders = /* @__PURE__ */ new Map();
|
|
665
|
+
waiters = /* @__PURE__ */ new Map();
|
|
666
|
+
/** @returns the holder when the resource is busy, otherwise undefined. */
|
|
667
|
+
holder(resource) {
|
|
668
|
+
return this.holders.get(resource)?.owner;
|
|
669
|
+
}
|
|
670
|
+
/** Drop all holders and wake waiters; used when the plugin fiber unloads. */
|
|
671
|
+
dispose() {
|
|
672
|
+
this.closed = true;
|
|
673
|
+
this.holders.clear();
|
|
674
|
+
for (const waiting of this.waiters.values()) for (const wake of waiting) wake();
|
|
675
|
+
this.waiters.clear();
|
|
676
|
+
}
|
|
677
|
+
/**
|
|
678
|
+
* Try to become the holder.
|
|
679
|
+
* @returns the release callback, or undefined when another owner holds it.
|
|
680
|
+
*/
|
|
681
|
+
tryAcquire(resource, owner) {
|
|
682
|
+
if (this.closed || this.holders.has(resource)) return void 0;
|
|
683
|
+
this.holders.set(resource, { owner });
|
|
684
|
+
let released = false;
|
|
685
|
+
return () => {
|
|
686
|
+
if (released) return;
|
|
687
|
+
released = true;
|
|
688
|
+
this.holders.delete(resource);
|
|
689
|
+
const waiting = this.waiters.get(resource);
|
|
690
|
+
if (waiting === void 0) return;
|
|
691
|
+
this.waiters.delete(resource);
|
|
692
|
+
for (const wake of waiting) wake();
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
/**
|
|
696
|
+
* Wait until the resource has no holder.
|
|
697
|
+
* @returns true when free, false on timeout/abort.
|
|
698
|
+
*/
|
|
699
|
+
async wait(resource, timeoutMs, signal) {
|
|
700
|
+
if (this.closed) return false;
|
|
701
|
+
if (!this.holders.has(resource)) return true;
|
|
702
|
+
if (signal.aborted) return false;
|
|
703
|
+
return await new Promise((resolve) => {
|
|
704
|
+
let finished = false;
|
|
705
|
+
const finish = (value) => {
|
|
706
|
+
if (finished) return;
|
|
707
|
+
finished = true;
|
|
708
|
+
clearTimeout(timer);
|
|
709
|
+
signal.removeEventListener("abort", onAbort);
|
|
710
|
+
this.waiters.get(resource)?.delete(wake);
|
|
711
|
+
if (this.waiters.get(resource)?.size === 0) this.waiters.delete(resource);
|
|
712
|
+
resolve(value);
|
|
713
|
+
};
|
|
714
|
+
const wake = () => {
|
|
715
|
+
if (this.closed) finish(false);
|
|
716
|
+
else if (!this.holders.has(resource)) finish(true);
|
|
717
|
+
};
|
|
718
|
+
const waiting = this.waiters.get(resource) ?? /* @__PURE__ */ new Set();
|
|
719
|
+
waiting.add(wake);
|
|
720
|
+
this.waiters.set(resource, waiting);
|
|
721
|
+
const timer = setTimeout(() => finish(false), Math.max(1, timeoutMs));
|
|
722
|
+
const onAbort = () => finish(false);
|
|
723
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
//#endregion
|
|
728
|
+
//#region lib/types/review-limiter.js
|
|
729
|
+
/**
|
|
730
|
+
* Process-local bound on concurrent AUX reviews.
|
|
731
|
+
*
|
|
732
|
+
* The family deliberately keeps this small: one semaphore for the plugin
|
|
733
|
+
* instance, no per-session or weighted fairness. A review waits for a slot
|
|
734
|
+
* before its first model request; the bounded queue is what keeps a burst of
|
|
735
|
+
* sessions from opening unbounded LLM streams.
|
|
736
|
+
*
|
|
737
|
+
* @module @lmzhen/dsh-evolution-review/review-limiter
|
|
738
|
+
*/
|
|
739
|
+
/** A tiny FIFO semaphore whose waiters can be aborted by unload/timeout. */
|
|
740
|
+
var ReviewLimiter = class {
|
|
741
|
+
limit;
|
|
742
|
+
active = 0;
|
|
743
|
+
closed = false;
|
|
744
|
+
waiters = [];
|
|
745
|
+
constructor(limit) {
|
|
746
|
+
this.limit = limit;
|
|
747
|
+
if (!Number.isInteger(limit) || limit < 1) throw new Error("review limiter limit must be a positive integer");
|
|
748
|
+
}
|
|
749
|
+
/** Wait for a slot; undefined means the wait was aborted or the limiter closed. */
|
|
750
|
+
async acquire(signal) {
|
|
751
|
+
if (this.closed || signal?.aborted === true) return void 0;
|
|
752
|
+
if (this.active < this.limit) {
|
|
753
|
+
this.active += 1;
|
|
754
|
+
return this.releaseOnce();
|
|
755
|
+
}
|
|
756
|
+
return await new Promise((resolve) => {
|
|
757
|
+
const waiter = { resolve };
|
|
758
|
+
if (signal !== void 0) {
|
|
759
|
+
waiter.signal = signal;
|
|
760
|
+
waiter.onAbort = () => {
|
|
761
|
+
const index = this.waiters.indexOf(waiter);
|
|
762
|
+
if (index >= 0) this.waiters.splice(index, 1);
|
|
763
|
+
resolve(void 0);
|
|
764
|
+
};
|
|
765
|
+
signal.addEventListener("abort", waiter.onAbort, { once: true });
|
|
766
|
+
}
|
|
767
|
+
this.waiters.push(waiter);
|
|
768
|
+
});
|
|
769
|
+
}
|
|
770
|
+
dispose() {
|
|
771
|
+
this.closed = true;
|
|
772
|
+
for (const waiter of this.waiters.splice(0)) {
|
|
773
|
+
if (waiter.signal !== void 0 && waiter.onAbort !== void 0) waiter.signal.removeEventListener("abort", waiter.onAbort);
|
|
774
|
+
waiter.resolve(void 0);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
releaseOnce() {
|
|
778
|
+
let released = false;
|
|
779
|
+
return () => {
|
|
780
|
+
if (released) return;
|
|
781
|
+
released = true;
|
|
782
|
+
this.active -= 1;
|
|
783
|
+
const waiter = this.waiters.shift();
|
|
784
|
+
if (waiter === void 0) return;
|
|
785
|
+
if (waiter.signal !== void 0 && waiter.onAbort !== void 0) waiter.signal.removeEventListener("abort", waiter.onAbort);
|
|
786
|
+
this.active += 1;
|
|
787
|
+
waiter.resolve(this.releaseOnce());
|
|
788
|
+
};
|
|
789
|
+
}
|
|
790
|
+
};
|
|
179
791
|
/**
|
|
180
792
|
* Whether a message is a notice this plugin delivered, judged only by durable source fields.
|
|
181
793
|
*
|
|
@@ -290,6 +902,9 @@ var SessionScopedState = class {
|
|
|
290
902
|
*/
|
|
291
903
|
/** Model requests per auxiliary review run. One skill of incremental edits may need many rounds. */
|
|
292
904
|
const DEFAULT_REVIEW_MAX_ROUNDS = 12;
|
|
905
|
+
/** Tool calls per auxiliary review run; completion is still required before this bound. */
|
|
906
|
+
const DEFAULT_REVIEW_MAX_TOOL_CALLS = 50;
|
|
907
|
+
const MAX_REVIEW_MAX_TOOL_CALLS = 500;
|
|
293
908
|
/** Keep a mistyped deployment value from turning one review into an unbounded loop. */
|
|
294
909
|
const MAX_REVIEW_MAX_ROUNDS = 200;
|
|
295
910
|
/** Emit one `evolution/review-scheduled` inside its OWN protection domain (V8-03, V5-19③/F-334).
|
|
@@ -330,6 +945,7 @@ const Config = z.object({
|
|
|
330
945
|
reviewSkillInterval: z.number().min(1).volatile(),
|
|
331
946
|
reviewTimeoutMs: z.number().min(1).max(MAX_TIMER_DELAY_MS).default(DEFAULT_REVIEW_TIMEOUT_MS),
|
|
332
947
|
reviewMaxRounds: z.number().min(1).max(MAX_REVIEW_MAX_ROUNDS).default(DEFAULT_REVIEW_MAX_ROUNDS),
|
|
948
|
+
reviewMaxToolCalls: z.number().min(1).max(MAX_REVIEW_MAX_TOOL_CALLS).default(DEFAULT_REVIEW_MAX_TOOL_CALLS),
|
|
333
949
|
skillReviewTrigger: z.union([
|
|
334
950
|
z.const("cadence"),
|
|
335
951
|
z.const("completion"),
|
|
@@ -348,6 +964,20 @@ const Config = z.object({
|
|
|
348
964
|
* kind: memory / skill / combined), both in the queue and in the session log.
|
|
349
965
|
*/
|
|
350
966
|
const cadenceSummary = (kind) => `auto-review:${kind}`;
|
|
967
|
+
/** Foreground delivery still combines both due domains into one prompt. */
|
|
968
|
+
function injectKind(debt) {
|
|
969
|
+
if (debt === null) return null;
|
|
970
|
+
if (debt.memory && debt.skill) return "combined";
|
|
971
|
+
return debt.memory ? "memory" : debt.skill ? "skill" : null;
|
|
972
|
+
}
|
|
973
|
+
function mergeDebt(a, b) {
|
|
974
|
+
if (a === null || a === void 0) return b ?? void 0;
|
|
975
|
+
if (b === null || b === void 0) return a;
|
|
976
|
+
return {
|
|
977
|
+
memory: a.memory || b.memory,
|
|
978
|
+
skill: a.skill || b.skill
|
|
979
|
+
};
|
|
980
|
+
}
|
|
351
981
|
/**
|
|
352
982
|
* The DEPLOYMENT layer of this row, clamped once at assembly: the restart-only
|
|
353
983
|
* numerics (registry tier E2) whose consumers read them from this snapshot. The
|
|
@@ -365,7 +995,8 @@ function clampReviewConfig(rawConfig, ctx) {
|
|
|
365
995
|
const field = (name, value, fallback, min, max) => clampOnce(warned, warn, name, value, fallback, min, max);
|
|
366
996
|
return Object.assign({}, rawConfig, {
|
|
367
997
|
reviewTimeoutMs: field("reviewTimeoutMs", rawConfig.reviewTimeoutMs, DEFAULT_REVIEW_TIMEOUT_MS, 1, MAX_TIMER_DELAY_MS),
|
|
368
|
-
reviewMaxRounds: field("reviewMaxRounds", rawConfig.reviewMaxRounds, DEFAULT_REVIEW_MAX_ROUNDS, 1, MAX_REVIEW_MAX_ROUNDS)
|
|
998
|
+
reviewMaxRounds: field("reviewMaxRounds", rawConfig.reviewMaxRounds, DEFAULT_REVIEW_MAX_ROUNDS, 1, MAX_REVIEW_MAX_ROUNDS),
|
|
999
|
+
reviewMaxToolCalls: field("reviewMaxToolCalls", rawConfig.reviewMaxToolCalls, DEFAULT_REVIEW_MAX_TOOL_CALLS, 1, MAX_REVIEW_MAX_TOOL_CALLS)
|
|
369
1000
|
});
|
|
370
1001
|
}
|
|
371
1002
|
/**
|
|
@@ -597,7 +1228,7 @@ function apply(ctx, rawConfig = {}) {
|
|
|
597
1228
|
turnsSinceSkill: 0,
|
|
598
1229
|
lastTurn: -1
|
|
599
1230
|
};
|
|
600
|
-
const advanced = {
|
|
1231
|
+
const advanced = { debt: null };
|
|
601
1232
|
if (settlesHere) await settleNotice(session.id, "turn-end");
|
|
602
1233
|
else await withReviewStateLock(session.id, async () => {
|
|
603
1234
|
state = await stateService?.loadReviewState(session.id) ?? {
|
|
@@ -605,7 +1236,7 @@ function apply(ctx, rawConfig = {}) {
|
|
|
605
1236
|
turnsSinceSkill: 0,
|
|
606
1237
|
lastTurn: -1
|
|
607
1238
|
};
|
|
608
|
-
advanced.
|
|
1239
|
+
advanced.debt = advanceReview(state, event.data.turn, signal, {
|
|
609
1240
|
memoryInterval: params().reviewMemoryInterval,
|
|
610
1241
|
skillInterval: params().reviewSkillInterval,
|
|
611
1242
|
substantiveMinToolCalls: snapshot?.substantiveMinToolCalls ?? DEFAULT_SUBSTANTIVE_MIN_TOOL_CALLS,
|
|
@@ -615,20 +1246,24 @@ function apply(ctx, rawConfig = {}) {
|
|
|
615
1246
|
});
|
|
616
1247
|
await stateService?.saveReviewState(session.id, state);
|
|
617
1248
|
});
|
|
618
|
-
const
|
|
1249
|
+
const debt = advanced.debt;
|
|
1250
|
+
const kind = injectKind(debt);
|
|
619
1251
|
const cumulative = (cumulativeToolCalls.get(session.id) ?? 0) + signal.toolCalls;
|
|
620
1252
|
cumulativeToolCalls.set(session.id, cumulative);
|
|
621
1253
|
if (event.data.reason.kind === "completed") {
|
|
622
|
-
const
|
|
623
|
-
if (
|
|
1254
|
+
const pendingDebt = params().reviewMode === "inject" ? debt ?? pendingCadenceReviews.get(session.id) : mergeDebt(pendingCadenceReviews.get(session.id), debt);
|
|
1255
|
+
if (pendingDebt !== void 0) {
|
|
624
1256
|
pendingCadenceReviews.delete(session.id);
|
|
625
1257
|
if (params().reviewMode === "aux") {
|
|
626
|
-
|
|
1258
|
+
await consumeReviewDebt(session.id, pendingDebt);
|
|
1259
|
+
await scheduleAuxDebt(session, agent, pendingDebt, signal, "cadence");
|
|
627
1260
|
return;
|
|
628
1261
|
}
|
|
1262
|
+
const pendingKind = injectKind(pendingDebt);
|
|
1263
|
+
if (pendingKind === null) return;
|
|
629
1264
|
if (params().reviewMode === "inject") {
|
|
630
1265
|
if (!deliverMessage(agent, reviewPrompt(pendingKind), cadenceSummary(pendingKind), true)) {
|
|
631
|
-
pendingCadenceReviews.set(session.id,
|
|
1266
|
+
pendingCadenceReviews.set(session.id, pendingDebt);
|
|
632
1267
|
return;
|
|
633
1268
|
}
|
|
634
1269
|
emitReviewScheduled(ctx, {
|
|
@@ -643,8 +1278,9 @@ function apply(ctx, rawConfig = {}) {
|
|
|
643
1278
|
return;
|
|
644
1279
|
}
|
|
645
1280
|
}
|
|
646
|
-
if (
|
|
647
|
-
pendingCadenceReviews.
|
|
1281
|
+
if (debt !== null && event.data.reason.kind !== "completed") {
|
|
1282
|
+
const pending = params().reviewMode === "inject" ? debt : mergeDebt(pendingCadenceReviews.get(session.id), debt);
|
|
1283
|
+
pendingCadenceReviews.set(session.id, pending);
|
|
648
1284
|
if (!pendingCadenceWarned.has(session.id)) {
|
|
649
1285
|
pendingCadenceWarned.add(session.id);
|
|
650
1286
|
ctx.logger.warn(`dsh-evolution-review: ${kind} review threshold reached; the review runs at the end of the conversation (no mid-task execution)`);
|
|
@@ -790,6 +1426,9 @@ function apply(ctx, rawConfig = {}) {
|
|
|
790
1426
|
* created; the parent Agent is used only for tool scope/approval, with no log.
|
|
791
1427
|
*/
|
|
792
1428
|
let inFlightControllers = /* @__PURE__ */ new Set();
|
|
1429
|
+
const reviewWriteLocks = new ReviewWriteLocks();
|
|
1430
|
+
const auxLimiter = new ReviewLimiter(2);
|
|
1431
|
+
let ptcToolHost;
|
|
793
1432
|
/**
|
|
794
1433
|
* Freeze the parent prefix for an aux review.
|
|
795
1434
|
*
|
|
@@ -821,40 +1460,77 @@ function apply(ctx, rawConfig = {}) {
|
|
|
821
1460
|
return typeof value === "function" ? value.bind(target) : value;
|
|
822
1461
|
} });
|
|
823
1462
|
}
|
|
1463
|
+
async function scheduleAuxDebt(session, agent, debt, signal, reason) {
|
|
1464
|
+
const tasks = [];
|
|
1465
|
+
if (debt.memory) tasks.push(tryAuxReview(session, agent, "memory", signal, reason));
|
|
1466
|
+
if (debt.skill) tasks.push(tryAuxReview(session, agent, "skill", signal, reason));
|
|
1467
|
+
await Promise.all(tasks);
|
|
1468
|
+
}
|
|
1469
|
+
async function consumeReviewDebt(sessionId, debt) {
|
|
1470
|
+
await withReviewStateLock(sessionId, async () => {
|
|
1471
|
+
const service = ctx.get("evolutionState");
|
|
1472
|
+
const state = await service?.loadReviewState(sessionId);
|
|
1473
|
+
if (state === void 0 || state === null) return;
|
|
1474
|
+
if (debt.memory) state.turnsSinceMemory = 0;
|
|
1475
|
+
if (debt.skill) state.turnsSinceSkill = 0;
|
|
1476
|
+
await service?.saveReviewState(sessionId, state);
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
824
1479
|
async function tryAuxReview(session, agent, kind, signal, reason) {
|
|
825
|
-
|
|
1480
|
+
let runningByKind = auxRunning.get(session.id);
|
|
1481
|
+
if (runningByKind === void 0) {
|
|
1482
|
+
runningByKind = /* @__PURE__ */ new Map();
|
|
1483
|
+
auxRunning.set(session.id, runningByKind);
|
|
1484
|
+
}
|
|
1485
|
+
const running = runningByKind.get(kind);
|
|
826
1486
|
if (running !== void 0) {
|
|
827
1487
|
running.rerun = kind;
|
|
828
1488
|
return true;
|
|
829
1489
|
}
|
|
1490
|
+
const state = {};
|
|
1491
|
+
runningByKind.set(kind, state);
|
|
1492
|
+
const releaseKind = () => {
|
|
1493
|
+
runningByKind.delete(kind);
|
|
1494
|
+
if (runningByKind.size === 0) auxRunning.delete(session.id);
|
|
1495
|
+
};
|
|
1496
|
+
const projectedPreset = ctx.get("sessionProjections")?.snapshot?.(session, ["agentPreset"])?.values?.agentPreset;
|
|
1497
|
+
const headerPreset = session.header?.agentPreset;
|
|
1498
|
+
if ((typeof projectedPreset === "string" ? projectedPreset : typeof headerPreset === "string" ? headerPreset : void 0) === "minimal") {
|
|
1499
|
+
releaseKind();
|
|
1500
|
+
ctx.logger.info("dsh-evolution-review: minimal preset has no family review surface");
|
|
1501
|
+
return true;
|
|
1502
|
+
}
|
|
830
1503
|
const reviewParent = snapshotReviewParent(agent);
|
|
831
1504
|
const header = session.requestHeader();
|
|
832
1505
|
if (header === void 0) {
|
|
1506
|
+
releaseKind();
|
|
833
1507
|
ctx.logger.warn("dsh-evolution-review: aux review skipped — parent has no request header");
|
|
834
1508
|
return false;
|
|
835
1509
|
}
|
|
836
1510
|
const llm = llmPort(ctx)?.streamRaw;
|
|
837
|
-
const
|
|
1511
|
+
const toolsService = toolsPort(ctx);
|
|
1512
|
+
const tools = toolsService?.execute;
|
|
838
1513
|
if (llm === void 0 || tools === void 0) {
|
|
1514
|
+
releaseKind();
|
|
839
1515
|
ctx.logger.warn("dsh-evolution-review: aux review skipped — llm/tools service is not mounted");
|
|
840
1516
|
return false;
|
|
841
1517
|
}
|
|
842
1518
|
const authority = ctx.get("evolutionMutationAuthority");
|
|
843
1519
|
let leaseToken;
|
|
844
1520
|
if (authority?.lease !== void 0) {
|
|
845
|
-
const lease = await authority.lease.acquire("background_review", "review:" + session.id, Math.max(config.reviewTimeoutMs + 3e4, 6e4)).catch(() => void 0);
|
|
1521
|
+
const lease = await authority.lease.acquire("background_review", "review:" + session.id + ":" + kind, Math.max(config.reviewTimeoutMs + 3e4, 6e4)).catch(() => void 0);
|
|
846
1522
|
if (lease === void 0) {
|
|
1523
|
+
releaseKind();
|
|
847
1524
|
ctx.logger.warn("dsh-evolution-review: aux review skipped — lease acquire failed");
|
|
848
1525
|
return false;
|
|
849
1526
|
}
|
|
850
1527
|
if (!lease.ok) {
|
|
1528
|
+
releaseKind();
|
|
851
1529
|
ctx.logger.warn("dsh-evolution-review: aux review already leased (" + lease.reason + ")");
|
|
852
1530
|
return false;
|
|
853
1531
|
}
|
|
854
1532
|
leaseToken = lease.token;
|
|
855
1533
|
}
|
|
856
|
-
const state = {};
|
|
857
|
-
auxRunning.set(session.id, state);
|
|
858
1534
|
const reviewId = "aux-" + randomUUID();
|
|
859
1535
|
const startedAt = Date.now();
|
|
860
1536
|
const controller = new AbortController();
|
|
@@ -882,6 +1558,35 @@ function apply(ctx, rawConfig = {}) {
|
|
|
882
1558
|
"grep"
|
|
883
1559
|
]);
|
|
884
1560
|
const toolAllow = new Set((header.tools ?? []).map((tool) => tool.name).filter((name) => AUX_TOOL_ALLOW.has(name)));
|
|
1561
|
+
const nativeChannel = nativeReviewToolChannel(reviewParent, toolAllow, { execute: tools }, agent);
|
|
1562
|
+
const ptcOnly = toolAllow.size === 0 && (header.tools ?? []).some((tool) => tool.name === "run_code");
|
|
1563
|
+
let reviewChild;
|
|
1564
|
+
let channel = nativeChannel;
|
|
1565
|
+
try {
|
|
1566
|
+
reviewChild = ptcOnly && toolsService !== void 0 ? await createReviewChildAgent(agent, reviewId, { ptc: true }) : void 0;
|
|
1567
|
+
if (reviewChild !== void 0 && toolsService !== void 0 && ptcToolHost === void 0) {
|
|
1568
|
+
ptcToolHost = new PtcReviewToolHost(toolsService, reviewWriteLocks);
|
|
1569
|
+
ptcToolHost.register();
|
|
1570
|
+
}
|
|
1571
|
+
if (reviewChild !== void 0 && ptcToolHost !== void 0) channel = ptcToolHost.channel(reviewId, header.tools ?? [], reviewChild.agent, {
|
|
1572
|
+
provider: header.config.provider,
|
|
1573
|
+
model: header.config.model
|
|
1574
|
+
}, new Set([
|
|
1575
|
+
...AUX_TOOL_ALLOW,
|
|
1576
|
+
"run_code",
|
|
1577
|
+
"review_done",
|
|
1578
|
+
"review_wait"
|
|
1579
|
+
]));
|
|
1580
|
+
} catch (error) {
|
|
1581
|
+
await reviewChild?.dispose();
|
|
1582
|
+
releaseKind();
|
|
1583
|
+
clearTimeout(timer);
|
|
1584
|
+
if (leaseRenewTimer !== void 0) clearInterval(leaseRenewTimer);
|
|
1585
|
+
inFlightControllers.delete(controller);
|
|
1586
|
+
if (leaseToken !== void 0 && authority?.lease !== void 0) await authority.lease.release(leaseToken).catch(() => {});
|
|
1587
|
+
ctx.logger.warn("dsh-evolution-review: aux review setup failed: " + (error instanceof Error ? error.message : String(error)));
|
|
1588
|
+
return false;
|
|
1589
|
+
}
|
|
885
1590
|
emitReviewScheduled(ctx, {
|
|
886
1591
|
sessionId: session.id,
|
|
887
1592
|
kind,
|
|
@@ -897,9 +1602,15 @@ function apply(ctx, rawConfig = {}) {
|
|
|
897
1602
|
let usage;
|
|
898
1603
|
let requests = 0;
|
|
899
1604
|
let toolCalls = 0;
|
|
1605
|
+
let waitCount = 0;
|
|
1606
|
+
let hitRoundLimit = false;
|
|
1607
|
+
let report;
|
|
900
1608
|
let error;
|
|
1609
|
+
let limiterRelease;
|
|
901
1610
|
try {
|
|
902
|
-
|
|
1611
|
+
limiterRelease = await auxLimiter.acquire(controller.signal);
|
|
1612
|
+
if (limiterRelease === void 0) throw new Error("aux review queue aborted");
|
|
1613
|
+
const prompt = reviewPrompt(kind, "aux") + "\n\nWhen all durable changes for this review are complete, call review_done as the only tool call in your final batch. Do not call it while more edits remain. A precise no-op is still a completed review: always finish with review_done and an unchanged report instead of stopping without it. If a write is locked, call review_wait once, then re-read the target and retry; never reapply a stale patch." + (channel.instruction === void 0 ? "" : "\n\n" + channel.instruction);
|
|
903
1614
|
const result = await withReviewContext({
|
|
904
1615
|
reviewId,
|
|
905
1616
|
runId: reviewId,
|
|
@@ -912,9 +1623,13 @@ function apply(ctx, rawConfig = {}) {
|
|
|
912
1623
|
signal: input.signal,
|
|
913
1624
|
agent
|
|
914
1625
|
}) },
|
|
1626
|
+
channel,
|
|
1627
|
+
writeLocks: reviewWriteLocks,
|
|
1628
|
+
owner: reviewId,
|
|
915
1629
|
instruction: prompt,
|
|
916
1630
|
toolAllow,
|
|
917
1631
|
maxRounds: config.reviewMaxRounds,
|
|
1632
|
+
maxToolCalls: config.reviewMaxToolCalls,
|
|
918
1633
|
signal: controller.signal,
|
|
919
1634
|
markReview: () => {},
|
|
920
1635
|
clearReview: () => {}
|
|
@@ -923,20 +1638,28 @@ function apply(ctx, rawConfig = {}) {
|
|
|
923
1638
|
actions = result.actions;
|
|
924
1639
|
requests = result.requests;
|
|
925
1640
|
toolCalls = result.toolCalls;
|
|
1641
|
+
waitCount = result.waitCount;
|
|
1642
|
+
hitRoundLimit = result.hitRoundLimit;
|
|
1643
|
+
report = result.report;
|
|
926
1644
|
if (result.usage !== void 0) usage = {
|
|
927
1645
|
inputTokens: result.usage.inputTokens ?? 0,
|
|
928
1646
|
outputTokens: result.usage.outputTokens ?? 0,
|
|
929
1647
|
cacheReadTokens: result.usage.cacheReadTokens ?? 0,
|
|
930
1648
|
cacheWriteTokens: 0
|
|
931
1649
|
};
|
|
932
|
-
status =
|
|
933
|
-
if (
|
|
1650
|
+
status = result.done && result.partialReason === void 0 ? "completed" : "partial";
|
|
1651
|
+
if (result.partialReason !== void 0) error = result.partialReason;
|
|
1652
|
+
if (toolAllow.size === 0 && reviewChild === void 0) {
|
|
1653
|
+
status = "failed";
|
|
1654
|
+
error = "aux review has no allowed tools for this parent; refusing to report completed";
|
|
1655
|
+
}
|
|
934
1656
|
} catch (caught) {
|
|
935
1657
|
error = caught instanceof Error ? caught.message : String(caught);
|
|
936
1658
|
if (caught instanceof ReviewPartialFailure && caught.actions.length > 0) actions = caught.actions;
|
|
937
1659
|
status = timedOut ? "timeout" : controller.signal.aborted ? "aborted" : "failed";
|
|
938
1660
|
ctx.logger.warn("dsh-evolution-review: aux review failed: " + error);
|
|
939
1661
|
} finally {
|
|
1662
|
+
limiterRelease?.();
|
|
940
1663
|
clearTimeout(timer);
|
|
941
1664
|
if (leaseRenewTimer !== void 0) clearInterval(leaseRenewTimer);
|
|
942
1665
|
const finishedAt = Date.now();
|
|
@@ -944,9 +1667,16 @@ function apply(ctx, rawConfig = {}) {
|
|
|
944
1667
|
ctx.emit("evolution/review-completed", {
|
|
945
1668
|
version: 1,
|
|
946
1669
|
reviewId,
|
|
1670
|
+
taskId: reviewId,
|
|
947
1671
|
sessionId: String(session.id),
|
|
948
1672
|
kind,
|
|
949
1673
|
status,
|
|
1674
|
+
toolMode: channel.mode,
|
|
1675
|
+
...(() => {
|
|
1676
|
+
const projected = ctx.get("sessionProjections")?.snapshot?.(session, ["agentPreset"])?.values?.agentPreset;
|
|
1677
|
+
const preset = typeof projected === "string" ? projected : typeof session.header?.agentPreset === "string" ? session.header.agentPreset : void 0;
|
|
1678
|
+
return preset === void 0 ? {} : { preset };
|
|
1679
|
+
})(),
|
|
950
1680
|
trigger: {
|
|
951
1681
|
reason,
|
|
952
1682
|
toolCalls: signal.toolCalls,
|
|
@@ -957,6 +1687,10 @@ function apply(ctx, rawConfig = {}) {
|
|
|
957
1687
|
actions,
|
|
958
1688
|
requests,
|
|
959
1689
|
toolCalls,
|
|
1690
|
+
waitCount,
|
|
1691
|
+
hitRoundLimit,
|
|
1692
|
+
...report === void 0 ? {} : { report },
|
|
1693
|
+
...status === "partial" && error !== void 0 ? { partialReason: error } : status === "timeout" ? { partialReason: "review-timeout" } : {},
|
|
960
1694
|
...usage === void 0 ? {} : { usage },
|
|
961
1695
|
startedAt,
|
|
962
1696
|
finishedAt,
|
|
@@ -983,8 +1717,15 @@ function apply(ctx, rawConfig = {}) {
|
|
|
983
1717
|
} catch (emitError) {
|
|
984
1718
|
ctx.logger.warn("dsh-evolution-review: aux plan-applied emit failed: " + (emitError instanceof Error ? emitError.message : String(emitError)));
|
|
985
1719
|
}
|
|
986
|
-
auxRunning.
|
|
1720
|
+
const active = auxRunning.get(session.id);
|
|
1721
|
+
active?.delete(kind);
|
|
1722
|
+
if (active !== void 0 && active.size === 0) auxRunning.delete(session.id);
|
|
987
1723
|
inFlightControllers.delete(controller);
|
|
1724
|
+
try {
|
|
1725
|
+
await reviewChild?.dispose();
|
|
1726
|
+
} catch (disposeError) {
|
|
1727
|
+
ctx.logger.warn("dsh-evolution-review: PTC review child dispose failed: " + (disposeError instanceof Error ? disposeError.message : String(disposeError)));
|
|
1728
|
+
}
|
|
988
1729
|
if (leaseToken !== void 0 && authority?.lease !== void 0) await authority.lease.release(leaseToken).catch(() => {});
|
|
989
1730
|
if (state.rerun !== void 0) tryAuxReview(session, agent, state.rerun, signal, reason);
|
|
990
1731
|
}
|
|
@@ -994,6 +1735,9 @@ function apply(ctx, rawConfig = {}) {
|
|
|
994
1735
|
ctx.effect(() => () => {
|
|
995
1736
|
for (const controller of inFlightControllers) controller.abort();
|
|
996
1737
|
inFlightControllers = /* @__PURE__ */ new Set();
|
|
1738
|
+
reviewWriteLocks.dispose();
|
|
1739
|
+
auxLimiter.dispose();
|
|
1740
|
+
ptcToolHost?.dispose();
|
|
997
1741
|
sessionState.dispose();
|
|
998
1742
|
}, "dsh-evolution-review.cleanup");
|
|
999
1743
|
}
|