# OpenCode - Managing and Searching Conversations
## What It Does
OpenCode provides multiple ways to navigate, search, and resume previous conversations (called "sessions"). You can access past conversations through the built-in `/sessions` command, CLI flags, or by directly searching session data.
## How to Use It
### Method 1: Interactive Session Browser (Recommended)
**Inside OpenCode TUI:**
```
/sessions
```
**Keyboard shortcut:** `Ctrl+X` then `L` (two-key sequence - press Ctrl+X, release, then press L)
**⚠️ Important:** This is a **two-step sequence**, not simultaneous keys:
1. Press `Ctrl+X` (you'll see a prompt waiting for next key)
2. Then press `L` (lowercase letter L)
**Aliases:** `/resume`, `/continue`
**Recommended:** Use `/sessions` command if keyboard shortcuts are confusing
This opens an interactive picker showing all your previous conversations with:
- Session nicknames (if set)
- Recent message previews
- Timestamps
- Current working directory
Use arrow keys to navigate and Enter to load a session.
### Method 2: Resume Last Session (Quick Method)
**From terminal (before starting OpenCode):**
```bash
opencode -c
# or
opencode --continue
```
This instantly loads your most recent conversation in the current directory.
### Method 3: Resume Specific Session by ID
**From terminal:**
```bash
opencode -s <session-id>
# or
opencode --session <session-id>
```
Example:
```bash
opencode -s 4XP1fce5
```
### Method 4: Export and Search (Advanced)
**Export a specific session:**
```bash
opencode export <sessionID>
```
This outputs the session as JSON, which you can:
- Pipe to `jq` for JSON parsing
- Grep for specific content
- Archive for documentation
**Export current session (from within OpenCode TUI):**
```
/export
```
This opens your default editor (`$EDITOR`) with the conversation in Markdown format.
## When to Use It
**Use `/sessions` when:**
- You remember working on something recently but can't recall exact details
- You want to browse multiple conversations to find the right one
- You need to see context (directory, recent messages) before choosing
**Use `--continue` when:**
- You just closed OpenCode and want to resume immediately
- You're actively iterating on a single project
**Use `--session <id>` when:**
- You have the exact session ID (from shared links or logs)
- Scripting OpenCode workflows
**Use `export` when:**
- Creating documentation from conversations
- Searching conversation content with external tools
- Archiving important sessions
## How It Works
### Session Storage
OpenCode stores each conversation as a session with:
- **Session ID**: Unique identifier (like `4XP1fce5`)
- **Working directory**: Where the session was started
- **Timestamps**: Creation and last update
- **Messages**: Full conversation history including tool calls
- **Optional nickname**: Custom label you can set
### Session Persistence
- Sessions are stored locally on your machine
- Each working directory can have multiple sessions
- Sessions persist across OpenCode restarts
- Shared sessions (via `/share`) get a public URL but remain private by default
### The /sessions Command
When you run `/sessions`:
1. OpenCode scans all stored sessions
2. Groups them by recency and working directory
3. Shows preview text from recent messages
4. Allows fuzzy search by typing to filter
## Where It Appears
**Configuration location:**
- Session data stored in OpenCode's data directory
- On macOS/Linux: Typically `~/.config/opencode/` or `~/.opencode/`
- On Windows: `%APPDATA%\opencode\`
**Access points:**
- `/sessions` command within TUI
- `--continue` / `-c` flag when launching
- `--session` / `-s` flag with session ID
- `opencode export` CLI command
## Pro Tips
### 1. Set Session Titles Programmatically
**Using `opencode run` with `--title` flag:**
```bash
# Set custom title when starting session
opencode run --title "Authentication Implementation" "Add OAuth to user management"
# Title is searchable in /sessions browser
opencode run --title "Bug Fix: Login Timeout" "Fix the session timeout issue"
# Use descriptive titles for scripted sessions
opencode run --title "Daily Code Review $(date +%Y-%m-%d)" "Review changes in src/"
```
**Alternative: Use descriptive first message (in TUI):**
```
Let's add authentication to the user management system
```
Both approaches create better previews in `/sessions` browser.
**Note:** The `--title` flag only works with `opencode run` (CLI mode), not in the TUI. For interactive sessions, your first message becomes the de facto title.
### 2. Combine with /share for Collaboration
```
/share
```
Copy the URL, share with teammates, then use `--session <id>` to resume the exact conversation later.
### 3. Semantic Search with Export + Grep
```bash
# Export all sessions and search
opencode export <session-id> | grep -i "authentication"
# Or use jq for structured search
opencode export <session-id> | jq '.messages[] | select(.content | contains("database"))'
```
### 4. Clean Workspace with /new
If `/sessions` gets cluttered, start fresh:
```
/new
```
This keeps your session list manageable.
### 5. Use /compact for Long Sessions
Before exporting or sharing long conversations:
```
/compact
```
This summarizes the session, making it easier to search and share.
## Current Limitations
**No built-in semantic search:** OpenCode doesn't currently offer vector-based search across conversations. You'll need to:
- Use `/sessions` interactive browser (filters by text matching)
- Export and use external tools like `grep`, `rg`, or `jq`
- Rely on descriptive session starts for better previews
**Workaround for semantic search:**
1. Export sessions as JSON: `opencode export <id>`
2. Use external semantic search tools (like local vector DB)
3. Or integrate with MCP servers that provide search capabilities
## Session Deletion and Recovery
### Understanding Session Deletion
**Common keyboard shortcut confusion:**
- `Ctrl+X L` (two-key sequence) - Opens session browser ✓
- `Ctrl+X` or `Cmd+X` (single key) - May delete current session ⚠️
**Important:** On Mac, if you press `Cmd+X` instead of the full `Ctrl+X L` sequence, you might trigger session deletion instead of opening the session browser.
### Where Sessions Are Stored
OpenCode stores sessions in your local filesystem:
```bash
# Session storage location (macOS/Linux)
~/.local/share/opencode/storage/session/
```
Each project has its own session subdirectory identified by a hash of the working directory path.
**Example structure:**
```
~/.local/share/opencode/storage/session/
├── 1e1209d1288cb1223a2070e8179f68bbbce051d4/ # Project hash
│ ├── ses_5995ba4b5ffeZCMdxwHh3clJ5D.json
│ ├── ses_59975f69bffelDux6q760oC14U.json
│ └── ...
└── global/ # Sessions not tied to specific directory
└── ...
```
### Recovering Accidentally Deleted Sessions
**Method 1: Check macOS Trash (if deleted via Finder)**
If you accidentally deleted session files through Finder:
```bash
# Open Trash in Finder
open ~/.Trash
# Search for session files
# Look for files starting with "ses_" and ending in ".json"
```
Then drag them back to `~/.local/share/opencode/storage/session/[project-hash]/`
**Method 2: Restore from Time Machine (macOS)**
```bash
# Open Time Machine for session directory
tmutil listlocalsnapshotdates / | tail -5 # Check recent snapshots
# Or use Time Machine GUI
open -a "Time Machine"
# Navigate to ~/.local/share/opencode/storage/session/
```
**Method 3: Check if Session Was Exported**
If you previously exported the session:
```bash
# Search for exported markdown files
find ~ -name "*.md" -type f -exec grep -l "opencode export" {} \; 2>/dev/null
# Or check common export locations
ls ~/Downloads/*.md
ls ~/Documents/*.md
```
**Method 4: Verify Sessions Still Exist**
Before panicking, verify the session is actually deleted:
```bash
# List all sessions for current project
PROJECT_HASH=$(echo -n "$(pwd)" | shasum -a 1 | cut -d' ' -f1)
ls -lth ~/.local/share/opencode/storage/session/$PROJECT_HASH/
# Or list all sessions across all projects
find ~/.local/share/opencode/storage/session -name "ses_*.json" -type f | head -20
```
### Preventing Accidental Deletion
**1. Backup Sessions Regularly**
Create a backup script (`~/bin/backup-opencode-sessions`):
```bash
#!/bin/bash
# Backup OpenCode sessions daily
BACKUP_DIR="$HOME/Documents/opencode-backups"
SESSION_DIR="$HOME/.local/share/opencode/storage/session"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
mkdir -p "$BACKUP_DIR"
# Create timestamped backup
tar -czf "$BACKUP_DIR/sessions_$TIMESTAMP.tar.gz" -C "$SESSION_DIR" .
# Keep only last 30 days of backups
find "$BACKUP_DIR" -name "sessions_*.tar.gz" -mtime +30 -delete
echo "✓ Backed up sessions to: $BACKUP_DIR/sessions_$TIMESTAMP.tar.gz"
```
Make it executable and run via cron:
```bash
chmod +x ~/bin/backup-opencode-sessions
# Add to crontab (run daily at 2am)
crontab -e
# Add line: 0 2 * * * /Users/yourusername/bin/backup-opencode-sessions
```
**2. Export Important Sessions Immediately**
After completing important work:
```bash
# From within OpenCode TUI
/export
# Or from terminal
opencode export ses_5995ba4b5ffeZCMdxwHh3clJ5D > ~/Documents/important-session.md
```
**3. Use Version Control for Session Exports**
```bash
# Create a git repo for session archives
mkdir -p ~/opencode-archives
cd ~/opencode-archives
git init
# Export and commit important sessions
opencode export ses_abc123 > authentication-work.md
git add .
git commit -m "Session: Authentication implementation"
```
### Restoring a Deleted Session
**If you have a backup:**
```bash
# Extract specific session from backup
BACKUP_FILE="$HOME/Documents/opencode-backups/sessions_20251108_140000.tar.gz"
SESSION_DIR="$HOME/.local/share/opencode/storage/session"
# Extract to temporary location first
mkdir -p /tmp/session-restore
tar -xzf "$BACKUP_FILE" -C /tmp/session-restore
# Copy specific session back
PROJECT_HASH="1e1209d1288cb1223a2070e8179f68bbbce051d4"
cp /tmp/session-restore/$PROJECT_HASH/ses_*.json "$SESSION_DIR/$PROJECT_HASH/"
# Clean up
rm -rf /tmp/session-restore
```
**If you have an exported markdown file:**
Unfortunately, OpenCode doesn't have a built-in "import" feature to recreate sessions from markdown exports. However, you can:
1. Start a new OpenCode session
2. Reference the exported markdown file
3. Ask OpenCode to continue from that context
```bash
opencode run --title "Restored: [Original Title]" "Continue from this exported session: @path/to/exported-session.md"
```
### Keyboard Shortcut Reference (Corrected)
**Session management shortcuts:**
- `Ctrl+X` then `L` (two separate keys) - Open session browser
- `/sessions` - Command alternative to keyboard shortcut
- `/new` - Start new session (current auto-saved)
**⚠️ Avoid:**
- `Cmd+X` on Mac - May trigger deletion or cut operation
- Single `Ctrl+X` without follow-up key - Incomplete shortcut
**Pro tip:** If you're unsure about keyboard shortcuts, use the slash commands instead:
- Type `/sessions` to browse
- Type `/new` to start fresh
- Type `/export` to backup current session
## Related Commands
- `/new` - Start fresh session (current one saved automatically)
- `/export` - Export current session to Markdown
- `/share` - Share session publicly
- `/compact` - Summarize long sessions
- `/undo` - Revert last message in current session
## Common Workflows
### "I was working on auth yesterday..."
1. Press `Ctrl+X L` (or type `/sessions`)
2. Type "auth" to filter
3. Select the matching session
### "What did I do in that Australia planning conversation?"
1. Press `Ctrl+X L`
2. Type "Australia" or "travel"
3. Review the preview
4. Hit Enter to load
### "Share conversation with teammate, then resume later"
1. In conversation: `/share`
2. Copy URL, send to teammate
3. Later: `opencode --session <id>` (extract from URL)
## Technical Details
**Session continuity:**
- Sessions are tied to working directory by default
- Use `-s` flag to load session from any directory
- File references (`@file.ts`) resolve relative to original working directory
**Performance:**
- `/sessions` browser loads metadata only (fast even with many sessions)
- Full session data loaded only when selected
- Export can be slow for very long conversations (1000+ messages)
## Advanced: External Semantic Search Integration
While OpenCode doesn't have built-in semantic search, you can build powerful search workflows using external tools.
### Option 1: Simple Text Search with ripgrep
**Find sessions mentioning specific topics:**
```bash
# Search all session exports for "authentication"
for session in $(ls ~/.config/opencode/sessions/*.json 2>/dev/null); do
opencode export $(basename $session .json) | rg -i "authentication" && echo "Found in: $session"
done
```
**Create searchable archive:**
```bash
# Export all sessions to markdown files
mkdir -p ~/opencode-archive
for session in ~/.config/opencode/sessions/*.json; do
id=$(basename $session .json)
opencode export $id > ~/opencode-archive/$id.md
done
# Search the archive
rg -i "database migration" ~/opencode-archive/
```
### Option 2: Structured Search with jq
**Find sessions by tool usage:**
```bash
# Find all sessions where you used the Edit tool
opencode export <session-id> | jq '.messages[] | select(.tool_calls[]?.name == "edit")'
# Extract all file paths edited in a session
opencode export <session-id> | jq -r '.messages[].tool_calls[]? | select(.name == "edit") | .parameters.filePath'
# Find sessions with errors
opencode export <session-id> | jq '.messages[] | select(.role == "tool" and .error != null)'
```
**Search across session metadata:**
```bash
# Find sessions in specific directory
opencode export <session-id> | jq 'select(.working_directory | contains("/path/to/project"))'
# Find sessions by date
opencode export <session-id> | jq 'select(.created_at > "2025-11-01")'
```
### Option 3: Semantic Search with Embeddings
**Using Python + sentence-transformers:**
```python
#!/usr/bin/env python3
"""
OpenCode Session Semantic Search
Requires: pip install sentence-transformers numpy
"""
import json
import subprocess
from pathlib import Path
from sentence_transformers import SentenceTransformer
import numpy as np
# Load model
model = SentenceTransformer('all-MiniLM-L6-v2')
# Get all session IDs
session_dir = Path.home() / '.config' / 'opencode' / 'sessions'
sessions = [f.stem for f in session_dir.glob('*.json')]
# Export and embed all sessions
embeddings = []
session_texts = []
for session_id in sessions:
result = subprocess.run(
['opencode', 'export', session_id],
capture_output=True,
text=True
)
if result.returncode == 0:
data = json.loads(result.stdout)
# Combine all message content
text = ' '.join([
msg.get('content', '')
for msg in data.get('messages', [])
if isinstance(msg.get('content'), str)
])
session_texts.append(text)
embeddings.append(model.encode(text))
# Search function
def search_sessions(query, top_k=5):
query_embedding = model.encode(query)
# Calculate cosine similarity
scores = [
np.dot(query_embedding, emb) / (np.linalg.norm(query_embedding) * np.linalg.norm(emb))
for emb in embeddings
]
# Get top results
top_indices = np.argsort(scores)[-top_k:][::-1]
results = []
for idx in top_indices:
results.append({
'session_id': sessions[idx],
'score': scores[idx],
'preview': session_texts[idx][:200]
})
return results
# Example usage
if __name__ == '__main__':
results = search_sessions("authentication and user management")
for r in results:
print(f"Session: {r['session_id']}")
print(f"Score: {r['score']:.3f}")
print(f"Preview: {r['preview']}...")
print()
```
**Usage:**
```bash
python opencode_search.py "implement OAuth flow"
```
### Option 4: SQLite Full-Text Search
**Index sessions in SQLite:**
```bash
#!/bin/bash
# create_session_db.sh
DB="$HOME/.opencode_search.db"
# Create database
sqlite3 "$DB" <<EOF
DROP TABLE IF EXISTS sessions;
CREATE VIRTUAL TABLE sessions USING fts5(
session_id,
working_dir,
created_at,
content
);
EOF
# Index all sessions
for session_file in ~/.config/opencode/sessions/*.json; do
session_id=$(basename "$session_file" .json)
# Export and extract data
export_data=$(opencode export "$session_id")
working_dir=$(echo "$export_data" | jq -r '.working_directory // ""')
created_at=$(echo "$export_data" | jq -r '.created_at // ""')
content=$(echo "$export_data" | jq -r '.messages[].content // "" | select(. != "")')
# Insert into database
sqlite3 "$DB" <<SQL
INSERT INTO sessions (session_id, working_dir, created_at, content)
VALUES (
'$session_id',
'$working_dir',
'$created_at',
'$(echo "$content" | sed "s/'/''/g")'
);
SQL
done
echo "Indexed $(sqlite3 "$DB" 'SELECT COUNT(*) FROM sessions;') sessions"
```
**Search the database:**
```bash
# Search for specific terms
sqlite3 ~/.opencode_search.db \
"SELECT session_id, snippet(sessions, 3, '**', '**', '...', 50)
FROM sessions
WHERE content MATCH 'authentication OR oauth'
ORDER BY rank
LIMIT 5;"
# Search by directory
sqlite3 ~/.opencode_search.db \
"SELECT session_id, created_at
FROM sessions
WHERE working_dir LIKE '%/myproject%'
ORDER BY created_at DESC;"
```
### Option 5: MCP Server Integration (Future)
**Concept:** Create an MCP server that provides semantic search:
```json
{
"mcpServers": {
"opencode-search": {
"command": "npx",
"args": ["-y", "opencode-search-server"],
"env": {
"OPENCODE_SESSION_DIR": "~/.config/opencode/sessions"
}
}
}
}
```
**This would enable:**
- Real-time semantic search within OpenCode TUI
- Natural language queries: "Find where I implemented the login system"
- Context-aware search based on current project
*Note: This is a potential future enhancement. Would require custom MCP server development.*
## Programmatic Session Naming
### Built-in: --title Flag (CLI Mode)
The `opencode run` command accepts a `--title` flag to set session names programmatically:
```bash
opencode run --title "Feature: Add Dark Mode" "Implement dark mode toggle in settings"
```
**Advantages:**
- Searchable in `/sessions` browser
- Appears in session metadata
- Scriptable for automation
**Limitations:**
- Only works with `opencode run` (not in TUI)
- Cannot rename existing sessions via CLI
- No built-in command to rename after creation
### Renaming Existing Sessions (Direct File Editing)
Since OpenCode stores sessions as JSON files, you can rename them by editing the session file directly.
**⚠️ Warning:** Direct file editing is not officially supported and may break in future OpenCode versions. Always backup sessions first.
**Method 1: Manual JSON Edit**
```bash
# 1. Find session file location (varies by OS/install method)
# Common locations:
# - ~/.config/opencode/sessions/
# - ~/.local/share/opencode/sessions/
# - ~/Library/Application Support/opencode/sessions/
# 2. List sessions to find the one to rename
ls ~/.config/opencode/sessions/
# 3. Edit the session file
# Look for a "title" or "nickname" field in the JSON structure
nano ~/.config/opencode/sessions/abc123xyz.json
# 4. Modify the appropriate field (structure may vary)
# Example structure (verify with actual file):
{
"id": "abc123xyz",
"title": "Old Name", // Change this
"metadata": {
"nickname": "Old Name" // Or this, depending on structure
}
}
```
**Method 2: Script-Based Renaming**
Save as `~/bin/opencode-rename-session`:
```bash
#!/bin/bash
# opencode-rename-session - Rename an OpenCode session
# Usage: opencode-rename-session <session-id> "New Title"
SESSION_ID="$1"
NEW_TITLE="$2"
# Detect session directory (try common locations)
for dir in \
"$HOME/.config/opencode/sessions" \
"$HOME/.local/share/opencode/sessions" \
"$HOME/Library/Application Support/opencode/sessions"; do
if [[ -d "$dir" ]]; then
SESSION_DIR="$dir"
break
fi
done
if [[ -z "$SESSION_DIR" ]]; then
echo "Error: Could not find OpenCode sessions directory"
exit 1
fi
SESSION_FILE="$SESSION_DIR/$SESSION_ID.json"
if [[ ! -f "$SESSION_FILE" ]]; then
echo "Error: Session $SESSION_ID not found"
exit 1
fi
if [[ -z "$NEW_TITLE" ]]; then
echo "Usage: opencode-rename-session <session-id> \"New Title\""
exit 1
fi
# Backup original
cp "$SESSION_FILE" "$SESSION_FILE.backup"
# Attempt to update title field (adjust based on actual structure)
# This assumes a "title" field exists - verify with actual session files
if command -v jq &> /dev/null; then
# Use jq if available
jq --arg title "$NEW_TITLE" '.title = $title' "$SESSION_FILE" > "$SESSION_FILE.tmp"
mv "$SESSION_FILE.tmp" "$SESSION_FILE"
echo "✓ Renamed session $SESSION_ID to: $NEW_TITLE"
echo " Backup saved: $SESSION_FILE.backup"
else
echo "Error: jq not found. Install jq to use this script."
exit 1
fi
```
**Make it executable:**
```bash
chmod +x ~/bin/opencode-rename-session
```
**Usage:**
```bash
# List sessions to get ID
opencode export | head -20 # Or check /sessions in TUI
# Rename session
opencode-rename-session abc123xyz "Authentication Feature Implementation"
```
**Method 3: Export, Edit, Re-import (Safest)**
Currently, OpenCode doesn't have a built-in "import" feature, but you can:
1. Export session to Markdown
2. Edit the title/content
3. Start a new session with the edited content
4. Archive the old session
```bash
# Export session
opencode export abc123xyz > session-backup.md
# Edit the exported file (add title at top, edit content)
nano session-backup.md
# Create new session with content (manual process)
# Start OpenCode and paste/reference the edited content
opencode --title "Renamed Session" --prompt "Continue from previous work..."
```
### Automated Session Organization
**Auto-title sessions by git branch:**
```bash
#!/bin/bash
# opencode-smart - Start OpenCode with auto-generated title
BRANCH=$(git branch --show-current 2>/dev/null || echo "no-branch")
DATE=$(date +%Y-%m-%d)
TITLE="[$BRANCH] Session $DATE"
opencode run --title "$TITLE" "$@"
```
**Usage:**
```bash
opencode-smart "Add user authentication"
# Creates session titled: "[feature/auth] Session 2025-11-08"
```
**Auto-title by directory:**
```bash
#!/bin/bash
# opencode-dir-title - Start session titled by project name
PROJECT_NAME=$(basename "$(pwd)")
TIMESTAMP=$(date +"%Y-%m-%d %H:%M")
TITLE="$PROJECT_NAME - $TIMESTAMP"
opencode run --title "$TITLE" "$@"
```
**Usage:**
```bash
cd ~/projects/myapp
opencode-dir-title "Fix the login bug"
# Creates session titled: "myapp - 2025-11-08 18:30"
```
### Feature Request: Native Rename Command
**Current status:** No built-in `/rename` command exists in OpenCode TUI.
**Workaround:** Use `--title` flag with `opencode run` or direct JSON editing.
**Potential future commands:**
```bash
# Hypothetical future syntax
/rename "New Session Title"
# Or via CLI
opencode session rename <session-id> "New Title"
```
If this is important to you, consider requesting it on the [OpenCode GitHub](https://github.com/sst/opencode/issues).
## Searching Sessions vs Searching Your Knowledge Base
### The Real Question: Do You Need to Search Sessions?
**Consider this workflow instead:**
- ✅ OpenCode conversations → Good insights → `/export` → Create article
- ✅ Search your curated articles (not messy session logs)
- ✅ Use `/sessions` only to resume recent work
**Your knowledge base is your articles, not your session history.**
### If You Do Need to Search Sessions
**Simple approach:**
```bash
# Find sessions in current project
ls -lth ~/.local/share/opencode/storage/session/*/
# Search session files directly with grep
grep -r "search term" ~/.local/share/opencode/storage/session/
```
```bash
# Use jq to parse session JSON
cat ~/.local/share/opencode/storage/session/*/ses_*.json | jq '.messages[].content' | grep -i "search term"
```
**Personal automation note:** I maintain search scripts in my private Coding Actions folder for more complex session searching workflows. The examples above show the core concepts.
## Advanced: Session Storage Format
**Session file location:**
```
~/.config/opencode/sessions/<session-id>.json
```
**Typical structure:**
```json
{
"id": "abc123xyz",
"created_at": "2025-11-08T18:30:00-08:00",
"updated_at": "2025-11-08T19:15:00-08:00",
"working_directory": "/path/to/project",
"model": "opencode/claude-sonnet-4-5",
"messages": [
{
"role": "user",
"content": "Add authentication to the app",
"timestamp": "2025-11-08T18:30:00-08:00"
},
{
"role": "assistant",
"content": "I'll help you add authentication...",
"tool_calls": [
{
"id": "call_123",
"name": "read",
"parameters": {
"filePath": "/path/to/project/src/auth.ts"
}
}
],
"timestamp": "2025-11-08T18:30:15-08:00"
},
{
"role": "tool",
"tool_call_id": "call_123",
"name": "read",
"result": "file contents...",
"timestamp": "2025-11-08T18:30:16-08:00"
}
],
"metadata": {
"nickname": "Add authentication feature",
"tags": ["auth", "security"],
"total_tokens": 15420,
"total_cost": 0.75
}
}
```
**Key fields for automation:**
- `id` - Session identifier
- `working_directory` - Where session was started
- `messages[].role` - "user", "assistant", or "tool"
- `messages[].tool_calls` - Tools invoked by assistant
- `metadata` - Custom fields (may vary by OpenCode version)
**Direct file access:**
```bash
# List all sessions
ls ~/.config/opencode/sessions/
# Read session directly
cat ~/.config/opencode/sessions/abc123xyz.json | jq '.messages[0]'
# Extract working directory
cat ~/.config/opencode/sessions/abc123xyz.json | jq -r '.working_directory'
```
**Automation possibilities:**
- Build custom session browsers
- Generate session reports
- Integrate with project management tools
- Create session backups
- Analyze tool usage patterns
## Pro Automation Workflows
### 1. Auto-Archive Completed Sessions
```bash
#!/bin/bash
# Auto-archive sessions older than 30 days
ARCHIVE_DIR="$HOME/Documents/opencode-archives"
SESSION_DIR="$HOME/.config/opencode/sessions"
CUTOFF_DATE=$(date -d '30 days ago' +%s 2>/dev/null || date -v-30d +%s)
mkdir -p "$ARCHIVE_DIR"
for session_file in "$SESSION_DIR"/*.json; do
session_id=$(basename "$session_file" .json)
# Get session creation date
created=$(cat "$session_file" | jq -r '.created_at')
created_ts=$(date -d "$created" +%s 2>/dev/null || date -j -f "%Y-%m-%dT%H:%M:%S%z" "$created" +%s)
if [[ $created_ts -lt $CUTOFF_DATE ]]; then
echo "Archiving: $session_id"
opencode export "$session_id" > "$ARCHIVE_DIR/$session_id.md"
fi
done
```
### 2. Session Cost Tracking
```bash
#!/bin/bash
# Track total OpenCode usage costs
TOTAL_COST=0
for session_file in ~/.config/opencode/sessions/*.json; do
cost=$(cat "$session_file" | jq -r '.metadata.total_cost // 0')
TOTAL_COST=$(echo "$TOTAL_COST + $cost" | bc)
done
echo "Total OpenCode cost: \$TOTAL_COST"
```
### 3. Project Session Browser
```bash
#!/bin/bash
# List all sessions for current project
PROJECT_DIR=$(pwd)
echo "Sessions for: $PROJECT_DIR"
echo ""
for session_file in ~/.config/opencode/sessions/*.json; do
working_dir=$(cat "$session_file" | jq -r '.working_directory')
if [[ "$working_dir" == "$PROJECT_DIR" ]]; then
session_id=$(basename "$session_file" .json)
created=$(cat "$session_file" | jq -r '.created_at')
nickname=$(cat "$session_file" | jq -r '.metadata.nickname // "Untitled"')
echo "[$session_id] $nickname"
echo " Created: $created"
echo " Resume: opencode -s $session_id"
echo ""
fi
done
```