Understand the agent loop, context assembly, session tree, branching and compression mechanism of Pi.

Difficulty: ★★ | Prerequisite: Complete 01 | This article is the basis for understanding subsequent extensions/SDK/RPC, please be sure to read it.

1. Panorama: Four things coordinated by Pi

Official "How Pi Works" in one sentence:Pi coordinates model requests, tool execution, context assembly, and session storage.

  • session:Pi A record of a conversation, including messages, tool calls and results, model switching, compression, and other events.
  • Messages and events in a session form a tree;Each path in the tree is a branch; to current entry The branch at the end is called active branch, which provides a history of the next model request.

All interfaces (interactive/print/JSON/RPC/SDK)

│ Share the same set

▼

Agent loop ←→ tool execution

│

▼

Context assembly (system prompt + active branch + tool definition + skill description)

│

▼

Session storage (tree of entries in JSONL file)

2. Agent loop

2.1 One-time running process

  1. The message you submitted is added active branch;
  2. For Pi System prompts + active branches + available tools + model settings Build model request, sent through the selected Provider;
  3. Provider streaming Returns the assistant reply, which may contain text and Tool call;
  4. Pi logs responses, performs each tool call and logs the results - and you're done a turn;
  5. If tool results or queued messages require the model to be requested again, Pi starts the next turn; otherwise, this run ends.

Definition of turn: an assistant reply + the tool calls and tool results it produces.

2.2 Two types of queued messages

  • Steering

    Interaction keys
    Enter
    when to enter
    After the current assistant turn (including its tool call) ends and before the next LLM call
  • Follow-up

    Interaction keys
    Alt+Enter
    when to enter
    After the agent completes all pending work
TypeInteraction keyswhen to enter
SteeringEnterAfter the current assistant turn (including its tool call) ends and before the next LLM call
Follow-upAlt+EnterAfter the agent completes all pending work

abort Will stop the current run and return the queued message to the editor. Setting items steeringMode / followUpMode Control queued messages are "one-at-a-time"(default) or "all" One-time delivery.

2.3 Event sequence (can be seen by JSON/RPC/SDK)

Events produced by a basic run (from JSON Event Stream documentation):

{"type":"agent_start"}
{"type":"turn_start"}
{"type":"message_start","message":{"role":"user","content":"Review this repository","timestamp":1733234401000}}
{"type":"message_end","message":{"role":"user","content":"Review this repository","timestamp":1733234401000}}
{"type":"message_start","message":{"role":"assistant","content":[],"stopReason":"pending","...":"..."}}
{"type":"message_update","usage":{"...":"..."},"assistantMessageEvent":{"type":"text_delta","contentIndex":0,"delta":"Hello"}}
{"type":"message_end","message":{"role":"assistant","...":"..."}}
{"type":"turn_end","message":{"role":"assistant","...":"..."},"toolResults":[]}
{"type":"agent_end","messages":[{"...":"..."}],"willRetry":false}
{"type":"agent_settled","aborted":false}

Key distinctions (often used when writing extensions, SDK, and RPC later):

  • agent_end:A low-level run end. There may still be automatic retries, overflow recovery, compaction retries, steering or follow-up afterwards;
  • agent_settled:Pi It will not continue automatically . When you need to know "really done", wait for it.

2.4 Execution characteristics of tool calls

  • Multiple tool calls in the same assistant message Possibly executed in parallel;
  • Pi default Do not ask one by one Tool call; when approval is required, use the extended tool_call event implementation (see 05 Extension development)。

3. How is the context assembled?

  • System prompt

    Source
    Pi basic instructions + discovered context files (AGENTS.md / CLAUDE.md etc.), can be SYSTEM.md replace or APPEND_SYSTEM.md Append
  • Conversation history

    Source
    active branch entries, converted into user/assistant/toolResult messages
  • Tool definition

    Source
    Currently active tool
  • Skills

    Source
    Just put name and description;complete SKILL.md Read by the model only when needed (loading on demand)
  • Expand

    Source
    Can add instructions or transform context
  • prompt template

    Source
    Input in editor becomes user message before Expand
  • Accessories

    Source
    Selected files, pictures, pasted text, and shell output can all become message content.
compositionSource
System promptPi basic instructions + discovered context files (AGENTS.md / CLAUDE.md etc.), can be SYSTEM.md replace or APPEND_SYSTEM.md Append
Conversation historyactive branch entries, converted into user/assistant/toolResult messages
Tool definitionCurrently active tool
SkillsJust put name and description;complete SKILL.md Read by the model only when needed (loading on demand)
ExpandCan add instructions or transform context
prompt templateInput in editor becomes user message before Expand
AccessoriesSelected files, pictures, pasted text, and shell output can all become message content.

The model receives active branch, instead of all branches in the session file.

4. Session: a tree in a JSONL file

4.1 Storage

  • Default storage:~/.pi/agent/sessions/--<path>--/<timestamp>_<session-id>.jsonl, grouped by working directory;
  • Available --session-dir, environment variables PI_CODING_AGENT_SESSION_DIR or set sessionDir Modify (CLI parameters have the highest priority);
  • --no-session: Temporary memory session, which cannot be restored after exiting.

4.2 Entry structure

Each tree entry has id, and pass parentId Points to the parent entry;Current entry (leaf) Decide on the activity branch. The first line of the file is the session header:

{"type":"session","version":3,"id":"uuid","timestamp":"2024-12-03T14:00:00.000Z","cwd":"/path/to/project"}

Example message entry (from Session File Format documentation):

{"type":"message","id":"a1b2c3d4","parentId":"prev1234","timestamp":"2024-12-03T14:00:01.000Z","message":{"role":"user","content":"Hello","timestamp":1733234401000}}
{"type":"message","id":"b2c3d4e5","parentId":"a1b2c3d4","timestamp":"2024-12-03T14:00:02.000Z","message":{"role":"assistant","content":[{"type":"text","text":"Hi!"}],"api":"anthropic-messages","provider":"anthropic","model":"claude-sonnet-4-5","usage":{...},"stopReason":"stop","timestamp":1733234402000}}

Main entry types:message、model_change、thinking_level_change、usage、compaction、context_edit、branch_summary、custom(Extended state, does not enter context),custom_message(Extended message, enter context),label、session_info。

In the new version, the system prompts and tool list are also role: "system" Message entry logging: complete sections and tool declarations are saved for the first request, and subsequent changes are logged as patches (toolsAdded / toolsRemoved)。

4.3 Tree representation

[user msg] ─── [assistant] ─── [user msg] ─── [assistant] ─┬─ [user msg] ← current leaf

│

└─ [branch_summary] ─── [user msg] ← alternate branch

5. Branch:/tree、/fork、/clone

  • /tree

    result
    in within the same session file move
    Applicable scenarios
    Related alternatives put together
  • /fork

    result
    From an earlier user message New session
    Applicable scenarios
    The alternative should be to work independently
  • /clone

    result
    branch activities Copy into new session
    Applicable scenarios
    Want an independent copy of the current state
OperationresultApplicable scenarios
/treein within the same session file moveRelated alternatives put together
/forkFrom an earlier user message New sessionThe alternative should be to work independently
/clonebranch activities Copy into new sessionWant an independent copy of the current state

/tree Usage details:

  • Select one User messages: Its text will be put back into the editor, and a new branch can be created after modification and submission;
  • Select assistant reply or other entry: continue after this entry, the editor is empty;
  • When the editor is empty Double click Escape Open by default /tree(Setting item doubleEscapeAction Can be changed to fork or none)。

CLI corresponds to:pi --fork <path|id> Fork from an existing session before starting;pi --session <path|id> Open the specified session.

5.1 Branch Summarization

when you use /tree When leaving a branch, Pi can Summarize the part of the job you left, and hang the summary on the branch you entered:

Before navigation:

┌─ B ─ C ─ D (old leaf, will be abandoned)

A ───┤

└─ E ─ F (target)

After navigation with summary:

┌─ B ─ C ─ D

A ───┤

└─ E ─ F ─ [Abstract of B,C,D] (new leaf)

Steps: Find the common ancestor → Collect entries from the old leaf back to the common ancestor → Prepare according to token budget (new priority) → Adjust LLM to generate structured summary → Append BranchSummaryEntry. settings branchSummary.skipPrompt: true Asking can be skipped.

6. Compression

6.1 Why compression is necessary

Model context window is limited. Compression meeting insert a summary entry, in subsequent requests Replaces older message;The original entry remains in the session tree, will not be deleted.

6.2 When to trigger

Automatic compression conditions:

contextTokens > contextWindow - reserveTokens

  • compaction.reserveTokens Default 16384;
  • compaction.keepRecentTokens Default 20000(Keep the most recent token that is not digested);
  • Manual:/compact [instructions], you can add instructions to focus the summary on a certain topic;
  • Pi can perform a "compact and retry" recovery when the provider returns a context overflow error.

6.3 Working steps

  1. Find the cutting point: Accumulate token estimates from back to front until reaching keepRecentTokens;
  2. Extract messages: Get the messages between the previous retention boundary (or the beginning of the session) and the cut point;
  3. Generate summary: Call LLM in structured format (when there is a previous summary as iteration context);
  4. Append entry: Save tape summary and firstKeptEntryId of CompactionEntry;
  5. Rebuild context: Next request uses digest + from firstKeptEntryId Start message.

LLM actually sees:

┌────────┬─────────┬─────┬─────┬──────┬──────┬─────┬──────┐

│ system │ summary │ usr │ ass │ tool │ tool │ ass │ tool │

└────────┴─────────┴─────┴─────┴──────┴──────┴─────┴──────┘

Point-cutting rules: You can cut at user, assistant, bashExecution, and custom messages;Never cut at tool results(The tool result must be together with its tool call).

6.4 Summary format

## Goal
## Constraints & Preferences
## Progress
### Done
### In Progress
### Blocked
## Key Decisions
## Next Steps
## Critical Context

<read-files> ... </read-files>

<modified-files> ... </modified-files>

The file read and write list will be updated between multiple compressions. Cumulative tracking。

6.5 Configuration example (~/.pi/agent/settings.json or .pi/settings.json)

{
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000
  }
}

Turning off automatic compression does not disable /compact. Compression failure is usually caused by the Provider being unavailable. Please try again after repairing it. /compact. Extensions are available session_before_compact Event custom summary (see 05 Extension development)。

7. Trust and authority (conceptual level)

  • Pi is loading project settings and resources before Make sure first Project trust;
  • Afterwards the context file is loaded (AGENTS.md Discovery of other context files No need project trust);
  • Enabled tools run with the operating system permissions of the Pi process; extensions execute within the Pi process.Project trust is not a sandbox.

8. Small exercises

  1. Observe events:Run pi --mode json "List files" 2>/dev/null | jq -c '.type', refer to Section 2.3 to tell the meaning of each event; find out agent_end with agent_settled。
  2. branch experiment: Let Pi use plan A to implement a small function; use /tree Go back to your user message, change it to "Use Plan B", and submit. reuse /tree Switch between the two branches and choose to generate a branch summary.
  3. fork vs clone: Execute separately /fork and /clone, use /session Compare the new session files and explain the differences between the two.
  4. Read session file: use /session To find the session file path, use jq -c '{type, id, parentId}' View the entry and draw the tree manually.
  5. Manual compression: Executed in a long session /compact 保留所有关于数据库 schema 的决定, then look at the JSONL again and find compaction entries and firstKeptEntryId。
  6. Thinking questions:Why does compression "never cut at tool results"? What happens if it is cut?

9. Official sources