示例工程 ch12-builtin-tools

ch12-builtin-tools/02-bash-timeout/index.ts

typescript · 3.3 KB

// 02-bash-timeout —— 内置 bash 的两种「失败」:超时与截断。
//
// 运行:node --experimental-strip-types index.ts
//
// 两次调用:
//   1. sleep 5 但 timeout=1  → 超时,isError
//   2. seq 1 20000          → 输出被截断(保留尾部 2000 行),并给出完整输出路径
// 观察点:错误文本可读、截断是「保留尾部」而不是头部(因为报错通常在最末)。
 
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createAgentSession, SessionManager } from "@earendil-works/pi-coding-agent";
import { createStubRuntime } from "./stub-provider.ts";
 
const cwd = mkdtempSync(join(tmpdir(), "pi-ch12-bash-"));
 
async function runOnce(id: string, args: Record<string, unknown>) {
	const stub = await createStubRuntime({ steps: [{ toolCalls: [{ id, name: "bash", arguments: args }] }, { text: "ok" }] });
	const { session } = await createAgentSession({
		model: stub.model,
		modelRuntime: stub.modelRuntime,
		agentDir: stub.agentDir,
		sessionManager: SessionManager.inMemory(cwd),
		cwd,
		tools: ["bash"],
	});
	await session.prompt("跑一下");
	const result = session.agent.state.messages.find((message) => message.role === "toolResult" && message.toolCallId === id);
	const text = result && "content" in result ? (result.content[0] as { text?: string })?.text ?? "" : "";
	const details = result && "details" in result ? (result.details as { truncation?: { truncated?: boolean; truncatedBy?: string; totalLines?: number } } | undefined) : undefined;
	const isError = result?.role === "toolResult" ? result.isError : true;
	session.dispose();
	return { text, isError, details };
}
 
const timeout = await runOnce("c1", { command: "sleep 5", timeout: 1 });
const many = await runOnce("c2", { command: "seq 1 20000" });
 
// 输出里含临时文件绝对路径,打印前替换掉,保证可 diff
const sanitize = (text: string) => text.replace(/\/[^\s\]]+\.log/g, "<log>");
const tailNotice = sanitize(many.text).split("\n").slice(-2).join(" ").trim();
 
console.log("超时结果:", JSON.stringify(sanitize(timeout.text)));
console.log("超时 isError:", timeout.isError);
console.log("大输出:字符数", many.text.length, ";行数", many.text.split("\n").length);
const truncation = many.details?.truncation;
console.log("截断信息:", JSON.stringify({ truncated: truncation?.truncated, truncatedBy: truncation?.truncatedBy, totalLines: truncation?.totalLines }));
console.log("尾部提示:", JSON.stringify(tailNotice));
 
const ok = (label: string, pass: boolean): void => {
	console.log(`${pass ? "✓" : "✗"} ${label}`);
	if (!pass) process.exitCode = 1;
};
 
ok("超时被标记为 isError", timeout.isError === true);
ok("超时文本提到 timeout", /timed out|timeout/i.test(timeout.text));
ok("超时文本不含堆栈", timeout.text.includes("    at ") === false);
ok("大输出的行数被截到约 2000 行", many.text.split("\n").length <= 2005);
ok("截断保留的是尾部(最后一行是 20000)", many.text.includes("20000"));
ok("尾部提示说明了范围", /Showing lines \d+-\d+ of \d+/.test(many.text));
ok("details.truncation.truncated 为 true", many.details?.truncation?.truncated === true);
ok("details 里记录了总行数 20000", many.details?.truncation?.totalLines === 20000);
 
console.log("✓ OK");