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,600 @@
1
+ """Session data extraction functions for OpenCode insights."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sqlite3
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from .types import AggregatedStats, SessionMeta
12
+
13
+
14
+ def _connect(db_path: Path | str) -> sqlite3.Connection:
15
+ """Open a read-only SQLite connection."""
16
+ conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
17
+ conn.row_factory = sqlite3.Row
18
+ return conn
19
+
20
+
21
+ def _time_params(
22
+ since: datetime | None,
23
+ until: datetime | None = None,
24
+ ) -> tuple[str, list[Any]]:
25
+ """Return WHERE clause fragments for message time filtering."""
26
+ params: list[Any] = []
27
+ clauses: list[str] = []
28
+ if since:
29
+ clauses.append("json_extract(m.data, '$.time.created') >= ?")
30
+ params.append(int(since.timestamp() * 1000))
31
+ if until:
32
+ clauses.append("json_extract(m.data, '$.time.created') < ?")
33
+ params.append(int(until.timestamp() * 1000))
34
+ where = ("AND " + " AND ".join(clauses)) if clauses else ""
35
+ return where, params
36
+
37
+
38
+ def _session_time_params(
39
+ since: datetime | None,
40
+ until: datetime | None = None,
41
+ ) -> tuple[str, list[Any]]:
42
+ """Return WHERE clause fragments for session time filtering."""
43
+ params: list[Any] = []
44
+ clauses: list[str] = []
45
+ if since:
46
+ clauses.append("s.time_created >= ?")
47
+ params.append(int(since.timestamp() * 1000))
48
+ if until:
49
+ clauses.append("s.time_created < ?")
50
+ params.append(int(until.timestamp() * 1000))
51
+ where = ("AND " + " AND ".join(clauses)) if clauses else ""
52
+ return where, params
53
+
54
+
55
+ # ── T5: Session Filtering & Metadata ─────────────────────────
56
+
57
+
58
+ def filter_sessions(
59
+ db_path: Path | str,
60
+ since: datetime | None,
61
+ until: datetime | None = None,
62
+ ) -> list[str]:
63
+ """Return root session IDs with sufficient activity in the time range."""
64
+ time_clause, params = _time_params(since, until)
65
+ sql = f"""
66
+ SELECT s.id,
67
+ COUNT(CASE WHEN json_extract(m.data, '$.role') = 'user'
68
+ THEN 1 END) AS user_count,
69
+ MAX(json_extract(m.data, '$.time.created'))
70
+ - MIN(json_extract(m.data, '$.time.created'))
71
+ AS duration_ms
72
+ FROM session s
73
+ LEFT JOIN message m ON m.session_id = s.id
74
+ WHERE s.parent_id IS NULL
75
+ {time_clause}
76
+ GROUP BY s.id
77
+ HAVING user_count >= 2 AND duration_ms >= 60000
78
+ """
79
+ conn = _connect(db_path)
80
+ try:
81
+ rows = conn.execute(sql, params).fetchall()
82
+ finally:
83
+ conn.close()
84
+ return [r["id"] for r in rows]
85
+
86
+
87
+ def extract_session_meta(
88
+ db_path: Path | str,
89
+ session_id: str,
90
+ ) -> SessionMeta:
91
+ """Populate SessionMeta from DB for a single session."""
92
+ conn = _connect(db_path)
93
+ try:
94
+ # 1. Message-level stats
95
+ row = conn.execute(
96
+ """
97
+ SELECT
98
+ s.title, s.parent_id,
99
+ MIN(json_extract(m.data, '$.time.created'))
100
+ AS start_ms,
101
+ MAX(json_extract(m.data, '$.time.created'))
102
+ AS end_ms,
103
+ COUNT(CASE WHEN json_extract(m.data, '$.role') = 'user'
104
+ THEN 1 END) AS user_count,
105
+ COUNT(CASE WHEN json_extract(m.data, '$.role') = 'assistant'
106
+ THEN 1 END) AS asst_count,
107
+ COALESCE(SUM(
108
+ CASE WHEN json_extract(m.data, '$.role') = 'assistant'
109
+ THEN json_extract(m.data, '$.tokens.input') END
110
+ ), 0) AS input_tok,
111
+ COALESCE(SUM(
112
+ CASE WHEN json_extract(m.data, '$.role') = 'assistant'
113
+ THEN json_extract(m.data, '$.tokens.output') END
114
+ ), 0) AS output_tok,
115
+ COALESCE(SUM(
116
+ CASE WHEN json_extract(m.data, '$.role') = 'assistant'
117
+ THEN json_extract(m.data, '$.tokens.total') END
118
+ ), 0) AS total_tok,
119
+ COALESCE(SUM(json_extract(m.data, '$.cost')), 0)
120
+ AS total_cost
121
+ FROM session s
122
+ LEFT JOIN message m ON m.session_id = s.id
123
+ WHERE s.id = ?
124
+ GROUP BY s.id
125
+ """,
126
+ [session_id],
127
+ ).fetchone()
128
+
129
+ if row is None:
130
+ return SessionMeta(id=session_id, title=session_id)
131
+
132
+ # 2. Agent/model counts
133
+ am_rows = conn.execute(
134
+ """
135
+ SELECT json_extract(data, '$.agent') AS agent,
136
+ json_extract(data, '$.modelID') AS model
137
+ FROM message
138
+ WHERE session_id = ?
139
+ AND json_extract(data, '$.role') = 'assistant'
140
+ """,
141
+ [session_id],
142
+ ).fetchall()
143
+
144
+ agent_counts: dict[str, int] = {}
145
+ model_counts: dict[str, int] = {}
146
+ for amr in am_rows:
147
+ ag = amr["agent"]
148
+ md = amr["model"]
149
+ if ag:
150
+ agent_counts[ag] = agent_counts.get(ag, 0) + 1
151
+ if md:
152
+ model_counts[md] = model_counts.get(md, 0) + 1
153
+
154
+ # 3. Tool counts
155
+ tool_rows = conn.execute(
156
+ """
157
+ SELECT json_extract(data, '$.tool') AS tool,
158
+ COUNT(*) AS cnt
159
+ FROM part
160
+ WHERE message_id IN (
161
+ SELECT id FROM message WHERE session_id = ?
162
+ )
163
+ AND json_extract(data, '$.type') = 'tool'
164
+ GROUP BY tool
165
+ """,
166
+ [session_id],
167
+ ).fetchall()
168
+ tool_counts = {r["tool"]: r["cnt"] for r in tool_rows if r["tool"]}
169
+
170
+ # 4. Language detection from file paths
171
+ fp_rows = conn.execute(
172
+ """
173
+ SELECT json_extract(data, '$.state.input.filePath') AS fp
174
+ FROM part
175
+ WHERE message_id IN (
176
+ SELECT id FROM message WHERE session_id = ?
177
+ )
178
+ AND json_extract(data, '$.type') = 'tool'
179
+ AND json_extract(data, '$.tool')
180
+ IN ('read', 'edit', 'write', 'patch')
181
+ AND json_extract(data, '$.state.input.filePath')
182
+ IS NOT NULL
183
+ """,
184
+ [session_id],
185
+ ).fetchall()
186
+ languages: dict[str, int] = {}
187
+ for fpr in fp_rows:
188
+ fp = fpr["fp"]
189
+ if fp:
190
+ ext = Path(fp).suffix.lstrip(".")
191
+ if ext:
192
+ languages[ext] = languages.get(ext, 0) + 1
193
+
194
+ # 5. Project path (table may not exist in all DBs)
195
+ project_path: str | None = None
196
+ try:
197
+ proj_row = conn.execute(
198
+ """
199
+ SELECT p.worktree
200
+ FROM project p
201
+ JOIN session s ON s.project_id = p.id
202
+ WHERE s.id = ?
203
+ """,
204
+ [session_id],
205
+ ).fetchone()
206
+ if proj_row:
207
+ project_path = proj_row["worktree"]
208
+ except sqlite3.OperationalError:
209
+ pass
210
+
211
+ finally:
212
+ conn.close()
213
+
214
+ start_ms = row["start_ms"] or 0
215
+ end_ms = row["end_ms"] or 0
216
+ dur = end_ms - start_ms if start_ms and end_ms else 0
217
+
218
+ return SessionMeta(
219
+ id=session_id,
220
+ title=row["title"] or session_id,
221
+ project_path=project_path,
222
+ parent_id=row["parent_id"],
223
+ duration_minutes=dur / 60_000,
224
+ user_msg_count=int(row["user_count"]),
225
+ assistant_msg_count=int(row["asst_count"]),
226
+ input_tokens=int(row["input_tok"]),
227
+ output_tokens=int(row["output_tok"]),
228
+ total_tokens=int(row["total_tok"]),
229
+ cost=float(row["total_cost"]),
230
+ tool_counts=tool_counts,
231
+ languages=languages,
232
+ agent_counts=agent_counts,
233
+ model_counts=model_counts,
234
+ start_time=int(start_ms),
235
+ end_time=int(end_ms),
236
+ )
237
+
238
+
239
+ # ── T6: Transcript Reconstruction ────────────────────────────
240
+
241
+
242
+ def reconstruct_transcript(
243
+ db_path: Path | str,
244
+ session_id: str,
245
+ max_chars: int = 30000,
246
+ ) -> str:
247
+ """Flatten session parts into a chronological transcript."""
248
+ conn = _connect(db_path)
249
+ try:
250
+ rows = conn.execute(
251
+ """
252
+ SELECT p.data, m.data AS msg_data
253
+ FROM part p
254
+ JOIN message m ON p.message_id = m.id
255
+ WHERE m.session_id = ?
256
+ ORDER BY p.time_created ASC, p.id ASC
257
+ """,
258
+ [session_id],
259
+ ).fetchall()
260
+ finally:
261
+ conn.close()
262
+
263
+ lines: list[str] = []
264
+ for r in rows:
265
+ try:
266
+ part = json.loads(r["data"])
267
+ msg = json.loads(r["msg_data"])
268
+ except (json.JSONDecodeError, TypeError):
269
+ continue
270
+
271
+ ptype = part.get("type", "")
272
+ if ptype == "text" and part.get("text"):
273
+ role = msg.get("role", "unknown")
274
+ lines.append(f"[{role}]: {part['text']}")
275
+ elif ptype == "tool":
276
+ tool = part.get("tool", "unknown")
277
+ state = part.get("state") or {}
278
+ status = state.get("status", "unknown")
279
+ lines.append(f"[assistant]: Used {tool} ({status})")
280
+ elif ptype == "reasoning" and part.get("text"):
281
+ text = part["text"][:200]
282
+ lines.append(f"[assistant]: (reasoning) {text}")
283
+
284
+ transcript = "\n".join(lines)
285
+
286
+ if len(transcript) > max_chars:
287
+ header = f"[TRUNCATED — showing last {max_chars} chars]\n"
288
+ transcript = header + transcript[-max_chars:]
289
+
290
+ return transcript
291
+
292
+
293
+ # ── T7: Statistics Extraction ─────────────────────────────────
294
+
295
+
296
+ def extract_agent_stats(
297
+ db_path: Path | str,
298
+ since: datetime | None,
299
+ until: datetime | None = None,
300
+ ) -> dict[str, dict[str, Any]]:
301
+ """Agent-level aggregated statistics."""
302
+ time_clause, params = _time_params(since, until)
303
+ sql = f"""
304
+ SELECT
305
+ json_extract(m.data, '$.agent') AS agent,
306
+ json_extract(m.data, '$.modelID') AS model,
307
+ COUNT(*) AS calls,
308
+ COALESCE(SUM(json_extract(m.data, '$.tokens.total')),
309
+ 0) AS tokens,
310
+ COALESCE(SUM(json_extract(m.data, '$.cost')),
311
+ 0) AS cost
312
+ FROM message m
313
+ WHERE json_extract(m.data, '$.role') = 'assistant'
314
+ {time_clause}
315
+ GROUP BY agent, model
316
+ """
317
+ conn = _connect(db_path)
318
+ try:
319
+ rows = conn.execute(sql, params).fetchall()
320
+ finally:
321
+ conn.close()
322
+
323
+ result: dict[str, dict[str, Any]] = {}
324
+ for r in rows:
325
+ agent = r["agent"]
326
+ if not agent:
327
+ continue
328
+ if agent not in result:
329
+ result[agent] = {
330
+ "calls": 0,
331
+ "tokens": 0,
332
+ "cost": 0.0,
333
+ "models_used": [],
334
+ }
335
+ result[agent]["calls"] += r["calls"]
336
+ result[agent]["tokens"] += r["tokens"]
337
+ result[agent]["cost"] += r["cost"]
338
+ model = r["model"]
339
+ if model and model not in result[agent]["models_used"]:
340
+ result[agent]["models_used"].append(model)
341
+ return result
342
+
343
+
344
+ def extract_model_stats(
345
+ db_path: Path | str,
346
+ since: datetime | None,
347
+ until: datetime | None = None,
348
+ ) -> dict[str, dict[str, Any]]:
349
+ """Model-level aggregated statistics."""
350
+ time_clause, params = _time_params(since, until)
351
+ sql = f"""
352
+ SELECT
353
+ json_extract(m.data, '$.modelID') AS model,
354
+ json_extract(m.data, '$.agent') AS agent,
355
+ COUNT(*) AS calls,
356
+ COALESCE(SUM(json_extract(m.data, '$.tokens.total')),
357
+ 0) AS tokens,
358
+ COALESCE(SUM(json_extract(m.data, '$.cost')),
359
+ 0) AS cost
360
+ FROM message m
361
+ WHERE json_extract(m.data, '$.role') = 'assistant'
362
+ {time_clause}
363
+ GROUP BY model, agent
364
+ """
365
+ conn = _connect(db_path)
366
+ try:
367
+ rows = conn.execute(sql, params).fetchall()
368
+ finally:
369
+ conn.close()
370
+
371
+ result: dict[str, dict[str, Any]] = {}
372
+ for r in rows:
373
+ model = r["model"]
374
+ if not model:
375
+ continue
376
+ if model not in result:
377
+ result[model] = {
378
+ "calls": 0,
379
+ "tokens": 0,
380
+ "cost": 0.0,
381
+ "agents_using": [],
382
+ }
383
+ result[model]["calls"] += r["calls"]
384
+ result[model]["tokens"] += r["tokens"]
385
+ result[model]["cost"] += r["cost"]
386
+ agent = r["agent"]
387
+ if agent and agent not in result[model]["agents_using"]:
388
+ result[model]["agents_using"].append(agent)
389
+ return result
390
+
391
+
392
+ def extract_tool_stats(
393
+ db_path: Path | str,
394
+ since: datetime | None,
395
+ until: datetime | None = None,
396
+ ) -> dict[str, dict[str, int]]:
397
+ """Tool completion/error counts from the part table."""
398
+ time_clause, params = _time_params(since, until)
399
+ sql = f"""
400
+ SELECT
401
+ json_extract(p.data, '$.tool') AS tool,
402
+ json_extract(p.data, '$.state.status') AS status,
403
+ COUNT(*) AS cnt
404
+ FROM part p
405
+ JOIN message m ON p.message_id = m.id
406
+ WHERE json_extract(p.data, '$.type') = 'tool'
407
+ {time_clause}
408
+ GROUP BY tool, status
409
+ """
410
+ conn = _connect(db_path)
411
+ try:
412
+ rows = conn.execute(sql, params).fetchall()
413
+ finally:
414
+ conn.close()
415
+
416
+ result: dict[str, dict[str, int]] = {}
417
+ for r in rows:
418
+ tool = r["tool"]
419
+ if not tool:
420
+ continue
421
+ if tool not in result:
422
+ result[tool] = {"completed": 0, "errors": 0, "total": 0}
423
+ cnt = r["cnt"]
424
+ result[tool]["total"] += cnt
425
+ if r["status"] == "error":
426
+ result[tool]["errors"] += cnt
427
+ else:
428
+ result[tool]["completed"] += cnt
429
+ return result
430
+
431
+
432
+ def extract_todo_stats(
433
+ db_path: Path | str,
434
+ since: datetime | None,
435
+ until: datetime | None = None,
436
+ ) -> dict[str, int]:
437
+ """Todo status counts joined with session for time filtering."""
438
+ time_clause, params = _session_time_params(since, until)
439
+ sql = f"""
440
+ SELECT t.status, COUNT(*) AS cnt
441
+ FROM todo t
442
+ JOIN session s ON t.session_id = s.id
443
+ WHERE 1=1
444
+ {time_clause}
445
+ GROUP BY t.status
446
+ """
447
+ conn = _connect(db_path)
448
+ try:
449
+ rows = conn.execute(sql, params).fetchall()
450
+ finally:
451
+ conn.close()
452
+
453
+ return {r["status"]: r["cnt"] for r in rows if r["status"]}
454
+
455
+
456
+ def extract_delegation_stats(
457
+ db_path: Path | str,
458
+ since: datetime | None,
459
+ until: datetime | None = None,
460
+ ) -> dict[str, Any]:
461
+ """Session hierarchy statistics."""
462
+ time_clause, params = _session_time_params(since, until)
463
+ sql = f"""
464
+ SELECT s.id, s.parent_id
465
+ FROM session s
466
+ WHERE 1=1
467
+ {time_clause}
468
+ """
469
+ conn = _connect(db_path)
470
+ try:
471
+ rows = conn.execute(sql, params).fetchall()
472
+ finally:
473
+ conn.close()
474
+
475
+ root_count = 0
476
+ sub_count = 0
477
+ children: dict[str, list[str]] = {}
478
+ parent_map: dict[str, str | None] = {}
479
+
480
+ for r in rows:
481
+ sid = r["id"]
482
+ pid = r["parent_id"]
483
+ parent_map[sid] = pid
484
+ if pid is None:
485
+ root_count += 1
486
+ else:
487
+ sub_count += 1
488
+ children.setdefault(pid, []).append(sid)
489
+
490
+ # Compute depths via parent traversal
491
+ depths: dict[str, int] = {}
492
+ for sid in parent_map:
493
+ depth = 0
494
+ current: str | None = sid
495
+ while current is not None and parent_map.get(current) is not None:
496
+ depth += 1
497
+ current = parent_map[current]
498
+ depths[sid] = depth
499
+
500
+ max_depth = max(depths.values()) if depths else 0
501
+ all_depths = list(depths.values())
502
+ avg_depth = sum(all_depths) / len(all_depths) if all_depths else 0.0
503
+
504
+ sub_types: dict[str, int] = {k: len(v) for k, v in children.items()}
505
+
506
+ return {
507
+ "root_sessions": root_count,
508
+ "sub_sessions": sub_count,
509
+ "sub_types": sub_types,
510
+ "max_depth": max_depth,
511
+ "avg_depth": avg_depth,
512
+ }
513
+
514
+
515
+ def extract_project_stats(
516
+ db_path: Path | str,
517
+ since: datetime | None,
518
+ until: datetime | None = None,
519
+ ) -> dict[str, int]:
520
+ """Project path to session count mapping."""
521
+ time_clause, params = _session_time_params(since, until)
522
+ sql = f"""
523
+ SELECT p.worktree AS project_path, COUNT(s.id) AS cnt
524
+ FROM session s
525
+ JOIN project p ON s.project_id = p.id
526
+ WHERE 1=1
527
+ {time_clause}
528
+ GROUP BY p.worktree
529
+ """
530
+ conn = _connect(db_path)
531
+ try:
532
+ rows = conn.execute(sql, params).fetchall()
533
+ finally:
534
+ conn.close()
535
+
536
+ return {r["project_path"]: r["cnt"] for r in rows if r["project_path"]}
537
+
538
+
539
+ def aggregate_all(
540
+ db_path: Path | str,
541
+ session_ids: list[str],
542
+ since: datetime | None,
543
+ until: datetime | None = None,
544
+ ) -> AggregatedStats:
545
+ """Build AggregatedStats from extraction functions."""
546
+ agent_stats = extract_agent_stats(db_path, since, until)
547
+ model_stats = extract_model_stats(db_path, since, until)
548
+ tool_stats = extract_tool_stats(db_path, since, until)
549
+
550
+ # Query date range and totals
551
+ time_clause, params = _time_params(since, until)
552
+ sql = f"""
553
+ SELECT
554
+ MIN(json_extract(m.data, '$.time.created')) AS min_time,
555
+ MAX(json_extract(m.data, '$.time.created')) AS max_time,
556
+ COUNT(*) AS total_messages,
557
+ COALESCE(SUM(json_extract(m.data, '$.cost')), 0)
558
+ AS total_cost
559
+ FROM message m
560
+ WHERE json_extract(m.data, '$.role')
561
+ IN ('user', 'assistant')
562
+ {time_clause}
563
+ """
564
+ conn = _connect(db_path)
565
+ try:
566
+ row = conn.execute(sql, params).fetchone()
567
+ finally:
568
+ conn.close()
569
+
570
+ min_time = int(row["min_time"] or 0)
571
+ max_time = int(row["max_time"] or 0)
572
+ total_messages = row["total_messages"] or 0
573
+ total_cost = float(row["total_cost"] or 0.0)
574
+
575
+ top_tools = sorted(
576
+ [(name, d["total"]) for name, d in tool_stats.items()],
577
+ key=lambda x: x[1],
578
+ reverse=True,
579
+ )[:10]
580
+ top_agents = sorted(
581
+ [(name, d["calls"]) for name, d in agent_stats.items()],
582
+ key=lambda x: x[1],
583
+ reverse=True,
584
+ )[:10]
585
+ top_models = sorted(
586
+ [(name, d["calls"]) for name, d in model_stats.items()],
587
+ key=lambda x: x[1],
588
+ reverse=True,
589
+ )[:10]
590
+
591
+ return AggregatedStats(
592
+ total_sessions=len(session_ids),
593
+ analyzed_sessions=0,
594
+ date_range=(min_time, max_time),
595
+ total_messages=total_messages,
596
+ total_cost=total_cost,
597
+ top_tools=top_tools,
598
+ top_agents=top_agents,
599
+ top_models=top_models,
600
+ )