9.1 实现内置工具与最小会话

从这一课开始,我们在 packages/nano-pi-coding-agent 里动手搭建自己的 Coding Agent。第一步先做出能真正在代码仓库里读文件、改代码、跑测试的最小闭环——对应第 8.1 课用官方包跑通的 createAgentSession() 场景。

内置四件套的工程细节

同样是包装 fs 与 child_process,面向大模型的编程工具必须处理三个实战边界:

  1. 输出截断方向(src/tools/truncate.ts):单个大文件或冗长测试日志很容易瞬间吃光上下文。read 使用 truncateHead()(保留前 2000 行 / 50KB,并提示模型用 offset 分页续读);bash 使用 truncateTail()(保留尾部,因为报错堆栈和测试汇总几乎总在末尾)。
  2. 精确唯一匹配替换(src/tools/edit.ts):edit 要求 oldText 在目标文件中恰好出现 1 次。出现 0 次说明模型记错了代码,超过 1 次说明片段太短有歧义——两种情况都必须立刻抛错让模型补充上下文重试,绝不能静默改错位置。
  3. 命令取消与超时(src/tools/bash.ts):bash 接收 AbortSignal 与可选 timeout,被中止或非零退出码时直接抛错并附带截断后的合并输出,让底层 Agent 自动标记 isError: true 回传给模型。

两层配置、项目上下文与 AgentSession

在工具之上,src/core/ 用三个小模块完成会话总装:

解答 展开 收起
GitHub 代码对比

三处实现分别补齐了“安全编辑”“两层配置合并”和“会话总装”:

  1. 精确唯一匹配替换(tools/edit.ts):
const content = readFileSync(targetPath, "utf8");
if (!params.oldText) {
	throw new Error(`edit 失败:oldText 不能为空(文件:${params.path})`);
}
const parts = content.split(params.oldText);
const matchCount = parts.length - 1;
if (matchCount === 0) {
	throw new Error(`edit 失败:在 ${params.path} 中未找到精确匹配的 oldText`);
}
if (matchCount > 1) {
	throw new Error(
		`edit 失败:在 ${params.path} 中匹配到 ${matchCount} 处 oldText,请补充更多上下文确保唯一匹配`,
	);
}
writeFileSync(targetPath, parts.join(params.newText), "utf8");
  1. 两层配置深度合并(core/settings.ts):
const userSettings = readOptionalJsonFile(join(agentDir, "settings.json"));
const projectSettings = readOptionalJsonFile(join(cwd, ".pi", "settings.json"));
const merged = deepMergeSettings(userSettings, projectSettings);
const manager = new SettingsManager(merged);
  1. 会话总装(core/session.ts):
export async function createAgentSession(
	options: CreateAgentSessionOptions,
): Promise<{ session: AgentSession }> {
	const settingsManager =
		options.settingsManager ??
		SettingsManager.create(options.cwd, options.agentDir);
	let resourceLoader = options.resourceLoader;
	if (!resourceLoader) {
		resourceLoader = new DefaultResourceLoader({
			cwd: options.cwd,
			agentDir: options.agentDir,
			settingsManager,
		});
		await resourceLoader.reload();
	}
	const tools = options.tools ?? createCodingTools(options.cwd);
	const systemPrompt = resourceLoader.buildSystemPrompt(tools);
	const agent = new Agent({
		initialState: { model: options.model, systemPrompt, tools },
		streamFn: options.streamFn,
	});
	return {
		session: new AgentSession({
			agent,
			cwd: options.cwd,
			settingsManager,
			resourceLoader,
		}),
	};
}

用 content.split(oldText) 既能一步算出精确匹配次数,又能避免 String.prototype.replace 中 $&、$1 等特殊替换符导致的意外转义。