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