Summary
The agent-core package of the open-source pi coding agent implements a model-agnostic agent loop as a stateless function wrapped by a stateful Agent class. The loop orchestrates LLM calls, tool execution, and streaming through a four-level event protocol, while all product policy (context compaction, permission checks, model switching, queueing) is injected through config hooks.
Key Takeaways
- The loop is a pure function: callers pass a context snapshot and config, and receive an event stream plus new messages, with no state retained between runs.
- A stateful Agent class owns the transcript, steering/follow-up queues, and event subscribers, feeding snapshots to the loop and committing only completed messages back.
- Failures never escape as exceptions: LLM stream errors and tool execution errors both become error tool results fed back to the model so it can self-correct.
- When an LLM response is truncated by the output token limit, all tool calls in that message are failed rather than executed, because streamed arguments may be salvaged from incomplete JSON.
- Tool calls in a batch execute in parallel by default, but any tool marked sequential downgrades the whole batch; preparation (validation, permission hooks) stays sequential even in parallel mode.
- A batch terminates the loop only when every tool result sets the terminate flag, so no single tool can end the session unilaterally.
- Nine config hooks (transformContext, beforeToolCall, afterToolCall, prepareNextTurn, shouldStopAfterTurn, and queue pollers) let products inject policy without forking the loop.
Extracted Notes
- A stateless loop core plus a stateful wrapper separates orchestration from session state
- Agent loops should encode failures as error tool results instead of throwing exceptions
- Snapshot boundaries between loop and state owner give crash safety for free
- Inject policy through hooks so the agent loop stays product-agnostic
- Truncated LLM output should fail all tool calls rather than execute salvaged arguments
- Stream partial messages in place so interrupted contexts stay structurally complete
- Require all tool results to agree before terminating a batch