skill-evolution 0.0.0-stage → 0.1.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.
@@ -0,0 +1,226 @@
1
+ /**
2
+ * 复盘器(Reflector)
3
+ *
4
+ * fork 一个只读子代理(或使用辅助 LLM 通道),把回合快照交给它跑审查提示词,拿回结构化结论。
5
+ *
6
+ * 移植自 Hermes `agent/background_review.py` 的 `_spawn_background_review_now`。
7
+ *
8
+ * 关键不变量(每一条都是 Hermes 用血换来的):
9
+ * 1. **绝不碰主对话**:复盘在独立子会话或辅助通道里跑,结论只通过返回值回到插件,
10
+ * 不注入主会话上下文,不改主会话 prompt cache。
11
+ * 2. **工具白名单**:复盘 fork 只能读(skill / glob / grep / read),
12
+ * 不能写、不能跑命令。写入由插件在闸门后自己做。
13
+ * 3. **可取消**:新回合到来时打断上一次复盘,避免堆积。
14
+ * 4. **有超时**:复盘卡住不能拖垮宿主。
15
+ * 5. **有界输入**:快照已经过 collector 的长度裁剪。
16
+ */
17
+
18
+ import { randomUUID } from "node:crypto";
19
+ import { buildReviewPrompt } from "./prompts.js";
20
+ import { extractJsonBlock } from "./synthesizer.js";
21
+ import { setCurrentWriteOrigin, resetCurrentWriteOrigin, BACKGROUND_REVIEW } from "./provenance.js";
22
+
23
+ /** 复盘 fork 允许使用的工具——只读集合。 */
24
+ export const REVIEW_TOOL_ALLOWLIST = ["skill", "glob", "grep", "read", "hindsight_search_knowledge_pages"];
25
+
26
+ /** 追踪当前正在运行的复盘子代理 sessionId,防止子代理自身的 turn/end 递归触发复盘。 */
27
+ export const activeReviewChildIds = new Set();
28
+
29
+ const ROLE_PROMPT = `You are a READ-ONLY self-evolution review fork of a DeepSeek Harness agent.
30
+
31
+ You are NOT talking to the user. Nobody will read your prose. Your only job is to decide whether
32
+ this session produced a durable lesson worth writing into the skill library, and to emit it as
33
+ structured JSON per the output contract at the end of your instructions.
34
+
35
+ Hard constraints:
36
+ - You may READ (skill tool, glob, grep, read). You may NOT write files, run commands, or spawn agents.
37
+ - Do not narrate what happened in the session. Distill it into rules.
38
+ - If no signal fired, emit action "nothing". Do not manufacture a lesson.
39
+ - Reply with the JSON block and nothing else.`;
40
+
41
+ /**
42
+ * 解析 OpenAI-compatible 辅助端点(用于轻量后台复盘与无父 Agent 兜底)。
43
+ *
44
+ * 刻意不内置任何网关地址与凭据:全部来自显式环境变量,避免把某台机器的本机网关写进发行版。
45
+ * - `DSH_EVOLUTION_BASE_URL` 形如 `https://host/v1`(OpenAI-compatible)
46
+ * - `DSH_EVOLUTION_API_KEY` Bearer token
47
+ * - `DSH_EVOLUTION_MODEL` 模型名(可被 `config.reviewModel.model` 覆盖)
48
+ *
49
+ * 未配置端点时 `runReview` 走宿主 subagent fork 通道,而不是静默请求一个不存在的本机端口。
50
+ */
51
+ function resolveAuxiliaryEndpoint(ctx, opts = {}) {
52
+ const baseURL = (process.env.DSH_EVOLUTION_BASE_URL || "").trim();
53
+ const apiKey = (process.env.DSH_EVOLUTION_API_KEY || "").trim();
54
+ const model = opts.model?.model || process.env.DSH_EVOLUTION_MODEL || "";
55
+ return { baseURL, apiKey, model };
56
+ }
57
+
58
+ /** 直接通过辅助 LLM 端点执行只读复盘(对齐 Hermes auxiliary_client,快速且不在退出阶段阻塞会话锁)。 */
59
+ async function runAuxiliaryReview(ctx, opts, promptText, signal) {
60
+ const { baseURL, apiKey, model } = resolveAuxiliaryEndpoint(ctx, opts);
61
+ if (!baseURL) {
62
+ throw new Error(
63
+ "no auxiliary endpoint configured: set DSH_EVOLUTION_BASE_URL (optional DSH_EVOLUTION_API_KEY / DSH_EVOLUTION_MODEL)",
64
+ );
65
+ }
66
+ if (!model) {
67
+ throw new Error("no auxiliary model configured: set DSH_EVOLUTION_MODEL or config.reviewModel.model");
68
+ }
69
+ const res = await fetch(`${baseURL.replace(/\/$/, "")}/chat/completions`, {
70
+ method: "POST",
71
+ headers: {
72
+ "content-type": "application/json",
73
+ authorization: `Bearer ${apiKey}`,
74
+ },
75
+ body: JSON.stringify({
76
+ model,
77
+ messages: [
78
+ { role: "system", content: ROLE_PROMPT },
79
+ { role: "user", content: promptText },
80
+ ],
81
+ max_tokens: 6000,
82
+ temperature: 0.2,
83
+ }),
84
+ signal,
85
+ });
86
+ if (!res.ok) {
87
+ const errText = await res.text().catch(() => "");
88
+ throw new Error(`auxiliary LLM HTTP ${res.status}: ${errText.slice(0, 240)}`);
89
+ }
90
+ const data = await res.json();
91
+ const raw = data?.choices?.[0]?.message?.content ?? "";
92
+ return raw;
93
+ }
94
+
95
+ /**
96
+ * 运行一次复盘。
97
+ *
98
+ * @param {object} ctx Cordis 上下文
99
+ * @param {object} opts
100
+ * @param {object} [opts.parent] 父 agent(用于 startActivation 的 parent)
101
+ * @param {string} opts.transcript 会话快照正文
102
+ * @param {string[]} [opts.signals] 预判信号
103
+ * @param {string[]} [opts.skillCatalog] 当前技能目录(名称+描述),供模型判断该改哪个
104
+ * @param {object} [opts.model] {provider, model, reasoningEffort}
105
+ * @param {number} [opts.timeoutMs=180000]
106
+ * @param {boolean} [opts.preferSubagent=false] 是否强制优先走 subagents.startActivation
107
+ * @param {AbortSignal} [opts.signal]
108
+ * @returns {Promise<{ok: boolean, review: object|null, raw: string, error?: string, childId: string}>}
109
+ */
110
+ export async function runReview(ctx, opts) {
111
+ const childId = randomUUID();
112
+ const timeoutMs = opts.timeoutMs ?? 180_000;
113
+
114
+ const catalogBlock =
115
+ Array.isArray(opts.skillCatalog) && opts.skillCatalog.length > 0
116
+ ? `\n\n## Current skill catalog\n\n${opts.skillCatalog.join("\n")}\n`
117
+ : "\n\n## Current skill catalog\n\n(empty — no skills exist yet)\n";
118
+
119
+ const promptText =
120
+ opts.promptOverride
121
+ ? opts.promptOverride
122
+ : buildReviewPrompt({ includeMemory: false }) +
123
+ catalogBlock +
124
+ `\n\n## Session transcript to review\n\n${opts.transcript}`;
125
+
126
+ const promptBlocks = [
127
+ { type: "text", text: ROLE_PROMPT },
128
+ { type: "text", text: promptText },
129
+ ];
130
+
131
+ const controller = new AbortController();
132
+ const onAbort = () => controller.abort();
133
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
134
+
135
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
136
+
137
+ // 绑定写来源:任何在复盘上下文中发生的写入都会被标记为 background_review
138
+ const prevOrigin = setCurrentWriteOrigin(BACKGROUND_REVIEW);
139
+ activeReviewChildIds.add(childId);
140
+
141
+ try {
142
+ // 1. 若显式要求走 subagent 且上下文具备 subagents + 有效 parent Agent,则通过 startActivation 分叉
143
+ const subagents = ctx?.subagents ?? ctx?.get?.("subagents");
144
+ const providerName = opts.providerName ?? (subagents?.getProvider?.("spawn") ? "spawn" : "fork");
145
+ // 没有配置辅助端点时,默认走宿主 subagent fork —— 发行版不该假设任何人跑着本机网关。
146
+ const canUseSubagent =
147
+ (opts.preferSubagent === true || !resolveAuxiliaryEndpoint(ctx, opts).baseURL) &&
148
+ Boolean(subagents?.startActivation) &&
149
+ Boolean(subagents?.getProvider?.(providerName)) &&
150
+ Boolean(opts.parent?.session);
151
+
152
+ if (canUseSubagent) {
153
+ try {
154
+ const activation = await subagents.startActivation({
155
+ childId,
156
+ provider: providerName,
157
+ label: "dsh-evolution review",
158
+ request: {
159
+ parent: opts.parent,
160
+ prompt: promptBlocks,
161
+ ...(opts.model?.model
162
+ ? {
163
+ agentOptions: {
164
+ provider: opts.model.provider,
165
+ model: opts.model.model,
166
+ ...(opts.model.reasoningEffort ? { reasoningEffort: opts.model.reasoningEffort } : {}),
167
+ },
168
+ }
169
+ : {}),
170
+ },
171
+ signal: controller.signal,
172
+ delivery: "caller",
173
+ });
174
+
175
+ const result = await activation.result;
176
+ const raw = extractAssistantText(result);
177
+ const review = extractJsonBlock(raw);
178
+ if (review) {
179
+ return { ok: true, review, raw, childId };
180
+ }
181
+ } catch (subErr) {
182
+ ctx?.logger?.warn?.(`[dsh-evolution] subagent review fallback to auxiliary LLM: ${subErr?.message ?? subErr}`);
183
+ }
184
+ }
185
+
186
+ // 2. 默认/兜底通道:直接调用辅助 LLM 端点(耗时 ~6s,不创建干扰会话,兼容 headless 退出阶段)
187
+ const raw = await runAuxiliaryReview(ctx, opts, promptText, controller.signal);
188
+ const review = extractJsonBlock(raw);
189
+ return { ok: Boolean(review), review, raw, childId };
190
+ } catch (error) {
191
+ return { ok: false, review: null, raw: "", error: String(error?.message ?? error), childId };
192
+ } finally {
193
+ clearTimeout(timer);
194
+ opts.signal?.removeEventListener?.("abort", onAbort);
195
+ activeReviewChildIds.delete(childId);
196
+ resetCurrentWriteOrigin(prevOrigin);
197
+ try {
198
+ const subagents = ctx?.subagents ?? ctx?.get?.("subagents");
199
+ subagents?.interrupt?.(childId, { kind: "user", parentSessionId: opts.parent?.id });
200
+ } catch {
201
+ /* 已结束,忽略 */
202
+ }
203
+ }
204
+ }
205
+
206
+ /** 从 activation 结果里抽助手最后一条文本。 */
207
+ function extractAssistantText(result) {
208
+ if (!result) return "";
209
+ if (typeof result === "string") return result;
210
+ const out = result.output ?? result.result ?? result;
211
+ if (typeof out === "string") return out;
212
+ if (Array.isArray(out)) {
213
+ const texts = out
214
+ .map((b) => (typeof b === "string" ? b : b?.text ?? ""))
215
+ .filter(Boolean);
216
+ return texts.join("\n");
217
+ }
218
+ if (typeof out?.text === "string") return out.text;
219
+ if (Array.isArray(out?.content)) {
220
+ return out.content
221
+ .map((b) => (typeof b === "string" ? b : b?.text ?? ""))
222
+ .filter(Boolean)
223
+ .join("\n");
224
+ }
225
+ return "";
226
+ }
@@ -0,0 +1,295 @@
1
+ /**
2
+ * 蒸馏器(Synthesizer)
3
+ *
4
+ * 把复盘 fork 输出的结构化 JSON 转成可落盘的技能产物。
5
+ *
6
+ * 职责边界(刻意保持窄):
7
+ * - 只做"JSON → 文件内容"的转换与结构校验
8
+ * - 不做安全检查(那是 gatekeeper 的事)
9
+ * - 不做落盘(那是应用层/审批层的事)
10
+ *
11
+ * 这样 Synthesizer 是纯函数,可以单独测试,也不会绕过闸门。
12
+ */
13
+
14
+ import { gate, renderSkillMarkdown, parseSkillMarkdown, MAX_SKILL_BODY_CHARS } from "./gatekeeper.js";
15
+
16
+ /**
17
+ * 转义字符串字面量里未转义的控制字符(真实换行/制表符会让 JSON.parse 直接失败)。
18
+ * 模型产出长中文 body 时经常漏转义 `\n`,这是 `no JSON in output` 的另一大来源。
19
+ */
20
+ function escapeControlCharsInStrings(src) {
21
+ let out = "";
22
+ let inStr = false;
23
+ let esc = false;
24
+ for (let i = 0; i < src.length; i += 1) {
25
+ const c = src[i];
26
+ if (!inStr) {
27
+ if (c === '"') inStr = true;
28
+ out += c;
29
+ continue;
30
+ }
31
+ if (esc) {
32
+ out += c;
33
+ esc = false;
34
+ continue;
35
+ }
36
+ if (c === "\\") {
37
+ out += c;
38
+ esc = true;
39
+ continue;
40
+ }
41
+ if (c === '"') {
42
+ out += c;
43
+ inStr = false;
44
+ continue;
45
+ }
46
+ const code = c.charCodeAt(0);
47
+ if (code < 0x20) {
48
+ if (c === "\n") out += "\\n";
49
+ else if (c === "\r") out += "\\r";
50
+ else if (c === "\t") out += "\\t";
51
+ else out += `\\u${code.toString(16).padStart(4, "0")}`;
52
+ continue;
53
+ }
54
+ out += c;
55
+ }
56
+ return out;
57
+ }
58
+
59
+ /**
60
+ * 把一段可能被截断的 JSON 补齐到可解析状态。
61
+ *
62
+ * 复盘模型产出长中文 Markdown 时很容易撞上输出 token 上限,导致围栏闭合符、
63
+ * 结尾的 `"` 与 `}` 全部缺失。此时直接 JSON.parse 必然失败,整轮复盘成果被丢弃
64
+ * (线上表现就是 `status: error / no JSON in output`)。这里按字符状态机补全。
65
+ */
66
+ function closeJsonString(src) {
67
+ let s = String(src);
68
+ if (!s.startsWith("{")) {
69
+ const i = s.indexOf("{");
70
+ if (i < 0) return null;
71
+ s = s.slice(i);
72
+ }
73
+
74
+ // 扫一遍,记录最后一个“安全截断点”(闭合字符串之后 / 闭合容器之后 / 逗号处)
75
+ const safePoints = [];
76
+ let inStr = false;
77
+ let esc = false;
78
+ for (let i = 0; i < s.length; i += 1) {
79
+ const c = s[i];
80
+ if (inStr) {
81
+ if (esc) esc = false;
82
+ else if (c === "\\") esc = true;
83
+ else if (c === '"') {
84
+ inStr = false;
85
+ safePoints.push(i + 1);
86
+ }
87
+ } else if (c === '"') inStr = true;
88
+ else if (c === "}" || c === "]") safePoints.push(i + 1);
89
+ else if (c === ",") safePoints.push(i);
90
+ }
91
+
92
+ const tryClose = (head) => {
93
+ let body = head.replace(/[,\s]+$/, "");
94
+ // 去掉尾部悬空的 `"key":` 或 `"key": ` 片段
95
+ body = body.replace(/,\s*"[^"\\]*"\s*:\s*$/, "").replace(/,\s*$/, "");
96
+
97
+ let openString = false;
98
+ let backslash = false;
99
+ const stack = [];
100
+ for (let i = 0; i < body.length; i += 1) {
101
+ const c = body[i];
102
+ if (openString) {
103
+ if (backslash) backslash = false;
104
+ else if (c === "\\") backslash = true;
105
+ else if (c === '"') openString = false;
106
+ } else if (c === '"') openString = true;
107
+ else if (c === "{" || c === "[") stack.push(c === "{" ? "}" : "]");
108
+ else if (c === "}" || c === "]") {
109
+ const want = stack.pop();
110
+ if (!want || want !== c) return null;
111
+ }
112
+ }
113
+ let out = body;
114
+ if (openString) out += '"';
115
+ while (stack.length) out += stack.pop();
116
+ return escapeControlCharsInStrings(out);
117
+ };
118
+
119
+ // 优先补全整段(保留 body 等长字段的已产出部分),补不齐再逐级回退截断
120
+ const attempts = [tryClose(s)];
121
+ for (let k = safePoints.length - 1; k >= 0 && k >= safePoints.length - 60; k -= 1) {
122
+ attempts.push(tryClose(s.slice(0, safePoints[k])));
123
+ }
124
+ return attempts;
125
+ }
126
+
127
+ /** 从模型输出里抽出那个 fenced JSON 块(容忍围栏缺失与输出截断)。 */
128
+ export function extractJsonBlock(text) {
129
+ if (typeof text !== "string") return null;
130
+
131
+ const candidates = [];
132
+ // 1. 已闭合的围栏
133
+ const closed = /```(?:json)?\s*\n([\s\S]*?)```/i.exec(text);
134
+ if (closed) candidates.push(closed[1]);
135
+ // 2. 未闭合的围栏(输出被截断)
136
+ const open = /```(?:json)?\s*\n([\s\S]*)$/i.exec(text);
137
+ if (open) candidates.push(open[1]);
138
+ // 3. 首尾大括号
139
+ const firstBrace = text.indexOf("{");
140
+ const lastBrace = text.lastIndexOf("}");
141
+ if (firstBrace >= 0) {
142
+ if (lastBrace > firstBrace) candidates.push(text.slice(firstBrace, lastBrace + 1));
143
+ candidates.push(text.slice(firstBrace));
144
+ }
145
+
146
+ const accept = (raw) => {
147
+ try {
148
+ const parsed = JSON.parse(String(raw).trim());
149
+ if (parsed && typeof parsed === "object" && ("action" in parsed || "operations" in parsed)) return parsed;
150
+ } catch {
151
+ /* 试下一个 */
152
+ }
153
+ return null;
154
+ };
155
+
156
+ // 第一轮:原文直接解析
157
+ for (const raw of candidates) {
158
+ const hit = accept(raw);
159
+ if (hit) return hit;
160
+ }
161
+ // 第二轮:截断修复后解析
162
+ for (const raw of candidates) {
163
+ for (const repaired of closeJsonString(raw) ?? []) {
164
+ if (!repaired) continue;
165
+ const hit = accept(repaired);
166
+ if (hit) return hit;
167
+ }
168
+ }
169
+ return null;
170
+ }
171
+
172
+ /** 归一化模型给的 action,容忍常见拼写差异。 */
173
+ function normalizeAction(action) {
174
+ const a = String(action ?? "").trim().toLowerCase();
175
+ if (["create", "patch", "add_reference", "nothing"].includes(a)) return a;
176
+ if (a === "update" || a === "edit") return "patch";
177
+ if (a === "add-reference" || a === "reference") return "add_reference";
178
+ if (a === "none" || a === "noop" || a === "no-op") return "nothing";
179
+ return null;
180
+ }
181
+
182
+ /**
183
+ * 把复盘输出转成候选产物。
184
+ *
185
+ * @param {object|null} review extractJsonBlock 的结果
186
+ * @param {object} [opts]
187
+ * @param {boolean} [opts.existingSkill] 目标技能是否已存在(决定 create/patch 是否合理)
188
+ * @returns {{ok: boolean, action: string, files: {path: string, content: string}[], errors: string[], warnings: string[], meta: object}}
189
+ */
190
+ export function synthesize(review, opts = {}) {
191
+ const empty = { ok: false, action: "nothing", files: [], errors: [], warnings: [], meta: {} };
192
+
193
+ if (!review || typeof review !== "object") {
194
+ return { ...empty, errors: ["no structured JSON block found in review output"] };
195
+ }
196
+
197
+ const action = normalizeAction(review.action);
198
+ if (!action) {
199
+ return { ...empty, errors: [`unknown action "${review.action}"`] };
200
+ }
201
+ if (action === "nothing") {
202
+ return {
203
+ ok: true,
204
+ action: "nothing",
205
+ files: [],
206
+ errors: [],
207
+ warnings: [],
208
+ meta: { rationale: review.rationale ?? "", confidence: review.confidence ?? "high" },
209
+ };
210
+ }
211
+
212
+ const target = String(review.target ?? "").trim();
213
+ const body = typeof review.body === "string" ? review.body : "";
214
+
215
+ // create / patch 需要 frontmatter;add_reference 不需要
216
+ let frontmatter = review.frontmatter;
217
+ if (action !== "add_reference") {
218
+ if (!frontmatter || typeof frontmatter !== "object") {
219
+ frontmatter = { name: target, description: "" };
220
+ }
221
+ // 容忍模型把 frontmatter 塞进 body 里
222
+ if (body.startsWith("---")) {
223
+ const parsed = parseSkillMarkdown(body);
224
+ if (parsed) {
225
+ frontmatter = { ...parsed.frontmatter, ...frontmatter };
226
+ review = { ...review, body: parsed.body };
227
+ }
228
+ }
229
+ }
230
+
231
+ const candidate = {
232
+ action,
233
+ target,
234
+ frontmatter,
235
+ body: review.body ?? "",
236
+ filePath: review.filePath,
237
+ };
238
+
239
+ const verdict = gate(candidate);
240
+ const files = [];
241
+ if (verdict.ok) {
242
+ if (action === "add_reference") {
243
+ files.push({ path: `${target}/${candidate.filePath}`, content: candidate.body.trim() + "\n" });
244
+ } else {
245
+ files.push({
246
+ path: `${target}/SKILL.md`,
247
+ content: renderSkillMarkdown(
248
+ {
249
+ name: frontmatter.name ?? target,
250
+ description: frontmatter.description,
251
+ ...(frontmatter.whenToUse ? { whenToUse: frontmatter.whenToUse } : {}),
252
+ metadata: { createdBy: "agent", ...(frontmatter.metadata ?? {}) },
253
+ },
254
+ candidate.body,
255
+ ),
256
+ });
257
+ }
258
+ }
259
+
260
+ const warnings = [...verdict.warnings];
261
+ if (action === "create" && opts.existingSkill) {
262
+ warnings.push(`action=create but skill "${target}" already exists — it will be treated as a patch`);
263
+ }
264
+ if (action === "patch" && opts.existingSkill === false) {
265
+ warnings.push(`action=patch but skill "${target}" does not exist — it will be treated as a create`);
266
+ }
267
+
268
+ return {
269
+ ok: verdict.ok,
270
+ action,
271
+ files,
272
+ errors: verdict.errors,
273
+ warnings,
274
+ meta: {
275
+ target,
276
+ rationale: review.rationale ?? "",
277
+ briefing: review.briefing && typeof review.briefing === "object" ? review.briefing : null,
278
+ signals: Array.isArray(review.signals) ? review.signals : [],
279
+ confidence: review.confidence ?? "medium",
280
+ },
281
+ };
282
+ }
283
+
284
+ /** 校验一个已存在的 SKILL.md 是否还能被安全 patch(长度不超限)。 */
285
+ export function canPatchExisting(existingText) {
286
+ const parsed = parseSkillMarkdown(existingText);
287
+ if (!parsed) return { ok: false, error: "existing SKILL.md has no parsable frontmatter" };
288
+ if (parsed.body.length > MAX_SKILL_BODY_CHARS) {
289
+ return {
290
+ ok: false,
291
+ error: `existing SKILL.md body is already ${parsed.body.length} chars (limit ${MAX_SKILL_BODY_CHARS}); consolidate before patching`,
292
+ };
293
+ }
294
+ return { ok: true, parsed };
295
+ }