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
Creation
New session created when:
- Starting OpenCode (
Ctrl+Nor startup) - Creating new conversation
- Auto-compacting existing session
- Spawning task session
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
Auto-compact (optional)
When approaching context limit:
- Session is automatically summarized
- New session created with summary
- Original session preserved
- Context extended for longer work
Session structure
Each session contains:Unique identifier (UUID)
ID of parent session (for compact/task sessions)
Auto-generated conversation title
Number of messages in session
Total input tokens consumed
Total output tokens generated
ID of summary message (for compacted sessions)
Total cost in USD based on model pricing
Session creation time (Unix milliseconds)
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
Monitor token usage
OpenCode tracks token consumption throughout the conversation:
- Counts prompt tokens (input)
- Counts completion tokens (output)
- Calculates total context usage
Detect threshold
When usage reaches 95% of model’s context window:
- Trigger auto-compact process
- Prevent “out of context” errors
- Maintain conversation continuity
Generate summary
AI creates a comprehensive summary:
- Key decisions and outcomes
- Important context to preserve
- File changes made
- Current state of work
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:
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: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:
Session list shows:
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
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
Initial state
When file is first modified:
- Original content stored in
filestable - Baseline for future comparisons
Version creation
On each modification:
- New version in
file_versionstable - Links to file and session
- Timestamps for ordering
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.
| 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 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