示例工程 ch32-capstone-cli-agent
ch32-capstone-cli-agent/capstone/index.ts
// index.ts —— capstone CLI:仓库健康检查器。
//
// 用法:
// node --experimental-strip-types index.ts --demo # 离线脚本化 run(校验用)
// node --experimental-strip-types index.ts --demo --dry-run # 只报告,不写文件
// node --experimental-strip-types index.ts --resume <file> # 恢复已有会话
//
// 设计要点(全书收敛):
// - 工具边界最小:list/read/search 只读,append_note 受 dry-run 控制(第 13、14 章)
// - 会话可恢复:落到 sessions/ 目录(第 7、29 章)
// - 成本上限:超过 --max-cost 就停(第 27 章)
// - 事件→时间线:stdout 只打「决策与动作」(第 31 章)
// - --live 走真实模型,非验收路径(第 25、26 章)
import { mkdtempSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createTools } from "./src/tools.ts";
import { openSession, runCost } from "./src/session.ts";
import { createStubRuntime } from "./stub-provider.ts";
const args = process.argv.slice(2);
const has = (flag: string) => args.includes(flag);
const valueOf = (flag: string) => {
const index = args.indexOf(flag);
return index >= 0 ? args[index + 1] : undefined;
};
// 默认走 demo(--demo 显式指定或未指定 --live 都算),保证「无参数直接跑」也是离线可验收的
const demo = has("--demo") || !has("--live");
const dryRun = has("--dry-run");
const maxCost = Number(valueOf("--max-cost") ?? "0.5");
const resumeFile = valueOf("--resume");
/** 构造一个「工作区」:几个待检查的文件。 */
function makeWorkspace(): string {
const root = mkdtempSync(join(tmpdir(), "capstone-root-"));
writeFileSync(join(root, "README.md"), "# Demo 项目\n\n这是一个演示仓库。\n\nTODO: 补测试\n");
writeFileSync(join(root, "package.json"), JSON.stringify({ name: "demo", version: "0.1.0", scripts: { test: "echo none" } }, null, 2));
writeFileSync(join(root, "index.ts"), "export function add(a: number, b: number) {\n\treturn a + b;\n}\n\n// TODO: 处理边界\n");
return root;
}
const root = valueOf("--root") ?? makeWorkspace();
const workDir = mkdtempSync(join(tmpdir(), "capstone-work-"));
const notesFile = join(workDir, "report.md");
mkdirSync(workDir, { recursive: true });
const tools = createTools({ root, dryRun, notesFile });
const stub = await createStubRuntime({
steps: [
{ text: "我先列出文件。", toolCalls: [{ id: "c1", name: "list_files", arguments: {} }] },
{ toolCalls: [{ id: "c2", name: "search", arguments: { query: "TODO" } }] },
{
toolCalls: [
{ id: "c3", name: "read_file", arguments: { path: "README.md" } },
{ id: "c4", name: "append_note", arguments: { text: "发现 2 处 TODO,建议补充测试。" } },
],
},
{ text: "检查完成:2 处 TODO。" },
],
});
const { session, dispose } = await openSession({
root,
workDir,
agentDir: stub.agentDir,
dryRun,
resumeFile,
model: { model: stub.model },
modelRuntime: { modelRuntime: stub.modelRuntime },
tools,
notesFile,
});
const timeline: string[] = [];
let turn = 0;
session.subscribe((event) => {
if (event.type === "turn_start") turn += 1;
if (event.type === "tool_execution_end") timeline.push(`[turn ${turn}] ${event.toolName} ${event.isError ? "error" : "ok"}`);
if (event.type === "message_end" && event.message.role === "assistant") {
const calls = event.message.content.filter((block) => block.type === "toolCall").length;
if (calls === 0) timeline.push(`[turn ${turn}] 模型 → 结束`);
}
});
await session.prompt(
"检查这个仓库:列出文件、找出 TODO、把结论写入报告(dry-run 时只说明会写什么)。",
);
const cost = runCost(session.agent.state.messages as Array<{ role: string; usage?: { cost?: { total?: number } } }>);
const answer = session.getLastAssistantText() ?? "";
const sessionFile = session.sessionFile ?? "";
const filesInSessions = readdirSync(join(workDir, "sessions")).filter((name) => name.endsWith(".jsonl")).length;
const report = dryRun ? "(dry-run,未写入)" : readFileSync(notesFile, "utf8").trim();
dispose();
console.log("时间线:");
for (const line of timeline) console.log(` ${line}`);
console.log("会话文件数:", filesInSessions);
console.log("本次成本(估算):", cost.toFixed(6), "上限", maxCost);
console.log("报告内容:", report);
console.log("最终回答:", answer);
const ok = (label: string, pass: boolean): void => {
console.log(`${pass ? "✓" : "✗"} ${label}`);
if (!pass) process.exitCode = 1;
};
ok("创建了 1 个会话文件", filesInSessions === 1);
ok("时间线里有 4 次工具执行", timeline.filter((line) => line.includes("ok") || line.includes("error")).length === 4);
ok("所有工具都成功", timeline.every((line) => !line.includes("error")));
ok("成本在上限内", cost <= maxCost);
ok("dry-run 时不写报告", dryRun ? report.includes("dry-run") : report.includes("TODO"));
ok("最终回答提到 TODO", answer.includes("TODO"));
ok("会话 id 可恢复(有文件路径)", sessionFile.endsWith(".jsonl"));
if (!dryRun && process.env.CAPSTONE_PRINT_RESUME === "1") {
console.log("恢复命令:--resume", sessionFile);
}
console.log("✓ OK");