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.
@@ -0,0 +1,18 @@
1
+ """OpenCode usage statistics CLI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from importlib.metadata import PackageNotFoundError, version
6
+
7
+
8
+ def _resolve_version() -> str:
9
+ """Return installed distribution version, with fallback for legacy or editable setups."""
10
+ for dist_name in ("opencode-usage-v2", "opencode-usage"):
11
+ try:
12
+ return version(dist_name)
13
+ except PackageNotFoundError:
14
+ continue
15
+ return "0.0.0+unknown"
16
+
17
+
18
+ __version__ = _resolve_version()
@@ -0,0 +1,5 @@
1
+ """Allow running as `python -m opencode_usage`."""
2
+
3
+ from .cli import main
4
+
5
+ main()
@@ -0,0 +1,158 @@
1
+ """Thin wrapper around the ``opencode`` CLI for dynamic path/config resolution.
2
+
3
+ Results are cached per-process so the CLI is invoked at most once per command.
4
+ Every function falls back to the legacy XDG-based heuristic when the binary is
5
+ not installed or the command fails.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ from functools import lru_cache
14
+ from pathlib import Path
15
+
16
+ # ── low-level helpers ────────────────────────────────────────
17
+
18
+
19
+ def _find_opencode() -> str | None:
20
+ """Return the absolute path to the ``opencode`` binary, or *None*."""
21
+ return shutil.which("opencode")
22
+
23
+
24
+ @lru_cache(maxsize=1)
25
+ def _run_db_path() -> str | None:
26
+ """Run ``opencode db path`` and return the trimmed output."""
27
+ binary = _find_opencode()
28
+ if binary is None:
29
+ return None
30
+ try:
31
+ result = subprocess.run(
32
+ [binary, "db", "path"],
33
+ capture_output=True,
34
+ text=True,
35
+ encoding="utf-8",
36
+ errors="replace",
37
+ timeout=10,
38
+ )
39
+ if result.returncode == 0 and result.stdout.strip():
40
+ return result.stdout.strip()
41
+ except (OSError, subprocess.TimeoutExpired):
42
+ pass
43
+ return None
44
+
45
+
46
+ @lru_cache(maxsize=1)
47
+ def _run_debug_paths() -> dict[str, str]:
48
+ """Run ``opencode debug paths`` and parse the TSV output into a dict.
49
+
50
+ Example CLI output::
51
+
52
+ home /home/user
53
+ data /home/user/.local/share/opencode
54
+ config /home/user/.config/opencode
55
+ ...
56
+
57
+ Returns an empty dict on failure.
58
+ """
59
+ binary = _find_opencode()
60
+ if binary is None:
61
+ return {}
62
+ try:
63
+ result = subprocess.run(
64
+ [binary, "debug", "paths"],
65
+ capture_output=True,
66
+ text=True,
67
+ encoding="utf-8",
68
+ errors="replace",
69
+ timeout=10,
70
+ )
71
+ if result.returncode != 0:
72
+ return {}
73
+ paths: dict[str, str] = {}
74
+ for line in result.stdout.splitlines():
75
+ parts = line.split(None, 1)
76
+ if len(parts) == 2:
77
+ paths[parts[0]] = parts[1]
78
+ return paths
79
+ except (OSError, subprocess.TimeoutExpired):
80
+ return {}
81
+
82
+
83
+ # ── XDG fallbacks (legacy behaviour) ────────────────────────
84
+
85
+
86
+ def _xdg_data_home() -> Path:
87
+ return Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
88
+
89
+
90
+ def _xdg_config_home() -> Path:
91
+ return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
92
+
93
+
94
+ # ── public API ───────────────────────────────────────────────
95
+
96
+
97
+ def get_db_path() -> Path:
98
+ """Return the OpenCode database path.
99
+
100
+ Resolution order:
101
+ 1. ``OPENCODE_DB`` environment variable (explicit override).
102
+ 2. ``opencode db path`` CLI output.
103
+ 3. Legacy XDG-based default.
104
+ """
105
+ if custom := os.environ.get("OPENCODE_DB"):
106
+ return Path(custom)
107
+ cli_path = _run_db_path()
108
+ if cli_path:
109
+ return Path(cli_path)
110
+ return _xdg_data_home() / "opencode" / "opencode.db"
111
+
112
+
113
+ def get_data_dir() -> Path:
114
+ """Return the OpenCode data directory (e.g. ``~/.local/share/opencode``)."""
115
+ paths = _run_debug_paths()
116
+ if data := paths.get("data"):
117
+ return Path(data)
118
+ return _xdg_data_home() / "opencode"
119
+
120
+
121
+ def get_config_dir() -> Path:
122
+ """Return the OpenCode config directory (e.g. ``~/.config/opencode``)."""
123
+ paths = _run_debug_paths()
124
+ if config := paths.get("config"):
125
+ return Path(config)
126
+ return _xdg_config_home() / "opencode"
127
+
128
+
129
+ def get_auth_path() -> Path:
130
+ """Return the path to OpenCode's ``auth.json``."""
131
+ return get_data_dir() / "auth.json"
132
+
133
+
134
+ def get_config_path() -> Path:
135
+ """Return the path to OpenCode's ``opencode.json`` config file."""
136
+ return get_config_dir() / "opencode.json"
137
+
138
+
139
+ @lru_cache(maxsize=1)
140
+ def run_models() -> list[str]:
141
+ """Run ``opencode models`` and return the list of model identifiers."""
142
+ binary = _find_opencode()
143
+ if binary is None:
144
+ return []
145
+ try:
146
+ result = subprocess.run(
147
+ [binary, "models"],
148
+ capture_output=True,
149
+ text=True,
150
+ encoding="utf-8",
151
+ errors="replace",
152
+ timeout=15,
153
+ )
154
+ if result.returncode == 0:
155
+ return [line.strip() for line in result.stdout.splitlines() if line.strip()]
156
+ except (OSError, subprocess.TimeoutExpired):
157
+ pass
158
+ return []
opencode_usage/auth.py ADDED
@@ -0,0 +1,82 @@
1
+ """Credential resolution for OpenCode insights service."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ from ._opencode_cli import get_auth_path, get_config_path
11
+
12
+
13
+ @dataclass
14
+ class Credentials:
15
+ """API credentials for insights service."""
16
+
17
+ api_key: str
18
+ base_url: str
19
+ model: str
20
+
21
+
22
+ def _default_auth_path() -> Path:
23
+ """Resolve the OpenCode auth.json path per platform."""
24
+ return get_auth_path()
25
+
26
+
27
+ def _default_config_path() -> Path:
28
+ """Resolve the OpenCode opencode.json config path per platform."""
29
+ return get_config_path()
30
+
31
+
32
+ def resolve_credentials(provider: str = "openai", *, model: str | None = None) -> Credentials:
33
+ """Resolve API credentials from environment, auth.json, and opencode.json."""
34
+ env_key = f"{provider.upper()}_API_KEY"
35
+ env_url = f"{provider.upper()}_BASE_URL"
36
+ if api_key := os.environ.get(env_key):
37
+ return Credentials(
38
+ api_key=api_key,
39
+ base_url=os.environ.get(env_url, ""),
40
+ model=model or "gpt-4o-mini",
41
+ )
42
+
43
+ auth_path = _default_auth_path()
44
+ if not auth_path.exists():
45
+ raise RuntimeError(f"Auth file not found at {auth_path}")
46
+ with open(auth_path, encoding="utf-8") as f:
47
+ auth_data = json.load(f)
48
+
49
+ if provider not in auth_data or auth_data[provider].get("type") != "api":
50
+ available = list_providers()
51
+ raise RuntimeError(
52
+ f"No API credentials for '{provider}'. Available: "
53
+ f"{', '.join(available) if available else 'none'}"
54
+ )
55
+
56
+ api_key = auth_data[provider].get("key")
57
+ base_url = ""
58
+ config_path = _default_config_path()
59
+ if config_path.exists():
60
+ with open(config_path, encoding="utf-8") as f:
61
+ config_data = json.load(f)
62
+ base_url = (
63
+ config_data.get("provider", {})
64
+ .get(provider, {})
65
+ .get("options", {})
66
+ .get("baseURL", "")
67
+ )
68
+ return Credentials(api_key=api_key, base_url=base_url, model=model or "gpt-4o-mini")
69
+
70
+
71
+ def list_providers() -> list[str]:
72
+ """List available API providers from auth.json."""
73
+ auth_path = _default_auth_path()
74
+ if not auth_path.exists():
75
+ return []
76
+ with open(auth_path, encoding="utf-8") as f:
77
+ auth_data = json.load(f)
78
+ return [
79
+ name
80
+ for name, entry in auth_data.items()
81
+ if isinstance(entry, dict) and entry.get("type") == "api"
82
+ ]
opencode_usage/cli.py ADDED
@@ -0,0 +1,271 @@
1
+ """CLI entry point for opencode-usage."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import re
8
+ import sys
9
+ from datetime import datetime, timedelta
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ from . import __version__, render
14
+ from .db import OpenCodeDB, UsageRow
15
+ from .render import render_daily, render_grouped, render_summary
16
+
17
+
18
+ def _parse_since(value: str) -> datetime:
19
+ """Parse a relative duration like '7d', '2w', '30d', '3h' or an ISO date."""
20
+ m = re.fullmatch(r"(\d+)([dhwm])", value.strip().lower())
21
+ if m:
22
+ n, unit = int(m.group(1)), m.group(2)
23
+ delta = {
24
+ "h": timedelta(hours=n),
25
+ "d": timedelta(days=n),
26
+ "w": timedelta(weeks=n),
27
+ "m": timedelta(days=n * 30),
28
+ }[unit]
29
+ return datetime.now().astimezone() - delta
30
+
31
+ try:
32
+ dt = datetime.fromisoformat(value)
33
+ if dt.tzinfo is None:
34
+ dt = dt.astimezone()
35
+ return dt
36
+ except ValueError:
37
+ pass
38
+
39
+ raise argparse.ArgumentTypeError(
40
+ f"Invalid time spec: '{value}'. Use '7d', '2w', '30d', '3h', or ISO date."
41
+ )
42
+
43
+
44
+ def _add_time_args(parser: argparse.ArgumentParser) -> None:
45
+ """Add --days and --since to *parser* (shared by run & insights)."""
46
+ parser.add_argument(
47
+ "--days",
48
+ type=int,
49
+ default=None,
50
+ metavar="N",
51
+ help="Show last N days (default: 7)",
52
+ )
53
+ parser.add_argument(
54
+ "--since",
55
+ type=_parse_since,
56
+ default=None,
57
+ metavar="SPEC",
58
+ help="Time filter: '7d', '2w', '30d', '3h', or ISO date",
59
+ )
60
+
61
+
62
+ def _detect_prog() -> str:
63
+ """Return the invoked CLI name when run via a known entry point."""
64
+ name = Path(sys.argv[0]).stem if sys.argv and sys.argv[0] else ""
65
+ if name in {"opencode-usage", "opencode-usage-v2"}:
66
+ return name
67
+ return "opencode-usage"
68
+
69
+
70
+ def _build_parser() -> argparse.ArgumentParser:
71
+ p = argparse.ArgumentParser(
72
+ prog=_detect_prog(),
73
+ description="Track and display OpenCode token usage statistics.",
74
+ )
75
+ p.add_argument("-V", "--version", action="version", version=f"%(prog)s {__version__}")
76
+
77
+ sub = p.add_subparsers(dest="subcommand")
78
+
79
+ # ── run ──────────────────────────────────────────────────
80
+ run_p = sub.add_parser("run", help="Token usage statistics (default)")
81
+ _add_time_args(run_p)
82
+ run_p.add_argument(
83
+ "--by",
84
+ choices=["model", "agent", "provider", "session", "day"],
85
+ default=None,
86
+ help="Group results by dimension",
87
+ )
88
+ run_p.add_argument(
89
+ "--limit",
90
+ type=int,
91
+ default=None,
92
+ metavar="N",
93
+ help="Max rows to display",
94
+ )
95
+ run_p.add_argument(
96
+ "--json",
97
+ action="store_true",
98
+ dest="json_output",
99
+ help="Output as JSON",
100
+ )
101
+ run_p.add_argument(
102
+ "--compare",
103
+ action="store_true",
104
+ help="Compare with previous period of same length",
105
+ )
106
+
107
+ # ── insights ────────────────────────────────────────────
108
+ ins_p = sub.add_parser("insights", help="LLM-powered usage analysis report")
109
+ _add_time_args(ins_p)
110
+ ins_p.add_argument(
111
+ "--model",
112
+ default=None,
113
+ help="Model ID for insights analysis (interactive picker if omitted)",
114
+ )
115
+ ins_p.add_argument(
116
+ "--force",
117
+ action="store_true",
118
+ dest="force",
119
+ help="Force re-analysis, ignoring cache",
120
+ )
121
+ ins_p.add_argument(
122
+ "--concurrency",
123
+ type=int,
124
+ default=None,
125
+ metavar="N",
126
+ help="Max parallel LLM workers (default: min(cpu_count, 8))",
127
+ )
128
+ ins_p.add_argument(
129
+ "--output",
130
+ default="./opencode-insights.html",
131
+ metavar="PATH",
132
+ help="Output path for HTML report",
133
+ )
134
+
135
+ return p
136
+
137
+
138
+ def _resolve_since(args: argparse.Namespace) -> tuple[datetime | None, str]:
139
+ """Resolve the effective 'since' datetime and a human-readable period label."""
140
+ now = datetime.now().astimezone()
141
+
142
+ if args.since is not None:
143
+ return args.since, f"Since {args.since.strftime('%Y-%m-%d')}"
144
+
145
+ if args.days is not None:
146
+ since = now - timedelta(days=args.days)
147
+ return since, f"Last {args.days} days"
148
+
149
+ since = now - timedelta(days=7)
150
+ return since, "Last 7 days"
151
+
152
+
153
+ def _fetch_rows(
154
+ db: OpenCodeDB,
155
+ group_by: str,
156
+ *,
157
+ since: datetime | None = None,
158
+ until: datetime | None = None,
159
+ limit: int | None = None,
160
+ ) -> list[UsageRow]:
161
+ """Fetch rows based on group_by dimension."""
162
+ if group_by == "day":
163
+ return db.daily(since=since, until=until, limit=limit)
164
+ if group_by == "model":
165
+ return db.by_model(since=since, until=until, limit=limit)
166
+ if group_by == "agent":
167
+ return db.by_agent(since=since, until=until, limit=limit)
168
+ if group_by == "provider":
169
+ return db.by_provider(since=since, until=until, limit=limit)
170
+ if group_by == "session":
171
+ return db.by_session(since=since, until=until, limit=limit)
172
+ return []
173
+
174
+
175
+ def _compute_deltas(
176
+ current: list[UsageRow],
177
+ previous: list[UsageRow],
178
+ ) -> list[float | None]:
179
+ """Compute token delta percentages between current and previous rows."""
180
+ prev_map: dict[str, int] = {}
181
+ for r in previous:
182
+ key = f"{r.label}:{r.detail}" if r.detail else r.label
183
+ prev_map[key] = prev_map.get(key, 0) + r.tokens.total
184
+
185
+ deltas: list[float | None] = []
186
+ for r in current:
187
+ key = f"{r.label}:{r.detail}" if r.detail else r.label
188
+ prev_val = prev_map.get(key)
189
+ if prev_val and prev_val > 0:
190
+ deltas.append((r.tokens.total - prev_val) / prev_val * 100)
191
+ else:
192
+ deltas.append(None)
193
+ return deltas
194
+
195
+
196
+ def _cmd_run(args: argparse.Namespace) -> None:
197
+ """Execute the ``run`` subcommand."""
198
+ try:
199
+ db = OpenCodeDB()
200
+ except FileNotFoundError as e:
201
+ render.console.print(f"[red]Error:[/red] {e}")
202
+ sys.exit(1)
203
+
204
+ since, period = _resolve_since(args)
205
+ group_by = args.by or "day"
206
+
207
+ now = datetime.now().astimezone()
208
+ prev_since = None
209
+ if args.compare and since is not None:
210
+ period_length = now - since
211
+ prev_since = since - period_length
212
+
213
+ rows = _fetch_rows(db, group_by, since=since, limit=args.limit)
214
+ total = db.totals(since=since)
215
+
216
+ prev_total = None
217
+ prev_rows: list[UsageRow] = []
218
+ if prev_since is not None:
219
+ prev_total = db.totals(since=prev_since, until=since)
220
+ if group_by != "day":
221
+ prev_rows = _fetch_rows(db, group_by, since=prev_since, until=since, limit=args.limit)
222
+
223
+ if args.json_output:
224
+ output: dict[str, Any] = {
225
+ "period": period,
226
+ "total": db.to_dicts([total])[0],
227
+ "rows": db.to_dicts(rows),
228
+ }
229
+ if prev_total is not None:
230
+ output["previous_total"] = db.to_dicts([prev_total])[0]
231
+ if prev_rows:
232
+ output["previous_rows"] = db.to_dicts(prev_rows)
233
+ print(json.dumps(output, indent=2, ensure_ascii=False))
234
+ return
235
+
236
+ render_summary(total, period, prev_total=prev_total)
237
+ render.console.print()
238
+
239
+ deltas = _compute_deltas(rows, prev_rows) if prev_rows else None
240
+
241
+ if group_by == "day":
242
+ render_daily(rows, period)
243
+ else:
244
+ render_grouped(rows, group_by, period, deltas=deltas)
245
+
246
+
247
+ def _cmd_insights(args: argparse.Namespace) -> None:
248
+ """Execute the ``insights`` subcommand."""
249
+ if args.model is None:
250
+ from .models import select_model_interactive
251
+
252
+ args.model = select_model_interactive(render.console)
253
+
254
+ from .insights.orchestrator import run_insights
255
+
256
+ run_insights(args)
257
+
258
+
259
+ def main(argv: list[str] | None = None) -> None:
260
+ parser = _build_parser()
261
+ raw = argv if argv is not None else sys.argv[1:]
262
+
263
+ if not raw or raw[0] not in ("run", "insights", "-h", "--help", "-V", "--version"):
264
+ raw = ["run", *raw]
265
+
266
+ args = parser.parse_args(raw)
267
+
268
+ if args.subcommand == "insights":
269
+ _cmd_insights(args)
270
+ else:
271
+ _cmd_run(args)