示例工程 ch04-session-lifecycle-events
ch04-session-lifecycle-events/01-event-trace/index.ts
// 01-event-trace —— 把一次两轮 run 的完整事件序列打成 JSONL,并断言顺序不变量。
//
// 运行:node --experimental-strip-types index.ts
//
// 这个示例是后面所有章节的调试基础设施:出问题时先看时间线,比在代码里打断点快。
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Type } from "typebox";
import { createAgentSession, defineTool, SessionManager } from "@earendil-works/pi-coding-agent";
import type { AgentSessionEvent } from "@earendil-works/pi-coding-agent";
import { createStubRuntime } from "./stub-provider.ts";
const cwd = mkdtempSync(join(tmpdir(), "pi-ch04-trace-"));
const stub = await createStubRuntime({
steps: [
{ text: "我查一下。", toolCalls: [{ id: "c1", name: "now", arguments: {} }] },
{ text: "查完了。" },
],
});
const now = defineTool({
name: "now",
label: "Now",
description: "返回一个固定字符串(示例不打印真实时间,保证输出稳定)",
parameters: Type.Object({}),
execute: async () => ({ content: [{ type: "text" as const, text: "T" }], details: {} }),
});
const { session } = await createAgentSession({
model: stub.model,
modelRuntime: stub.modelRuntime,
agentDir: stub.agentDir,
sessionManager: SessionManager.inMemory(cwd),
cwd,
tools: ["now"],
customTools: [now],
});
// 只保留「结构」字段:时间戳、耗时这类非确定值不进 JSONL,否则 diff 不稳定
const trace: Array<Record<string, unknown>> = [];
const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
const line: Record<string, unknown> = { seq: trace.length + 1, type: event.type };
if ("message" in event) line.role = (event.message as { role?: string }).role;
if (event.type === "tool_execution_start" || event.type === "tool_execution_end") line.tool = event.toolName;
if (event.type === "tool_execution_end") line.isError = event.isError;
if (event.type === "agent_end") line.willRetry = event.willRetry;
if (event.type === "agent_settled") line.aborted = event.aborted;
trace.push(line);
});
await session.prompt("几点了?");
const lines = trace.map((line) => JSON.stringify(line));
for (const line of lines) console.log(line);
const types = trace.map((line) => line.type as string);
const count = (type: string) => types.filter((t) => t === type).length;
const firstIndex = (type: string) => types.indexOf(type);
const lastIndex = (type: string) => types.lastIndexOf(type);
const ok = (label: string, pass: boolean): void => {
console.log(`${pass ? "✓" : "✗"} ${label}`);
if (!pass) process.exitCode = 1;
};
ok("第 1 个事件是 agent_start", types[0] === "agent_start");
ok("最后 2 个事件是 agent_end、agent_settled", types.at(-2) === "agent_end" && types.at(-1) === "agent_settled");
ok("agent_end 带 willRetry=false", trace.find((l) => l.type === "agent_end")?.willRetry === false);
ok("agent_settled 带 aborted=false", trace.find((l) => l.type === "agent_settled")?.aborted === false);
ok("有两轮 turn_start/turn_end", count("turn_start") === 2 && count("turn_end") === 2);
ok("message_start 与 message_end 数量相同", count("message_start") === count("message_end"));
ok("tool_execution_start 早于 tool_execution_end", firstIndex("tool_execution_start") < firstIndex("tool_execution_end"));
ok("工具执行发生在 turn 内", firstIndex("turn_start") < firstIndex("tool_execution_start") && lastIndex("tool_execution_end") < lastIndex("turn_end"));
ok("只在 assistant 消息上有 message_update", trace.filter((l) => l.type === "message_update").every((l) => l.role === "assistant"));
ok("message_update 不少于 4 次(两轮各两段 delta)", count("message_update") >= 4);
unsubscribe();
session.dispose();
console.log("✓ OK");