Refresh every reference against https://pi.dev/docs/latest and the four ecosystem package pages, cross-checked with the published npm READMEs. New reference pages (docs added them; the site nav does not surface them): - environment-variables.md: PI_* process config, the PI_CODING_AGENT child marker, and the session variables injected into the bash tool. The old env-var list lived in usage.md, which no longer has that section. - llama-cpp.md: llama.cpp router setup, /login llama.cpp, /llama. Notable upstream drift now reflected: - SDK: ModelRuntime.create() replaces AuthStorage + ModelRegistry; createAgentSessionServices/FromServices runtime factory; resolveCliModel and resolveModelScopeWithDiagnostics. - Providers: full 30+ API-key table with env vars and auth.json keys; xAI/OpenRouter/Radius subscription logins; provider-scoped env blocks in credentials; models-store.json; Bedrock proxy variables. - New thinking level "max" across settings, CLI, RPC, thinkingLevelMap, and the themes' thinkingMax token. - New commands: /trust, /import, /llama; pi update --all/--models/--self; pi config; .pi/SYSTEM.md and APPEND_SYSTEM.md; trust.json. - RPC: get_entries (with since cursor), get_tree, get_available_thinking_levels, agent_settled, bash_execution_update, summarization_retry_*, and the extension UI sub-protocol. - Extensions: expanded from a summary to the real API surface, including session-replacement semantics and footguns, withFileMutationQueue, terminate, prepareArguments, and dynamic tool loading. - Session format: retainedTail checkpoints and buildContextEntries(). - Packages: pi-web-access gained source_check and nine search providers and dropped code_search, which the old reference still documented; pi-mcp-adapter gained six config locations, lazy-keep-alive, the output guard, and MCP_STATUS_EVENT; pi-subagents gained the watchdog, profiles, modelScope, per-agent memory, the fleet inspector, and RPC v1. Also fixes escape sequences that had been corrupted in earlier versions: the Git Bash path in windows.md, the shellCommandPrefix JSON in shell-aliases.md, and the CSI-u sequences in tmux.md and terminal-setup.md. Bumps metadata.version to 1.2.
5.8 KiB
Session File Format
Source: https://pi.dev/docs/latest/session-format
Sessions are JSONL files. Each line is a JSON object with a type. Entries form a tree through id / parentId, enabling in-place branching without new files.
Location
~/.pi/agent/sessions/--<path>--/<timestamp>_<uuid>.jsonl
<path> is the working directory with / replaced by -. Delete sessions by removing the .jsonl file, or from /resume with Ctrl+D (Pi uses the trash CLI when available).
Versions
- v1: linear entry sequence (legacy, auto-migrated on load)
- v2: tree structure with
id/parentId - v3: renamed the
hookMessagerole tocustom(extensions unification)
Existing sessions auto-migrate to v3 when loaded.
Content Blocks
TextContent { type: "text", text }, ImageContent { type: "image", data (base64), mimeType }, ThinkingContent { type: "thinking", thinking }, ToolCall { type: "toolCall", id, name, arguments }.
Message Types
Base (from pi-ai):
UserMessage—role: "user",contentstring or(Text|Image)[],timestamp(Unix ms)AssistantMessage—content: (Text|Thinking|ToolCall)[],api,provider,model,usage,stopReason∈stop/length/toolUse/error/aborted, optionalerrorMessage,timestampToolResultMessage—toolCallId,toolName,content: (Text|Image)[], optionaldetails, optionalusage(nested LLM work performed by the tool),isError,timestampUsage—input,output,cacheRead,cacheWrite,totalTokens, andcostwith the same four fields plustotal
Extended (from pi-coding-agent):
BashExecutionMessage—command,output,exitCode,cancelled,truncated, optionalfullOutputPath, optionalexcludeFromContext(true for!!)CustomMessage—customType,content,display, optionaldetailsBranchSummaryMessage—summary,fromIdCompactionSummaryMessage—summary,tokensBefore
AgentMessage is the union of all seven.
Entry Types
All entries except the header extend SessionEntryBase { type, id (8-char hex), parentId (null for the first entry), timestamp (ISO string) }.
session— header, first line, metadata only (noid/parentId):version,id,timestamp,cwd, plusparentSessionfor sessions created via/fork,/clone, ornewSession({ parentSession })message— wraps anAgentMessageinmessagemodel_change—provider,modelIdthinking_level_change—thinkingLevelcompaction—summary,tokensBefore, plus optionalusage,details,fromHook,firstKeptEntryId(old format), andretainedTailbranch_summary—summary,fromId, plus optionalusage,details,fromHookcustom—customType,data; extension state, not in LLM context. Renderable in the transcript viapi.registerEntryRenderer(customType, renderer)custom_message—customType,content,display, optionaldetails; extension-injected and in LLM contextlabel—targetId,label(setlabeltoundefinedto clear)session_info—name; set via/name,--name/-n, orpi.setSessionName(). Shown in/resumeinstead of the first message
retainedTail is a materialized AgentMessage[] kept after compaction. Newer harness-generated compactions include it so context rebuilds from that checkpoint without walking entries before the compaction. It is optional only for backward compatibility with sessions that store only firstKeptEntryId.
Context Building
buildContextEntries() walks from the current leaf to the root and produces the active entry list honoring compaction:
- Collect all entries on the path.
- If a
CompactionEntryis on the path: include the compaction entry first; ifretainedTailis present it acts as a self-contained checkpoint and entries after the compaction are included; otherwise include entries fromfirstKeptEntryIdto the compaction, then entries after it. - Preserve non-message entries in the selected range so interactive mode can render them.
buildSessionContext() builds the LLM message list on top of that: it extracts the current model and thinking level from the full path, then converts entries — message → stored AgentMessage, compaction → compactionSummary plus retainedTail when present, branch_summary → branchSummary, custom_message → CustomMessage, custom → no context message.
SessionManager API
Static creation: create(cwd, sessionDir?), open(path, sessionDir?), continueRecent(cwd, sessionDir?), inMemory(cwd?), forkFrom(sourcePath, targetCwd, sessionDir?).
Static listing: list(cwd, sessionDir?, onProgress?), listAll(onProgress?).
Session management: newSession({ parentSession? }), setSessionFile(path), createBranchedSession(leafId).
Appending (each returns an entry ID): appendMessage, appendThinkingLevelChange, appendModelChange, appendCompaction(summary, firstKeptEntryId, tokensBefore, details?, fromHook?), appendCustomEntry(customType, data?), appendSessionInfo(name), appendCustomMessageEntry(customType, content, display, details?), appendLabelChange(targetId, label).
Tree navigation: getLeafId, getLeafEntry, getEntry, getBranch(fromId?), getTree, getChildren, getLabel, branch(entryId), resetLeaf(), branchWithSummary(entryId, summary, details?, fromHook?).
Context and info: buildContextEntries, buildSessionContext, getEntries, getHeader, getSessionName, getCwd, getSessionDir, getSessionId, getSessionFile (undefined in memory), isPersisted.
Parsing
Read the file line by line and switch on entry.type; treat entry.version ?? 1 on the header, and ignore unknown types for forward compatibility. For TypeScript definitions inspect node_modules/@earendil-works/pi-coding-agent/dist/ and node_modules/@earendil-works/pi-ai/dist/.