opencode-usage-v2 0.2.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
opencode_usage/llm.py ADDED
@@ -0,0 +1,93 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import ssl
5
+ import urllib.error
6
+ import urllib.request
7
+ from typing import Any
8
+
9
+ from .auth import Credentials
10
+
11
+ """Thin OpenAI-compatible HTTP client using stdlib urllib."""
12
+
13
+
14
+ def chat_complete(
15
+ credentials: Credentials,
16
+ messages: list[dict[str, str]],
17
+ *,
18
+ temperature: float = 0.3,
19
+ max_tokens: int = 4096,
20
+ timeout: int = 60,
21
+ ) -> str:
22
+ """Call OpenAI-compatible API and return response text."""
23
+ url = credentials.base_url.rstrip("/") + "/chat/completions"
24
+
25
+ body = {
26
+ "model": credentials.model,
27
+ "messages": messages,
28
+ "temperature": temperature,
29
+ "max_tokens": max_tokens,
30
+ }
31
+ data = json.dumps(body).encode()
32
+
33
+ req = urllib.request.Request(
34
+ url,
35
+ data=data,
36
+ method="POST",
37
+ headers={
38
+ "Authorization": f"Bearer {credentials.api_key}",
39
+ "Content-Type": "application/json",
40
+ },
41
+ )
42
+
43
+ ctx = ssl.create_default_context()
44
+ try:
45
+ response = urllib.request.urlopen(req, context=ctx, timeout=timeout)
46
+ except urllib.error.HTTPError as e:
47
+ if e.code == 401:
48
+ raise RuntimeError("Authentication failed: check your API key") from e
49
+ elif e.code == 429:
50
+ raise RuntimeError("Rate limit exceeded") from e
51
+ else:
52
+ raise RuntimeError(f"HTTP {e.code}: {e.reason}") from e
53
+ except urllib.error.URLError as e:
54
+ raise RuntimeError(f"Network error: {e.reason}") from e
55
+ except TimeoutError as e:
56
+ raise RuntimeError(f"Request timed out after {timeout}s") from e
57
+
58
+ try:
59
+ result = json.loads(response.read().decode())
60
+ # Defensive checks for malformed responses
61
+ if "choices" not in result or not result["choices"]:
62
+ raise RuntimeError("LLM returned empty choices array")
63
+ choice = result["choices"][0]
64
+ if "message" not in choice or "content" not in choice["message"]:
65
+ raise RuntimeError("LLM returned malformed response structure")
66
+ return choice["message"]["content"]
67
+ finally:
68
+ response.close()
69
+
70
+
71
+ def chat_complete_json(
72
+ credentials: Credentials,
73
+ messages: list[dict[str, str]],
74
+ **kwargs: Any,
75
+ ) -> dict[str, Any]:
76
+ """Call OpenAI-compatible API and return parsed JSON response."""
77
+ raw = chat_complete(credentials, messages, **kwargs)
78
+
79
+ # Strip markdown code fences if present
80
+ stripped = raw
81
+ if stripped.startswith("```json\n"):
82
+ stripped = stripped[8:]
83
+ if stripped.startswith("```\n"):
84
+ stripped = stripped[4:]
85
+ if stripped.endswith("\n```"):
86
+ stripped = stripped[:-4]
87
+ elif stripped.endswith("```"):
88
+ stripped = stripped[:-3]
89
+
90
+ try:
91
+ return json.loads(stripped)
92
+ except json.JSONDecodeError as e:
93
+ raise RuntimeError(f"LLM returned non-JSON: {raw[:200]}") from e
@@ -0,0 +1,145 @@
1
+ """Model discovery, ranking, and interactive selection via ``opencode models``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from rich.console import Console
8
+ from rich.prompt import Prompt
9
+ from rich.table import Table
10
+
11
+ from ._opencode_cli import run_models
12
+
13
+ _PREFERRED: list[str] = [
14
+ "minimax-m2.5-free",
15
+ "kimi-k2.5",
16
+ "glm-5",
17
+ "claude-sonnet-4",
18
+ "gpt-5.2",
19
+ ]
20
+
21
+ _TOP_N = 5
22
+
23
+
24
+ def list_models() -> list[str]:
25
+ """Return all connected model IDs from ``opencode models``."""
26
+ return run_models()
27
+
28
+
29
+ def search_models(models: list[str], query: str) -> list[str]:
30
+ """Filter *models* by case-insensitive substring match on *query*."""
31
+ q = query.lower()
32
+ return [m for m in models if q in m.lower()]
33
+
34
+
35
+ def _tier(model_id: str) -> tuple[int, int]:
36
+ """Return ``(tier, preferred_index)`` for sorting.
37
+
38
+ Tier 0 — matches a *_PREFERRED* substring (sub-sorted by preference order).
39
+ Tier 1 — ``opencode/*`` models not in the preferred list.
40
+ Tier 2 — ``github-copilot/*`` models.
41
+ Tier 3 — everything else.
42
+ """
43
+ lower = model_id.lower()
44
+ for idx, pattern in enumerate(_PREFERRED):
45
+ if pattern.lower() in lower:
46
+ return 0, idx
47
+ if lower.startswith("opencode/"):
48
+ return 1, 0
49
+ if lower.startswith("github-copilot/"):
50
+ return 2, 0
51
+ return 3, 0
52
+
53
+
54
+ def rank_models(models: list[str]) -> list[str]:
55
+ """Sort *models* by tier then alphabetically within each tier."""
56
+ return sorted(models, key=lambda m: (*_tier(m), m.lower()))
57
+
58
+
59
+ def select_model_interactive(console: Console) -> str:
60
+ """Interactive model picker — exits with code 1 if opencode is unavailable."""
61
+ all_models = list_models()
62
+ if not all_models:
63
+ console.print(
64
+ "[red]Error:[/red] Could not list models — is [bold]opencode[/bold] installed?"
65
+ )
66
+ sys.exit(1)
67
+
68
+ ranked = rank_models(all_models)
69
+ top = ranked[:_TOP_N]
70
+
71
+ console.print()
72
+ console.print("[cyan]Select a model for insights analysis:[/cyan]")
73
+ _print_choices(console, top)
74
+ console.print(f" [dim]s[/dim] Search from all {len(all_models)} models")
75
+ console.print()
76
+
77
+ while True:
78
+ answer = Prompt.ask("Choice", console=console).strip()
79
+
80
+ if answer.lower() == "s":
81
+ model = _search_flow(console, ranked)
82
+ if model is not None:
83
+ return model
84
+ console.print()
85
+ _print_choices(console, top)
86
+ console.print(f" [dim]s[/dim] Search from all {len(all_models)} models")
87
+ console.print()
88
+ continue
89
+
90
+ try:
91
+ idx = int(answer) - 1
92
+ if 0 <= idx < len(top):
93
+ selected = top[idx]
94
+ console.print(f" → [green]{selected}[/green]")
95
+ return selected
96
+ except ValueError:
97
+ pass
98
+
99
+ console.print(f"[yellow]Invalid choice.[/yellow] Enter 1-{len(top)} or 's' to search.")
100
+
101
+
102
+ def _print_choices(console: Console, models: list[str]) -> None:
103
+ """Print a numbered list of model IDs."""
104
+ for i, m in enumerate(models, 1):
105
+ console.print(f" [bold]{i}[/bold] {m}")
106
+
107
+
108
+ def _search_flow(console: Console, ranked: list[str]) -> str | None:
109
+ """Prompt for a search query, display matches, and let user pick one."""
110
+ query = Prompt.ask("Search", console=console).strip()
111
+ if not query:
112
+ return None
113
+
114
+ matches = search_models(ranked, query)
115
+ if not matches:
116
+ console.print(f"[yellow]No models matching '{query}'.[/yellow]")
117
+ return None
118
+
119
+ show = matches[:15]
120
+ table = Table(show_header=False, box=None, padding=(0, 2))
121
+ table.add_column(style="bold", width=4, justify="right")
122
+ table.add_column()
123
+ for i, m in enumerate(show, 1):
124
+ table.add_row(str(i), m)
125
+ console.print(table)
126
+
127
+ if len(matches) > 15:
128
+ console.print(f" [dim]… and {len(matches) - 15} more[/dim]")
129
+
130
+ console.print()
131
+ pick = Prompt.ask("Pick (or Enter to go back)", default="", console=console).strip()
132
+ if not pick:
133
+ return None
134
+
135
+ try:
136
+ idx = int(pick) - 1
137
+ if 0 <= idx < len(show):
138
+ selected = show[idx]
139
+ console.print(f" → [green]{selected}[/green]")
140
+ return selected
141
+ except ValueError:
142
+ pass
143
+
144
+ console.print("[yellow]Invalid choice.[/yellow]")
145
+ return None
@@ -0,0 +1,240 @@
1
+ """Rich table rendering for usage stats."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+ from rich.table import Table
10
+ from rich.text import Text
11
+
12
+ if TYPE_CHECKING:
13
+ from .db import UsageRow
14
+
15
+ console = Console()
16
+
17
+
18
+ def _fmt_tokens(n: int) -> str:
19
+ """Human-readable token count."""
20
+ if n >= 1_000_000_000:
21
+ return f"{n / 1_000_000_000:.1f}B"
22
+ if n >= 1_000_000:
23
+ return f"{n / 1_000_000:.1f}M"
24
+ if n >= 1_000:
25
+ return f"{n / 1_000:.1f}K"
26
+ return str(n)
27
+
28
+
29
+ def _fmt_cost(c: float) -> str:
30
+ if c == 0:
31
+ return "-"
32
+ if c < 0.01:
33
+ return f"${c:.4f}"
34
+ return f"${c:.2f}"
35
+
36
+
37
+ _BAR_FULL = "█"
38
+ _BAR_EMPTY = "░"
39
+ _BAR_WIDTH_DEFAULT = 8
40
+
41
+
42
+ def _spark_bar(value: int, max_value: int, width: int = _BAR_WIDTH_DEFAULT) -> str:
43
+ """Horizontal bar proportional to value/max, fixed *width* characters."""
44
+ if width < 1:
45
+ width = 1
46
+ if max_value <= 0 or value <= 0:
47
+ return _BAR_EMPTY * width
48
+ filled = max(1, round(value / max_value * width))
49
+ filled = min(filled, width)
50
+ return _BAR_FULL * filled + _BAR_EMPTY * (width - filled)
51
+
52
+
53
+ def _fmt_delta(pct: float) -> str:
54
+ """Format a percentage delta with color and arrow."""
55
+ if pct > 0:
56
+ return f"[red]↑{pct:.0f}%[/]"
57
+ if pct < 0:
58
+ return f"[green]↓{abs(pct):.0f}%[/]"
59
+ return "[dim]→0%[/]"
60
+
61
+
62
+ def _short_model(name: str) -> str:
63
+ """Abbreviate common model names to save table width."""
64
+ import re
65
+
66
+ # Strip vendor prefix: "vendor-variant-1-2-20251016" → "variant-1-2"
67
+ m = re.match(r"\w+-([a-z]\w+)-(\d+-\d+)(?:-\d+)?$", name)
68
+ if m:
69
+ return f"{m.group(1)}-{m.group(2)}"
70
+
71
+ # gemini-3-pro-preview → gemini-3-pro
72
+ name = re.sub(r"-preview$", "", name)
73
+ # grok-code-fast-1 → grok-fast-1
74
+ name = name.replace("grok-code-", "grok-")
75
+ # minimax-m2.5-free → minimax-m2.5
76
+ name = re.sub(r"-free$", "", name)
77
+ return name
78
+
79
+
80
+ def _make_table(
81
+ title: str,
82
+ label_header: str,
83
+ rows: list[UsageRow],
84
+ show_breakdown: bool = True,
85
+ show_detail: str | None = None,
86
+ trend_values: list[int] | None = None,
87
+ deltas: list[float | None] | None = None,
88
+ ) -> Table:
89
+ table = Table(
90
+ title=title,
91
+ show_header=True,
92
+ header_style="bold cyan",
93
+ border_style="dim",
94
+ title_style="bold white",
95
+ pad_edge=True,
96
+ )
97
+
98
+ label_max = 24 if show_detail else 30
99
+ detail_max = 18 if show_detail else 0
100
+
101
+ # Estimate fixed column widths (content + padding + borders)
102
+ # Each column has ~3 chars overhead (padding + border).
103
+ col_overhead = 3
104
+ fixed_width = label_max + col_overhead # label
105
+ if show_detail:
106
+ fixed_width += detail_max + col_overhead
107
+ fixed_width += 5 + col_overhead # Calls
108
+ if show_breakdown:
109
+ fixed_width += (6 + col_overhead) * 4 # Input, Output, Cache R, Cache W
110
+ fixed_width += (7 + col_overhead) * 2 # Total, Cost
111
+ if deltas is not None:
112
+ fixed_width += 6 + col_overhead
113
+ fixed_width += 4 # table outer borders + edge padding
114
+
115
+ # Compute trend bar width from remaining terminal space
116
+ term_width = console.width or 80
117
+ bar_width = min(24, max(_BAR_WIDTH_DEFAULT, term_width - fixed_width - col_overhead))
118
+
119
+ table.add_column(label_header, style="bold", no_wrap=True, max_width=label_max)
120
+ if show_detail:
121
+ table.add_column(show_detail, style="dim cyan", no_wrap=True, max_width=detail_max)
122
+ table.add_column("Calls", justify="right", style="magenta", min_width=5)
123
+ if show_breakdown:
124
+ table.add_column("Input", justify="right", style="green", min_width=6)
125
+ table.add_column("Output", justify="right", style="yellow", min_width=6)
126
+ table.add_column("Cache R", justify="right", style="dim", min_width=6)
127
+ table.add_column("Cache W", justify="right", style="dim", min_width=6)
128
+ table.add_column("Total", justify="right", style="bold white", min_width=7)
129
+ table.add_column("Cost", justify="right", style="bold red", min_width=7)
130
+ if trend_values is not None:
131
+ table.add_column("Trend", justify="left", style="cyan", no_wrap=True, min_width=bar_width)
132
+ if deltas is not None:
133
+ table.add_column("Δ", justify="right", min_width=6)
134
+
135
+ # Precompute max for sparkline
136
+ trend_max = max(trend_values) if trend_values else 0
137
+
138
+ # Track previous label for deduplication + group separators
139
+ prev_label = None
140
+ for _i, r in enumerate(rows):
141
+ # Insert blank separator between agent groups
142
+ if show_detail and prev_label is not None and r.label != prev_label:
143
+ table.add_section()
144
+
145
+ display_label = r.label if r.label != prev_label else ""
146
+ prev_label = r.label
147
+
148
+ cols: list[str] = [display_label]
149
+ if show_detail:
150
+ cols.append(_short_model(r.detail) if r.detail else "")
151
+ cols.append(str(r.calls))
152
+ if show_breakdown:
153
+ cols.extend(
154
+ [
155
+ _fmt_tokens(r.tokens.input),
156
+ _fmt_tokens(r.tokens.output),
157
+ _fmt_tokens(r.tokens.cache_read),
158
+ _fmt_tokens(r.tokens.cache_write),
159
+ ]
160
+ )
161
+ cols.extend([_fmt_tokens(r.tokens.total), _fmt_cost(r.cost)])
162
+ if trend_values is not None:
163
+ tv = trend_values[_i] if _i < len(trend_values) else 0
164
+ cols.append(_spark_bar(tv, trend_max, bar_width))
165
+ if deltas is not None:
166
+ d = deltas[_i] if _i < len(deltas) else None
167
+ cols.append(_fmt_delta(d) if d is not None else "[dim]-[/]")
168
+ table.add_row(*cols)
169
+
170
+ return table
171
+
172
+
173
+ def render_summary(
174
+ total: UsageRow,
175
+ period: str,
176
+ prev_total: UsageRow | None = None,
177
+ ) -> None:
178
+ """Print a one-line summary panel."""
179
+ text = Text()
180
+ text.append(" Calls: ", style="dim")
181
+ text.append(f"{total.calls:,}", style="bold magenta")
182
+ if prev_total is not None and prev_total.calls > 0:
183
+ pct = (total.calls - prev_total.calls) / prev_total.calls * 100
184
+ text.append(Text.from_markup(f" {_fmt_delta(pct)}"))
185
+ text.append(" │ Tokens: ", style="dim")
186
+ text.append(_fmt_tokens(total.tokens.total), style="bold white")
187
+ if prev_total is not None and prev_total.tokens.total > 0:
188
+ pct = (total.tokens.total - prev_total.tokens.total) / prev_total.tokens.total * 100
189
+ text.append(Text.from_markup(f" {_fmt_delta(pct)}"))
190
+ text.append(" │ Cost: ", style="dim")
191
+ text.append(_fmt_cost(total.cost), style="bold red")
192
+ if prev_total is not None and prev_total.cost > 0:
193
+ pct = (total.cost - prev_total.cost) / prev_total.cost * 100
194
+ text.append(Text.from_markup(f" {_fmt_delta(pct)}"))
195
+ console.print(Panel(text, title=f"[bold]OpenCode Usage — {period}[/bold]", border_style="blue"))
196
+
197
+
198
+ def render_daily(rows: list[UsageRow], period: str) -> None:
199
+ """Render the daily breakdown table."""
200
+ trend = [r.tokens.total for r in rows]
201
+ table = _make_table(
202
+ title=f"Daily Usage ({period})",
203
+ label_header="Date",
204
+ rows=rows,
205
+ show_breakdown=True,
206
+ trend_values=trend,
207
+ )
208
+ console.print(table)
209
+
210
+
211
+ def render_grouped(
212
+ rows: list[UsageRow],
213
+ group_by: str,
214
+ period: str,
215
+ deltas: list[float | None] | None = None,
216
+ ) -> None:
217
+ """Render a grouped breakdown table."""
218
+ label_map = {
219
+ "model": "Model",
220
+ "agent": "Agent",
221
+ "provider": "Provider",
222
+ "session": "Session",
223
+ }
224
+ label_header = label_map.get(group_by, group_by.title())
225
+
226
+ # Agent view has extra Model column — skip breakdown to save width
227
+ show_breakdown = group_by not in ("session", "agent")
228
+
229
+ # For agent view, show model as an extra column
230
+ show_detail = "Model" if group_by == "agent" else None
231
+
232
+ table = _make_table(
233
+ title=f"Usage by {label_header} ({period})",
234
+ label_header=label_header,
235
+ rows=rows,
236
+ show_breakdown=show_breakdown,
237
+ show_detail=show_detail,
238
+ deltas=deltas,
239
+ )
240
+ console.print(table)
@@ -0,0 +1,217 @@
1
+ Metadata-Version: 2.5
2
+ Name: opencode-usage-v2
3
+ Version: 0.2.5
4
+ Summary: CLI tool to track and display OpenCode token usage statistics (v1 and v2)
5
+ Project-URL: Changelog, https://github.com/fcomovaz/opencode-usage-v2-supp/blob/main/CHANGELOG.md
6
+ Project-URL: Homepage, https://github.com/fcomovaz/opencode-usage-v2-supp
7
+ Project-URL: Issues, https://github.com/fcomovaz/opencode-usage-v2-supp/issues
8
+ Project-URL: Repository, https://github.com/fcomovaz/opencode-usage-v2-supp
9
+ Author: rchardx
10
+ Maintainer: fcomovaz
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: analytics,cli,opencode,sqlite,tokens,usage
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Environment :: Console
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Utilities
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: rich>=13.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # opencode-usage-v2
29
+
30
+ [![CI](https://github.com/fcomovaz/opencode-usage-v2-supp/actions/workflows/ci.yml/badge.svg)](https://github.com/fcomovaz/opencode-usage-v2-supp/actions/workflows/ci.yml)
31
+ [![PyPI version](https://img.shields.io/pypi/v/opencode-usage-v2)](https://pypi.org/project/opencode-usage-v2/)
32
+ [![Python versions](https://img.shields.io/pypi/pyversions/opencode-usage-v2)](https://pypi.org/project/opencode-usage-v2/)
33
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
34
+
35
+ > **Maintained fork:** `opencode-usage-v2` is a maintained fork of the deleted upstream `opencode-usage` repository (`rchardx/opencode-usage`), updated with full support for OpenCode v1, OpenCode v2, and migrated mixed SQLite schemas.
36
+
37
+ CLI tool to track and display [OpenCode](https://github.com/opencodeco/opencode) token usage statistics. Reads directly from OpenCode's local SQLite database — no API keys or external services needed for basic usage.
38
+
39
+ ## Features
40
+
41
+ - **OpenCode v1 & v2 support** — reads legacy `message`/`session`, current `session_message`/`session_v2`, and migrated mixed databases without double-counting
42
+ - **Daily breakdown** — token usage and cost per day
43
+ - **Group by dimension** — model, agent, provider, or session
44
+ - **Agent × Model view** — see which model each agent uses
45
+ - **Time filtering** — last N days, relative durations (`7d`, `2w`), or ISO dates
46
+ - **Period comparison** — compare current vs previous period with `--compare`
47
+ - **JSON output** — pipe to `jq` or other tools
48
+ - **LLM-powered insights** — analyze session transcripts and generate a self-contained HTML report
49
+ - **Cross-platform** — macOS, Linux, Windows
50
+
51
+ ## Installation
52
+
53
+ ### From PyPI (Recommended)
54
+
55
+ Run directly without installing using `uvx`:
56
+
57
+ ```bash
58
+ uvx opencode-usage-v2
59
+ uvx opencode-usage-v2 run --by model
60
+ ```
61
+
62
+ Or install globally / into a virtual environment:
63
+
64
+ ```bash
65
+ # With uv
66
+ uv tool install opencode-usage-v2
67
+
68
+ # With pip
69
+ pip install opencode-usage-v2
70
+ ```
71
+
72
+ Installing `opencode-usage-v2` exposes both `opencode-usage-v2` and `opencode-usage` CLI commands (drop-in compatible).
73
+
74
+ > **Warning:** Do **not** install `opencode-usage-v2` into the same virtual environment as the legacy `opencode-usage` package. Both distributions provide the `opencode_usage` Python namespace and `opencode-usage` script, so co-installing them in one environment causes file conflicts. Uninstall `opencode-usage` first if upgrading in an existing environment.
75
+
76
+ ### From source (local development)
77
+
78
+ ```bash
79
+ # Clone repository
80
+ git clone https://github.com/fcomovaz/opencode-usage-v2-supp.git
81
+ cd opencode-usage-v2-supp
82
+
83
+ # Option 1: with standard Python venv & pip
84
+ python -m venv .venv
85
+ # macOS / Linux:
86
+ source .venv/bin/activate
87
+ # Windows (PowerShell):
88
+ .venv\Scripts\Activate.ps1
89
+ # Windows (Command Prompt):
90
+ .venv\Scripts\activate.bat
91
+ pip install -e .
92
+
93
+ # Option 2: with uv
94
+ uv sync
95
+ uv tool install -e .
96
+ ```
97
+
98
+ ## Usage
99
+
100
+ Both `opencode-usage-v2` and `opencode-usage` invoke the same CLI, which has two subcommands: `run` (default) and `insights`. You can also invoke it as `python -m opencode_usage`.
101
+
102
+ ### `run` — Token usage statistics
103
+
104
+ ```bash
105
+ # Default: last 7 days, daily breakdown
106
+ opencode-usage-v2
107
+
108
+ # Time filtering
109
+ opencode-usage-v2 run --days 30
110
+ opencode-usage-v2 run --since 7d
111
+ opencode-usage-v2 run --since 2025-01-01
112
+
113
+ # Group by dimension
114
+ opencode-usage-v2 run --by model
115
+ opencode-usage-v2 run --by agent # shows model per agent
116
+ opencode-usage-v2 run --by provider
117
+ opencode-usage-v2 run --by session --limit 10
118
+
119
+ # JSON output
120
+ opencode-usage-v2 run --json
121
+ opencode-usage-v2 run --by model --json | jq '.rows[].label'
122
+
123
+ # Compare with previous period
124
+ opencode-usage-v2 run --since 7d --compare
125
+ ```
126
+
127
+ ### `insights` — LLM-powered analysis
128
+
129
+ Analyze your OpenCode sessions and generate an HTML report with workflow insights, friction patterns, agent performance, and actionable suggestions.
130
+
131
+ ```bash
132
+ # Interactive model picker
133
+ opencode-usage-v2 insights
134
+
135
+ # Specific model
136
+ opencode-usage-v2 insights --model gpt-4o-mini
137
+
138
+ # Customize analysis
139
+ opencode-usage-v2 insights --days 30 --concurrency 4 --output report.html
140
+
141
+ # Force re-analysis (ignore cache)
142
+ opencode-usage-v2 insights --force
143
+ ```
144
+
145
+ Requires an API key for the LLM provider — set via environment variable (e.g. `OPENAI_API_KEY`) or OpenCode's `auth.json`.
146
+
147
+ > **Note:** The `insights` extraction queries currently target the legacy v1 schema tables (`session`, `message`, `part`). Token usage reporting (`run`) supports both v1 and v2 schemas.
148
+
149
+ ### Example output
150
+
151
+ ```
152
+ ╭──────────────── OpenCode Usage — Last 7 days ────────────────╮
153
+ │ Calls: 1,280 │ Tokens: 52.3M │ Cost: $0.00 │
154
+ ╰──────────────────────────────────────────────────────────────╯
155
+
156
+ Usage by Agent (Last 7 days)
157
+ ┏━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━┳━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┓
158
+ ┃ Agent ┃ Model ┃ Calls ┃ Total ┃ Cost ┃
159
+ ┡━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━╇━━━━━━━╇━━━━━━━━━╇━━━━━━━━━┩
160
+ │ build │ deepseek-r1 │ 420 │ 18.2M │ - │
161
+ │ │ qwen-3-coder │ 105 │ 4.7M │ - │
162
+ ├────────────────────────┼──────────────┼───────┼─────────┼─────────┤
163
+ │ explore │ gemma-3 │ 310 │ 12.5M │ - │
164
+ │ │ minimax-m2.5 │ 198 │ 8.1M │ - │
165
+ ├────────────────────────┼──────────────┼───────┼─────────┼─────────┤
166
+ │ librarian │ llama-4 │ 156 │ 5.8M │ - │
167
+ ├────────────────────────┼──────────────┼───────┼─────────┤
168
+ │ oracle │ qwen-3-coder │ 91 │ 3.0M │ - │
169
+ └────────────────────────┴──────────────┴───────┴─────────┴─────────┘
170
+ ```
171
+
172
+ ## Schema Support
173
+
174
+ `opencode-usage-v2` supports both OpenCode v1 and v2 database schemas, as well as migrated (mixed) databases:
175
+
176
+ | OpenCode Version | Session Table | Message Table | Status |
177
+ |---|---|---|---|
178
+ | **v1** (legacy) | `session` | `message` (`role = 'assistant'`) | Supported |
179
+ | **v2** (current) | `session_v2` | `session_message` (`type = 'assistant'`) | Supported |
180
+ | **Mixed / Migrated** | Both tables present | Both tables present | Supported (deduplicated by ID) |
181
+
182
+ In mixed databases migrated from v1 to v2, messages present in both tables are automatically deduplicated by message ID to prevent double-counting.
183
+
184
+ ## Configuration
185
+
186
+ | Environment Variable | Description |
187
+ |---|---|
188
+ | `OPENCODE_DB` | Override database path (default: auto-detected per platform) |
189
+ | `NO_COLOR` | Disable colored output when set (see [no-color.org](https://no-color.org)) |
190
+ | `{PROVIDER}_API_KEY` | API key for insights LLM provider (e.g. `OPENAI_API_KEY`) |
191
+ | `{PROVIDER}_BASE_URL` | Base URL override for insights LLM provider |
192
+
193
+ Default database locations:
194
+
195
+ - **All platforms** (macOS, Linux, Windows): `~/.local/share/opencode/opencode.db`
196
+
197
+ ## Development
198
+
199
+ ```bash
200
+ git clone https://github.com/fcomovaz/opencode-usage-v2-supp.git
201
+ cd opencode-usage-v2-supp
202
+ uv sync
203
+
204
+ # Run tests
205
+ uv run pytest
206
+
207
+ # Lint & format
208
+ uvx ruff check .
209
+ uvx ruff format --check .
210
+
211
+ # Install pre-commit hooks
212
+ uvx pre-commit install
213
+ ```
214
+
215
+ ## License
216
+
217
+ [MIT](LICENSE)