skill-evolution 0.0.0-stage → 0.1.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/CHANGELOG.md +59 -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/lib/applier.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 应用层(Applier)
|
|
3
|
+
*
|
|
4
|
+
* 把 Synthesizer 产出的文件内容安全落盘。
|
|
5
|
+
*
|
|
6
|
+
* 这是整条链路唯一碰磁盘的地方,也是所有护栏的汇合点:
|
|
7
|
+
* - 先过 provenance 归属检查(用户技能不许自动改)
|
|
8
|
+
* - 再捕获 before 快照(回滚依据)
|
|
9
|
+
* - 写入(create 走 staging → 提升;patch 走原地替换)
|
|
10
|
+
* - 最后记账
|
|
11
|
+
*
|
|
12
|
+
* 默认模式是 `draft`:只写 `.staging/`,不碰正式技能目录。
|
|
13
|
+
* 这是专家团终裁明确要求的保守默认值。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from "node:fs/promises";
|
|
17
|
+
import path from "node:path";
|
|
18
|
+
import { captureSnapshot, appendEntry } from "./ledger.js";
|
|
19
|
+
import { parseSkillMarkdown } from "./gatekeeper.js";
|
|
20
|
+
import { getCurrentWriteOrigin, mayAutoModify } from "./provenance.js";
|
|
21
|
+
import { bumpUsage } from "./usage.js";
|
|
22
|
+
|
|
23
|
+
export const STAGING_DIRNAME = ".staging";
|
|
24
|
+
|
|
25
|
+
/** 读一个技能的现有 SKILL.md;不存在返回 null。 */
|
|
26
|
+
export async function readExistingSkill(skillsRoot, name) {
|
|
27
|
+
try {
|
|
28
|
+
return await fs.readFile(path.join(skillsRoot, name, "SKILL.md"), "utf8");
|
|
29
|
+
} catch {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 列出技能根目录下所有技能目录(跳过隐藏目录)。 */
|
|
35
|
+
export async function listSkills(skillsRoot) {
|
|
36
|
+
let entries;
|
|
37
|
+
try {
|
|
38
|
+
entries = await fs.readdir(skillsRoot, { withFileTypes: true });
|
|
39
|
+
} catch {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
const out = [];
|
|
43
|
+
for (const e of entries) {
|
|
44
|
+
if (!e.isDirectory() || e.name.startsWith(".")) continue;
|
|
45
|
+
const text = await readExistingSkill(skillsRoot, e.name);
|
|
46
|
+
if (!text) continue;
|
|
47
|
+
const parsed = parseSkillMarkdown(text);
|
|
48
|
+
out.push({
|
|
49
|
+
name: e.name,
|
|
50
|
+
description: parsed?.frontmatter?.description ?? "",
|
|
51
|
+
createdBy: parsed?.frontmatter?.metadata?.createdBy ?? null,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 落盘一个候选产物。
|
|
59
|
+
*
|
|
60
|
+
* @param {string} skillsRoot
|
|
61
|
+
* @param {object} synthesized synthesize() 的结果
|
|
62
|
+
* @param {object} opts
|
|
63
|
+
* @param {"draft"|"apply"} [opts.mode="draft"]
|
|
64
|
+
* @param {string} [opts.actor="curator"]
|
|
65
|
+
* @param {object} [opts.extra] 写进账本的额外元数据
|
|
66
|
+
* @returns {Promise<{ok: boolean, mode: string, written: string[], errors: string[], entryId?: string}>}
|
|
67
|
+
*/
|
|
68
|
+
export async function applySynthesis(skillsRoot, synthesized, opts = {}) {
|
|
69
|
+
const mode = opts.mode === "apply" ? "apply" : "draft";
|
|
70
|
+
const actor = opts.actor ?? "curator";
|
|
71
|
+
const errors = [];
|
|
72
|
+
const written = [];
|
|
73
|
+
|
|
74
|
+
if (!synthesized?.ok) {
|
|
75
|
+
return { ok: false, mode, written, errors: synthesized?.errors ?? ["synthesis failed"] };
|
|
76
|
+
}
|
|
77
|
+
if (synthesized.action === "nothing") {
|
|
78
|
+
return { ok: true, mode, written, errors: [] };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const target = synthesized.meta?.target;
|
|
82
|
+
if (!target) return { ok: false, mode, written, errors: ["no target skill"] };
|
|
83
|
+
|
|
84
|
+
const existingText = await readExistingSkill(skillsRoot, target);
|
|
85
|
+
const existingParsed = existingText ? parseSkillMarkdown(existingText) : null;
|
|
86
|
+
|
|
87
|
+
// 护栏:自动复盘不得改写用户手写的技能(除非它自己创建的)
|
|
88
|
+
if (existingText) {
|
|
89
|
+
const meta = {
|
|
90
|
+
createdBy: existingParsed?.frontmatter?.metadata?.createdBy ?? null,
|
|
91
|
+
};
|
|
92
|
+
if (!mayAutoModify(meta)) {
|
|
93
|
+
return {
|
|
94
|
+
ok: false,
|
|
95
|
+
mode,
|
|
96
|
+
written,
|
|
97
|
+
errors: [
|
|
98
|
+
`refusing to auto-modify "${target}": it was not created by the evolution loop ` +
|
|
99
|
+
`(no metadata.createdBy: agent). User-authored skills belong to the user.`,
|
|
100
|
+
],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const before = existingText ? await captureSnapshot(skillsRoot, path.join(skillsRoot, target)) : null;
|
|
106
|
+
|
|
107
|
+
const baseDir = mode === "draft" ? path.join(skillsRoot, STAGING_DIRNAME) : skillsRoot;
|
|
108
|
+
|
|
109
|
+
try {
|
|
110
|
+
for (const file of synthesized.files) {
|
|
111
|
+
const dest = path.join(baseDir, file.path);
|
|
112
|
+
await fs.mkdir(path.dirname(dest), { recursive: true });
|
|
113
|
+
await fs.writeFile(dest, file.content, "utf8");
|
|
114
|
+
written.push(path.relative(skillsRoot, dest));
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (synthesized.meta?.briefing) {
|
|
118
|
+
const briefPath = path.join(baseDir, target, ".briefing.json");
|
|
119
|
+
await fs.mkdir(path.dirname(briefPath), { recursive: true });
|
|
120
|
+
await fs.writeFile(briefPath, JSON.stringify(synthesized.meta.briefing, null, 2), "utf8");
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const after = await captureSnapshot(baseDir, path.join(baseDir, target));
|
|
124
|
+
|
|
125
|
+
const entryId = await appendEntry(skillsRoot, {
|
|
126
|
+
action: mode === "draft" ? `draft_${synthesized.action}` : synthesized.action,
|
|
127
|
+
target,
|
|
128
|
+
actor,
|
|
129
|
+
before,
|
|
130
|
+
after,
|
|
131
|
+
extra: {
|
|
132
|
+
origin: getCurrentWriteOrigin(),
|
|
133
|
+
rationale: synthesized.meta?.rationale,
|
|
134
|
+
signals: synthesized.meta?.signals,
|
|
135
|
+
confidence: synthesized.meta?.confidence,
|
|
136
|
+
warnings: synthesized.warnings,
|
|
137
|
+
...(opts.extra ?? {}),
|
|
138
|
+
},
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
// 只有真正落盘到正式目录才计入使用遥测
|
|
142
|
+
if (mode === "apply") {
|
|
143
|
+
await bumpUsage(skillsRoot, target, { createdBy: "agent" });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
return { ok: true, mode, written, errors: [], entryId };
|
|
147
|
+
} catch (error) {
|
|
148
|
+
errors.push(String(error?.message ?? error));
|
|
149
|
+
return { ok: false, mode, written, errors };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* 把一个已审阅的草稿从 .staging/ 提升到正式技能目录。
|
|
155
|
+
*
|
|
156
|
+
* 这是"人工审阅后放行"的入口——也是 Phase 1 的收尾动作。
|
|
157
|
+
*/
|
|
158
|
+
export async function promoteDraft(skillsRoot, name, { actor = "user", comment = "", aiAnalysis = "", refinedContent = null } = {}) {
|
|
159
|
+
const stagingSkill = path.join(skillsRoot, STAGING_DIRNAME, name);
|
|
160
|
+
const finalSkill = path.join(skillsRoot, name);
|
|
161
|
+
|
|
162
|
+
let files;
|
|
163
|
+
try {
|
|
164
|
+
files = await fs.readdir(stagingSkill, { recursive: true, withFileTypes: true });
|
|
165
|
+
} catch (error) {
|
|
166
|
+
return { ok: false, error: `no draft at ${stagingSkill}: ${error?.message ?? error}` };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const before = await captureSnapshot(skillsRoot, finalSkill);
|
|
170
|
+
try {
|
|
171
|
+
await fs.mkdir(finalSkill, { recursive: true });
|
|
172
|
+
for (const f of files) {
|
|
173
|
+
if (!f.isFile()) continue;
|
|
174
|
+
const rel = path.relative(stagingSkill, path.join(f.parentPath ?? f.path, f.name));
|
|
175
|
+
const src = path.join(stagingSkill, rel);
|
|
176
|
+
const dest = path.join(finalSkill, rel);
|
|
177
|
+
await fs.mkdir(path.dirname(dest), { recursive: true });
|
|
178
|
+
await fs.copyFile(src, dest);
|
|
179
|
+
}
|
|
180
|
+
if (typeof refinedContent === "string" && refinedContent.trim()) {
|
|
181
|
+
await fs.writeFile(path.join(finalSkill, "SKILL.md"), refinedContent, "utf8");
|
|
182
|
+
}
|
|
183
|
+
const after = await captureSnapshot(skillsRoot, finalSkill);
|
|
184
|
+
const entryId = await appendEntry(skillsRoot, {
|
|
185
|
+
action: "promote",
|
|
186
|
+
target: name,
|
|
187
|
+
actor,
|
|
188
|
+
before,
|
|
189
|
+
after,
|
|
190
|
+
extra: {
|
|
191
|
+
from: STAGING_DIRNAME,
|
|
192
|
+
...(comment ? { userComment: comment } : {}),
|
|
193
|
+
...(aiAnalysis ? { aiAnalysis } : {}),
|
|
194
|
+
},
|
|
195
|
+
});
|
|
196
|
+
await fs.rm(stagingSkill, { recursive: true, force: true });
|
|
197
|
+
await bumpUsage(skillsRoot, name, { createdBy: "agent" });
|
|
198
|
+
return { ok: true, entryId, aiAnalysis };
|
|
199
|
+
} catch (error) {
|
|
200
|
+
return { ok: false, error: String(error?.message ?? error) };
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** 列出待审阅的草稿。 */
|
|
205
|
+
export async function listDrafts(skillsRoot) {
|
|
206
|
+
const staging = path.join(skillsRoot, STAGING_DIRNAME);
|
|
207
|
+
let entries;
|
|
208
|
+
try {
|
|
209
|
+
entries = await fs.readdir(staging, { withFileTypes: true });
|
|
210
|
+
} catch {
|
|
211
|
+
return [];
|
|
212
|
+
}
|
|
213
|
+
const out = [];
|
|
214
|
+
for (const e of entries) {
|
|
215
|
+
if (!e.isDirectory() || e.name.startsWith(".")) continue;
|
|
216
|
+
const text = await readExistingSkill(staging, e.name);
|
|
217
|
+
const parsed = text ? parseSkillMarkdown(text) : null;
|
|
218
|
+
out.push({ name: e.name, description: parsed?.frontmatter?.description ?? "", path: path.join(staging, e.name) });
|
|
219
|
+
}
|
|
220
|
+
return out;
|
|
221
|
+
}
|
package/lib/collector.js
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 采集器(Collector)
|
|
3
|
+
*
|
|
4
|
+
* 订阅 DSH 会话生命周期事件,在回合结束时提取一份"可复盘快照"。
|
|
5
|
+
*
|
|
6
|
+
* 设计要点(全部来自 Hermes background_review 的实战约束):
|
|
7
|
+
* 1. **节流**:不是每个回合都值得复盘。纯问答轮次(无工具调用、无用户纠正)直接跳过。
|
|
8
|
+
* 2. **有界**:快照必须有长度上限,否则一次长会话的复盘成本会失控。
|
|
9
|
+
* 3. **不阻塞**:采集只做内存操作,绝不在事件回调里做 I/O 或 await 长任务。
|
|
10
|
+
* 4. **可取消**:新回合到来时,未完成的复盘应被放弃(由 reflector 负责)。
|
|
11
|
+
*
|
|
12
|
+
* 触发信号判定(与提示词里的 signals 对应):
|
|
13
|
+
* - 有复杂工具调用 → 可能产生"新技术/新调试路径"
|
|
14
|
+
* - 用户消息含纠正性措辞 → "user-correction"
|
|
15
|
+
* - 本次加载过技能(skill 工具被调用)→ 技能可能被证明是错的
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import fsSync from "node:fs";
|
|
19
|
+
import pathSync from "node:path";
|
|
20
|
+
|
|
21
|
+
/** 用户纠正性措辞(中英双语)。命中任一即视为一等技能信号。 */
|
|
22
|
+
const CORRECTION_PATTERNS = [
|
|
23
|
+
/stop\s+doing/i,
|
|
24
|
+
/too\s+verbose/i,
|
|
25
|
+
/don'?t\s+(format|do|write)\s+like/i,
|
|
26
|
+
/why\s+are\s+you\s+explaining/i,
|
|
27
|
+
/just\s+(give\s+me|the)\s+(the\s+)?answer/i,
|
|
28
|
+
/you\s+always\s+/i,
|
|
29
|
+
/i\s+hate\s+(when|it|that)/i,
|
|
30
|
+
/remember\s+this/i,
|
|
31
|
+
/from\s+now\s+on/i,
|
|
32
|
+
/不要这样/,
|
|
33
|
+
/别这样/,
|
|
34
|
+
/太啰嗦/,
|
|
35
|
+
/太长了/,
|
|
36
|
+
/你总是/,
|
|
37
|
+
/我说过/,
|
|
38
|
+
/记住/,
|
|
39
|
+
/以后都/,
|
|
40
|
+
/改成/,
|
|
41
|
+
/应该是/,
|
|
42
|
+
/不对/,
|
|
43
|
+
/错了/,
|
|
44
|
+
/改错了/,
|
|
45
|
+
/不要解释/,
|
|
46
|
+
/直接给/,
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
/** DSH 注入到 user/message 中的系统上下文块前缀(不应算作用户本人发言)。 */
|
|
50
|
+
const SYSTEM_INJECTION_MARKERS = [
|
|
51
|
+
"Current runtime context. This snapshot supersedes",
|
|
52
|
+
"<system-reminder>",
|
|
53
|
+
"<available_skills>",
|
|
54
|
+
"<hindsight_knowledge>",
|
|
55
|
+
"<hindsight_memory>",
|
|
56
|
+
"Nowledge Mem Context Bundle for this DSH session",
|
|
57
|
+
"Nowledge Mem recall for this DSH turn",
|
|
58
|
+
"Time sampled while preparing turn",
|
|
59
|
+
];
|
|
60
|
+
|
|
61
|
+
export function isSystemInjectedUserText(text) {
|
|
62
|
+
if (typeof text !== "string" || !text) return false;
|
|
63
|
+
const trimmed = text.trim();
|
|
64
|
+
return SYSTEM_INJECTION_MARKERS.some((marker) => trimmed.startsWith(marker));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function looksLikeCorrection(text) {
|
|
68
|
+
if (typeof text !== "string" || !text) return false;
|
|
69
|
+
if (isSystemInjectedUserText(text)) return false;
|
|
70
|
+
return CORRECTION_PATTERNS.some((re) => re.test(text));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 从消息块里抽纯文本(兼容纯字符串、DSH ContentBlock 数组与对象)。 */
|
|
74
|
+
export function textOf(content) {
|
|
75
|
+
if (typeof content === "string") return content.trim();
|
|
76
|
+
if (Array.isArray(content)) {
|
|
77
|
+
return content
|
|
78
|
+
.map((b) => {
|
|
79
|
+
if (typeof b === "string") return b;
|
|
80
|
+
if (b && typeof b === "object") {
|
|
81
|
+
if (b.type === "tool-call") return "";
|
|
82
|
+
if (typeof b.text === "string") return b.text;
|
|
83
|
+
if (typeof b.content === "string") return b.content;
|
|
84
|
+
}
|
|
85
|
+
return "";
|
|
86
|
+
})
|
|
87
|
+
.filter(Boolean)
|
|
88
|
+
.join(" ")
|
|
89
|
+
.trim();
|
|
90
|
+
}
|
|
91
|
+
if (content && typeof content === "object" && typeof content.text === "string") {
|
|
92
|
+
return content.text.trim();
|
|
93
|
+
}
|
|
94
|
+
return "";
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 解析工具参数(兼容对象与 JSON 字符串)。 */
|
|
98
|
+
function parseToolArgs(raw) {
|
|
99
|
+
if (!raw) return {};
|
|
100
|
+
if (typeof raw === "object") return raw;
|
|
101
|
+
if (typeof raw === "string") {
|
|
102
|
+
try {
|
|
103
|
+
const parsed = JSON.parse(raw);
|
|
104
|
+
return parsed && typeof parsed === "object" ? parsed : { value: raw };
|
|
105
|
+
} catch {
|
|
106
|
+
return { value: raw };
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return {};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 判断一个回合是否值得复盘。
|
|
114
|
+
* 返回 { worth: boolean, signals: string[], reason: string }
|
|
115
|
+
*/
|
|
116
|
+
export function assessTurn({ userTexts, toolCalls, skillsLoaded }) {
|
|
117
|
+
const signals = [];
|
|
118
|
+
let worth = false;
|
|
119
|
+
const reasons = [];
|
|
120
|
+
|
|
121
|
+
// 用户纠正 → 一等信号,永远值得复盘
|
|
122
|
+
const corrected = userTexts.some((t) => looksLikeCorrection(t));
|
|
123
|
+
if (corrected) {
|
|
124
|
+
signals.push("user-correction");
|
|
125
|
+
worth = true;
|
|
126
|
+
reasons.push("user correction detected");
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 加载过技能 → 技能可能被证明是错的
|
|
130
|
+
if (skillsLoaded.length > 0) {
|
|
131
|
+
signals.push("skill-was-wrong");
|
|
132
|
+
worth = true;
|
|
133
|
+
reasons.push(`skill(s) consulted: ${skillsLoaded.join(", ")}`);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// 工具调用:只有"复杂"才算新技术。
|
|
137
|
+
// 单次 mv/cat/ls 这类原子操作不产生可复用教训——Hermes 的
|
|
138
|
+
// "一次性任务叙事不是一类工作" 规则在这里落地。
|
|
139
|
+
const validTools = toolCalls.filter((t) => t && t !== "?");
|
|
140
|
+
const distinctTools = new Set(validTools);
|
|
141
|
+
const complex = validTools.length >= 3 || distinctTools.size >= 2;
|
|
142
|
+
if (complex) {
|
|
143
|
+
signals.push("new-technique");
|
|
144
|
+
worth = true;
|
|
145
|
+
reasons.push(`${validTools.length} tool call(s) across ${distinctTools.size} tool(s)`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (!worth) {
|
|
149
|
+
return {
|
|
150
|
+
worth: false,
|
|
151
|
+
signals: [],
|
|
152
|
+
reason: validTools.length
|
|
153
|
+
? `${validTools.length} trivial tool call(s) — no reusable lesson`
|
|
154
|
+
: "no tool calls, no correction, no skill consulted",
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return { worth: true, signals: [...new Set(signals)], reason: reasons.join("; ") };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* 从会话事件流构建一份有界快照。
|
|
162
|
+
* 同时兼容:
|
|
163
|
+
* - 真实 DSH SessionEvent(字段在 `ev.data` / `ev.data.message` 下)
|
|
164
|
+
* - 单元测试简化事件(字段直接在 `ev` 顶层)
|
|
165
|
+
*
|
|
166
|
+
* @param {object[]} events 会话事件数组(按时间顺序)
|
|
167
|
+
* @param {object} opts
|
|
168
|
+
* @param {number} [opts.maxMessages=24] 保留的最近消息条数(对应 Hermes 的 tail=24)
|
|
169
|
+
* @param {number} [opts.maxChars=24000] 快照总字符上限
|
|
170
|
+
* @param {number} [opts.digestHead=300] 更早轮次压成摘要时每条保留的字符数
|
|
171
|
+
*/
|
|
172
|
+
export function buildSnapshot(events, opts = {}) {
|
|
173
|
+
const maxMessages = opts.maxMessages ?? 24;
|
|
174
|
+
const maxChars = opts.maxChars ?? 24000;
|
|
175
|
+
const digestHead = opts.digestHead ?? 300;
|
|
176
|
+
|
|
177
|
+
const messages = []; // { role, text, toolName? }
|
|
178
|
+
const toolCalls = [];
|
|
179
|
+
const skillsLoaded = [];
|
|
180
|
+
const userTexts = [];
|
|
181
|
+
|
|
182
|
+
for (const ev of events) {
|
|
183
|
+
if (!ev || typeof ev !== "object") continue;
|
|
184
|
+
const type = ev.type ?? ev.kind;
|
|
185
|
+
const data = ev.data && typeof ev.data === "object" ? ev.data : ev;
|
|
186
|
+
|
|
187
|
+
switch (type) {
|
|
188
|
+
case "user/message": {
|
|
189
|
+
const rawContent = data.content ?? data.message?.content ?? ev.content ?? ev.text;
|
|
190
|
+
const text = textOf(rawContent);
|
|
191
|
+
if (!text) break;
|
|
192
|
+
// 跳过 DSH 自动注入的系统上下文块(如 runtime context / available_skills / memory recall)
|
|
193
|
+
if (isSystemInjectedUserText(text)) break;
|
|
194
|
+
messages.push({ role: "user", text });
|
|
195
|
+
userTexts.push(text);
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
case "assistant/message": {
|
|
199
|
+
const rawContent = data.message?.content ?? data.content ?? ev.content ?? ev.text;
|
|
200
|
+
const text = textOf(rawContent);
|
|
201
|
+
if (text) messages.push({ role: "assistant", text });
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
case "tool/call": {
|
|
205
|
+
const toolName = data.name ?? data.toolName ?? ev.toolName ?? ev.name ?? ev.tool ?? "?";
|
|
206
|
+
toolCalls.push(toolName);
|
|
207
|
+
const argObj = parseToolArgs(data.arguments ?? data.args ?? data.input ?? ev.arguments ?? ev.args ?? ev.input);
|
|
208
|
+
const argSummary = JSON.stringify(argObj).slice(0, 240);
|
|
209
|
+
messages.push({ role: "assistant", text: `[tool_call: ${toolName}(${argSummary})]` });
|
|
210
|
+
if (toolName === "skill") {
|
|
211
|
+
const skillName = argObj?.name ?? argObj?.skill ?? (typeof argObj?.value === "string" ? argObj.value : "");
|
|
212
|
+
if (skillName) skillsLoaded.push(String(skillName));
|
|
213
|
+
}
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
case "tool/result": {
|
|
217
|
+
const rawContent = data.message?.content ?? data.content ?? data.result ?? ev.content ?? ev.text ?? ev.result;
|
|
218
|
+
const text = textOf(rawContent);
|
|
219
|
+
if (text) messages.push({ role: "tool", text: text.slice(0, 1500) });
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
default:
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const assessment = assessTurn({ userTexts, toolCalls, skillsLoaded });
|
|
228
|
+
|
|
229
|
+
// 有界化:保留最近 maxMessages 条原文,更早的压成摘要(对应 _digest_history)
|
|
230
|
+
let kept = messages;
|
|
231
|
+
let digest = "";
|
|
232
|
+
if (messages.length > maxMessages) {
|
|
233
|
+
let tail = maxMessages;
|
|
234
|
+
// 保证保留段不以 tool 结果开头(否则模型看到孤立的工具输出)
|
|
235
|
+
while (tail < messages.length && messages[messages.length - tail]?.role === "tool") tail += 1;
|
|
236
|
+
kept = messages.slice(messages.length - tail);
|
|
237
|
+
const older = messages.slice(0, messages.length - tail);
|
|
238
|
+
const lines = [];
|
|
239
|
+
for (const m of older) {
|
|
240
|
+
const t = m.text.replace(/\s+/g, " ").slice(0, digestHead);
|
|
241
|
+
if (m.role === "user") lines.push(`USER: ${t}`);
|
|
242
|
+
else if (m.role === "assistant") lines.push(`ASSISTANT: ${t}`);
|
|
243
|
+
else if (m.role === "tool") lines.push(`TOOL: ${t}`);
|
|
244
|
+
}
|
|
245
|
+
digest =
|
|
246
|
+
"[Earlier conversation digest — older turns summarised to bound the review's cost. " +
|
|
247
|
+
"Recent turns follow verbatim below.]\n" +
|
|
248
|
+
lines.join("\n");
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// 总字符上限:从尾部往前累加,超了就截断
|
|
252
|
+
const parts = [];
|
|
253
|
+
for (const m of kept) {
|
|
254
|
+
const label = m.role === "user" ? "USER" : m.role === "assistant" ? "ASSISTANT" : "TOOL";
|
|
255
|
+
parts.push(`${label}: ${m.text}`);
|
|
256
|
+
}
|
|
257
|
+
let body = parts.join("\n\n");
|
|
258
|
+
if (digest) body = digest + "\n\n---\n\n" + body;
|
|
259
|
+
if (body.length > maxChars) {
|
|
260
|
+
body = "…[truncated to fit review budget]…\n\n" + body.slice(body.length - maxChars);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return {
|
|
264
|
+
...assessment,
|
|
265
|
+
transcript: body,
|
|
266
|
+
stats: {
|
|
267
|
+
messages: messages.length,
|
|
268
|
+
keptMessages: kept.length,
|
|
269
|
+
toolCalls: toolCalls.filter((t) => t && t !== "?").length,
|
|
270
|
+
skillsLoaded: [...new Set(skillsLoaded)],
|
|
271
|
+
chars: body.length,
|
|
272
|
+
},
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* 节流器:控制复盘频率,防止成本失控。
|
|
278
|
+
*
|
|
279
|
+
* 与 Hermes Curator 的 `interval_hours` / `min_idle_hours` 同构,
|
|
280
|
+
* 但作用在"每次复盘"这一级而不是"每次 curator 运行"。
|
|
281
|
+
*/
|
|
282
|
+
export class Throttle {
|
|
283
|
+
constructor({ minTurnsBetween = 3, minMinutesBetween = 5, persistPath = null } = {}) {
|
|
284
|
+
this.minTurnsBetween = minTurnsBetween;
|
|
285
|
+
this.minMsBetween = minMinutesBetween * 60 * 1000;
|
|
286
|
+
this.persistPath = persistPath;
|
|
287
|
+
this.turnCount = 0;
|
|
288
|
+
this.lastRunAt = 0;
|
|
289
|
+
this._load();
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
_load() {
|
|
293
|
+
if (!this.persistPath) return;
|
|
294
|
+
try {
|
|
295
|
+
const raw = fsSync.readFileSync(this.persistPath, "utf8");
|
|
296
|
+
const s = JSON.parse(raw);
|
|
297
|
+
if (Number.isFinite(s.turnCount)) this.turnCount = s.turnCount;
|
|
298
|
+
if (Number.isFinite(s.lastRunAt)) this.lastRunAt = s.lastRunAt;
|
|
299
|
+
} catch {
|
|
300
|
+
/* 首次运行或文件损坏:用默认值 */
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
_save() {
|
|
305
|
+
if (!this.persistPath) return;
|
|
306
|
+
try {
|
|
307
|
+
fsSync.mkdirSync(pathSync.dirname(this.persistPath), { recursive: true });
|
|
308
|
+
fsSync.writeFileSync(
|
|
309
|
+
this.persistPath,
|
|
310
|
+
JSON.stringify({ turnCount: this.turnCount, lastRunAt: this.lastRunAt }),
|
|
311
|
+
"utf8",
|
|
312
|
+
);
|
|
313
|
+
} catch {
|
|
314
|
+
/* 遥测失败不阻断 */
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** 动态更新节流阈值(供 UI 保存配置时即时生效)。 */
|
|
319
|
+
updateLimits({ minTurnsBetween, minMinutesBetween } = {}) {
|
|
320
|
+
if (minTurnsBetween !== undefined) {
|
|
321
|
+
this.minTurnsBetween = Math.max(1, Number(minTurnsBetween) || 1);
|
|
322
|
+
}
|
|
323
|
+
if (minMinutesBetween !== undefined) {
|
|
324
|
+
this.minMsBetween = Math.max(0, Number(minMinutesBetween) || 0) * 60_000;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** 记一个回合,返回该回合是否允许触发复盘。 */
|
|
329
|
+
tick({ worth }) {
|
|
330
|
+
this.turnCount += 1;
|
|
331
|
+
if (!worth) {
|
|
332
|
+
this._save();
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
if (this.turnCount < this.minTurnsBetween) {
|
|
336
|
+
this._save();
|
|
337
|
+
return false;
|
|
338
|
+
}
|
|
339
|
+
const now = Date.now();
|
|
340
|
+
if (now - this.lastRunAt < this.minMsBetween) {
|
|
341
|
+
this._save();
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
this.turnCount = 0;
|
|
345
|
+
this.lastRunAt = now;
|
|
346
|
+
this._save();
|
|
347
|
+
return true;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** 手动放行(用户显式触发时用)。 */
|
|
351
|
+
force() {
|
|
352
|
+
this.turnCount = 0;
|
|
353
|
+
this.lastRunAt = Date.now();
|
|
354
|
+
this._save();
|
|
355
|
+
}
|
|
356
|
+
}
|