Skip to main content
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
Sessions are the primary unit of organization in OpenCode. Each session has a unique ID and can spawn child sessions.

Session lifecycle

1

Creation

New session created when:
  • Starting OpenCode (Ctrl+N or startup)
  • Creating new conversation
  • Auto-compacting existing session
  • Spawning task session
2

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
3

Auto-compact (optional)

When approaching context limit:
  • Session is automatically summarized
  • New session created with summary
  • Original session preserved
  • Context extended for longer work
4

Persistence

Session state is continuously saved:
  • Messages written to SQLite
  • Token counts updated
  • File history tracked
  • Metadata synchronized

Session structure

Each session contains:
ID
string
Unique identifier (UUID)
ParentSessionID
string
ID of parent session (for compact/task sessions)
Title
string
Auto-generated conversation title
MessageCount
integer
Number of messages in session
PromptTokens
integer
Total input tokens consumed
CompletionTokens
integer
Total output tokens generated
SummaryMessageID
string
ID of summary message (for compacted sessions)
Cost
float
Total cost in USD based on model pricing
CreatedAt
timestamp
Session creation time (Unix milliseconds)
UpdatedAt
timestamp
Last update time (Unix milliseconds)

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

1

Monitor token usage

OpenCode tracks token consumption throughout the conversation:
  • Counts prompt tokens (input)
  • Counts completion tokens (output)
  • Calculates total context usage
2

Detect threshold

When usage reaches 95% of model’s context window:
  • Trigger auto-compact process
  • Prevent “out of context” errors
  • Maintain conversation continuity
3

Generate summary

AI creates a comprehensive summary:
  • Key decisions and outcomes
  • Important context to preserve
  • File changes made
  • Current state of work
4

Create new session

New session spawned with summary:
  • Parent session ID recorded
  • Summary as initial context
  • Token counter resets
  • Continue seamlessly

Configuration

{
  "autoCompact": true  // Default: true
}
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

Manual compact

You can manually trigger compaction:
1

Open command palette

Press Ctrl+K
2

Select Compact Session

Choose the “Compact Session” command
3

Confirm

AI generates summary and creates new session
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:
  • Agreements reached
  • Solutions implemented
  • Approaches decided
  • Trade-offs made
  • File changes made
  • Functions modified
  • Dependencies added
  • Configuration changes
  • What works now
  • Known issues
  • Next steps planned
  • Blockers identified
  • Project structure
  • Key constraints
  • Requirements
  • Architecture decisions

Session switching

Quickly switch between recent conversations:
1

Open session dialog

Press Ctrl+A
2

Browse sessions

  • Most recent first
  • Shows title and timestamp
  • Navigate with arrows or j/k
3

Select session

Press Enter to switch
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:
{
  "data": {
    "directory": ".opencode"  // Relative to working directory
  }
}

Database schema

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.

Database operations

OpenCode performs these operations:

Create session

session, err := sessions.Create(ctx, "New conversation")
Inserts new session record

Save message

message, err := messages.Create(ctx, sessionID, role, content)
Appends message to session

Update session

session, err := sessions.Save(ctx, session)
Updates token counts, cost, title

List sessions

sessions, err := sessions.List(ctx)
Retrieves all sessions, sorted by updated_at

Track file change

file, err := files.Create(ctx, sessionID, path, content)
version, err := files.CreateVersion(ctx, sessionID, path, newContent)
Records file modifications

Delete session

err := sessions.Delete(ctx, sessionID)
Removes session and associated data

File history tracking

OpenCode tracks all file changes within sessions:

How it works

1

Initial state

When file is first modified:
  • Original content stored in files table
  • Baseline for future comparisons
2

Version creation

On each modification:
  • New version in file_versions table
  • Links to file and session
  • Timestamps for ordering
3

Intermediate changes

If file modified outside OpenCode:
  • Intermediate version created
  • Preserves manual changes
  • Maintains complete history

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

Input tokens include:
  • User messages
  • System prompts
  • Tool descriptions
  • Previous conversation context
  • File contents in context
Counted per API request and aggregated per session.

Cost calculation

Costs calculated using model-specific pricing:
// 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

Costs are estimates based on published pricing and may not reflect actual billing.
ModelPrompt (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:
{
  "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

Parallel research

Investigate multiple approaches simultaneously

Code exploration

Deep dive into specific subsystems without cluttering main conversation

Batch operations

Process multiple files or items independently

Specialized analysis

Focused analysis with different context or model

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

Let auto-compact work

Keep autoCompact: true for seamless long conversations

Name sessions meaningfully

First message sets context for auto-generated title

Use manual compact strategically

When switching focus or starting new sub-task

Monitor token usage

Watch token counts to understand costs

Review session history

Use session list to return to previous work

Backup database

Periodically backup ~/.opencode/opencode.db

Database maintenance

Backup

# 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

# 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

# Delete old sessions (SQL)
DELETE FROM sessions WHERE updated_at < strftime('%s', 'now', '-30 days') * 1000;

# Vacuum to reclaim space
VACUUM;
Always backup before manual database operations

Troubleshooting

Check:
  • Database file permissions
  • Disk space available
  • SQLite not corrupted: sqlite3 opencode.db "PRAGMA integrity_check;"
  • No concurrent access issues
Verify:
  • autoCompact: true in config
  • Token usage actually reaching threshold
  • Model context window correctly detected
  • Check logs for errors
Possible causes:
  • Database corruption
  • Incorrect data directory
  • Session deleted
  • Wrong working directory
Check: ls -la ~/.opencode/
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

Next steps

Commands

Learn about Initialize Project and Compact Session commands

Configuration

Configure data directory and auto-compact

AI tools

Explore agent tool for task sessions

Keyboard shortcuts

Session management shortcuts

Build docs developers (and LLMs) love