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+Nor 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:string
Unique identifier (UUID)
string
ID of parent session (for compact/task sessions)
string
Auto-generated conversation title
integer
Number of messages in session
integer
Total input tokens consumed
integer
Total output tokens generated
string
ID of summary message (for compacted sessions)
float
Total cost in USD based on model pricing
timestamp
Session creation time (Unix milliseconds)
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
- Enabled (default)
- Disabled
Benefits:
- Never hit context limits
- Conversations can continue indefinitely
- Important context preserved
- Seamless user experience
- 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+K2
Select Compact Session
Choose the “Compact Session” command
3
Confirm
AI generates summary and creates new session
- Switching to a new task
- Conversation has diverged
- Want a clean slate with context
- Proactively managing tokens
Compact summary format
Summaries preserve:Decisions and outcomes
Decisions and outcomes
- Agreements reached
- Solutions implemented
- Approaches decided
- Trade-offs made
Technical context
Technical context
- File changes made
- Functions modified
- Dependencies added
- Configuration changes
Current state
Current state
- What works now
- Known issues
- Next steps planned
- Blockers identified
Important background
Important background
- Project structure
- Key constraints
- Requirements
- Architecture decisions
Session switching
Quickly switch between recent conversations:1
Open session dialog
Press
Ctrl+A2
Browse sessions
- Most recent first
- Shows title and timestamp
- Navigate with arrows or
j/k
3
Select session
Press
Enter to switchSQLite 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
Database schema
- Sessions table
- Messages table
- Files table
- File versions table
Database operations
OpenCode performs these operations:Create session
Save message
Update session
List sessions
Track file change
Delete session
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
filestable - Baseline for future comparisons
2
Version creation
On each modification:
- New version in
file_versionstable - 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
Token tracking and costs
OpenCode tracks token usage and calculates costs in real-time:Token counting
- Prompt tokens
- Completion tokens
Input tokens include:
- User messages
- System prompts
- Tool descriptions
- Previous conversation context
- File contents in context
Cost calculation
Costs calculated using model-specific pricing:- 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.
Task sessions
OpenCode can spawn child sessions for sub-tasks:Agent tool
The AI can create task sessions using theagent tool:
- Has
parent_session_idset - 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:- 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 conversationsName 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.dbDatabase maintenance
Backup
Inspection
Cleanup
Troubleshooting
Session not saving
Session not saving
Check:
- Database file permissions
- Disk space available
- SQLite not corrupted:
sqlite3 opencode.db "PRAGMA integrity_check;" - No concurrent access issues
Auto-compact not triggering
Auto-compact not triggering
Verify:
autoCompact: truein config- Token usage actually reaching threshold
- Model context window correctly detected
- Check logs for errors
Missing session history
Missing session history
Possible causes:
- Database corruption
- Incorrect data directory
- Session deleted
- Wrong working directory
ls -la ~/.opencode/High token counts
High token counts
Token usage accumulates from:
- Large file contents in context
- Long conversation history
- Many tool calls
- Repeated context
- 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