Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/badlogic/pi-mono/llms.txt

Use this file to discover all available pages before exploring further.

The SessionManager class handles session persistence, history tracking, and session tree operations. Each session is stored as an append-only log of entries.

Import

import { SessionManager } from "@mariozechner/pi-coding-agent";

Constructor

new SessionManager(sessionDir?: string)
sessionDir
string
Directory for session storage. Default: ~/.pi/sessions/

Methods

createSession

Create a new session.
createSession(cwd: string, options?: NewSessionOptions): SessionInfo
cwd
string
required
Working directory for the session
options
NewSessionOptions
SessionInfo
object

loadSession

Load an existing session.
loadSession(sessionId: string): SessionInfo
sessionId
string
required
The session ID to load

appendEntry

Append an entry to the current session.
appendEntry(entry: SessionEntry): void
entry
SessionEntry
required
Entry to append (message, model change, compaction, etc.)
Entry Types:
  • SessionMessageEntry - Agent message
  • ModelChangeEntry - Model switch
  • ThinkingLevelChangeEntry - Thinking level change
  • CompactionEntry - Context compaction
  • BranchSummaryEntry - Branch summary
  • CustomEntry - Extension data (not sent to LLM)
  • CustomMessageEntry - Extension message (sent to LLM)

readEntries

Read entries from a specific point in the session.
readEntries(fromId?: string): SessionEntry[]
fromId
string
Entry ID to start from. If omitted, returns all entries.
Returns entries in chronological order with proper parent-child relationships.

getTree

Get the session tree structure.
getTree(): SessionTreeNode[]
Returns a defensive copy of the session tree showing the branching structure.

listSessions

List all available sessions.
listSessions(): SessionInfo[]
Returns metadata for all sessions, sorted by creation time.

deleteSession

Delete a session.
deleteSession(sessionId: string): void
sessionId
string
required
The session ID to delete

Session Context Building

buildSessionContext

Build LLM context from session entries.
buildSessionContext(
  entries: SessionEntry[],
  systemPrompt: string,
  currentModel: Model
): SessionContext
entries
SessionEntry[]
required
Session entries to process
systemPrompt
string
required
System prompt for the agent
currentModel
Model
required
Current model (for model-specific formatting)
SessionContext
object

Entry Types

SessionMessageEntry

Stores an agent message (user, assistant, or tool result).
interface SessionMessageEntry {
  type: "message";
  id: string;
  parentId: string | null;
  timestamp: string;
  message: AgentMessage;
}

CompactionEntry

Records a context compaction operation.
interface CompactionEntry<T = unknown> {
  type: "compaction";
  id: string;
  parentId: string | null;
  timestamp: string;
  summary: string;
  firstKeptEntryId: string;
  tokensBefore: number;
  details?: T;           // Extension data
  fromHook?: boolean;    // True if from extension
}

CustomEntry

Extension-specific data (not sent to LLM).
interface CustomEntry<T = unknown> {
  type: "custom";
  id: string;
  parentId: string | null;
  timestamp: string;
  customType: string;    // Extension identifier
  data?: T;
}

CustomMessageEntry

Extension message sent to LLM.
interface CustomMessageEntry<T = unknown> {
  type: "custom_message";
  id: string;
  parentId: string | null;
  timestamp: string;
  customType: string;
  content: string | (TextContent | ImageContent)[];
  details?: T;           // Extension data (not sent to LLM)
  display: boolean;      // Show in TUI?
}

Example

import { SessionManager, buildSessionContext } from "@mariozechner/pi-coding-agent";

const manager = new SessionManager();

// Create a new session
const session = manager.createSession(process.cwd());
console.log(`Session ID: ${session.id}`);

// Append a message entry
manager.appendEntry({
  type: "message",
  id: randomUUID(),
  parentId: null,
  timestamp: new Date().toISOString(),
  message: {
    role: "user",
    content: "Hello, agent!",
    timestamp: Date.now(),
  },
});

// Read all entries
const entries = manager.readEntries();

// Build context for LLM
const context = buildSessionContext(
  entries,
  "You are a helpful coding assistant.",
  model
);

// List all sessions
const sessions = manager.listSessions();
console.log(`Total sessions: ${sessions.length}`);

Session File Format

Sessions are stored as newline-delimited JSON (NDJSON) in ~/.pi/sessions/:
~/.pi/sessions/
  ├── abc123.session        # Session file
  ├── def456.session
  └── ...
Each line in a session file is a JSON object:
{"type":"session","version":3,"id":"abc123","timestamp":"2026-02-28T10:00:00Z","cwd":"/path"}
{"type":"message","id":"msg1","parentId":null,"timestamp":"...","message":{...}}
{"type":"compaction","id":"cmp1","parentId":"msg5","timestamp":"...","summary":"..."}