> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/opencode-ai/opencode/llms.txt
> Use this file to discover all available pages before exploring further.

# Session management

> Understanding sessions, auto-compact, SQLite storage, and conversation history in OpenCode

OpenCode manages conversations through sessions, which track messages, token usage, costs, and provide powerful features like automatic context compression and conversation summarization.

## What are sessions?

A session represents a single conversation with the AI, including:

* **All messages** exchanged with the AI
* **Token usage** tracking (prompt and completion)
* **Cost calculation** based on model pricing
* **File changes** made during the session
* **Tool calls** and their results
* **Metadata** like title, timestamps, and parent sessions

<Note>
  Sessions are the primary unit of organization in OpenCode. Each session has a unique ID and can spawn child sessions.
</Note>

## Session lifecycle

<Steps>
  <Step title="Creation">
    New session created when:

    * Starting OpenCode (`Ctrl+N` or startup)
    * Creating new conversation
    * Auto-compacting existing session
    * Spawning task session
  </Step>

  <Step title="Active conversation">
    During a session:

    * Messages are appended to history
    * Token counts are tracked
    * Costs are calculated in real-time
    * File changes are recorded
    * Title is generated after first exchange
  </Step>

  <Step title="Auto-compact (optional)">
    When approaching context limit:

    * Session is automatically summarized
    * New session created with summary
    * Original session preserved
    * Context extended for longer work
  </Step>

  <Step title="Persistence">
    Session state is continuously saved:

    * Messages written to SQLite
    * Token counts updated
    * File history tracked
    * Metadata synchronized
  </Step>
</Steps>

## Session structure

Each session contains:

<ParamField path="ID" type="string">
  Unique identifier (UUID)
</ParamField>

<ParamField path="ParentSessionID" type="string">
  ID of parent session (for compact/task sessions)
</ParamField>

<ParamField path="Title" type="string">
  Auto-generated conversation title
</ParamField>

<ParamField path="MessageCount" type="integer">
  Number of messages in session
</ParamField>

<ParamField path="PromptTokens" type="integer">
  Total input tokens consumed
</ParamField>

<ParamField path="CompletionTokens" type="integer">
  Total output tokens generated
</ParamField>

<ParamField path="SummaryMessageID" type="string">
  ID of summary message (for compacted sessions)
</ParamField>

<ParamField path="Cost" type="float">
  Total cost in USD based on model pricing
</ParamField>

<ParamField path="CreatedAt" type="timestamp">
  Session creation time (Unix milliseconds)
</ParamField>

<ParamField path="UpdatedAt" type="timestamp">
  Last update time (Unix milliseconds)
</ParamField>

## Auto-compact feature

Auto-compact automatically manages context window limits by summarizing conversations when they approach the model's maximum context length.

### How it works

<Steps>
  <Step title="Monitor token usage">
    OpenCode tracks token consumption throughout the conversation:

    * Counts prompt tokens (input)
    * Counts completion tokens (output)
    * Calculates total context usage
  </Step>

  <Step title="Detect threshold">
    When usage reaches 95% of model's context window:

    * Trigger auto-compact process
    * Prevent "out of context" errors
    * Maintain conversation continuity
  </Step>

  <Step title="Generate summary">
    AI creates a comprehensive summary:

    * Key decisions and outcomes
    * Important context to preserve
    * File changes made
    * Current state of work
  </Step>

  <Step title="Create new session">
    New session spawned with summary:

    * Parent session ID recorded
    * Summary as initial context
    * Token counter resets
    * Continue seamlessly
  </Step>
</Steps>

### Configuration

```json theme={null}
{
  "autoCompact": true  // Default: true
}
```

<Tabs>
  <Tab title="Enabled (default)">
    **Benefits:**

    * Never hit context limits
    * Conversations can continue indefinitely
    * Important context preserved
    * Seamless user experience

    **Behavior:**

    * Automatic at 95% usage
    * Summary generation transparent
    * New session created automatically
    * Original session preserved
  </Tab>

  <Tab title="Disabled">
    **When to disable:**

    * Short, focused conversations
    * Want full message history always
    * Manual session management preferred
    * Testing or debugging

    **Consequences:**

    * May hit context window limit
    * Conversation will stop
    * Must start new session manually
    * Lose conversation continuity
  </Tab>
</Tabs>

### Manual compact

You can manually trigger compaction:

<Steps>
  <Step title="Open command palette">
    Press `Ctrl+K`
  </Step>

  <Step title="Select Compact Session">
    Choose the "Compact Session" command
  </Step>

  <Step title="Confirm">
    AI generates summary and creates new session
  </Step>
</Steps>

**Use manual compact when:**

* Switching to a new task
* Conversation has diverged
* Want a clean slate with context
* Proactively managing tokens

### Compact summary format

Summaries preserve:

<AccordionGroup>
  <Accordion title="Decisions and outcomes" icon="check-double">
    * Agreements reached
    * Solutions implemented
    * Approaches decided
    * Trade-offs made
  </Accordion>

  <Accordion title="Technical context" icon="code">
    * File changes made
    * Functions modified
    * Dependencies added
    * Configuration changes
  </Accordion>

  <Accordion title="Current state" icon="flag">
    * What works now
    * Known issues
    * Next steps planned
    * Blockers identified
  </Accordion>

  <Accordion title="Important background" icon="book">
    * Project structure
    * Key constraints
    * Requirements
    * Architecture decisions
  </Accordion>
</AccordionGroup>

## Session switching

Quickly switch between recent conversations:

<Steps>
  <Step title="Open session dialog">
    Press `Ctrl+A`
  </Step>

  <Step title="Browse sessions">
    * Most recent first
    * Shows title and timestamp
    * Navigate with arrows or `j`/`k`
  </Step>

  <Step title="Select session">
    Press `Enter` to switch
  </Step>
</Steps>

**Session list shows:**

```
┌─ Sessions (Ctrl+A) ──────────────────────┐
│ > Fix authentication bug                      │
│   2 minutes ago                              │
│                                              │
│   Add user profile API                       │
│   1 hour ago                                 │
│                                              │
│   Refactor database layer                    │
│   Yesterday at 3:24 PM                       │
│                                              │
│   Setup Docker environment                   │
│   2 days ago                                 │
└──────────────────────────────────────────────┘
```

## SQLite storage

OpenCode uses SQLite for persistent storage, providing:

* **Fast queries**: Efficient message retrieval
* **Reliability**: ACID transactions
* **Portability**: Single file database
* **No dependencies**: Built into OpenCode
* **Version control**: Schema migrations

### Database location

```
$HOME/.opencode/
├── opencode.db          # Main database
├── logs/                 # Debug logs
└── commands/             # Custom commands
```

Or configured location:

```json theme={null}
{
  "data": {
    "directory": ".opencode"  // Relative to working directory
  }
}
```

### Database schema

<Tabs>
  <Tab title="Sessions table">
    ```sql theme={null}
    CREATE TABLE sessions (
      id TEXT PRIMARY KEY,
      parent_session_id TEXT,
      title TEXT NOT NULL,
      message_count INTEGER DEFAULT 0,
      prompt_tokens INTEGER DEFAULT 0,
      completion_tokens INTEGER DEFAULT 0,
      summary_message_id TEXT,
      cost REAL DEFAULT 0,
      created_at INTEGER NOT NULL,
      updated_at INTEGER NOT NULL
    );
    ```

    Stores session metadata and aggregates.
  </Tab>

  <Tab title="Messages table">
    ```sql theme={null}
    CREATE TABLE messages (
      id TEXT PRIMARY KEY,
      session_id TEXT NOT NULL,
      role TEXT NOT NULL,
      content TEXT NOT NULL,
      model TEXT,
      prompt_tokens INTEGER,
      completion_tokens INTEGER,
      created_at INTEGER NOT NULL,
      FOREIGN KEY (session_id) REFERENCES sessions(id)
    );
    ```

    Stores all messages in conversations.
  </Tab>

  <Tab title="Files table">
    ```sql theme={null}
    CREATE TABLE files (
      id TEXT PRIMARY KEY,
      session_id TEXT NOT NULL,
      path TEXT NOT NULL,
      content TEXT NOT NULL,
      created_at INTEGER NOT NULL,
      FOREIGN KEY (session_id) REFERENCES sessions(id)
    );
    ```

    Tracks file changes per session.
  </Tab>

  <Tab title="File versions table">
    ```sql theme={null}
    CREATE TABLE file_versions (
      id TEXT PRIMARY KEY,
      file_id TEXT NOT NULL,
      session_id TEXT NOT NULL,
      content TEXT NOT NULL,
      created_at INTEGER NOT NULL,
      FOREIGN KEY (file_id) REFERENCES files(id),
      FOREIGN KEY (session_id) REFERENCES sessions(id)
    );
    ```

    Maintains version history for files.
  </Tab>
</Tabs>

### Database operations

OpenCode performs these operations:

<CardGroup cols={2}>
  <Card title="Create session" icon="plus">
    ```go theme={null}
    session, err := sessions.Create(ctx, "New conversation")
    ```

    Inserts new session record
  </Card>

  <Card title="Save message" icon="message">
    ```go theme={null}
    message, err := messages.Create(ctx, sessionID, role, content)
    ```

    Appends message to session
  </Card>

  <Card title="Update session" icon="pen">
    ```go theme={null}
    session, err := sessions.Save(ctx, session)
    ```

    Updates token counts, cost, title
  </Card>

  <Card title="List sessions" icon="list">
    ```go theme={null}
    sessions, err := sessions.List(ctx)
    ```

    Retrieves all sessions, sorted by updated\_at
  </Card>

  <Card title="Track file change" icon="file">
    ```go theme={null}
    file, err := files.Create(ctx, sessionID, path, content)
    version, err := files.CreateVersion(ctx, sessionID, path, newContent)
    ```

    Records file modifications
  </Card>

  <Card title="Delete session" icon="trash">
    ```go theme={null}
    err := sessions.Delete(ctx, sessionID)
    ```

    Removes session and associated data
  </Card>
</CardGroup>

## File history tracking

OpenCode tracks all file changes within sessions:

### How it works

<Steps>
  <Step title="Initial state">
    When file is first modified:

    * Original content stored in `files` table
    * Baseline for future comparisons
  </Step>

  <Step title="Version creation">
    On each modification:

    * New version in `file_versions` table
    * Links to file and session
    * Timestamps for ordering
  </Step>

  <Step title="Intermediate changes">
    If file modified outside OpenCode:

    * Intermediate version created
    * Preserves manual changes
    * Maintains complete history
  </Step>
</Steps>

### Version tracking example

```
Session starts:
  files:
    - id: file-1
      path: src/auth.ts
      content: (original)
      
AI modifies file:
  file_versions:
    - version 1: (AI changes)
    
User edits manually:
  file_versions:
    - version 2: (intermediate - user changes)
    
AI modifies again:
  file_versions:
    - version 3: (AI changes on top of user changes)
```

## Token tracking and costs

OpenCode tracks token usage and calculates costs in real-time:

### Token counting

<Tabs>
  <Tab title="Prompt tokens">
    **Input tokens** include:

    * User messages
    * System prompts
    * Tool descriptions
    * Previous conversation context
    * File contents in context

    Counted per API request and aggregated per session.
  </Tab>

  <Tab title="Completion tokens">
    **Output tokens** include:

    * AI responses
    * Tool call arguments
    * Generated content

    Returned by API and recorded per message.
  </Tab>
</Tabs>

### Cost calculation

Costs calculated using model-specific pricing:

```go theme={null}
// Example pricing (varies by model)
promptCost := (promptTokens / 1_000_000) * model.PromptPrice
completionCost := (completionTokens / 1_000_000) * model.CompletionPrice
totalCost := promptCost + completionCost
```

**Displayed in UI:**

* Per-session totals
* Real-time updates
* Multiple currency support (future)

### Example costs

<Info>
  Costs are estimates based on published pricing and may not reflect actual billing.
</Info>

| Model             | Prompt (per 1M tokens) | Completion (per 1M tokens) |
| ----------------- | ---------------------- | -------------------------- |
| GPT-4o            | \$5.00                 | \$15.00                    |
| GPT-4o Mini       | \$0.15                 | \$0.60                     |
| Claude 3.5 Sonnet | \$3.00                 | \$15.00                    |
| Claude 3.5 Haiku  | \$0.80                 | \$4.00                     |
| Gemini 2.5 Pro    | \$1.25                 | \$5.00                     |

## Task sessions

OpenCode can spawn child sessions for sub-tasks:

### Agent tool

The AI can create task sessions using the `agent` tool:

```json theme={null}
{
  "tool": "agent",
  "parameters": {
    "prompt": "Search for all TODO comments in the codebase and create a list"
  }
}
```

**Task session characteristics:**

* Has `parent_session_id` set
* Separate token tracking
* Independent context
* Can access same tools
* Results returned to parent

### Use cases

<CardGroup cols={2}>
  <Card title="Parallel research" icon="magnifying-glass">
    Investigate multiple approaches simultaneously
  </Card>

  <Card title="Code exploration" icon="map">
    Deep dive into specific subsystems without cluttering main conversation
  </Card>

  <Card title="Batch operations" icon="list-check">
    Process multiple files or items independently
  </Card>

  <Card title="Specialized analysis" icon="microscope">
    Focused analysis with different context or model
  </Card>
</CardGroup>

## Session hierarchy

Sessions form a parent-child tree:

```
Main Session (UUID-1)
├── Task: Search TODOs (UUID-2)
├── Task: Analyze dependencies (UUID-3)
└── Compacted Session (UUID-4)
    └── Task: Generate tests (UUID-5)
```

**Navigation:**

* View parent via `parent_session_id`
* Find children by querying `parent_session_id = current_id`
* Breadcrumb in UI (future feature)

## Best practices

<CardGroup cols={2}>
  <Card title="Let auto-compact work" icon="wand-magic-sparkles">
    Keep `autoCompact: true` for seamless long conversations
  </Card>

  <Card title="Name sessions meaningfully" icon="tag">
    First message sets context for auto-generated title
  </Card>

  <Card title="Use manual compact strategically" icon="scissors">
    When switching focus or starting new sub-task
  </Card>

  <Card title="Monitor token usage" icon="gauge">
    Watch token counts to understand costs
  </Card>

  <Card title="Review session history" icon="clock-rotate-left">
    Use session list to return to previous work
  </Card>

  <Card title="Backup database" icon="floppy-disk">
    Periodically backup `~/.opencode/opencode.db`
  </Card>
</CardGroup>

## Database maintenance

### Backup

```bash theme={null}
# Backup database
cp ~/.opencode/opencode.db ~/.opencode/opencode.db.backup

# Or with timestamp
cp ~/.opencode/opencode.db \
   ~/.opencode/opencode.db.$(date +%Y%m%d)
```

### Inspection

```bash theme={null}
# Open with sqlite3
sqlite3 ~/.opencode/opencode.db

# Useful queries
SQLite> SELECT id, title, message_count, cost FROM sessions ORDER BY updated_at DESC LIMIT 10;
SQLite> SELECT COUNT(*) FROM messages;
SQLite> SELECT SUM(cost) FROM sessions;
```

### Cleanup

```bash theme={null}
# Delete old sessions (SQL)
DELETE FROM sessions WHERE updated_at < strftime('%s', 'now', '-30 days') * 1000;

# Vacuum to reclaim space
VACUUM;
```

<Warning>
  Always backup before manual database operations
</Warning>

## Troubleshooting

<AccordionGroup>
  <Accordion title="Session not saving" icon="floppy-disk-circle-xmark">
    Check:

    * Database file permissions
    * Disk space available
    * SQLite not corrupted: `sqlite3 opencode.db "PRAGMA integrity_check;"`
    * No concurrent access issues
  </Accordion>

  <Accordion title="Auto-compact not triggering" icon="circle-pause">
    Verify:

    * `autoCompact: true` in config
    * Token usage actually reaching threshold
    * Model context window correctly detected
    * Check logs for errors
  </Accordion>

  <Accordion title="Missing session history" icon="clock-rotate-left">
    Possible causes:

    * Database corruption
    * Incorrect data directory
    * Session deleted
    * Wrong working directory

    Check: `ls -la ~/.opencode/`
  </Accordion>

  <Accordion title="High token counts" icon="arrow-up">
    Token usage accumulates from:

    * Large file contents in context
    * Long conversation history
    * Many tool calls
    * Repeated context

    Solutions:

    * Use manual compact
    * Start fresh session for new task
    * Avoid reading large files unnecessarily
  </Accordion>
</AccordionGroup>

## Next steps

<CardGroup cols={2}>
  <Card title="Commands" href="/essentials/commands" icon="terminal">
    Learn about Initialize Project and Compact Session commands
  </Card>

  <Card title="Configuration" href="/reference/configuration" icon="gear">
    Configure data directory and auto-compact
  </Card>

  <Card title="AI tools" href="/features/ai-tools" icon="wrench">
    Explore agent tool for task sessions
  </Card>

  <Card title="Keyboard shortcuts" href="/essentials/keyboard-shortcuts" icon="keyboard">
    Session management shortcuts
  </Card>
</CardGroup>
