# Session File Format

Sessions are stored as JSONL (JSON Lines) files. Each line is a JSON object with a `type` field. Session entries form a tree structure via `id`/`parentId` fields, enabling in-place branching without creating new files.

This document describes the CLI session files written by `SessionManager` in `packages/coding-agent`. The agent harness in `packages/agent` keeps its own durable session data (header version 4, with compaction checkpoints that embed retained context) and the CBOR `pi-protocol` server/client stack speaks protocol v8. Those formats are separate from the CLI JSONL described here and are not interchangeable with it.

## File Location

```
~/.senpi/agent/sessions/--<path>--/<timestamp>_<session-id>.jsonl
```

By default, `<session-id>` is a UUID. Callers can supply a custom ID through the SDK or `--session-id`. For `<path>`, Senpi removes the leading path separator and replaces `/`, `\\`, and `:` with `-`.

## Deleting Sessions

Sessions can be removed by deleting their `.jsonl` files under `~/.senpi/agent/sessions/`.

Senpi also supports deleting sessions interactively from `/resume` (select a session and press `Ctrl+D`, then confirm). When available, senpi uses the `trash` CLI to avoid permanent deletion.

## Session Version

Sessions have a version field in the header:

- **Version 1**: Linear entry sequence (legacy, auto-migrated on load)
- **Version 2**: Tree structure with `id`/`parentId` linking
- **Version 3**: Renamed `hookMessage` role to `custom` (extensions unification)

Existing sessions are automatically migrated to the current version (v3) when loaded.

## Source Files

Source on GitHub ([pi](https://github.com/earendil-works/pi)):
- [`packages/coding-agent/src/core/session-manager.ts`](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/core/session-manager.ts) - Session entry types and SessionManager
- [`packages/coding-agent/src/core/messages.ts`](https://github.com/earendil-works/pi/blob/main/packages/coding-agent/src/core/messages.ts) - Extended message types (BashExecutionMessage, CustomMessage, etc.)
- [`packages/ai/src/types.ts`](https://github.com/earendil-works/pi/blob/main/packages/ai/src/types.ts) - Base message types (UserMessage, AssistantMessage, ToolResultMessage)
- [`packages/agent/src/types.ts`](https://github.com/earendil-works/pi/blob/main/packages/agent/src/types.ts) - AgentMessage union type

For TypeScript definitions in your project, inspect `node_modules/@code-yeongyu/senpi/dist/` and `node_modules/@earendil-works/pi-ai/dist/`.

## Message Types

Session entries contain `AgentMessage` objects. Understanding these types is essential for parsing sessions and writing extensions.

### Content Blocks

Messages contain arrays of typed content blocks:

```typescript
interface TextContent {
  type: "text";
  text: string;
  textSignature?: string;
}

interface ImageContent {
  type: "image";
  data: string;      // base64 encoded
  mimeType: string;  // e.g., "image/jpeg", "image/png"
}

interface ThinkingContent {
  type: "thinking";
  thinking: string;
  startedAt?: number;  // Unix epoch milliseconds
  endedAt?: number;    // Unix epoch milliseconds
  thinkingSignature?: string;
  redacted?: boolean;
}

`startedAt` and `endedAt` are optional epoch milliseconds stamped by the agent loop at stream-event receipt on a best-effort basis. They are absent on pre-feature sessions and on messages not produced through the agent loop. Renderers must treat their absence as "no timing available".

interface ToolCall {
  type: "toolCall";
  id: string;
  name: string;
  arguments: Record<string, any>;
  thoughtSignature?: string;
  namespace?: string;
}
```

### Base Message Types (from pi-ai)

```typescript
interface UserMessage {
  role: "user";
  content: string | (TextContent | ImageContent)[];
  timestamp: number;  // Unix ms
}
```

A `message` entry holding a user message the session admitted through `prompt`, `steer` or `followUp` (including an extension's `sendUserMessage`) also carries `inputSource` on the entry itself: `"interactive"`, `"rpc"` or `"extension"`, the same value the message's `input` event reported. It is stored on the entry and never on the message, so it is not part of any provider request. Queued input restored after a host restart keeps the source its durable record carries. Input whose record has no source, input requeued by a session move, and edited input have no `inputSource`; treat an absent value as unknown origin, never as typed input.

**Call keys (senpi#5374).** Every `toolCall` part of an assistant `message` entry carries `runtimeItemKey`, the opaque key of its call: `blk:<messageId>:<contentIndex>` for a block, or `exe:<uuid>` for a call whose execution started before its block streamed. A `toolResult` `message` entry carries `runtimeItemKey` on the entry itself when its `toolCallId` names exactly one toolCall part of the latest assistant entry before it that no earlier result closed. Every other toolResult entry carries `callUnknown: true` instead and no key: an id that assistant message holds on more than one part, a call an earlier result already closed, or an id with no keyed part. It never carries a guessed key, and an entry written since senpi#5374 never carries neither. Both are session-file data only: loading takes them out of the entries into a side table, so they never reach an in-memory message, a provider request or a legacy RPC answer, and every rewrite of the file (migration, branch) writes them back. A key is a string written once, never derived again from a stored id: a branch, a fork, a compaction, a migration and an export copy each key as it is, so no two toolCall parts of one session share a key, and a later message gets a fresh `messageId`. A reload reuses each persisted key. Sessions written before senpi#5374 have neither field and load unchanged with no migration; nothing mints a key for their parts, at load or on a rewrite, and a result appended to such a session for one of those calls carries `callUnknown: true`. A reader that does not know the fields ignores them: every session reader since v0.12.14 parses a line with plain `JSON.parse`.

```typescript

interface AssistantMessage {
  role: "assistant";
  content: (TextContent | ThinkingContent | ToolCall)[];
  api: string;
  provider: string;
  model: string;
  responseModel?: string;
  responseId?: string;
  providerThinkingLevel?: string;
  diagnostics?: AssistantMessageDiagnostic[];
  usage: Usage;
  stopReason: "pending" | "stop" | "length" | "toolUse" | "error" | "aborted" | "deferred";
  deferred?: DeferredHandle;
  errorMessage?: string;
  rawStopReason?: string;
  endTurn?: boolean;
  timestamp: number;
}

interface ToolResultMessage {
  role: "toolResult";
  toolCallId: string;
  toolName: string;
  content: (TextContent | ImageContent)[];
  details?: any;      // Tool-specific metadata
  usage?: Usage;      // Nested LLM work performed by the tool
  addedToolNames?: string[];
  isError: boolean;
  timestamp: number;
}

interface Usage {
  input: number;
  output: number;
  cacheRead: number;
  cacheWrite: number;
  cacheWrite1h?: number;
  reasoning?: number;
  totalTokens: number;
  cost: {
    input: number;
    output: number;
    cacheRead: number;
    cacheWrite: number;
    total: number;
  };
}
```

`"pending"` is reserved for partial messages in streaming events. Terminal events replace it with a completion reason before Senpi persists the assistant message, so `"pending"` should never appear in session JSONL. `"deferred"` is a terminal reason for a provider response that will complete later; its `deferred` handle contains the provider data needed to retrieve that response.

### Extended Message Types (from @code-yeongyu/senpi)

```typescript
interface BashExecutionMessage {
  role: "bashExecution";
  command: string;
  output: string;
  exitCode: number | undefined;
  cancelled: boolean;
  truncated: boolean;
  fullOutputPath?: string;
  excludeFromContext?: boolean;  // true for !! prefix commands
  timestamp: number;
}

interface CustomMessage {
  role: "custom";
  customType: string;            // Extension identifier
  content: string | (TextContent | ImageContent)[];
  display: boolean;              // Show in TUI
  details?: any;                 // Extension-specific metadata
  timestamp: number;
}

interface BranchSummaryMessage {
  role: "branchSummary";
  summary: string;
  fromId: string | null;         // Previous leaf whose abandoned path was summarized
  timestamp: number;
}

interface CompactionSummaryMessage {
  role: "compactionSummary";
  summary: string;
  tokensBefore: number;
  timestamp: number;
}
```

### AgentMessage Union

```typescript
type AgentMessage =
  | UserMessage
  | AssistantMessage
  | ToolResultMessage
  | BashExecutionMessage
  | CustomMessage
  | BranchSummaryMessage
  | CompactionSummaryMessage;
```

## Entry Base

All entries (except `SessionHeader`) extend `SessionEntryBase`:

```typescript
interface SessionEntryBase {
  type: string;
  id: string;           // Usually an 8-char hex ID; may fall back to a full UUID
  parentId: string | null;  // Parent entry ID (null for a root entry)
  timestamp: string;    // ISO timestamp
}
```

## Entry Types

### SessionHeader

First line of the file. Metadata only, not part of the tree (no `id`/`parentId`).

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

For sessions with a parent (created via `/fork`, `/clone`, or `newSession({ parentSession })`):

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

Execution children additionally store `spawnedBy: { parentSessionId, rootSessionId,
taskId }` in their header. Only `spawnedBy` establishes lifecycle role `child`;
an ordinary fork with `parentSession` remains a root.

Lifecycle persistence uses custom entries on the session that owes the work:

- `session-lifecycle`: the wire snapshot plus session identity, sealed-epoch and
  revision high-water marks, open synthetic attention occurrences, consuming run
  identity, and any unsealed self-settle intent. It is appended before publication.
- `work-custody`: obligation identity/key/kind and `open`, `queued`, `consumed`,
  `settled`, `held`, `cancelled`, or `passive` state. Queued records retain a delivery
  ticket and payload; consumed records name the run and transcript entry; held
  records name the durable notice. The custom message itself carries `details.ticketId`.
- `child-lifecycle`: the runner's latest task report, fenced by `runEpoch` and
  `generation`, persisted before changing the parent's lifecycle.

- `interrupted-run`: `{ ticketId, runId, status: "INTERRUPTED", reason: "host_restart", at }`,
  appended on restore for a delivery its run had consumed when the host stopped. Each
  tool call of that run without a result also gets a synthetic `toolResult` with
  `isError: true` and `details.interrupted.reason: "host_restart"`; the tool is not re-run.

These records are durable even before a first conversation message; a file that holds
only them (and setup entries) is still discarded when the session closes unused. Reopening
holds the restore barrier until producers rehydrate and custody recovery completes. A
restored wake source whose producer does not publish again by then is retired.
A delivery that leaves the queue unconsumed (cleared, or left queued by an abort for the
person's next turn) is cancelled or turns passive, so it is never redelivered.
Consumed but interrupted work is not redelivered; it requires human continuation
(or remains held unattended). Unsealed self-settle requests are invalidated on
restart, while a sealed decision and completion identity remain unchanged.

### SessionMessageEntry

A message in the conversation. The `message` field contains an `AgentMessage`.

```json
{"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}}
{"type":"message","id":"c3d4e5f6","parentId":"b2c3d4e5","timestamp":"2024-12-03T14:00:03.000Z","message":{"role":"toolResult","toolCallId":"call_123","toolName":"bash","content":[{"type":"text","text":"output"}],"isError":false,"timestamp":1733234403000}}
```

### ModelChangeEntry

Emitted when the user switches models mid-session. The latest entry is the selected model, which may be a [virtual model](virtual-models.md); assistant messages then name the physical model that answered.

```json
{"type":"model_change","id":"d4e5f6g7","parentId":"c3d4e5f6","timestamp":"2024-12-03T14:05:00.000Z","provider":"openai","modelId":"gpt-4o","originalProvider":"anthropic","originalModelId":"claude-sonnet-4-5","source":"picker","actor":"model-selector"}
```

`source` says what made the switch: `command` (a typed `/model`), `picker` (the model or favorites picker), `cycle` (the favorites cycle key), `control` (a terminal's control endpoint), `rpc` (RPC `set_model`, `cycle_model` and `set_fast_mode`; `actor` names the latter two), `app-server` (retained for historical entries from the retired compatibility mode), `extension` (`actor` is the extension path), `provider-login`, `fallback`, `fallback-revert`, `held-switch` (a switch held until compaction made room; `actor` names what first asked for it), `restore`, or `sdk` (an SDK caller that named none). `actor` says who issued it where that is known. `duringTurn: true` marks a switch that landed while a turn was streaming; the terminal shows those as a transcript row. Entries written before these fields existed omit them. A `thinking_level_change` written because a switch re-applied the model's level carries the same `triggerSource` and `triggerActor`.

### ThinkingLevelChangeEntry

Emitted when the user changes the thinking/reasoning level.

```json
{"type":"thinking_level_change","id":"e5f6g7h8","parentId":"d4e5f6g7","timestamp":"2024-12-03T14:06:00.000Z","thinkingLevel":"high"}
```

### CompactionEntry

Created when context is compacted. Stores a summary of earlier messages.

```json
{"type":"compaction","id":"f6g7h8i9","parentId":"e5f6g7h8","timestamp":"2024-12-03T14:10:00.000Z","summary":"User discussed X, Y, Z...","firstKeptEntryId":"c3d4e5f6","tokensBefore":50000}
```

`firstKeptEntryId` is required. It identifies the first entry retained from before the compaction entry. When rebuilding context, Pi replaces older summarized entries with the compaction summary and keeps the range beginning at this entry. A retain-none compaction (`appendCompaction(summary, null, tokensBefore)`) stores its own ID in this field, so no preceding entries are retained.

Optional fields:
- `usage`: LLM usage from generating the summary; included in session token and cost totals
- `details`: Implementation-specific data (e.g., `{ readFiles: string[], modifiedFiles: string[] }` for default, or custom data for extensions)
- `fromHook`: `true` if generated by an extension, `false`/`undefined` if senpi-generated (legacy field name)

### ContextEditEntry

Append-only edit of one earlier context-producing entry. It changes only future model context; the target entry and its metadata stay unchanged in raw history, UI, exports, and session accounting.

```json
{"type":"context_edit","id":"g6h7i8j9","parentId":"f6g7h8i9","timestamp":"2024-12-03T14:11:00.000Z","targetId":"c3d4e5f6","replacement":null}
```

Targets may be user, assistant, tool-result, or custom-message entries. `replacement: null` omits the target from model context. A non-null `replacement` replaces only the target message content; string replacements for assistant and tool-result entries are normalized to one text block. If several edits target the same entry, the latest edit on the active branch wins. Edits are branch-relative: navigating to a point before the edit reveals the target's original contribution again. `ContextEditEntry` is part of the exported `SessionEntry` union, so exhaustive entry switches must handle `context_edit`.

### BranchSummaryEntry

Created when switching branches via `/tree` with an LLM generated summary of the left branch up to the common ancestor. Captures context from the abandoned path.

```json
{"type":"branch_summary","id":"g7h8i9j0","parentId":"a1b2c3d4","timestamp":"2024-12-03T14:15:00.000Z","fromId":"f6g7h8i9","summary":"Branch explored approach A..."}
```

`parentId` is the entry from which the new branch continues. `fromId` is the previous leaf whose abandoned path was summarized.

Optional fields:
- `usage`: LLM usage from generating the summary; included in session token and cost totals
- `details`: File tracking data (`{ readFiles: string[], modifiedFiles: string[] }`) for default, or custom data for extensions
- `fromHook`: `true` if generated by an extension, `false`/`undefined` if senpi-generated (legacy field name)

### CustomEntry

Extension state persistence. Does NOT participate in LLM context.

```json
{"type":"custom","id":"h8i9j0k1","parentId":"g7h8i9j0","timestamp":"2024-12-03T14:20:00.000Z","customType":"my-extension","data":{"count":42}}
```

Optional field: `startupBookkeeping: true` marks an entry its extension wrote at session start without any user action (`pi.appendEntry(customType, data, { startupBookkeeping: true })`). A session file this process created that holds only setup entries and such marked entries is removed when the session closes without a conversation; an unmarked custom entry keeps the file.

Use `customType` to identify your extension's entries on reload. Interactive mode can render custom entries via `pi.registerEntryRenderer(customType, renderer)`, but they still do not participate in LLM context.

[Virtual model](virtual-models.md) router state is stored as custom entries with `customType` `pi.virtual-model-state` and `data` `{ provider, modelId, state }`.

#### Goal and engine self-stop entries

These custom entries are persisted in the session and delivered to RPC clients as `entry_appended`. They do not enter model context. Existing `engine-turn-limit`, `ttsr-loop-stopped`, and notices remain unchanged.

- `goal-continuation-stopped`: `data` is `{ goalId: string, reason: "stale" | "repetition" | "cap" | "no-progress" | "length-exhausted" | "context-overflow", consecutiveContinuations: number, unattendedContinuations: number, noProgressContinuations: number, at: number }`. `no-progress` (omo#10280) replaced `unattended`, which older sessions may still contain; `unattendedContinuations` counts deliveries since the last human input and no longer stops anything. Every active-goal denial except `not-eligible` and `single-flight` records one decision, not one entry per evaluation probe. Blocking guards still block; stale leaves the goal active but commits the remaining measured time and closes its measurement window. An accepted user message or `/goal resume` resets the stop and continuation streak and opens accounting again. The stop entry remains historical; a subsequent continuation can stop again.
- `engine-paused`: `data` is `{ reason: "repetition" | "goal-repeat" | "cap-per-message" | "cap-per-minute" | "goal-stale", rule?: string, customType?: string, count?: number, at: number }`. The engine limit maps `per-user-input` to `cap-per-message` (`count` is `sinceUserInput`) and `tool-free-rate` to `cap-per-minute` (`count` is `toolFreeInWindow`). TTSR uses `repetition` and names the rule when it refuses another correction or its one-shot repetitive-turns correction reaches final idle without another turn starting. Goal output repetition uses `goal-repeat`; stale uses `goal-stale`, with the consecutive-continuation count and `customType: "goal-continuation"`.

`at` is Unix epoch milliseconds. Consumers can use these entries instead of parsing notice wording, and replay them from session history after reopen.

Stale-stopped goals stay stopped when reopened. A notice at the stale stop and on each session open tells the user to send a message or run `/goal resume` to continue; rendering and extension reloads do not repeat the notice.

Goal usage measures work while the goal's accounting window is open. Non-user-input turns, including extension `sendUserMessage` and `sendMessage({ triggerTurn: true })` deliveries, add neither tokens nor time to a stale-stopped goal, just as later turns do not accrue usage for a user-paused or completed goal. The same turns count assistant input/output tokens and elapsed time while the goal is active with an open window. Usage is display-only; it does not impose a budget limit.

The footer shows `Goal stopped: no progress (send a message or /goal resume)` without a pursuit timer, and `/goal` identifies the stop while retaining committed usage totals. The persisted goal keeps `status: "active"` plus `continuationStoppedAt` so accepted input and `/goal resume` retain their existing behavior. Goal-tool snapshots instead report `status: "paused"` and include `continuationStoppedAt` for the stopped label; their cards use the paused glyph and styling. Active, user-paused, blocked, and completed goals otherwise retain their displays.

In the persisted goal state, `lastStartedAt` is the last usage checkpoint, in Unix epoch seconds, not the start of the entire run. Clients displaying live elapsed time use committed `timeUsedSeconds` plus the nonnegative time since `lastStartedAt`. When `lastStartedAt` is absent, including after a stale stop, display only committed `timeUsedSeconds`.

Model-facing goal tool JSON additionally includes `continuation: { status: "stale_stopped", message: string }` for a stale-stopped goal. The message explains that progress was stale and the goal resumes when the user sends a message or runs `/goal resume`. This object is absent for ordinary active, user-paused, and completed goals; it is not part of the stored goal or UI snapshot.

### CustomMessageEntry

Extension-injected messages that DO participate in LLM context.

```json
{"type":"custom_message","id":"i9j0k1l2","parentId":"h8i9j0k1","timestamp":"2024-12-03T14:25:00.000Z","customType":"my-extension","content":"Injected context...","display":true}
```

Fields:
- `content`: String or `(TextContent | ImageContent)[]` (same as UserMessage)
- `display`: `true` = show in TUI with distinct styling, `false` = hidden
- `details`: Optional extension-specific metadata (not sent to LLM)

### LabelEntry

User-defined bookmark/marker on an entry.

```json
{"type":"label","id":"j0k1l2m3","parentId":"i9j0k1l2","timestamp":"2024-12-03T14:30:00.000Z","targetId":"a1b2c3d4","label":"checkpoint-1"}
```

Set `label` to `undefined` to clear a label.

### SessionInfoEntry

Session metadata (e.g., user-defined display name). Set via `/rename` or `/name`, `--name` / `-n`, or `pi.setSessionName()` in extensions.

```json
{"type":"session_info","id":"k1l2m3n4","parentId":"j0k1l2m3","timestamp":"2024-12-03T14:35:00.000Z","name":"Refactor auth module"}
```

The session name is displayed in the session selector (`/resume`) instead of the first message when set.

## Tree Structure

Entries normally form one tree, but navigation APIs can create multiple roots:
- A root entry has `parentId: null`; the first entry is initially the root
- Each non-root entry points to its parent via `parentId`
- Branching creates new children from an earlier entry
- The "leaf" is the current position in the tree
- Calling `resetLeaf()` or `branchWithSummary(null, ...)` allows a later entry to become another root

```
[user msg] ─── [assistant] ─── [user msg] ─── [assistant] ─┬─ [user msg] ← current leaf
                                                            │
                                                            └─ [branch_summary] ─── [user msg] ← alternate branch
```

## Context Building

`buildContextEntries()` walks from the current leaf to the root, producing the active entry list while honoring compaction:

1. Collects all entries on the path
2. If one or more `CompactionEntry` values are on the path, uses the latest one:
   - Includes the compaction entry first
   - Includes entries from `firstKeptEntryId` up to, but not including, the compaction entry
   - Includes entries after the compaction entry
3. Preserves non-message entries in the selected range so interactive mode can render them

`buildSessionContext()` builds on that entry list to produce the message list for the LLM:

1. Extracts current model and thinking level settings from the full path
2. Converts selected entries to messages:
   - `message` -> stored `AgentMessage`
   - `compaction` -> `compactionSummary`
   - `branch_summary` -> `branchSummary`
   - `custom_message` -> `CustomMessage`
   - `custom` -> no context message
   - `context_edit` -> no context message of its own; the latest edit for each target omits or replaces that target's message

The compaction summary replaces entries before `firstKeptEntryId`. The retained entries and all entries after the compaction remain available to the LLM.

## Parsing Example

```typescript
import { readFileSync } from "fs";

const lines = readFileSync("session.jsonl", "utf8").trim().split("\n");

for (const line of lines) {
  const entry = JSON.parse(line);

  switch (entry.type) {
    case "session":
      console.log(`Session v${entry.version ?? 1}: ${entry.id}`);
      break;
    case "message":
      console.log(`[${entry.id}] ${entry.message.role}: ${JSON.stringify(entry.message.content)}`);
      break;
    case "compaction":
      console.log(`[${entry.id}] Compaction: ${entry.tokensBefore} tokens summarized`);
      break;
    case "branch_summary":
      console.log(`[${entry.id}] Branch from ${entry.fromId}`);
      break;
    case "custom":
      console.log(`[${entry.id}] Custom (${entry.customType}): ${JSON.stringify(entry.data)}`);
      break;
    case "custom_message":
      console.log(`[${entry.id}] Extension message (${entry.customType}): ${entry.content}`);
      break;
    case "label":
      console.log(`[${entry.id}] Label "${entry.label}" on ${entry.targetId}`);
      break;
    case "model_change":
      console.log(`[${entry.id}] Model: ${entry.provider}/${entry.modelId}`);
      break;
    case "thinking_level_change":
      console.log(`[${entry.id}] Thinking: ${entry.thinkingLevel}`);
      break;
  }
}
```

## SessionManager API

Key methods for working with sessions programmatically.

### Static Creation Methods
- `SessionManager.create(cwd, sessionDir?, options?)` - New session; `options` can set `id` and `parentSession`
- `SessionManager.open(path, sessionDir?, cwdOverride?)` - Open existing session file
- `SessionManager.continueRecent(cwd, sessionDir?)` - Continue most recent or create new
- `SessionManager.inMemory(cwd?, options?, entries?)` - No file persistence, optionally initialized from entries
- `SessionManager.forkFrom(sourcePath, targetCwd, sessionDir?, options?)` - Fork session from another project

### Static Listing Methods
- `SessionManager.list(cwd, sessionDir?, onProgress?)` - List sessions for a directory
- `SessionManager.listAll(onProgress?)` - List all sessions across all projects
- `SessionManager.listAll(sessionDir?, onProgress?)` - List sessions from a custom session root

### Instance Methods - Session Management
- `newSession(options?)` - Start a new session (options: `{ id?: string, parentSession?: string }`)
- `setSessionFile(path)` - Switch to a different session file
- `createBranchedSession(leafId)` - Extract branch to new session file

### Instance Methods - Appending (all return entry ID)
- `appendMessage(message)` - Add message (the session history keeps its own JSON copy)
- `appendOwnedMessage(message)` - Add a message the session's own agent produced: the history keeps a shallow copy sharing the message's content (falls back to the JSON copy for a message with a resident string or a non-JSON value)
- `appendThinkingLevelChange(level)` - Record thinking change
- `appendModelChange(provider, modelId)` - Record model change
- `appendCompaction(summary, firstKeptEntryId, tokensBefore, details?, fromHook?, usage?)` - Add compaction; pass `null` as `firstKeptEntryId` to retain no earlier entries
- `appendContextEdit(targetId, replacement)` - Omit (`null`) or replace one entry's message in future model context without changing raw history
- `appendCustomEntry(customType, data?, options?)` - Extension state (not in context); `options.startupBookkeeping` marks startup bookkeeping
- `appendSessionInfo(name)` - Set session display name
- `appendCustomMessageEntry(customType, content, display, details?)` - Extension message (in context)
- `appendLabelChange(targetId, label)` - Set/clear label

### Instance Methods - Tree Navigation
- `getLeafId()` - Current position
- `getLeafEntry()` - Get current leaf entry
- `getEntry(id)` - Get entry by ID
- `getBranch(fromId?)` - Walk from entry to root
- `getTree()` - Get full tree structure
- `getChildren(parentId)` - Get direct children
- `getLabel(id)` - Get label for entry
- `branch(entryId)` - Move leaf to earlier entry
- `resetLeaf()` - Reset leaf to null (before any entries)
- `branchWithSummary(entryId, summary, details?, fromHook?, usage?)` - Branch with context summary; `entryId` may be `null` to branch from the root

### Instance Methods - Context & Info
- `buildContextEntries()` - Get active branch entries with compaction applied
- `buildSessionContext()` - Get messages, thinkingLevel, and model for LLM
- `getEntries()` - All entries (excluding header)
- `getHeader()` - Session header metadata
- `getSessionName()` - Get display name from latest session_info entry
- `getCwd()` - Working directory
- `getSessionDir()` - Session storage directory
- `getSessionId()` - Session UUID
- `getSessionFile()` - Session file path (undefined for in-memory)
- `isPersisted()` - Whether session is saved to disk
