OpenCode CLI - Token-Efficient Configuration
Use OpenCode as an autonomous coding worker with Hermes for maximum token savings.
When to Use
- User explicitly asks to use OpenCode
- You want an external coding agent to implement/refactor/review code
- Long-running coding sessions with progress checks
- Parallel task execution in isolated workdirs
Prerequisites (Token-Efficient)
- OpenCode installed:
npm i -g opencode-ai@latest - Auth configured:
opencode auth loginor set provider env vars - Verify:
opencode auth listshould show at least one provider - Git repository for code tasks (avoids repo detection overhead)
- Use
pty=trueonly when interactive; otherwise useopencode runfor one-shot
Token-Saving Modes
One-Shot Mode (RECOMMENDED - Saves 40-60% tokens)
terminal(command="opencode run 'Add retry logic to API calls and update tests'", workdir="~/project")
- Runs once, returns result, exits immediately
- No conversation history overhead
- Best for: bug fixes, single features, code reviews
Background Mode (For iterative work)
terminal(command="opencode", workdir="~/project", background=true, pty=true)
# Returns session_id
# Send prompt (only when needed)
process(action="submit", session_id="<id>", data="Implement OAuth refresh flow")
# Poll for completion, don't log every turn
process(action="poll", session_id="<id>")
Key Token Optimization Tips
Use
--modelflag to specify cheapest adequate modelopencode run 'fix bug' --model anthropic/claude-3-5-sonnet-20241022Use
--allowedToolsto limit tool access and reduce prompt sizeclaude -p 'Add error handling' --allowedTools 'Read,Edit'Set
--max-turnsto bound conversation lengthopencode run 'refactor' --max-turns 5Use
--json-schemafor structured output instead of natural language descriptionsPrefer
opencode runover interactive TUI for bounded tasks - avoids PTY overhead and session stateCache results - if same task repeats, store and reuse successful prompts
Avoid unnecessary context - only pass relevant files, not entire project
Common Workflows
Code Generation (One-Shot)
opencode run 'Create REST API for user management' --model openrouter/anthropic/claude-3.5-sonnet
Debugging (One-Shot)
opencode run 'Why does this return null? Debug and fix' --max-turns 3
Code Review (One-Shot)
opencode run 'Review this code for security vulnerabilities' --allowedTools 'Read'