skill-evolution 0.0.0-stage → 0.3.1
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 +52 -0
- package/LICENSE +21 -0
- package/README.en.md +208 -0
- package/README.md +207 -2
- package/assets/icon-180.png +0 -0
- package/assets/screenshots/workbench.png +0 -0
- package/client.js +2135 -0
- package/cordis.patch.yml +41 -0
- package/icon.svg +6 -0
- package/index.js +884 -0
- package/lib/applier.js +221 -0
- package/lib/collector.js +356 -0
- package/lib/consolidation.js +344 -0
- package/lib/gatekeeper.js +293 -0
- package/lib/http-api.js +919 -0
- package/lib/ledger.js +316 -0
- package/lib/prompts.js +514 -0
- package/lib/provenance.js +103 -0
- package/lib/reflector.js +226 -0
- package/lib/synthesizer.js +295 -0
- package/lib/tidy.js +263 -0
- package/lib/usage.js +223 -0
- package/locale/en.json +8 -0
- package/locale/zh.json +8 -0
- package/package.json +87 -4
- package/screenshots.json +3 -0
package/index.js
ADDED
|
@@ -0,0 +1,884 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH 自进化(skill-evolution)
|
|
3
|
+
*
|
|
4
|
+
* 让 DSH 拥有 Hermes 的 closed learning loop:
|
|
5
|
+
* 回合结束 → 采集快照 → fork 只读复盘 → 蒸馏成技能 → 闸门校验 → 落盘草稿 → 记账
|
|
6
|
+
*
|
|
7
|
+
* 设计原则:
|
|
8
|
+
* 1. 不侵入 DSH 内核 —— 纯插件,不改宿主
|
|
9
|
+
* 2. 复用而非重造 —— 技能格式/注册表/热更新全部复用 DSH 现有能力
|
|
10
|
+
* 3. 默认保守 —— 只产草稿到 .staging/,不自动落盘
|
|
11
|
+
* 4. 可回滚 —— 每次变更记账,支持单条回滚
|
|
12
|
+
* 5. 不污染 —— 绝不自动写权威记忆层
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import fs from "node:fs";
|
|
16
|
+
import path from "node:path";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import z from "@deepseek-ai/schemastery";
|
|
19
|
+
|
|
20
|
+
import { buildSnapshot, Throttle } from "./lib/collector.js";
|
|
21
|
+
import { runReview, activeReviewChildIds } from "./lib/reflector.js";
|
|
22
|
+
import { synthesize } from "./lib/synthesizer.js";
|
|
23
|
+
import { applySynthesis, listDrafts, promoteDraft, listSkills } from "./lib/applier.js";
|
|
24
|
+
import { readEntries, rollbackEntry, maybeRotateLedger, gcBlobs } from "./lib/ledger.js";
|
|
25
|
+
import { applyAutomaticTransitions, adoptSkill, disownSkill, bumpUsage } from "./lib/usage.js";
|
|
26
|
+
import { registerEvolutionHttp, buildSnapshot as buildHttpSnapshot, refineDraftWithComment } from "./lib/http-api.js";
|
|
27
|
+
import { runConsolidation } from "./lib/consolidation.js";
|
|
28
|
+
|
|
29
|
+
export const name = "skill-evolution";
|
|
30
|
+
export const inject = ["agents", "subagents", "commands", "tools"];
|
|
31
|
+
|
|
32
|
+
export const Config = z.object({
|
|
33
|
+
enabled: z.boolean().default(true).description("是否启用 DSH 自进化复盘"),
|
|
34
|
+
|
|
35
|
+
skillsRoot: z
|
|
36
|
+
.string()
|
|
37
|
+
.default("")
|
|
38
|
+
.description("技能根目录(留空则用 ~/.dsh/skills);账本、草稿、遥测都放这里"),
|
|
39
|
+
|
|
40
|
+
mode: z
|
|
41
|
+
.union(["draft", "apply"])
|
|
42
|
+
.default("draft")
|
|
43
|
+
.description("draft=只写 .staging/ 等人工审阅(推荐);apply=通过闸门后直接落盘"),
|
|
44
|
+
|
|
45
|
+
minTurnsBetween: z.number().default(1).description("两次复盘之间至少间隔多少个回合"),
|
|
46
|
+
minMinutesBetween: z.number().default(2).description("两次复盘之间至少间隔多少分钟"),
|
|
47
|
+
|
|
48
|
+
maxMessages: z.number().default(24).description("快照保留的最近消息条数"),
|
|
49
|
+
maxChars: z.number().default(24000).description("快照总字符上限"),
|
|
50
|
+
|
|
51
|
+
reviewTimeoutSeconds: z.number().default(180).description("单次复盘超时(秒)"),
|
|
52
|
+
|
|
53
|
+
reviewModel: z
|
|
54
|
+
.object({
|
|
55
|
+
provider: z.string().default(""),
|
|
56
|
+
model: z.string().default(""),
|
|
57
|
+
reasoningEffort: z.string().default(""),
|
|
58
|
+
})
|
|
59
|
+
.default({ provider: "", model: "", reasoningEffort: "" })
|
|
60
|
+
.description("复盘专用模型;留空继承当前会话模型,也可指定更便宜的辅助模型"),
|
|
61
|
+
|
|
62
|
+
curatorEnabled: z.boolean().default(true).description("是否启用技能生命周期维护(active/stale/archived)"),
|
|
63
|
+
consolidate: z.boolean().default(false).description("是否启用 LLM 建伞合并(把多个窄技能合并成类级别伞技能)"),
|
|
64
|
+
consolidateDryRun: z.boolean().default(true).description("合并时只分析不执行(默认 true,确认无误后再关掉)"),
|
|
65
|
+
staleAfterDays: z.number().default(14).description("多少天未使用标记为 stale"),
|
|
66
|
+
archiveAfterDays: z.number().default(30).description("多少天未使用归档(永不删除)"),
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
function resolveSkillsRoot(config) {
|
|
70
|
+
if (config.skillsRoot && config.skillsRoot.trim()) return path.resolve(config.skillsRoot.trim());
|
|
71
|
+
const dshHome = process.env.DSH_HOME || path.join(os.homedir(), ".dsh");
|
|
72
|
+
return path.join(dshHome, "skills");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 从 DSH state 目录读回 UI 保存过的配置。 */
|
|
76
|
+
function loadPersistedSettings(config) {
|
|
77
|
+
try {
|
|
78
|
+
const stateDir = path.join(process.env.DSH_HOME || path.join(os.homedir(), ".dsh"), "state");
|
|
79
|
+
const file = path.join(stateDir, "dsh-evolution-settings.json");
|
|
80
|
+
if (!fs.existsSync(file)) return;
|
|
81
|
+
const saved = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
82
|
+
if (!saved || typeof saved !== "object") return;
|
|
83
|
+
for (const key of [
|
|
84
|
+
"enabled",
|
|
85
|
+
"mode",
|
|
86
|
+
"minTurnsBetween",
|
|
87
|
+
"minMinutesBetween",
|
|
88
|
+
"maxMessages",
|
|
89
|
+
"maxChars",
|
|
90
|
+
"reviewTimeoutSeconds",
|
|
91
|
+
"curatorEnabled",
|
|
92
|
+
"consolidate",
|
|
93
|
+
"consolidateDryRun",
|
|
94
|
+
"staleAfterDays",
|
|
95
|
+
"archiveAfterDays",
|
|
96
|
+
]) {
|
|
97
|
+
if (saved[key] !== undefined) config[key] = saved[key];
|
|
98
|
+
}
|
|
99
|
+
if (saved.reviewModel && typeof saved.reviewModel === "object") {
|
|
100
|
+
config.reviewModel = { ...config.reviewModel, ...saved.reviewModel };
|
|
101
|
+
}
|
|
102
|
+
} catch {
|
|
103
|
+
/* 损坏的配置文件忽略 */
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 从 live Session 读取持久化的相关事件(当内存缓冲为空时兜底)。 */
|
|
108
|
+
function extractSessionEvents(session) {
|
|
109
|
+
if (!session || typeof session.seq !== "number" || typeof session.eventAt !== "function") return [];
|
|
110
|
+
const out = [];
|
|
111
|
+
const start = Math.max(0, session.seq - 240);
|
|
112
|
+
for (let seq = start; seq < session.seq; seq += 1) {
|
|
113
|
+
try {
|
|
114
|
+
const ev = session.eventAt(seq);
|
|
115
|
+
if (!ev) continue;
|
|
116
|
+
const t = ev.type ?? ev.kind;
|
|
117
|
+
if (t === "user/message" || t === "assistant/message" || t === "tool/call" || t === "tool/result") {
|
|
118
|
+
out.push(ev);
|
|
119
|
+
}
|
|
120
|
+
} catch {
|
|
121
|
+
/* ignore */
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
function writeLastReviewState(skillsRoot, data) {
|
|
129
|
+
try {
|
|
130
|
+
fs.mkdirSync(skillsRoot, { recursive: true });
|
|
131
|
+
const file = path.join(skillsRoot, ".last_review.json");
|
|
132
|
+
let prev = null;
|
|
133
|
+
try {
|
|
134
|
+
prev = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
135
|
+
} catch {
|
|
136
|
+
prev = null;
|
|
137
|
+
}
|
|
138
|
+
const lastSaved =
|
|
139
|
+
data.status === "saved"
|
|
140
|
+
? { ts: new Date().toISOString(), ...data }
|
|
141
|
+
: prev?.status === "saved"
|
|
142
|
+
? prev
|
|
143
|
+
: prev?.lastSaved ?? null;
|
|
144
|
+
fs.writeFileSync(
|
|
145
|
+
file,
|
|
146
|
+
JSON.stringify({ ts: new Date().toISOString(), ...data, ...(lastSaved ? { lastSaved } : {}) }, null, 2),
|
|
147
|
+
"utf8",
|
|
148
|
+
);
|
|
149
|
+
} catch {
|
|
150
|
+
/* ignore */
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function collectTurnEvents(events, session) {
|
|
155
|
+
if (Array.isArray(events) && events.length > 0) return events;
|
|
156
|
+
return extractSessionEvents(session);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function apply(ctx, rawConfig = {}) {
|
|
160
|
+
const config = { ...Config(rawConfig) };
|
|
161
|
+
loadPersistedSettings(config);
|
|
162
|
+
|
|
163
|
+
const skillsRoot = resolveSkillsRoot(config);
|
|
164
|
+
const throttle = new Throttle({
|
|
165
|
+
minTurnsBetween: config.minTurnsBetween,
|
|
166
|
+
minMinutesBetween: config.minMinutesBetween,
|
|
167
|
+
persistPath: path.join(skillsRoot, ".throttle.json"),
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
/** 每个会话的事件缓冲:sessionId -> events[] */
|
|
171
|
+
const buffers = new Map();
|
|
172
|
+
/** 每个会话正在跑的复盘:sessionId -> AbortController */
|
|
173
|
+
const inflight = new Map();
|
|
174
|
+
/** 每个会话正在跑的复盘 Promise(供 session/flush 在进程退出前等待):sessionId -> Promise */
|
|
175
|
+
const inflightPromises = new Map();
|
|
176
|
+
|
|
177
|
+
ctx.logger?.info?.(`[dsh-evolution] loaded · enabled=${config.enabled} · skillsRoot=${skillsRoot} · mode=${config.mode}`);
|
|
178
|
+
|
|
179
|
+
// ---- 1. 采集:订阅会话事件,缓冲到回合结束 ----
|
|
180
|
+
const offEvent = ctx.on("session/event", (session, event) => {
|
|
181
|
+
if (!config.enabled) return;
|
|
182
|
+
if (!session?.id || !event) return;
|
|
183
|
+
// 子代理会话(含复盘 fork 自身)绝不触发复盘,防止无限递归
|
|
184
|
+
if (session.header?.origin === "subagent" || activeReviewChildIds.has(session.id)) return;
|
|
185
|
+
|
|
186
|
+
const type = event.type ?? event.kind;
|
|
187
|
+
if (!type) return;
|
|
188
|
+
|
|
189
|
+
if (type === "turn/start") {
|
|
190
|
+
if (!buffers.has(session.id)) buffers.set(session.id, []);
|
|
191
|
+
// 新回合到来时打断同一会话上一次未完成的复盘
|
|
192
|
+
inflight.get(session.id)?.abort();
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
let buf = buffers.get(session.id);
|
|
197
|
+
if (!buf) {
|
|
198
|
+
buf = [];
|
|
199
|
+
buffers.set(session.id, buf);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (type === "turn/end") {
|
|
203
|
+
const snapshotEvents = [...buf];
|
|
204
|
+
const p = handleTurnEnd(session, snapshotEvents, ctx, {
|
|
205
|
+
config,
|
|
206
|
+
skillsRoot,
|
|
207
|
+
throttle,
|
|
208
|
+
inflight,
|
|
209
|
+
bypassThrottle: false,
|
|
210
|
+
}).finally(() => {
|
|
211
|
+
if (inflightPromises.get(session.id) === p) inflightPromises.delete(session.id);
|
|
212
|
+
});
|
|
213
|
+
inflightPromises.set(session.id, p);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// 只缓冲我们关心的类型,避免内存膨胀
|
|
218
|
+
if (
|
|
219
|
+
type === "user/message" ||
|
|
220
|
+
type === "assistant/message" ||
|
|
221
|
+
type === "tool/call" ||
|
|
222
|
+
type === "tool/result"
|
|
223
|
+
) {
|
|
224
|
+
buf.push(event);
|
|
225
|
+
// 硬上限:单会话最多缓冲 500 条
|
|
226
|
+
if (buf.length > 500) buf.splice(0, buf.length - 500);
|
|
227
|
+
|
|
228
|
+
// 当模型在真实会话中调用 `skill` 工具加载某个技能时,实时累加 .usage.json 的 useCount 与 lastUsedAt
|
|
229
|
+
if (type === "tool/call") {
|
|
230
|
+
const d = event.data && typeof event.data === "object" ? event.data : event;
|
|
231
|
+
const toolName = d.name ?? d.toolName ?? event.toolName ?? event.name;
|
|
232
|
+
if (toolName === "skill") {
|
|
233
|
+
let argObj = d.arguments ?? event.arguments;
|
|
234
|
+
if (typeof argObj === "string") {
|
|
235
|
+
try { argObj = JSON.parse(argObj); } catch { argObj = null; }
|
|
236
|
+
}
|
|
237
|
+
const loadedName = argObj?.name ?? argObj?.skill;
|
|
238
|
+
if (loadedName && typeof loadedName === "string") {
|
|
239
|
+
void bumpUsage(skillsRoot, loadedName.trim());
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
// ---- 1b. Flush 屏障:保证 headless 等短生命周期进程在退出前等待正在进行的复盘落盘 ----
|
|
247
|
+
const offFlush = ctx.on("session/flush", async (session) => {
|
|
248
|
+
if (!session?.id) return;
|
|
249
|
+
const pending = inflightPromises.get(session.id);
|
|
250
|
+
if (pending) {
|
|
251
|
+
try {
|
|
252
|
+
await pending;
|
|
253
|
+
} catch {
|
|
254
|
+
/* 复盘内部已自行捕获,不阻塞 session flush */
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
// ---- 2. 会话销毁时清理 ----
|
|
260
|
+
const offDisposed = ctx.on("session/disposed", (session) => {
|
|
261
|
+
if (!session?.id) return;
|
|
262
|
+
buffers.delete(session.id);
|
|
263
|
+
inflight.get(session.id)?.abort();
|
|
264
|
+
inflight.delete(session.id);
|
|
265
|
+
inflightPromises.delete(session.id);
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
// ---- 3. 定时 curator:生命周期维护 + LLM 建伞合并 + 账本轮转 + blob GC ----
|
|
269
|
+
let curatorTimer;
|
|
270
|
+
if (config.curatorEnabled) {
|
|
271
|
+
const runCurator = async () => {
|
|
272
|
+
try {
|
|
273
|
+
// 3a. 确定性状态转换(不需要模型)
|
|
274
|
+
const counts = await applyAutomaticTransitions(skillsRoot, {
|
|
275
|
+
staleAfterDays: config.staleAfterDays,
|
|
276
|
+
archiveAfterDays: config.archiveAfterDays,
|
|
277
|
+
});
|
|
278
|
+
if (counts.marked_stale || counts.archived || counts.reactivated) {
|
|
279
|
+
ctx.logger?.info?.(
|
|
280
|
+
`[dsh-evolution] curator: stale=${counts.marked_stale} archived=${counts.archived} reactivated=${counts.reactivated}`,
|
|
281
|
+
);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// 3b. LLM 建伞合并(需要模型,可关闭)
|
|
285
|
+
if (config.consolidate) {
|
|
286
|
+
const agents = ctx.agents?.list?.() ?? [];
|
|
287
|
+
const host = agents.find((a) => a?.session?.id) ?? null;
|
|
288
|
+
const result = await runConsolidation(skillsRoot, {
|
|
289
|
+
dryRun: config.consolidateDryRun,
|
|
290
|
+
runFork: async (prompt) => {
|
|
291
|
+
const r = await runReview(ctx, {
|
|
292
|
+
parent: host ?? null,
|
|
293
|
+
transcript: "",
|
|
294
|
+
promptOverride: prompt,
|
|
295
|
+
timeoutMs: config.reviewTimeoutSeconds * 1000,
|
|
296
|
+
});
|
|
297
|
+
return r.raw ?? "";
|
|
298
|
+
},
|
|
299
|
+
});
|
|
300
|
+
if (result.done?.length) {
|
|
301
|
+
ctx.logger?.info?.(`[dsh-evolution] curator consolidated: ${result.done.join("; ")}`);
|
|
302
|
+
} else if (result.planned?.length) {
|
|
303
|
+
ctx.logger?.info?.(`[dsh-evolution] curator (dry-run) planned: ${result.planned.join("; ")}`);
|
|
304
|
+
} else if (result.skipped) {
|
|
305
|
+
ctx.logger?.info?.(`[dsh-evolution] curator: ${result.reason}`);
|
|
306
|
+
} else if (result.errors?.length) {
|
|
307
|
+
ctx.logger?.warn?.(`[dsh-evolution] curator consolidation rejected: ${result.errors.join("; ")}`);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// 3c. 账本维护
|
|
312
|
+
await maybeRotateLedger(skillsRoot);
|
|
313
|
+
await gcBlobs(skillsRoot);
|
|
314
|
+
} catch (error) {
|
|
315
|
+
ctx.logger?.warn?.(`[dsh-evolution] curator failed: ${error?.message ?? error}`);
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
// 启动 60 秒后跑一次,之后每 6 小时一次
|
|
319
|
+
curatorTimer = setTimeout(() => {
|
|
320
|
+
void runCurator();
|
|
321
|
+
curatorTimer = setInterval(() => void runCurator(), 6 * 3600 * 1000);
|
|
322
|
+
curatorTimer?.unref?.();
|
|
323
|
+
}, 60_000);
|
|
324
|
+
curatorTimer?.unref?.();
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** 手动触发一次复盘:用指定或当前活跃会话的最近事件。 */
|
|
328
|
+
const triggerReview = async (targetAgent = null) => {
|
|
329
|
+
const agents = ctx.agents?.list?.() ?? [];
|
|
330
|
+
const rootAgents = agents.filter((a) => a?.session?.id && a.session.header?.origin !== "subagent");
|
|
331
|
+
const agent = targetAgent ?? rootAgents[rootAgents.length - 1] ?? agents.find((a) => a?.session?.id) ?? null;
|
|
332
|
+
if (!agent?.session) return { ok: false, error: "没有活跃会话可供复盘" };
|
|
333
|
+
const events = collectTurnEvents(buffers.get(agent.session.id), agent.session);
|
|
334
|
+
if (!events.length) return { ok: false, error: "当前会话没有可复盘的回合事件(需要至少一个含工具调用或纠正的回合)" };
|
|
335
|
+
throttle.force();
|
|
336
|
+
const res = await handleTurnEnd(agent.session, events, ctx, {
|
|
337
|
+
config,
|
|
338
|
+
skillsRoot,
|
|
339
|
+
throttle,
|
|
340
|
+
inflight,
|
|
341
|
+
bypassThrottle: true,
|
|
342
|
+
});
|
|
343
|
+
return {
|
|
344
|
+
ok: true,
|
|
345
|
+
message: res?.written?.length
|
|
346
|
+
? `复盘完成:${res.action} "${res.target}" → ${res.written.join(", ")}`
|
|
347
|
+
: `复盘完成:${res?.action ?? "nothing"}(${res?.reason ?? "无新增技能"})`,
|
|
348
|
+
detail: res,
|
|
349
|
+
};
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
/** 供 UI / 命令手动触发的合并 pass。 */
|
|
353
|
+
const triggerConsolidation = async ({ dryRun = true } = {}) => {
|
|
354
|
+
const agents = ctx.agents?.list?.() ?? [];
|
|
355
|
+
const host = agents.find((a) => a?.session?.id) ?? null;
|
|
356
|
+
return runConsolidation(skillsRoot, {
|
|
357
|
+
dryRun,
|
|
358
|
+
runFork: async (prompt) => {
|
|
359
|
+
const r = await runReview(ctx, {
|
|
360
|
+
parent: host ?? null,
|
|
361
|
+
transcript: "",
|
|
362
|
+
promptOverride: prompt,
|
|
363
|
+
timeoutMs: config.reviewTimeoutSeconds * 1000,
|
|
364
|
+
});
|
|
365
|
+
return r.raw ?? "";
|
|
366
|
+
},
|
|
367
|
+
});
|
|
368
|
+
};
|
|
369
|
+
|
|
370
|
+
// ---- 4. 注册用户命令:/evolution ----
|
|
371
|
+
ctx.commands?.register?.({
|
|
372
|
+
name: "evolution",
|
|
373
|
+
description: "DSH 自进化:手机/聊天端中文简报审阅、带批示进化采纳、账本回滚与建伞合并",
|
|
374
|
+
input: {
|
|
375
|
+
hint: "brief [name] | approve <name> <批示> | refine <name> <批示> | reject <name> <批示> | status | drafts | skills | ledger | review | consolidate [--apply] | rollback <id>",
|
|
376
|
+
},
|
|
377
|
+
async handler(invocation) {
|
|
378
|
+
const raw = String(invocation?.rawInput ?? "").trim();
|
|
379
|
+
const parts = raw.split(/\s+/).filter(Boolean);
|
|
380
|
+
const sub = parts[0] || "status";
|
|
381
|
+
const ok = (text) => ({ kind: "success", text });
|
|
382
|
+
const fail = (text) => ({ kind: "error", text });
|
|
383
|
+
try {
|
|
384
|
+
switch (sub) {
|
|
385
|
+
case "brief":
|
|
386
|
+
case "drafts": {
|
|
387
|
+
const snap = await buildHttpSnapshot(skillsRoot, config);
|
|
388
|
+
const targetName = parts[1];
|
|
389
|
+
const list = targetName ? snap.drafts.filter((d) => d.name === targetName) : snap.drafts;
|
|
390
|
+
if (!list.length) return ok("当前没有待审阅的技能草稿。");
|
|
391
|
+
const blocks = list.map((d, i) => {
|
|
392
|
+
const b = d.briefing || {};
|
|
393
|
+
const rules = Array.isArray(b.keyRules) ? b.keyRules.map((r) => ` • ${r}`).join("\n") : "";
|
|
394
|
+
return [
|
|
395
|
+
`### 📋 待审草稿 #${i + 1}:\`${d.name}\` — ${b.titleZh || d.name}`,
|
|
396
|
+
`- **类型**:${d.isPatch ? "现有技能升级补丁" : "新蒸馏类级技能"}`,
|
|
397
|
+
`- **💡 这是什么**:${b.whatItIs || d.description || "(无描述)"}`,
|
|
398
|
+
rules ? `- **📌 核心规则**:\n${rules}` : null,
|
|
399
|
+
`- **✅ 同意后果**:${b.ifApprove || "升入正式技能库并立即生效"}`,
|
|
400
|
+
`- **🚫 驳回后果**:${b.ifReject || "销毁草稿并记录驳回原因"}`,
|
|
401
|
+
b.aiAnalysis ? `- **🤖 AI 批示融合汇报**:${b.aiAnalysis}` : null,
|
|
402
|
+
`- **📱 手机/命令快捷批示**:`,
|
|
403
|
+
` - 修订预览:\`/evolution refine ${d.name} <您的批示想法>\``,
|
|
404
|
+
` - 进化采纳:\`/evolution approve ${d.name} <您的批示想法>\``,
|
|
405
|
+
` - 批示驳回:\`/evolution reject ${d.name} <您的驳回理由>\``,
|
|
406
|
+
]
|
|
407
|
+
.filter(Boolean)
|
|
408
|
+
.join("\n");
|
|
409
|
+
});
|
|
410
|
+
return ok(blocks.join("\n\n---\n\n"));
|
|
411
|
+
}
|
|
412
|
+
case "refine": {
|
|
413
|
+
const target = parts[1];
|
|
414
|
+
const comment = parts.slice(2).join(" ").trim();
|
|
415
|
+
if (!target || !comment) return fail("用法:/evolution refine <skill-name> <您的批示/修改意见>");
|
|
416
|
+
const r = await refineDraftWithComment(skillsRoot, target, comment, runPromptFork);
|
|
417
|
+
if (!r.ok) return fail(`批示修订失败:${r.error}`);
|
|
418
|
+
return ok(`🤖 AI 已根据您的批示修订草稿 "${target}":\n\n${r.aiAnalysis}`);
|
|
419
|
+
}
|
|
420
|
+
case "approve":
|
|
421
|
+
case "promote": {
|
|
422
|
+
const target = parts[1];
|
|
423
|
+
const comment = parts.slice(2).join(" ").trim();
|
|
424
|
+
if (!target) return fail("用法:/evolution approve <skill-name> <您的批示>");
|
|
425
|
+
if (!comment) return fail("请附上您的强制批示,例如:/evolution approve " + target + " 同意,按此规则入库");
|
|
426
|
+
const refined = await refineDraftWithComment(skillsRoot, target, comment, runPromptFork);
|
|
427
|
+
const r = await promoteDraft(skillsRoot, target, {
|
|
428
|
+
actor: "user",
|
|
429
|
+
comment,
|
|
430
|
+
aiAnalysis: refined.ok ? refined.aiAnalysis : "",
|
|
431
|
+
refinedContent: refined.ok ? refined.refinedContent : null,
|
|
432
|
+
});
|
|
433
|
+
if (!r.ok) return fail(`采纳失败:${r.error}`);
|
|
434
|
+
return ok(
|
|
435
|
+
`✅ 已按您的批示进化并采纳 "${target}" 到正式技能库!\n` +
|
|
436
|
+
(refined.ok ? `\n🤖 AI 进化汇报:${refined.aiAnalysis}` : ""),
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
case "reject":
|
|
440
|
+
case "discard": {
|
|
441
|
+
const target = parts[1];
|
|
442
|
+
const comment = parts.slice(2).join(" ").trim();
|
|
443
|
+
if (!target || !comment) return fail("用法:/evolution reject <skill-name> <您的驳回理由>");
|
|
444
|
+
const stagingDir = path.join(skillsRoot, ".staging", target);
|
|
445
|
+
fs.rmSync(stagingDir, { recursive: true, force: true });
|
|
446
|
+
return ok(`🚫 已按您的批示驳回并销毁草稿 "${target}"(批示:${comment})。`);
|
|
447
|
+
}
|
|
448
|
+
case "ledger": {
|
|
449
|
+
const entries = await readEntries(skillsRoot, { limit: 20 });
|
|
450
|
+
if (!entries.length) return ok("账本为空。");
|
|
451
|
+
return ok(
|
|
452
|
+
"最近账本记录:\n" +
|
|
453
|
+
entries.map((e) => `- ${e.ts} ${e.action} ${e.target} (${e.actor}) id=${e.id}`).join("\n"),
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
case "skills": {
|
|
457
|
+
const skills = await listSkills(skillsRoot);
|
|
458
|
+
if (!skills.length) return ok(`技能根目录为空:${skillsRoot}`);
|
|
459
|
+
return ok(
|
|
460
|
+
`技能(${skills.length}):\n` +
|
|
461
|
+
skills.map((s) => `- ${s.name}${s.createdBy === "agent" ? " [agent]" : ""} — ${s.description}`).join("\n"),
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
case "promote": {
|
|
465
|
+
const target = parts[1];
|
|
466
|
+
if (!target) return fail("用法:/evolution promote <skill-name>");
|
|
467
|
+
const r = await promoteDraft(skillsRoot, target);
|
|
468
|
+
return r.ok ? ok(`已提升草稿 "${target}" 到正式技能目录。`) : fail(`提升失败:${r.error}`);
|
|
469
|
+
}
|
|
470
|
+
case "adopt": {
|
|
471
|
+
const target = parts[1];
|
|
472
|
+
if (!target) return fail("用法:/evolution adopt <skill-name>");
|
|
473
|
+
const r = await adoptSkill(skillsRoot, target);
|
|
474
|
+
return r.ok ? ok(`已接管技能 "${target}"。`) : fail(`接管失败:${r.error}`);
|
|
475
|
+
}
|
|
476
|
+
case "disown": {
|
|
477
|
+
const target = parts[1];
|
|
478
|
+
if (!target) return fail("用法:/evolution disown <skill-name>");
|
|
479
|
+
const r = await disownSkill(skillsRoot, target);
|
|
480
|
+
return r.ok ? ok(`已取消接管技能 "${target}"。`) : fail(`操作失败:${r.error}`);
|
|
481
|
+
}
|
|
482
|
+
case "rollback": {
|
|
483
|
+
const id = parts[1];
|
|
484
|
+
if (!id) return fail("用法:/evolution rollback <ledger-entry-id>");
|
|
485
|
+
const r = await rollbackEntry(skillsRoot, id);
|
|
486
|
+
return r.ok ? ok(`已回滚 ${r.restored} 个文件。`) : fail(`回滚失败:${r.error}`);
|
|
487
|
+
}
|
|
488
|
+
case "review": {
|
|
489
|
+
const r = await triggerReview(invocation?.agent ?? null);
|
|
490
|
+
return r.ok ? ok(r.message) : fail(r.error);
|
|
491
|
+
}
|
|
492
|
+
case "consolidate": {
|
|
493
|
+
const applyFlag = parts.includes("--apply");
|
|
494
|
+
const r = await triggerConsolidation({ dryRun: !applyFlag });
|
|
495
|
+
if (!r.ok) return fail(`合并失败:${(r.errors || [r.error]).join("; ")}`);
|
|
496
|
+
if (r.skipped) return ok(`合并跳过:${r.reason}`);
|
|
497
|
+
if (r.dryRun) return ok(`合并预览(dry-run):\n${(r.planned || []).map((x) => `- ${x}`).join("\n")}\n\n摘要:${r.summary}`);
|
|
498
|
+
return ok(`合并已执行:\n${(r.done || []).map((x) => `- ${x}`).join("\n")}\n\n摘要:${r.summary}`);
|
|
499
|
+
}
|
|
500
|
+
case "status":
|
|
501
|
+
default: {
|
|
502
|
+
const drafts = await listDrafts(skillsRoot);
|
|
503
|
+
const entries = await readEntries(skillsRoot);
|
|
504
|
+
const skills = await listSkills(skillsRoot);
|
|
505
|
+
return ok(
|
|
506
|
+
[
|
|
507
|
+
"DSH 自进化状态",
|
|
508
|
+
`- 技能根目录:${skillsRoot}`,
|
|
509
|
+
`- 模式:${config.mode}${config.mode === "draft" ? "(只产草稿,需人工审阅)" : "(自动落盘)"}`,
|
|
510
|
+
`- 技能数:${skills.length}(其中 agent 创建:${skills.filter((s) => s.createdBy === "agent").length})`,
|
|
511
|
+
`- 待审阅草稿:${drafts.length}`,
|
|
512
|
+
`- 账本记录:${entries.length}`,
|
|
513
|
+
`- 节流:每 ${config.minTurnsBetween} 回合 / ${config.minMinutesBetween} 分钟最多一次`,
|
|
514
|
+
].join("\n"),
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
} catch (error) {
|
|
519
|
+
return fail(`自进化命令失败:${error?.message ?? error}`);
|
|
520
|
+
}
|
|
521
|
+
},
|
|
522
|
+
});
|
|
523
|
+
|
|
524
|
+
// ---- 4b. 注册面向 DSH Go / 移动端的原生交互式工具:evolution_review_center ----
|
|
525
|
+
const offTool = ctx.tools?.register?.({
|
|
526
|
+
name: "evolution_review_center",
|
|
527
|
+
description:
|
|
528
|
+
"DSH 自进化移动端/DSH Go 审阅与批示中心。当用户在 DSH Go 手机端或聊天中询问“看看自进化待审稿”、“审阅自进化草稿”、“通过/驳回某个自进化技能”时调用。支持输出中文简报、弹出 DSH Go 原生交互式批示卡片(ask_user_question),并根据用户的批示由 AI 二次修订后升入正式技能库。",
|
|
529
|
+
parameters: {
|
|
530
|
+
type: "object",
|
|
531
|
+
additionalProperties: false,
|
|
532
|
+
properties: {
|
|
533
|
+
action: {
|
|
534
|
+
type: "string",
|
|
535
|
+
enum: ["brief", "interactive_review", "refine", "approve", "reject"],
|
|
536
|
+
description:
|
|
537
|
+
"brief=仅查看中文简报;interactive_review=弹出 DSH Go 原生问答卡片让用户点选或输入批示并自动执行(默认);refine=按批示修订草稿;approve=按批示进化并采纳;reject=按批示驳回",
|
|
538
|
+
},
|
|
539
|
+
target: {
|
|
540
|
+
type: "string",
|
|
541
|
+
description: "目标草稿技能名(kebab-case);留空则默认取第一个待审草稿或列出全部",
|
|
542
|
+
},
|
|
543
|
+
comment: {
|
|
544
|
+
type: "string",
|
|
545
|
+
description: "用户的审阅批示/想法(在 refine/approve/reject 时必填)",
|
|
546
|
+
},
|
|
547
|
+
},
|
|
548
|
+
},
|
|
549
|
+
output: {
|
|
550
|
+
schema: { type: "string" },
|
|
551
|
+
render: (_args, value) => [{ type: "text", text: String(value ?? "") }],
|
|
552
|
+
},
|
|
553
|
+
presentCall(args) {
|
|
554
|
+
return {
|
|
555
|
+
card: "generic",
|
|
556
|
+
title: `🧬 自进化审阅中心 · ${args?.target || "待审草稿"}`,
|
|
557
|
+
kind: "other",
|
|
558
|
+
};
|
|
559
|
+
},
|
|
560
|
+
presentResult(_args, result) {
|
|
561
|
+
return {
|
|
562
|
+
card: "generic",
|
|
563
|
+
title: "🧬 自进化审阅与批示结果",
|
|
564
|
+
content: result.content,
|
|
565
|
+
};
|
|
566
|
+
},
|
|
567
|
+
async execute(args, toolCtx) {
|
|
568
|
+
const action = args?.action || "interactive_review";
|
|
569
|
+
const snap = await buildHttpSnapshot(skillsRoot, config);
|
|
570
|
+
const drafts = snap.drafts || [];
|
|
571
|
+
if (!drafts.length) {
|
|
572
|
+
return "当前没有待审阅的自进化技能草稿(正式技能库已有 " + (snap.stats?.skills || 0) + " 个技能)。";
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
const targetDraft = args?.target ? drafts.find((d) => d.name === args.target) : drafts[0];
|
|
576
|
+
if (args?.target && !targetDraft) {
|
|
577
|
+
return `未找到名为 "${args.target}" 的待审草稿。当前待审草稿有:${drafts.map((d) => d.name).join(", ")}`;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
const formatBriefMarkdown = (d, idx = 0) => {
|
|
581
|
+
const b = d.briefing || {};
|
|
582
|
+
const rules = Array.isArray(b.keyRules) ? b.keyRules.map((r) => ` - ${r}`).join("\n") : "";
|
|
583
|
+
return [
|
|
584
|
+
`### 📋 待审草稿 #${idx + 1}:\`${d.name}\` — ${b.titleZh || d.name}`,
|
|
585
|
+
`- **类型**:${d.isPatch ? "现有技能升级补丁" : "新蒸馏类级技能"}`,
|
|
586
|
+
`- **💡 这是什么**:${b.whatItIs || d.description || "(无描述)"}`,
|
|
587
|
+
rules ? `- **📌 提炼出的核心铁律**:\n${rules}` : null,
|
|
588
|
+
`- **✅ 如果同意采纳**:${b.ifApprove || "升入正式技能库并立即生效"}`,
|
|
589
|
+
`- **🚫 如果不同意驳回**:${b.ifReject || "销毁草稿并记录驳回原因"}`,
|
|
590
|
+
b.aiAnalysis ? `- **🤖 AI 上次批示融合汇报**:${b.aiAnalysis}` : null,
|
|
591
|
+
]
|
|
592
|
+
.filter(Boolean)
|
|
593
|
+
.join("\n");
|
|
594
|
+
};
|
|
595
|
+
|
|
596
|
+
if (action === "brief") {
|
|
597
|
+
return drafts.map((d, i) => formatBriefMarkdown(d, i)).join("\n\n---\n\n");
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
let comment = String(args?.comment ?? "").trim();
|
|
601
|
+
let chosenAction = action;
|
|
602
|
+
|
|
603
|
+
// DSH Go 原生交互卡片模式:通过 ctx.userQuestions.ask 在手机端弹出可点选/可输入自定义批示的原生卡片
|
|
604
|
+
if (action === "interactive_review") {
|
|
605
|
+
const userQuestions = ctx.get?.("userQuestions");
|
|
606
|
+
const b = targetDraft.briefing || {};
|
|
607
|
+
if (userQuestions?.ask && toolCtx?.agent) {
|
|
608
|
+
const ans = await userQuestions.ask({
|
|
609
|
+
agent: toolCtx.agent,
|
|
610
|
+
questions: [
|
|
611
|
+
{
|
|
612
|
+
id: "directive",
|
|
613
|
+
header: `审阅 ${targetDraft.name}`,
|
|
614
|
+
question:
|
|
615
|
+
`【${b.titleZh || targetDraft.name}】\n` +
|
|
616
|
+
`💡 作用:${b.whatItIs || targetDraft.description}\n` +
|
|
617
|
+
`✅ 同意后果:${b.ifApprove}\n` +
|
|
618
|
+
`🚫 驳回后果:${b.ifReject}\n\n` +
|
|
619
|
+
`请选择预设批示,或在下方输入框直接填写您的自定义批示想法:`,
|
|
620
|
+
options: [
|
|
621
|
+
{
|
|
622
|
+
label: "同意:转全中文规范后入库 (Recommended)",
|
|
623
|
+
description: "让 AI 将技能正文整理为清晰易读的中文规范,融合后升入正式技能库",
|
|
624
|
+
},
|
|
625
|
+
{
|
|
626
|
+
label: "同意:按当前提炼规则直接入库",
|
|
627
|
+
description: "认可当前提炼的步骤与防坑规则,直接升入正式技能库",
|
|
628
|
+
},
|
|
629
|
+
{
|
|
630
|
+
label: "仅修订草稿:先加上备份与安全检查要求",
|
|
631
|
+
description: "让 AI 先按批示改写草稿并汇报分析,暂不入库",
|
|
632
|
+
},
|
|
633
|
+
{
|
|
634
|
+
label: "不同意驳回:属于一次性偶发问题",
|
|
635
|
+
description: "销毁该草稿并将驳回原因记入账本",
|
|
636
|
+
},
|
|
637
|
+
],
|
|
638
|
+
},
|
|
639
|
+
],
|
|
640
|
+
});
|
|
641
|
+
const item = ans?.answers?.find?.((a) => a.id === "directive") ?? ans?.answers?.[0];
|
|
642
|
+
const customText = String(item?.custom ?? "").trim();
|
|
643
|
+
const selectedText = Array.isArray(item?.selected) ? item.selected[0] || "" : "";
|
|
644
|
+
comment = customText || selectedText;
|
|
645
|
+
if (!comment) {
|
|
646
|
+
return formatBriefMarkdown(targetDraft, 0) + "\n\n(您跳过了本次批示卡片,草稿保持待审状态。)";
|
|
647
|
+
}
|
|
648
|
+
if (comment.startsWith("不同意") || comment.startsWith("驳回")) {
|
|
649
|
+
chosenAction = "reject";
|
|
650
|
+
} else if (comment.startsWith("仅修订")) {
|
|
651
|
+
chosenAction = "refine";
|
|
652
|
+
} else {
|
|
653
|
+
chosenAction = "approve";
|
|
654
|
+
}
|
|
655
|
+
} else {
|
|
656
|
+
return (
|
|
657
|
+
formatBriefMarkdown(targetDraft, 0) +
|
|
658
|
+
`\n\n请直接回复您的批示(例如:“同意 ${targetDraft.name},请转成中文后入库” 或 “驳回 ${targetDraft.name},理由是…”)。`
|
|
659
|
+
);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
if (!comment) {
|
|
664
|
+
return `请提供您的强制批示(comment)后再执行 ${chosenAction}。`;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
if (chosenAction === "refine") {
|
|
668
|
+
const r = await refineDraftWithComment(skillsRoot, targetDraft.name, comment, runPromptFork);
|
|
669
|
+
if (!r.ok) return `批示修订失败:${r.error}`;
|
|
670
|
+
return `🤖 **AI 已根据您的批示修订草稿 \`${targetDraft.name}\`**\n\n- **您的批示**:${comment}\n- **AI 进化分析**:${r.aiAnalysis}`;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
if (chosenAction === "reject") {
|
|
674
|
+
const stagingDir = path.join(skillsRoot, ".staging", targetDraft.name);
|
|
675
|
+
fs.rmSync(stagingDir, { recursive: true, force: true });
|
|
676
|
+
return `🚫 **已按您的批示驳回并销毁草稿 \`${targetDraft.name}\`**\n- **驳回批示**:${comment}`;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
// approve
|
|
680
|
+
const refined = await refineDraftWithComment(skillsRoot, targetDraft.name, comment, runPromptFork);
|
|
681
|
+
const r = await promoteDraft(skillsRoot, targetDraft.name, {
|
|
682
|
+
actor: "user",
|
|
683
|
+
comment,
|
|
684
|
+
aiAnalysis: refined.ok ? refined.aiAnalysis : "",
|
|
685
|
+
refinedContent: refined.ok ? refined.refinedContent : null,
|
|
686
|
+
});
|
|
687
|
+
if (!r.ok) return `采纳失败:${r.error}`;
|
|
688
|
+
return (
|
|
689
|
+
`✅ **已按您的批示完成自进化并升入正式技能库:\`${targetDraft.name}\`**\n\n` +
|
|
690
|
+
`- **您的批示**:${comment}\n` +
|
|
691
|
+
(refined.ok ? `- **🤖 AI 批示融合分析**:${refined.aiAnalysis}\n` : "") +
|
|
692
|
+
`- **账本记录 ID**:\`${r.entryId}\``
|
|
693
|
+
);
|
|
694
|
+
},
|
|
695
|
+
});
|
|
696
|
+
|
|
697
|
+
// ---- 5. HTTP API(供 UI 读取真实数据)----
|
|
698
|
+
const saveConfig = (patch) => {
|
|
699
|
+
if (!patch || typeof patch !== "object") return;
|
|
700
|
+
for (const key of [
|
|
701
|
+
"enabled",
|
|
702
|
+
"mode",
|
|
703
|
+
"minTurnsBetween",
|
|
704
|
+
"minMinutesBetween",
|
|
705
|
+
"maxMessages",
|
|
706
|
+
"maxChars",
|
|
707
|
+
"reviewTimeoutSeconds",
|
|
708
|
+
"curatorEnabled",
|
|
709
|
+
"consolidate",
|
|
710
|
+
"consolidateDryRun",
|
|
711
|
+
"staleAfterDays",
|
|
712
|
+
"archiveAfterDays",
|
|
713
|
+
]) {
|
|
714
|
+
if (patch[key] !== undefined) config[key] = patch[key];
|
|
715
|
+
}
|
|
716
|
+
if (patch.reviewModel && typeof patch.reviewModel === "object") {
|
|
717
|
+
config.reviewModel = { ...config.reviewModel, ...patch.reviewModel };
|
|
718
|
+
}
|
|
719
|
+
throttle.updateLimits?.({
|
|
720
|
+
minTurnsBetween: config.minTurnsBetween,
|
|
721
|
+
minMinutesBetween: config.minMinutesBetween,
|
|
722
|
+
});
|
|
723
|
+
try {
|
|
724
|
+
const stateDir = path.join(process.env.DSH_HOME || path.join(os.homedir(), ".dsh"), "state");
|
|
725
|
+
fs.mkdirSync(stateDir, { recursive: true });
|
|
726
|
+
fs.writeFileSync(
|
|
727
|
+
path.join(stateDir, "dsh-evolution-settings.json"),
|
|
728
|
+
JSON.stringify(config, null, 2),
|
|
729
|
+
"utf8",
|
|
730
|
+
);
|
|
731
|
+
} catch (error) {
|
|
732
|
+
ctx.logger?.warn?.(`[dsh-evolution] failed to persist settings: ${error?.message ?? error}`);
|
|
733
|
+
}
|
|
734
|
+
};
|
|
735
|
+
|
|
736
|
+
const runPromptFork = async (prompt) => {
|
|
737
|
+
const agents = ctx.agents?.list?.() ?? [];
|
|
738
|
+
const host = agents.find((a) => a?.session?.id) ?? null;
|
|
739
|
+
const r = await runReview(ctx, {
|
|
740
|
+
parent: host ?? null,
|
|
741
|
+
transcript: "",
|
|
742
|
+
promptOverride: prompt,
|
|
743
|
+
timeoutMs: config.reviewTimeoutSeconds * 1000,
|
|
744
|
+
});
|
|
745
|
+
return r.raw ?? "";
|
|
746
|
+
};
|
|
747
|
+
|
|
748
|
+
registerEvolutionHttp(ctx, {
|
|
749
|
+
config,
|
|
750
|
+
skillsRoot,
|
|
751
|
+
saveConfig,
|
|
752
|
+
triggerReview: () => triggerReview(null),
|
|
753
|
+
runConsolidation: triggerConsolidation,
|
|
754
|
+
runFork: runPromptFork,
|
|
755
|
+
});
|
|
756
|
+
|
|
757
|
+
// 清理
|
|
758
|
+
return () => {
|
|
759
|
+
offEvent?.();
|
|
760
|
+
offFlush?.();
|
|
761
|
+
offDisposed?.();
|
|
762
|
+
offTool?.();
|
|
763
|
+
if (curatorTimer) clearTimeout(curatorTimer);
|
|
764
|
+
for (const c of inflight.values()) c.abort();
|
|
765
|
+
inflight.clear();
|
|
766
|
+
inflightPromises.clear();
|
|
767
|
+
buffers.clear();
|
|
768
|
+
};
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/**
|
|
772
|
+
* 回合结束处理:判定 → 节流 → 复盘 → 蒸馏 → 落盘。
|
|
773
|
+
* 全程异步,绝不阻塞主对话;在 session/flush 时由 flush 屏障等待落盘完成。
|
|
774
|
+
*/
|
|
775
|
+
async function handleTurnEnd(session, events, ctx, { config, skillsRoot, throttle, inflight, bypassThrottle = false }) {
|
|
776
|
+
try {
|
|
777
|
+
const snapshot = buildSnapshot(collectTurnEvents(events, session), {
|
|
778
|
+
maxMessages: config.maxMessages,
|
|
779
|
+
maxChars: config.maxChars,
|
|
780
|
+
});
|
|
781
|
+
|
|
782
|
+
const allowed = bypassThrottle ? true : throttle.tick({ worth: snapshot.worth });
|
|
783
|
+
if (!snapshot.worth) {
|
|
784
|
+
writeLastReviewState(skillsRoot, {
|
|
785
|
+
status: "skipped",
|
|
786
|
+
sessionId: session.id,
|
|
787
|
+
reason: snapshot.reason,
|
|
788
|
+
chars: snapshot.stats?.chars ?? 0,
|
|
789
|
+
});
|
|
790
|
+
return { ok: true, action: "skipped", reason: snapshot.reason };
|
|
791
|
+
}
|
|
792
|
+
if (!allowed) {
|
|
793
|
+
writeLastReviewState(skillsRoot, {
|
|
794
|
+
status: "throttled",
|
|
795
|
+
sessionId: session.id,
|
|
796
|
+
reason: "throttled by turn/time window",
|
|
797
|
+
signals: snapshot.signals,
|
|
798
|
+
});
|
|
799
|
+
return { ok: true, action: "throttled", reason: "throttled by turn/time window" };
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
writeLastReviewState(skillsRoot, { status: "running", sessionId: session.id, signals: snapshot.signals, chars: snapshot.stats.chars });
|
|
803
|
+
// 新回合到来时放弃上一次未完成的复盘
|
|
804
|
+
inflight.get(session.id)?.abort();
|
|
805
|
+
const controller = new AbortController();
|
|
806
|
+
inflight.set(session.id, controller);
|
|
807
|
+
|
|
808
|
+
const skills = await listSkills(skillsRoot);
|
|
809
|
+
const skillCatalog = skills.map((s) => `- ${s.name}: ${s.description}`);
|
|
810
|
+
|
|
811
|
+
const reviewModel = config.reviewModel?.model
|
|
812
|
+
? {
|
|
813
|
+
provider: config.reviewModel.provider,
|
|
814
|
+
model: config.reviewModel.model,
|
|
815
|
+
reasoningEffort: config.reviewModel.reasoningEffort || undefined,
|
|
816
|
+
}
|
|
817
|
+
: null;
|
|
818
|
+
|
|
819
|
+
const parentAgent = ctx.agents?.get?.(session.id) ?? null;
|
|
820
|
+
|
|
821
|
+
const result = await runReview(ctx, {
|
|
822
|
+
parent: parentAgent,
|
|
823
|
+
transcript: snapshot.transcript,
|
|
824
|
+
signals: snapshot.signals,
|
|
825
|
+
skillCatalog,
|
|
826
|
+
model: reviewModel,
|
|
827
|
+
timeoutMs: config.reviewTimeoutSeconds * 1000,
|
|
828
|
+
signal: controller.signal,
|
|
829
|
+
});
|
|
830
|
+
|
|
831
|
+
if (controller.signal.aborted) {
|
|
832
|
+
return { ok: false, action: "aborted", reason: "aborted by newer turn" };
|
|
833
|
+
}
|
|
834
|
+
if (!result.ok) {
|
|
835
|
+
writeLastReviewState(skillsRoot, { status: "error", sessionId: session.id, error: result.error ?? "no JSON in output", rawPreview: (result.raw || "").slice(0, 400) });
|
|
836
|
+
ctx.logger?.warn?.(`[dsh-evolution] review failed: ${result.error ?? "no JSON in output"}`);
|
|
837
|
+
return { ok: false, action: "error", reason: result.error ?? "no JSON in output" };
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
const existingNames = new Set(skills.map((s) => s.name));
|
|
841
|
+
const target = String(result.review?.target ?? "").trim();
|
|
842
|
+
const synthesized = synthesize(result.review, {
|
|
843
|
+
existingSkill: target ? existingNames.has(target) : undefined,
|
|
844
|
+
});
|
|
845
|
+
|
|
846
|
+
if (!synthesized.ok) {
|
|
847
|
+
writeLastReviewState(skillsRoot, { status: "rejected", sessionId: session.id, errors: synthesized.errors, review: result.review });
|
|
848
|
+
ctx.logger?.warn?.(`[dsh-evolution] gate rejected: ${synthesized.errors.join("; ")}`);
|
|
849
|
+
return { ok: false, action: "rejected", reason: synthesized.errors.join("; ") };
|
|
850
|
+
}
|
|
851
|
+
if (synthesized.action === "nothing") {
|
|
852
|
+
writeLastReviewState(skillsRoot, { status: "nothing", sessionId: session.id, rationale: synthesized.meta?.rationale || "nothing to save" });
|
|
853
|
+
ctx.logger?.info?.("[dsh-evolution] review found nothing to save");
|
|
854
|
+
return { ok: true, action: "nothing", reason: synthesized.meta?.rationale || "nothing to save" };
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
const applied = await applySynthesis(skillsRoot, synthesized, {
|
|
858
|
+
mode: config.mode,
|
|
859
|
+
actor: "curator",
|
|
860
|
+
extra: { signals: snapshot.signals, sessionId: session.id },
|
|
861
|
+
});
|
|
862
|
+
|
|
863
|
+
if (applied.ok) {
|
|
864
|
+
writeLastReviewState(skillsRoot, { status: "saved", sessionId: session.id, mode: applied.mode, action: synthesized.action, target: synthesized.meta.target, written: applied.written, entryId: applied.entryId, rationale: synthesized.meta.rationale });
|
|
865
|
+
ctx.logger?.info?.(
|
|
866
|
+
`[dsh-evolution] ${applied.mode} ${synthesized.action} "${synthesized.meta.target}" → ${applied.written.join(", ")}`,
|
|
867
|
+
);
|
|
868
|
+
return {
|
|
869
|
+
ok: true,
|
|
870
|
+
action: `${applied.mode}_${synthesized.action}`,
|
|
871
|
+
target: synthesized.meta.target,
|
|
872
|
+
written: applied.written,
|
|
873
|
+
entryId: applied.entryId,
|
|
874
|
+
};
|
|
875
|
+
}
|
|
876
|
+
ctx.logger?.warn?.(`[dsh-evolution] apply failed: ${applied.errors.join("; ")}`);
|
|
877
|
+
return { ok: false, action: "apply_failed", reason: applied.errors.join("; ") };
|
|
878
|
+
} catch (error) {
|
|
879
|
+
ctx.logger?.warn?.(`[dsh-evolution] turn-end handling failed: ${error?.message ?? error}`);
|
|
880
|
+
return { ok: false, action: "exception", reason: String(error?.message ?? error) };
|
|
881
|
+
} finally {
|
|
882
|
+
inflight.delete(session.id);
|
|
883
|
+
}
|
|
884
|
+
}
|