Pi Agent Session Management

Pi Agent's session management system is one of its most powerful features.

This chapter details session saving, resuming, branching, and exporting.


Session Storage Mechanism

Each conversation is automatically saved as a session file in JSONL format, stored in~/.pi/agent/sessions/a directory categorized by project path.

The directory name is derived from the project's absolute path: slashes are replaced with hyphens, and it is wrapped with -- on both sides.

The file name is formed by concatenating the creation timestamp and the session UUID.

Internally, each session is organized as a tree structure—this means you can fork at any historical node without losing previous conversation content.

~/.pi/agent/sessions/
└── --Users-example-projects-example-demo--/        # 目录名为项目路径,斜杠已替换为连字符
    ├── 2026-08-31T02-40-11-000Z_019fc2a1-93b4-7c22-8d5e-2b3c4d5e6f7a.jsonl    # 时间戳_UUID.jsonl
    ├── 2026-08-31T04-12-38-000Z_2c8f71ba-4a19-4e63-9d02-7f5a6b8c9d0e.jsonl
    └── 2026-08-31T08-55-02-000Z_5e3d92f4-8b26-47ac-a174-9c0d1e2f3a4b.jsonl

Internal Structure of Session Files

The first line of a session file is fixed metadata, recording the session format version, session ID, creation time, and working directory.

This metadata does not have id and parentId fields and does not participate in the conversation tree.

Starting from the second line, each line is an entry, all with id and parentId fields, which together form the tree structure.

Entry types include message, compaction, branch_summary, label, custom, etc.

Sessions created by /fork or /clone also have an additional parentSession field in the first-line metadata, pointing to the original session file.

{"type":"session","version":3,"id":"019fc2a1-93b4-7c22-8d5e-2b3c4d5e6f7a","timestamp":"2026-08-31T02:40:11.000Z","cwd":"/Users/example/projects/example-demo"}
{"type":"message","id":"m1","parentId":null,"message":{"role":"user","content":[{"type":"text","text":"帮我实现登录功能"}]}}
{"type":"message","id":"m2","parentId":"m1","message":{"role":"assistant","content":[{"type":"text","text":"好的,我用 JWT 来实现"}]}}

The session directory can also be customized; the priority from high to low is: the --session-dir argument, the environment variablePI_CODING_AGENT_SESSION_DIR, and the one in settings.jsonsessionDir。


Session Options at Startup

Control session behavior at startup via command-line arguments:

$ pi -c
Resumed session abc123-def456 (42 messages, model claude-sonnet-4-5)

$ pi -r
┌ 选择要恢复的会话:
│ > abc123  快速审查      3 分钟前
│   def456  重构认证模块  2 小时前
└

$ pi --session ~/.pi/agent/sessions/--Users-example-projects-example-demo--/2026-08-30T09-15-04-000Z_019fbb5d-7a2e-7f31-b5c4-1a2b3c4d5e6f.jsonl
Resumed session 019fbb5d-7a2e-7f31-b5c4-1a2b3c4d5e6f

$ pi --session abc123
Resumed session abc123-def456

$ pi --fork abc123
Forked to session 9f2e7a01-5c48

$ pi --name "重构认证模块"
Session renamed: 重构认证模块

$ pi --no-session
Temporary session (will not be saved)

Session Management Commands

Once in interactive mode, the following commands cover the day-to-day management of sessions.

CommandFunctionUse Case
/resumeBrowse and resume historical sessionsSwitch to a previous conversation and continue working
/newStart a new sessionStart a brand-new task unrelated to history
/name <name>Set the session nameGive the session an easy-to-remember name
/sessionView session informationView file path, message count, token usage, and cost
/treeOpen the session tree browserJump to any node in the conversation tree
/forkFork sessionCreate a new session from a previous user message
/cloneClone sessionCopy the current active branch to a new session file
/export <file>Export as HTML or JSONL fileLocal archiving or offline sharing
/shareShare sessionUpload as a GitHub Gist, generating a shareable link

/resume Session Selector

Entering /resume or starting with pi -r opens the session selector for the current project.

You can type characters directly in the list to filter sessions; the remaining operation keys are as follows:

ActionKeyDescription
Filter sessionsType characters directlyFilter the current project's session list in real time based on input
Toggle path displayCtrl+PShow or hide the working directory path of sessions
Toggle sortingCtrl+SSwitch between sorting methods
Show only named sessionsCtrl+NFilter to sessions that have been named
RenameCtrl+RModify the name of the selected session
DeleteCtrl+DConfirmed before execution; if the system has the trash command, moves to the recycle bin instead of direct deletion.

Session Tree (/tree)

This is Pi Agent's most unique feature—sessions are stored as a tree structure, and you can fork at any historical node.

Tree Structure

The following is a typical session tree structure:

├─ user: "帮我实现一个登录功能..."
│  └─ assistant: "好的,我来实现..."
│     ├─ user: "用 JWT 方案..."
│     │  └─ assistant: "使用 JWT 实现..."
│     │     └─ user: "测试通过了"  ← 当前活跃分支
│     └─ user: "还是用 Session 方案..."
│        └─ assistant: "使用 Session 实现..."

In this example, starting from the same origin, you explored two approaches, JWT and Session, and the conversations for each approach are fully preserved.

Tree Browser Operations

After opening /tree, use the following keys to move and select in the tree.

ActionShortcutDescription
Move up/down↑/↓Move the cursor among visible entries
Page up/down←/→Page up / page down
Collapse/ExpandCtrl+←/Ctrl+→ or Alt+←/Alt+→Collapse/expand branch segments or jump
Set labelShift+LSet a label for the selected node
Toggle timestampShift+TShow/hide timestamps on entry labels (labels are set with Shift+L)
Confirm selectionEnterSelect the current node
CancelEscape / Ctrl+CExit the tree browser
Toggle filter modeCtrl+OCycle through filter modes (only effective within the /tree browser)

Filter Modes

Filter modes determine which entries are shown in the tree browser; press Ctrl+O to cycle through them.

ModeDisplayed Content
defaultDefault view, collapses tool call details
no-toolsHide all tool calls and results
user-onlyShow only user messages
labeled-onlyShow only labeled entries
allShow all entries

Selecting a user message fills its text into the editor, allowing you to edit and resubmit it, creating a new branch.

Selecting an AI reply or tool call jumps directly to that position, allowing you to continue the conversation from there.


Differences Between /tree, /fork, and /clone

All three can return to a historical position; the difference lies in whether a new session file is created and how much of the conversation can be seen.

CommandOutputViewTypical UseBranch SummaryOne-sentence memory
/treeSame session fileFull conversation treeExplore alternative approaches within the same sessionOptional summaryManage multiple ideas together for easy comparison
/forkNew session fileShow only user messagesStart a new session from an earlier promptNoneRestart from a historical point, completely independent
/cloneNew session fileCurrent active branchCopy the current work and continueNoneMake a copy before continuing, keeping a fallback

Branch Summary

When you jump from one branch to another via /tree, Pi Agent can generate a summary of the abandoned branch for you.

This summary is attached to the new location, so you know what the previous branch did:

ModeBehaviorApplicable Scenario
No summary generatedJump directly without retaining any information about the abandoned branchThe abandoned attempt has no value worth retaining
Default summaryUse the default prompt to let the AI summarize the abandoned branchOnly want a rough idea of what was done before
Custom summarySpecify the focus, and the AI summarizes according to your needsNeed to take away specific conclusions, such as pitfalls encountered

You can~/.pi/agent/settings.jsoncontrol the summary behavior in:

Example

{
  "branchSummary": {
    "reserveTokens": 16384,
    "skipPrompt": false
  }
}

SettingskipPromptSet to true to skip the "whether to generate summary" prompt when navigating with /tree.

After skipping the prompt, no summary is generated by default, and it jumps directly to the target position.


Export and Share Sessions

Sessions can be exported as local files, or uploaded directly to generate a share link.

Export as HTML

Exporting generates a single-file page that can be opened directly in a browser, suitable for offline viewing.

# 导出到默认位置
/export

# 导出到指定文件
/export ~/Desktop/my-session.html

Share as GitHub Gist

When you don't want to upload files, use the /share command to generate an online link.

/share

After execution, a private GitHub Gist will be created and a shareable HTML link will be generated.

Command-Line Export

Existing sessions can be exported without entering interactive mode.

$ pi --export session.jsonl output.html
Exported to output.html (128 KB)

If you work on an open-source project and want to publish sessions for research purposes, you can check outpi-share-hfa tool that can publish sessions to Hugging Face datasets.

Other extensions