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,19 @@
1
+ """OpenCode insights extraction, analysis, and reporting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .cache import FacetCache
6
+ from .types import (
7
+ AggregatedStats,
8
+ InsightsConfig,
9
+ SessionFacet,
10
+ SessionMeta,
11
+ )
12
+
13
+ __all__ = [
14
+ "AggregatedStats",
15
+ "FacetCache",
16
+ "InsightsConfig",
17
+ "SessionFacet",
18
+ "SessionMeta",
19
+ ]
@@ -0,0 +1,384 @@
1
+ """LLM runner for insights analysis via opencode run subprocess."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import subprocess
8
+ import tempfile
9
+ import threading
10
+ import time
11
+ import warnings
12
+ from collections import defaultdict
13
+ from concurrent.futures import ThreadPoolExecutor, as_completed
14
+ from pathlib import Path
15
+ from typing import TYPE_CHECKING, Any
16
+
17
+ from .cache import FacetCache
18
+ from .extract import extract_session_meta, reconstruct_transcript
19
+ from .prompts import (
20
+ build_agent_performance_prompt,
21
+ build_at_a_glance_prompt,
22
+ build_facet_prompt,
23
+ build_friction_prompt,
24
+ build_horizon_prompt,
25
+ build_interaction_style_prompt,
26
+ build_project_areas_prompt,
27
+ build_suggestions_prompt,
28
+ build_tool_health_prompt,
29
+ )
30
+ from .types import AggregatedStats, InsightsConfig, SessionFacet
31
+
32
+ if TYPE_CHECKING:
33
+ from collections.abc import Callable
34
+
35
+
36
+ def parse_ndjson(output: str) -> tuple[str, float, dict[str, int]]:
37
+ """Parse NDJSON output from opencode run --format json.
38
+
39
+ Returns (text_content, cost, tokens_dict).
40
+ """
41
+ text_parts: list[str] = []
42
+ cost: float = 0.0
43
+ tokens: dict[str, int] = {}
44
+
45
+ for line in output.splitlines():
46
+ line = line.strip()
47
+ if not line:
48
+ continue
49
+ try:
50
+ event = json.loads(line)
51
+ except json.JSONDecodeError:
52
+ # Skip non-JSON lines like [config-context] warnings
53
+ continue
54
+
55
+ event_type = event.get("type")
56
+ part = event.get("part", {})
57
+
58
+ if event_type == "text":
59
+ text = part.get("text", "")
60
+ if text:
61
+ text_parts.append(text)
62
+ elif event_type == "step_finish":
63
+ cost = float(part.get("cost", 0.0))
64
+ raw_tokens = part.get("tokens", {})
65
+ if isinstance(raw_tokens, dict):
66
+ tokens = {k: int(v) for k, v in raw_tokens.items() if isinstance(v, int | float)}
67
+
68
+ return "".join(text_parts), cost, tokens
69
+
70
+
71
+ def extract_json_from_response(text: str) -> dict[str, Any]:
72
+ """Strip markdown code fences and parse JSON from LLM response text."""
73
+ stripped = text.strip()
74
+
75
+ # Strip ```json ... ``` or ``` ... ```
76
+ if stripped.startswith("```json\n"):
77
+ stripped = stripped[8:]
78
+ elif stripped.startswith("```json"):
79
+ stripped = stripped[7:]
80
+ elif stripped.startswith("```\n"):
81
+ stripped = stripped[4:]
82
+ elif stripped.startswith("```"):
83
+ stripped = stripped[3:]
84
+
85
+ if stripped.endswith("\n```"):
86
+ stripped = stripped[:-4]
87
+ elif stripped.endswith("```"):
88
+ stripped = stripped[:-3]
89
+
90
+ stripped = stripped.strip()
91
+
92
+ try:
93
+ result = json.loads(stripped)
94
+ if not isinstance(result, dict):
95
+ raise ValueError(f"Expected JSON object, got {type(result).__name__}")
96
+ return result
97
+ except json.JSONDecodeError as e:
98
+ raise ValueError(f"LLM returned non-JSON: {text[:200]}") from e
99
+
100
+
101
+ def run_llm(
102
+ prompt: str,
103
+ model: str = "opencode/minimax-m2.5-free",
104
+ timeout: int = 120,
105
+ ) -> dict[str, Any]:
106
+ """Run opencode LLM analysis via subprocess and return parsed JSON result.
107
+
108
+ Retries up to 3 times on timeout with exponential backoff.
109
+ Raises FileNotFoundError if opencode binary not found (returncode 127).
110
+ Raises PermissionError if opencode binary not executable (returncode 126).
111
+ Raises TimeoutError after 3 timeout retries.
112
+ Raises RuntimeError on other non-zero return codes.
113
+ """
114
+ max_retries = 3
115
+ last_exc: Exception | None = None
116
+
117
+ for attempt in range(max_retries):
118
+ try:
119
+ result = subprocess.run(
120
+ [
121
+ "opencode",
122
+ "run",
123
+ prompt,
124
+ "--format",
125
+ "json",
126
+ "--model",
127
+ model,
128
+ "--dir",
129
+ tempfile.gettempdir(),
130
+ ],
131
+ capture_output=True,
132
+ encoding="utf-8",
133
+ errors="replace",
134
+ timeout=timeout,
135
+ )
136
+ except subprocess.TimeoutExpired as exc:
137
+ last_exc = exc
138
+ if attempt < max_retries - 1:
139
+ wait = min(2**attempt * 2, 60)
140
+ time.sleep(wait)
141
+ continue
142
+
143
+ if result.returncode == 127:
144
+ raise FileNotFoundError("opencode binary not found")
145
+ if result.returncode == 126:
146
+ raise PermissionError("opencode binary not executable")
147
+ if result.returncode != 0:
148
+ raise RuntimeError(
149
+ f"opencode run failed with code {result.returncode}: {result.stderr[:200]}"
150
+ )
151
+
152
+ text, _cost, _tokens = parse_ndjson(result.stdout)
153
+ return extract_json_from_response(text)
154
+
155
+ raise TimeoutError("opencode run timed out after 3 attempts") from last_exc
156
+
157
+
158
+ _MAX_NEW_SESSIONS = 50
159
+ _MAX_CONCURRENCY = 8
160
+
161
+
162
+ def _default_concurrency(override: int | None = None) -> int:
163
+ """Return worker count: override > 0, else min(cpu_count, _MAX_CONCURRENCY)."""
164
+ if override is not None and override > 0:
165
+ return override
166
+ try:
167
+ cpu = os.cpu_count() or 4
168
+ except Exception:
169
+ cpu = 4
170
+ return min(cpu, _MAX_CONCURRENCY)
171
+
172
+
173
+ def _count_outcomes(facets: dict[str, SessionFacet]) -> dict[str, int]:
174
+ """Count outcome values across facets."""
175
+ counts: dict[str, int] = defaultdict(int)
176
+ for f in facets.values():
177
+ if f.outcome:
178
+ counts[f.outcome] += 1
179
+ return dict(counts)
180
+
181
+
182
+ def _count_satisfaction(facets: dict[str, SessionFacet]) -> dict[str, int]:
183
+ """Count satisfaction keys set to 1 across facets."""
184
+ counts: dict[str, int] = defaultdict(int)
185
+ for f in facets.values():
186
+ for key, val in f.satisfaction.items():
187
+ if val:
188
+ counts[key] += 1
189
+ return dict(counts)
190
+
191
+
192
+ def _count_friction(facets: dict[str, SessionFacet]) -> dict[str, int]:
193
+ """Sum friction counts across facets."""
194
+ counts: dict[str, int] = defaultdict(int)
195
+ for f in facets.values():
196
+ for key, val in f.friction_counts.items():
197
+ counts[key] += val
198
+ return dict(counts)
199
+
200
+
201
+ def _count_goal_categories(facets: dict[str, SessionFacet]) -> dict[str, int]:
202
+ """Count goal categories set to 1 across facets."""
203
+ counts: dict[str, int] = defaultdict(int)
204
+ for f in facets.values():
205
+ for key, val in f.goal_categories.items():
206
+ if val:
207
+ counts[key] += 1
208
+ return dict(counts)
209
+
210
+
211
+ def _extract_single_facet(
212
+ db_path: Path | str,
213
+ sid: str,
214
+ model: str,
215
+ ) -> SessionFacet:
216
+ """Extract facets for a single session (thread-safe)."""
217
+ transcript = reconstruct_transcript(db_path, sid)
218
+ meta = extract_session_meta(db_path, sid)
219
+ meta_summary = (
220
+ f"Title: {meta.title}\n"
221
+ f"Duration: {meta.duration_minutes:.1f} min\n"
222
+ f"User messages: {meta.user_msg_count}\n"
223
+ f"Assistant messages: {meta.assistant_msg_count}\n"
224
+ f"Total tokens: {meta.total_tokens}\n"
225
+ f"Cost: ${meta.cost:.4f}\n"
226
+ f"Tools: {', '.join(meta.tool_counts) if meta.tool_counts else 'none'}\n"
227
+ f"Languages: {', '.join(meta.languages) if meta.languages else 'none'}\n"
228
+ f"Agents: {', '.join(meta.agent_counts) if meta.agent_counts else 'none'}"
229
+ )
230
+ prompt = build_facet_prompt(transcript, meta_summary)
231
+ llm_result = run_llm(prompt, model=model)
232
+ return SessionFacet(
233
+ session_id=sid,
234
+ underlying_goal=llm_result.get("underlying_goal", ""),
235
+ goal_categories=llm_result.get("goal_categories", {}),
236
+ outcome=llm_result.get("outcome", ""),
237
+ satisfaction=llm_result.get("satisfaction", {}),
238
+ helpfulness=llm_result.get("helpfulness", ""),
239
+ session_type=llm_result.get("session_type", ""),
240
+ friction_counts=llm_result.get("friction_counts", {}),
241
+ friction_detail=llm_result.get("friction_detail", ""),
242
+ primary_success=llm_result.get("primary_success", ""),
243
+ brief_summary=llm_result.get("brief_summary", ""),
244
+ )
245
+
246
+
247
+ def extract_facets(
248
+ db_path: Path | str,
249
+ session_ids: list[str],
250
+ config: InsightsConfig,
251
+ cache: FacetCache | None = None,
252
+ on_progress: Callable[[int, int], None] | None = None,
253
+ ) -> dict[str, SessionFacet]:
254
+ """Extract per-session facets with caching and concurrent LLM calls."""
255
+ if cache is None:
256
+ cache = FacetCache()
257
+
258
+ result: dict[str, SessionFacet] = {}
259
+
260
+ if config.force:
261
+ uncached = list(session_ids)
262
+ cached_ids: list[str] = []
263
+ else:
264
+ cached_ids = [sid for sid in session_ids if cache.has(sid)]
265
+ uncached = [sid for sid in session_ids if not cache.has(sid)]
266
+
267
+ # Load cached facets
268
+ for sid in cached_ids:
269
+ facet = cache.get(sid)
270
+ if facet is not None:
271
+ result[sid] = facet
272
+
273
+ # Limit new sessions
274
+ if not config.force:
275
+ uncached = uncached[:_MAX_NEW_SESSIONS]
276
+
277
+ total = len(uncached)
278
+ if total == 0:
279
+ return result
280
+
281
+ workers = _default_concurrency(config.concurrency)
282
+ completed = 0
283
+ lock = threading.Lock()
284
+
285
+ def _on_done(sid: str, facet: SessionFacet | None) -> None:
286
+ nonlocal completed
287
+ with lock:
288
+ completed += 1
289
+ if facet is not None:
290
+ cache.put(sid, facet)
291
+ result[sid] = facet
292
+ if on_progress is not None:
293
+ on_progress(completed, total)
294
+
295
+ with ThreadPoolExecutor(max_workers=workers) as executor:
296
+ futures = {
297
+ executor.submit(_extract_single_facet, db_path, sid, config.model): sid
298
+ for sid in uncached
299
+ }
300
+ for future in as_completed(futures):
301
+ sid = futures[future]
302
+ try:
303
+ facet = future.result()
304
+ _on_done(sid, facet)
305
+ except Exception:
306
+ warnings.warn(
307
+ f"Failed to extract facets for session {sid}",
308
+ stacklevel=2,
309
+ )
310
+ _on_done(sid, None)
311
+
312
+ return result
313
+
314
+
315
+ def run_aggregate_analysis(
316
+ facets: dict[str, SessionFacet],
317
+ stats: AggregatedStats,
318
+ config: InsightsConfig,
319
+ ) -> dict[str, dict[str, Any]]:
320
+ """Run 7 aggregate LLM prompts and return results."""
321
+ aggregated_data = {
322
+ "session_count": stats.total_sessions,
323
+ "analyzed_count": len(facets),
324
+ "total_cost": stats.total_cost,
325
+ "top_agents": stats.top_agents,
326
+ "top_models": stats.top_models,
327
+ "top_tools": stats.top_tools,
328
+ "outcome_distribution": _count_outcomes(facets),
329
+ "satisfaction_distribution": _count_satisfaction(facets),
330
+ "friction_distribution": _count_friction(facets),
331
+ "session_summaries": [f.brief_summary for f in facets.values() if f.brief_summary][:20],
332
+ "goal_categories": _count_goal_categories(facets),
333
+ }
334
+
335
+ prompts = [
336
+ ("project_areas", build_project_areas_prompt),
337
+ ("interaction_style", build_interaction_style_prompt),
338
+ ("agent_performance", build_agent_performance_prompt),
339
+ ("friction", build_friction_prompt),
340
+ ("suggestions", build_suggestions_prompt),
341
+ ("tool_health", build_tool_health_prompt),
342
+ ("horizon", build_horizon_prompt),
343
+ ]
344
+
345
+ results: dict[str, dict[str, Any]] = {}
346
+ workers = min(_default_concurrency(config.concurrency), len(prompts))
347
+
348
+ def _run_prompt(key: str, builder) -> tuple[str, dict[str, Any]]:
349
+ try:
350
+ prompt_text = builder(aggregated_data)
351
+ return key, run_llm(prompt_text, model=config.model)
352
+ except Exception:
353
+ return key, {}
354
+
355
+ with ThreadPoolExecutor(max_workers=workers) as executor:
356
+ futures = [executor.submit(_run_prompt, key, builder) for key, builder in prompts]
357
+ for future in as_completed(futures):
358
+ key, val = future.result()
359
+ results[key] = val
360
+
361
+ return results
362
+
363
+
364
+ def generate_at_a_glance(
365
+ aggregate_results: dict[str, dict[str, Any]],
366
+ stats: AggregatedStats,
367
+ config: InsightsConfig,
368
+ ) -> dict[str, Any]:
369
+ """Synthesize all insights into an at-a-glance summary."""
370
+ stats_summary = {
371
+ "total_sessions": stats.total_sessions,
372
+ "analyzed_sessions": stats.analyzed_sessions,
373
+ "date_range": stats.date_range,
374
+ "total_messages": stats.total_messages,
375
+ "total_cost": stats.total_cost,
376
+ "top_tools": stats.top_tools,
377
+ "top_agents": stats.top_agents,
378
+ "top_models": stats.top_models,
379
+ }
380
+ try:
381
+ prompt = build_at_a_glance_prompt(aggregate_results, stats_summary)
382
+ return run_llm(prompt, model=config.model)
383
+ except Exception:
384
+ return {}
@@ -0,0 +1,60 @@
1
+ """Cache layer for per-session facet data with atomic writes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from dataclasses import asdict
8
+ from pathlib import Path
9
+ from typing import TYPE_CHECKING
10
+
11
+ if TYPE_CHECKING:
12
+ from .types import SessionFacet
13
+
14
+
15
+ def _default_cache_dir() -> Path:
16
+ """Resolve the default facet cache directory per platform."""
17
+ base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
18
+ return base / "opencode-usage" / "facets"
19
+
20
+
21
+ class FacetCache:
22
+ """Per-session facet caching with atomic writes."""
23
+
24
+ def __init__(self, cache_dir: Path | None = None) -> None:
25
+ """Initialize cache with optional custom cache directory."""
26
+ if cache_dir is None:
27
+ cache_dir = _default_cache_dir()
28
+ self.cache_dir = Path(cache_dir)
29
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
30
+
31
+ def has(self, session_id: str) -> bool:
32
+ """Check if cached facet exists for session."""
33
+ return (self.cache_dir / f"{session_id}.json").exists()
34
+
35
+ def get(self, session_id: str) -> SessionFacet | None:
36
+ """Read and deserialize cached facet, return None if missing or corrupt."""
37
+ json_file = self.cache_dir / f"{session_id}.json"
38
+ if not json_file.exists():
39
+ return None
40
+ try:
41
+ data = json.loads(json_file.read_text(encoding="utf-8"))
42
+ from .types import SessionFacet
43
+
44
+ return SessionFacet(**data)
45
+ except (json.JSONDecodeError, TypeError, ValueError):
46
+ return None
47
+
48
+ def put(self, session_id: str, facet: SessionFacet) -> None:
49
+ """Atomically write facet to cache using .tmp then os.replace()."""
50
+ data = asdict(facet)
51
+ tmp_path = self.cache_dir / f"{session_id}.json.tmp"
52
+ json_path = self.cache_dir / f"{session_id}.json"
53
+ with open(tmp_path, "w", encoding="utf-8") as f:
54
+ json.dump(data, f, ensure_ascii=False, indent=2)
55
+ os.replace(tmp_path, json_path)
56
+
57
+ def clear(self) -> None:
58
+ """Remove all cached *.json files."""
59
+ for json_file in self.cache_dir.glob("*.json"):
60
+ json_file.unlink()