示例工程 ch23-compaction

ch23-compaction/02-custom-summary/index.ts

typescript · 4.7 KB

// 02-custom-summary —— 自定义摘要:决定「压缩后保留什么」。
//
// 运行:node --experimental-strip-types index.ts
//
// 对比两种摘要:
//   naive  —— 只记「压缩了多少条」,关键信息全丢
//   custom —— 按「已完成 / 决定 / 待办」三段抽取,保住后续需要的事实
// 观察点:摘要不是「越短越好」,而是「保住后续要用的信息」。
 
import { estimateTokens } from "@earendil-works/pi-coding-agent";
import type { AgentMessage } from "@earendil-works/pi-agent-core";
 
const history: AgentMessage[] = [
	{ role: "user", content: "把配置迁移到 zod 校验,先看现有配置。", timestamp: 0 },
	{ role: "assistant", content: [{ type: "text", text: "先读 config/schema.ts 与 config/defaults.ts。" }], api: "stub", provider: "stub", model: "m", usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "toolUse", timestamp: 1 },
	{ role: "toolResult", toolCallId: "c1", toolName: "read", content: [{ type: "text", text: "export const schema = yup.object({...});" }], isError: false, timestamp: 2 },
	{ role: "assistant", content: [{ type: "text", text: "决定:用 zod 重写,不用 yup 的兼容层。迁移范围限定在 config/ 目录。" }], api: "stub", provider: "stub", model: "m", usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "toolUse", timestamp: 3 },
	{ role: "toolResult", toolCallId: "c2", toolName: "read", content: [{ type: "text", text: "export const defaults = { port: 3000 };\n" + "// 历史遗留配置,逐行注释……\n".repeat(80) }], isError: false, timestamp: 4 },
	{ role: "assistant", content: [{ type: "text", text: "已改 config/schema.ts 与 config/defaults.ts。待办:更新 README 与测试。" }], api: "stub", provider: "stub", model: "m", usage: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 2, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "stop", timestamp: 5 },
];
 
const textOf = (message: AgentMessage) => {
	if (!("content" in message)) return "";
	const content = message.content;
	if (typeof content === "string") return content;
	return content.map((block) => ("text" in block ? block.text : "")).join(" ");
};
 
const fullText = history.map(textOf).join("\n");
 
/** 朴素摘要:只记数量。 */
function naiveSummary(messages: AgentMessage[]): string {
	return `[摘要] 已压缩 ${messages.length} 条消息。`;
}
 
/** 自定义摘要:抽取「决定」「待办」「已读文件」。 */
function customSummary(messages: AgentMessage[]): string {
	const text = messages.map(textOf).join("\n");
	const decisions = text.split("\n").filter((line) => line.includes("决定:"));
	const todos = text.split("\n").filter((line) => line.includes("待办:"));
	const files = [...text.matchAll(/config\/[\w.-]+\.ts/g)].map((match) => match[0]);
	const uniqueFiles = [...new Set(files)];
	return [
		"[摘要]",
		`已完成:读取并修改 ${uniqueFiles.length} 个文件(${uniqueFiles.join(", ")})。`,
		decisions.length > 0 ? `决定:${decisions.map((line) => line.replace(/^.*决定:/, "")).join(";")}` : "决定:(无)",
		todos.length > 0 ? `待办:${todos.map((line) => line.replace(/^.*待办:/, "")).join(";")}` : "待办:(无)",
	].join("\n");
}
 
const naive = naiveSummary(history);
const custom = customSummary(history);
const tokens = (text: string) => Math.ceil(text.length / 4);
 
console.log("原始历史 token(估算):", tokens(fullText));
console.log("naive 摘要:", naive);
console.log("custom 摘要:\n" + custom);
console.log("custom 是否保住「决定」:", custom.includes("zod"));
console.log("custom 是否保住「待办」:", custom.includes("README"));
 
const ok = (label: string, pass: boolean): void => {
	console.log(`${pass ? "✓" : "✗"} ${label}`);
	if (!pass) process.exitCode = 1;
};
 
ok("两种摘要都比原文短", tokens(naive) < tokens(fullText) && tokens(custom) < tokens(fullText));
ok("naive 摘要丢掉了决定", naive.includes("zod") === false);
ok("custom 摘要保住了决定", custom.includes("决定:") && custom.includes("zod"));
ok("custom 摘要保住了待办", custom.includes("待办:") && custom.includes("README"));
ok("custom 摘要列出了改动过的文件", custom.includes("config/schema.ts") && custom.includes("config/defaults.ts"));
ok("custom 摘要记录了文件数量", custom.includes("2 个文件"));
ok("custom 比 naive 长(因为它保留了更多事实)", tokens(custom) > tokens(naive));
ok("custom 仍明显小于原文", tokens(custom) < tokens(fullText) / 2);
 
console.log("✓ OK");