opencode-agent-optimizer
v0.1.0
Published
Analyze OpenCode log files to optimize model and agent configurations for cost savings
Maintainers
Readme
opencode-agent-optimizer
Analyze OpenCode's log files to see which models and agents are actually being used, flag configuration mismatches, and get concrete recommendations for reducing costs without compromising quality.
Features
- Usage visibility — timeline, per-model call counts, per-agent breakdowns, and session listings from OpenCode log files
- Configuration comparison — side-by-side table of configured model vs actual model for every agent, with mismatch detection
- Recommendation engine — suggests model downgrades for subagents, config pinning to prevent drift, and new specialized agent ideas
- Delegation analysis — measures how often primary agents delegate to subagents vs doing work directly, with streak and heavy-session reporting
- Real-time watching — live tail of the active log file showing LLM calls and session creations as they happen
- Before/after impact — projected reduction in expensive-tier calls if all recommendations are applied
- OpenCode integration — installs a
/analyze-usageslash command andanalyze-usageskill into OpenCode for in-editor access - Zero external dependencies — pure Node.js standard library, no npm dependencies at runtime
- Timezone-aware filtering —
--sinceand--untilaccept local dates; log timestamps (UTC) are converted correctly
Quick Start
npm install -g opencode-agent-optimizer
# First-time setup: pick your cost tiers and install OpenCode integration
opencode-agent-optimizer install
# See recommendations across all logs
opencode-agent-optimizer suggest --all
# Full usage summary for today's log
opencode-agent-optimizer summary
# Live tail the active log
opencode-agent-optimizer watchRequirements
- Node.js >= 18.0.0
- OpenCode installed and in use (log files are read from
~/.local/share/opencode/logby default)
Commands
install
Interactive first-time setup. Discovers available models by running opencode models, prompts you to select providers and assign a model to each cost tier (expensive / moderate / cheap), then saves your preferences and installs the OpenCode skill and command files.
opencode-agent-optimizer installExample session:
OpenCode Agent Analyzer — Install ──────────────────────────────
Fetching available models from OpenCode...
Found 24 models across 2 providers.
Which providers do you use? (enter comma-separated numbers)
1. github-copilot (12 models)
2. google (12 models)
> 1
Filtering to 12 models from github-copilot.
Select your EXPENSIVE tier model (for primary/orchestrator agents):
1. github-copilot/claude-haiku-4.5
2. github-copilot/claude-opus-4.6
3. github-copilot/claude-sonnet-4.6
...
> 2
→ github-copilot/claude-opus-4.6
Select your MODERATE tier model (for subagents doing complex work):
> 3
→ github-copilot/claude-sonnet-4.6
Select your CHEAP tier model (for subagents doing simple lookups):
> 1
→ github-copilot/claude-haiku-4.5
✓ Saved preferences to ~/.config/opencode-agent-optimizer/config.json
✓ Installed skill ~/.config/opencode/skills/analyze-usage/SKILL.md
✓ Installed command ~/.config/opencode/commands/analyze-usage.md
Use /analyze-usage in OpenCode to invoke the skill.After install, use /analyze-usage inside OpenCode to run the full suggestion engine and have the AI interpret results and offer to write config files for you.
uninstall
Removes all files installed by the install command: the skill file, the command file, and the skill directory (if empty). Does not remove your preferences config.
opencode-agent-optimizer uninstallsummary
Full analysis of one or more log files: timeline, totals, calls by model, calls by agent (with model breakdowns), session list, and a config-vs-actual comparison table.
opencode-agent-optimizer summary
opencode-agent-optimizer summary --all
opencode-agent-optimizer summary --since 2026-02-20Example output:
OpenCode Log Analyzer ──────────────────────────────────────────
Source: 3 log files in ~/.local/share/opencode/log (2026-02-25 → 2026-02-27)
Timeline 07:12:44 → 18:43:01 (11h 30m 17s)
Totals 412 LLM calls 38 sessions 0 errors
(+14 internal calls: title/compaction)
LLM Calls by Model
claude-opus-4.6 198 ██████████████████████
claude-sonnet-4.6 156 █████████████████
claude-haiku-4.5 58 ██████
LLM Calls by Agent
🤖 build (primary) 198 calls claude-opus-4.6 ×198
🔧 coder (subagent) 134 calls claude-sonnet-4.6 ×134
🔧 explore (subagent) 52 calls claude-opus-4.6 ×52
🔧 review (subagent) 22 calls claude-sonnet-4.6 ×22
🔧 docs-lookup (subagent) 6 calls claude-haiku-4.5 ×6
Sessions
15 parent sessions 23 subagent sessions
07:14:02 @coder Implement retry logic in auth module
07:31:55 @explore Find all usages of deprecated API
08:02:11 @coder Add unit tests for payment service
...
Config vs Actual
Agent Configured Model Actual Model(s) Status
──────────────────────────────────────────────────────────────────────────────────
🔧 coder claude-sonnet-4.6 claude-sonnet-4.6 ✓ match
🤖 build claude-opus-4.6 claude-opus-4.6 ✓ match
🔧 explore claude-opus-4.6 no config
🔧 review claude-sonnet-4.6 claude-sonnet-4.6 ✓ matchwatch
Real-time tail of the active (or specified) log file. Prints each LLM call and session creation as it occurs. Warns inline if a call uses a different model than the agent's config specifies.
opencode-agent-optimizer watch
opencode-agent-optimizer watch /path/to/specific.logExample output:
OpenCode Live Log Watcher ────────────────────────────────────────
Watching: ~/.local/share/opencode/log/2026-02-27T081234.log
Press Ctrl+C to stop
[08:14:02] 🤖 build (primary) → claude-opus-4.6 ✓
[08:14:18] 📋 Session: "Implement retry logic in auth module" (@coder)
[08:14:19] 🔧 coder (subagent) → claude-sonnet-4.6 ✓
[08:14:35] 🔧 coder (subagent) → claude-sonnet-4.6 ✓
[08:15:01] 🔧 explore (subagent) → claude-opus-4.6 ⚠ expected: claude-sonnet-4.6
[08:15:44] 🤖 build (primary) → claude-opus-4.6 ✓Watch mode does not support --all, --since, or --until; it always operates on a single file.
compare
Standalone config-vs-actual comparison table. Lists every agent from both config files and log data, showing the configured model, the model(s) actually used, and a match/mismatch status.
opencode-agent-optimizer compare
opencode-agent-optimizer compare --all
opencode-agent-optimizer compare --since 2026-02-20 --until 2026-02-27Example output:
OpenCode Config vs Actual Usage ────────────────────────────────
Source: 5 log files in ~/.local/share/opencode/log (2026-02-23 → 2026-02-27)
Config: ~/.config/opencode/agents
Configured vs Actual Model Usage
Agent Configured Model Actual Model(s) Status
────────────────────────────────────────────────────────────────────────────────
🔧 browser claude-sonnet-4.6 claude-sonnet-4.6 ✓ match
🤖 build claude-opus-4.6 claude-opus-4.6 ✓ match
🔧 coder claude-sonnet-4.6 claude-sonnet-4.6 ✓ match
🔧 docs-lookup claude-haiku-4.5 claude-haiku-4.5 ✓ match
🔧 explore claude-opus-4.6 no config
🔧 review claude-sonnet-4.6 claude-opus-4.6 ✗ mismatch
✗ 1 agent(s) used models different from their configuration.suggest
The full recommendation engine. Analyzes usage patterns across all agents, produces prioritized optimization suggestions, shows copyable config snippets, and reports before/after projected impact on expensive-tier call volume. Also includes a delegation analysis section for primary agents.
opencode-agent-optimizer suggest
opencode-agent-optimizer suggest --all
opencode-agent-optimizer suggest --all --since 2026-02-20
opencode-agent-optimizer suggest --all --no-config
opencode-agent-optimizer suggest --all --write-configs ~/.config/opencode/agentsExample output:
OpenCode Agent Suggestions ────────────────────────────────────────
CURRENT COST PROFILE
Model Tier Calls % of Total
$$$ expensive 198 48% ██████████████████████
$$ moderate 178 43% ████████████████████
$ cheap 36 9% ████
RECOMMENDATIONS
1. Downgrade explore: claude-opus-4.6 → claude-sonnet-4.6 [HIGH]
52 calls across 18 sessions (avg 2.9/session, median 2)
Task nature: read-only — find, check, investigate, search
Impact: 26% of expensive-tier calls
Sample tasks:
• Find all usages of deprecated API
• Check where config is loaded
• Investigate slow query in billing module
2. Pin explore config: claude-sonnet-4.6 [LOW]
52 calls across 18 sessions (avg 2.9/session, median 2)
Currently using $$$ expensive — make explicit to prevent drift
Impact: Prevents accidental model drift
NEW AGENT IDEAS
3. Consider: "search" agent with claude-haiku-4.5
11 of 18 explore sessions are simple lookups (<=5 calls)
Potential savings: Move ~33 calls from moderate to cheap tier
SUGGESTED CONFIGS
--- explore.md (update model line) ───────────────────────────────
---
description: Explore and investigate the codebase.
mode: subagent
model: github-copilot/claude-sonnet-4.6
---
--- search.md (NEW) ──────────────────────────────────────────────
---
description: Fast file and code search using glob and grep patterns.
mode: subagent
model: github-copilot/claude-haiku-4.5
---
You are a file search specialist. Use glob, grep, and read tools
to quickly locate files, code patterns, and configuration.
Return concise, structured findings.
ESTIMATED IMPACT
Before: 198 expensive / 178 moderate / 36 cheap (48%/43%/9%)
After: 146 expensive / 230 moderate / 69 cheap (35%/56%/17%)
Expensive-tier calls reduced by ~26%
DELEGATION ANALYSIS
build (primary agent)
Direct LLM calls: 198 Subagent spawns: 23 Ratio: 0.12 (moderate)
Avg calls between delegations: 8.6 Longest streak: 31
Delegates to: coder×14 explore×6 review×3
Heavy sessions (>=10 direct calls):
• 01f3a2b8c4d1… 24 direct calls, 3 delegations
• 00e9d1f7a3c2… 18 direct calls, 2 delegations
Use --write-configs <dir> to write these filesOptions
All options that take a value use a space separator (e.g. --since 2026-02-20).
| Flag | Commands | Description |
|------|----------|-------------|
| --all | summary, compare, suggest | Analyze all log files in the log directory, not just the latest |
| --since YYYY-MM-DD | summary, compare, suggest | Include only events on or after this local date |
| --until YYYY-MM-DD | summary, compare, suggest | Include only events before this local date (exclusive) |
| --write-configs PATH | suggest | Write each suggested config file directly to the given directory |
| --no-config | summary, compare, suggest | Ignore agent config files on disk; treat all agents as unconfigured |
| --skip-config | install | Skip the interactive model-selection step during install |
| --log-dir PATH | all | Override the default log directory (~/.local/share/opencode/log) |
| --config-dir PATH | all | Override the default agent config directory (~/.config/opencode/agents) |
| --help / -h | — | Print help and exit |
Date filtering
--since and --until accept dates in YYYY-MM-DD format and are interpreted as local time. OpenCode logs timestamps in UTC, so the tool converts your local date to the correct UTC boundary before filtering. Combining both flags produces a closed window:
# Last 7 days
opencode-agent-optimizer suggest --all --since 2026-02-20
# A specific week
opencode-agent-optimizer summary --all --since 2026-02-17 --until 2026-02-24Writing config files
Pass --write-configs with a directory path to have the suggest command write all recommended config files to disk instead of only printing them:
opencode-agent-optimizer suggest --all --write-configs ~/.config/opencode/agentsThe tool will not silently overwrite files without prompting when invoked via the /analyze-usage OpenCode integration (the AI handles that interaction). When called directly with --write-configs it writes unconditionally, so review suggestions first with a plain suggest run.
Configuration
Tool preferences (~/.config/opencode-agent-optimizer/config.json)
Created by opencode-agent-optimizer install. Stores the three model tier assignments and your active providers. You can edit it manually at any time:
{
"preferredModels": {
"expensive": "github-copilot/claude-opus-4.6",
"moderate": "github-copilot/claude-sonnet-4.6",
"cheap": "github-copilot/claude-haiku-4.5"
},
"providers": ["github-copilot"]
}If this file is absent or invalid, the suggestion engine falls back to inferring a provider prefix from existing agent configs or log data, then guessing appropriate model names. Running install again will re-create it.
Agent configs (~/.config/opencode/agents/*.md)
These are standard OpenCode agent config files with YAML frontmatter. The tool reads the model and mode fields for comparison and mismatch detection:
---
description: Explore and investigate the codebase.
mode: subagent
model: github-copilot/claude-sonnet-4.6
---
Your system prompt here...Log files (~/.local/share/opencode/log/)
OpenCode writes structured log files named by start timestamp (e.g. 2026-02-27T081234.log). The tool reads these directly with no additional setup required.
Philosophy
The tool is built around a clear principle: use your best model where quality matters most (planning and orchestration), and let cheaper models handle the execution work.
In practice this means:
- Primary / orchestrator agents (
build,plan, and anything running inprimarymode) should stay on your expensive tier. They set direction, decompose tasks, and decide what to delegate. Their quality directly affects the quality of everything downstream. - Subagents do the actual work — writing code, reading files, searching, reviewing, browsing. Most of that work does not require a frontier reasoning model. A read-only file search or a simple lookup that takes 2-3 LLM calls can almost always be handled by a cheap-tier model.
The suggestion engine reflects this philosophy with a hard rule: it never suggests downgrading a primary agent. Every downgrade and new-agent recommendation targets subagents only.
How the engine decides what to suggest
The engine classifies each agent's workload by examining session titles and the agent name itself:
read-only— sessions dominated by exploration keywords (find, check, investigate, search, analyze)write— sessions dominated by modification keywords (fix, implement, create, refactor, update)docs/review/browser/orchestration— inferred from agent namemixed— significant presence of both read and write keywords
It then applies these rules:
- Subagent on expensive tier, read-only or docs tasks, trivially simple (median ≤ 3 calls/session) → suggest cheap tier directly (skip moderate). Priority scales with call count.
- Subagent on expensive tier, read-only or docs tasks, more complex (median > 3 calls/session) → suggest moderate tier.
- Subagent on expensive tier, any other task nature → suggest moderate tier.
- No explicit model in agent config → suggest pinning the model currently in use to prevent drift when OpenCode's default changes.
- Config model differs from most-used model in logs → flag the mismatch (may indicate a recent config change that hasn't fully propagated in logs yet).
- Mixed-task agent with many simple sessions (≥ 30% of sessions ≤ 4 calls) → suggest creating a dedicated
searchagent on the cheap tier to handle the simple cases. - Read-only agent where ≥ 50% of sessions are simple lookups (≤ 5 calls) → suggest a
searchagent split if one hasn't already been recommended. - Moderate-tier agent with median ≤ 3 calls/session (excluding review/browser/orchestration) → suggest cheap tier.
Recommendations are sorted by priority (high → medium → low), then by call count descending.
Cost tiers
The tool works entirely in relative tiers rather than dollar amounts, because pricing varies by provider, account type, and changes over time. You define what "expensive", "moderate", and "cheap" mean for your setup during install.
Built-in heuristics classify models by name when no user config is present:
- Cheap: models containing
haiku,mini,nano,flash,lite,8b, orscout - Expensive: models containing
opus,o1,o3,o3-pro,gpt-5(non-mini),gemini-3-pro(non-flash),r1, ork2.5 - Moderate: everything else (sonnet, gpt-4.x, gemini-2.5-pro, deepseek-v3, llama-405b, etc.)
OpenCode Integration
Running install sets up two files inside your OpenCode config directory:
/analyze-usage slash command
Located at ~/.config/opencode/commands/analyze-usage.md. When you type /analyze-usage in OpenCode, it runs opencode-agent-optimizer suggest --all and feeds the output to the AI, which:
- Summarizes the most impactful recommendations and explains the reasoning behind each
- Flags delegation efficiency concerns and what they mean in practice
- Checks whether any recommendation is already reflected in your current config (log data can lag behind recent config changes)
- Offers to write updated config files directly to
~/.config/opencode/agents/on your behalf — asking before overwriting anything
You can pass arguments after the command (e.g. /analyze-usage --since 2026-02-20) and they are forwarded to the underlying CLI call.
analyze-usage skill
Located at ~/.config/opencode/skills/analyze-usage/SKILL.md. This skill teaches the AI how to interpret the analyzer's output, explains the cost profile sections and recommendation types, describes the delegation analysis metrics, and sets the expectation that config changes should be applied by writing files — not by asking you to copy ANSI-colored terminal snippets.
The skill is automatically invoked when the /analyze-usage command runs. You can also load it explicitly with @analyze-usage in any session when discussing agent optimization.
Alternative invocations
The package can also be run without a global install:
# Using Bun directly from source
bun run opencode-agent-optimizer.ts suggest --all
# Using npx with tsx
npx tsx opencode-agent-optimizer.ts suggest --all
# Using Node.js 22.6+ native TypeScript stripping
node --experimental-strip-types opencode-agent-optimizer.ts suggest --allContributing
Bug reports and pull requests are welcome at github.com/jasoncabot-ms/opencode-agent-optimizer.
To build from source:
git clone https://github.com/jasoncabot-ms/opencode-agent-optimizer
cd opencode-agent-optimizer
npm run buildThe build script compiles opencode-agent-optimizer.ts with Bun targeting Node ESM and prepends the #!/usr/bin/env node shebang. The output goes to dist/opencode-agent-optimizer.js.
To run tests:
bun testLicense
MIT — see LICENSE for details.
Author: Jason Cabot
