6.3 组装最简 Agent TUI

前两课分别搭好了备用屏全屏布局(TuiAltScreen + VStack + ScrollView)与焦点输入交互(Input + Loader + 全局快捷键)。本课把它们与第 4 章的 Agent 接在一起,组装出一个真正可用的最简 Agent 终端界面。

点击下方终端区域,输入例如 查一下 KB-75 的库存 后按 Enter:观察工具卡片从“执行中…”原地更新为查询结果、助手逐字流式输出;也可以在生成期间继续输入文字按 Enter 进行引导,或按 Escape 中止:

正在初始化交互终端…

从 AgentEvent 到 TUI 组件树的映射

Agent 自身完全不感知终端,它只通过 agent.subscribe(listener) 推送标准生命周期事件;TUI 也完全不感知大模型,它只关心组件树何时变化以及何时调用 tui.requestRender()。本课的 createAgentTui() 就是两者之间的一层薄桥:

flowchart TD
    Input["底部 Input 提交"] -- "空闲:agent.prompt()" --> Agent["Agent 运行循环"]
    Input -- "运行中:agent.steer()" --> Agent
    Esc["全局按键 Escape"] -- "运行中:agent.abort()" --> Agent
    Agent -- "agent_start / agent_end" --> Dock["Loader 启停 + 状态栏切换"]
    Agent -- "message_update (text_delta)" --> Assistant["助手 Text.setText() 原地流式刷新"]
    Agent -- "tool_execution_start / update / end" --> Card["Map<toolCallId, Text> 原地刷新工具卡片"]
    Dock --> Render["tui.requestRender() 备用屏按行差分"]
    Assistant --> Render
    Card --> Render

这套桥接设计有三个关键细节:

  1. 按 toolCallId 原地更新工具卡片:收到 tool_execution_start 时,先创建一张带内边距的 Box(1, 0),把内部的 Text 以 toolCallId 为键存入 Map<string, Text>;后续收到 tool_execution_update 或 tool_execution_end 时,直接取出对应的 Text 调用 setText()。即使模型在同一轮并行调用多个工具,每张卡片也能准确原地刷新,且未变化的历史消息行不会触发重绘。
  2. 复用同一个底部 Input 区分 prompt 与 steer:当 agent.state.isStreaming 为 false 时,提交的文本作为新一轮用户消息交给 agent.prompt(text);当 agent.state.isStreaming 为 true 时,直接交给 agent.steer(...) 并在消息区追加 [Steer] ...,在当前工具结束后引导模型转向。
  3. 借助 ScrollView 默认支持历史回看:消息区包裹在 ScrollView(messages, { follow: "end", primary: true, scrollbar: "auto" }) 中,新消息到来时自动贴底跟随;对话变长后可直接用 PageUp / PageDown 或鼠标滚轮回看历史。
解答 展开 收起
GitHub 代码对比

在 examples/hello-pi-tui/agent/agent-tui.ts 中,补全 agent.subscribe() 事件映射、全局快捷键拦截以及 input.onSubmit 的空闲/引导分流:

import type { Agent, AgentToolResult } from "@earendil-works/pi-agent-core";
import { contentText } from "@earendil-works/pi-ai";
import {
	Box,
	type Container,
	type Input,
	matchesKey,
	Text,
	type TuiAltScreen,
} from "@earendil-works/pi-tui";

export function wireAgentEvents(
	tui: TuiAltScreen,
	agent: Agent,
	messages: Container,
	hooks: {
		onStart: () => void;
		onEnd: () => void;
	},
) {
	let activeAssistantText: Text | undefined;
	let activeAssistantBuffer = "";
	const toolCards = new Map<string, Text>();

	const readText = (result: unknown) => {
		const typed = result as AgentToolResult<unknown> | undefined;
		return contentText(typed?.content ?? []).trim() || "已完成";
	};

	return agent.subscribe((event) => {
		switch (event.type) {
			case "agent_start":
				hooks.onStart();
				break;
			case "message_start":
				if (event.message.role === "assistant") {
					activeAssistantText = undefined;
					activeAssistantBuffer = "";
				}
				break;
			case "message_update":
				if (event.assistantMessageEvent.type === "text_delta") {
					activeAssistantBuffer += event.assistantMessageEvent.delta;
					if (!activeAssistantText) {
						activeAssistantText = new Text(
							`[Assistant] ${activeAssistantBuffer}`,
							0,
							0,
						);
						messages.addChild(activeAssistantText);
					} else {
						activeAssistantText.setText(`[Assistant] ${activeAssistantBuffer}`);
					}
					tui.requestRender();
				}
				break;
			case "tool_execution_start": {
				const cardText = new Text(`[Tool] ${event.toolName}: 执行中...`, 0, 0);
				const cardBox = new Box(1, 0);
				cardBox.addChild(cardText);
				toolCards.set(event.toolCallId, cardText);
				messages.addChild(cardBox);
				tui.requestRender();
				break;
			}
			case "tool_execution_update": {
				const cardText = toolCards.get(event.toolCallId);
				if (cardText) {
					cardText.setText(
						`[Tool] ${event.toolName}: ${readText(event.partialResult)}`,
					);
					tui.requestRender();
				}
				break;
			}
			case "tool_execution_end": {
				const cardText = toolCards.get(event.toolCallId);
				if (cardText) {
					const summary = readText(event.result);
					cardText.setText(
						event.isError
							? `[Tool] ${event.toolName} [Error]: ${summary}`
							: `[Tool] ${event.toolName}: ${summary}`,
					);
					toolCards.delete(event.toolCallId);
					tui.requestRender();
				}
				break;
			}
			case "agent_end":
				activeAssistantText = undefined;
				activeAssistantBuffer = "";
				hooks.onEnd();
				break;
			default:
				break;
		}
	});
}

export function wireAgentInput(
	tui: TuiAltScreen,
	agent: Agent,
	messages: Container,
	input: Input,
	onExit?: () => void,
) {
	tui.setFocus(input);
	const removeListener = tui.addInputListener((data) => {
		if (matchesKey(data, "ctrl+c")) {
			agent.abort();
			tui.stop();
			onExit?.();
			return { consume: true };
		}
		if (matchesKey(data, "escape") && agent.state.isStreaming) {
			agent.abort();
			messages.addChild(new Text("[System] 已请求中止当前回复", 0, 0));
			tui.requestRender();
			return { consume: true };
		}
		return undefined;
	});

	input.onSubmit = (raw) => {
		const text = raw.trim();
		if (!text) return;
		input.setValue("");
		if (agent.state.isStreaming) {
			messages.addChild(new Text(`[Steer] ${text}`, 0, 0));
			tui.requestRender();
			agent.steer({ role: "user", content: text, timestamp: Date.now() });
			return;
		}
		messages.addChild(new Text(`[User] ${text}`, 0, 0));
		tui.requestRender();
		void agent.prompt(text).catch((err) => {
			const message = err instanceof Error ? err.message : String(err);
			messages.addChild(new Text(`[System] 错误:${message}`, 0, 0));
			tui.requestRender();
		});
	};

	return removeListener;
}

实现要点:

  • 原地更新与缓存失效:无论是助手的流式文本 activeAssistantText.setText(...),还是 toolCards.get(event.toolCallId)?.setText(...),都只让对应 Text 组件的缓存失效;备用屏渲染器对比前后两帧视口行数组后,仅向终端输出发生变化的这几行。
  • agent_end 统一收口:无论一轮对话是正常结束、工具报错还是被 Escape 中止,Agent 都会发出 agent_end 事件,在这里统一卸载 Loader 并恢复状态栏,避免状态残留。