CH 02 · The Agent Loop Pattern · 10/15
Read as one pageReal code: pi's typed event timeline
pi is a small open-source coding agent whose loop lives in packages/agent. Every action the loop takes is reported as one value of a single type, AgentEvent: the timeline this section describes, written as a type. Watch how the events nest: run, then turn, then message and tool.
export type AgentEvent =
// Agent lifecycle
| { type: "agent_start" } // [1]
| { type: "agent_end"; messages: AgentMessage[] }
// Turn lifecycle - a turn is one assistant response + any tool calls/results
| { type: "turn_start" } // [2]
| { type: "turn_end"; message: AgentMessage; toolResults: ToolResultMessage[] }
// Message lifecycle - emitted for system, user, assistant, and toolResult messages
| { type: "message_start"; message: AgentMessage } // [3]
// Only emitted for assistant messages during streaming
| { type: "message_update"; message: AgentMessage; assistantMessageEvent: AssistantMessageEvent } // [4]
| { type: "message_end"; message: AgentMessage }
// Tool execution lifecycle
| { type: "tool_execution_start"; toolCallId: string; toolName: string; args: any } // [5]
| { type: "tool_execution_update"; toolCallId: string; toolName: string; args: any; partialResult: any }
| {
type: "tool_execution_end";
toolCallId: string;
toolName: string;
result: any;
isError: boolean; // [6]
/** Milliseconds `execute()` took, measured with a monotonic clock; absent when the tool did not run. */
durationMs?: number;
};
Source: earendil-works/pi, packages/agent/src/types.ts (MIT)
What to notice
- [1]
agent_startandagent_endbracket one whole run, from the prompt until the loop stops. On the normal path,agent_endcarriesnewMessages: the prompt plus everything the run appended. If the executor throws,handleRunFailure(the catch around that run) emitsagent_endwith only the synthetic failure message.AgentMessageis pi's message type: the usual roles plus custom kinds an app can add. - [2] A turn is one pass of this chapter's loop: one model reply plus the tool calls it caused.
turn_endhands over the reply and the tool results from that pass. Anerrororabortedstop emitsturn_endwith an empty result list and does not run tool calls still sitting in the message. - [3] Every message gets
message_startandmessage_end, even one that arrives complete, so a consumer can rely on one rule: a message is final atmessage_end. - [4] Only the assistant reply streams. Its
AssistantMessageEventcarries pieces of text, thinking, or a tool call as they arrive (text_delta,toolcall_delta, and so on). - [5]
toolCallIdlets a UI match start, progress (partialResult) and end even when several tools run in parallel. - [6] Failure is a field, not a sentence to parse. A monotonic clock, used for
durationMs, is a timer that does not jump when someone changes the system time.
Every member has a type string, so switch (event.type) tells TypeScript which fields exist in that branch. Reading event.toolCallId in the turn_end case fails to compile. A log of sentences such as "called tool X" cannot do that, because every reader of the log has to parse text.
Read it yourself: read processEvents in packages/agent/src/agent.ts. The agent's message list grows only on message_end, and the same event writes the saved session (search packages/coding-agent/src/core/agent-session.ts for Handle session persistence). The terminal UI in interactive-mode.ts switches on these same type values. One stream feeds both. Question: which two events would you use to show and hide a spinner next to a running tool?
Finished this idea?
Your learning progress stays in this browser.