opencode-usage-v2 0.2.5__py3-none-any.whl → 0.2.6__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.
@@ -99,11 +99,14 @@ def get_db_path() -> Path:
99
99
 
100
100
  Resolution order:
101
101
  1. ``OPENCODE_DB`` environment variable (explicit override).
102
- 2. ``opencode db path`` CLI output.
103
- 3. Legacy XDG-based default.
102
+ 2. ``db`` entry from ``opencode debug paths`` (OpenCode v2 CLI).
103
+ 3. ``opencode db path`` CLI output (OpenCode v1 CLI fallback).
104
+ 4. Legacy XDG-based default.
104
105
  """
105
106
  if custom := os.environ.get("OPENCODE_DB"):
106
107
  return Path(custom)
108
+ if debug_db := _run_debug_paths().get("db"):
109
+ return Path(debug_db)
107
110
  cli_path = _run_db_path()
108
111
  if cli_path:
109
112
  return Path(cli_path)
opencode_usage/db.py CHANGED
@@ -445,40 +445,74 @@ class OpenCodeDB:
445
445
 
446
446
  # ── insights queries ─────────────────────────────────────────
447
447
 
448
+ def _table_cols(self, conn: sqlite3.Connection, table: str) -> set[str]:
449
+ """Return column names for *table* (caller passes known table identifier)."""
450
+ return {c[1] for c in conn.execute(f'PRAGMA table_info("{table}")')}
451
+
452
+ def _sessions_meta_sql(self, conn: sqlite3.Connection) -> str:
453
+ """Return unified session SELECT with (id, title, parent_id, time_updated)."""
454
+ tables = self._detect_tables(conn)
455
+ parts: list[str] = []
456
+ has_v2 = "session_v2" in tables
457
+
458
+ if has_v2:
459
+ cols = self._table_cols(conn, "session_v2")
460
+ title = "title" if "title" in cols else "NULL"
461
+ parent = "parent_id" if "parent_id" in cols else "NULL"
462
+ updated = "time_updated" if "time_updated" in cols else "0"
463
+ parts.append(
464
+ f"SELECT id, {title} AS title, {parent} AS parent_id, "
465
+ f"{updated} AS time_updated FROM session_v2"
466
+ )
467
+ if "session" in tables:
468
+ cols = self._table_cols(conn, "session")
469
+ title = "title" if "title" in cols else "NULL"
470
+ parent = "parent_id" if "parent_id" in cols else "NULL"
471
+ updated = "time_updated" if "time_updated" in cols else "0"
472
+ dedup = "WHERE id NOT IN (SELECT id FROM session_v2)" if has_v2 else ""
473
+ parts.append(
474
+ f"SELECT id, {title} AS title, {parent} AS parent_id, "
475
+ f"{updated} AS time_updated FROM session {dedup}"
476
+ )
477
+ if not parts:
478
+ return (
479
+ "SELECT NULL AS id, NULL AS title, NULL AS parent_id, 0 AS time_updated WHERE 1 = 0"
480
+ )
481
+ return " UNION ALL ".join(parts)
482
+
448
483
  def session_meta(
449
484
  self,
450
485
  since: datetime | None = None,
451
486
  until: datetime | None = None,
452
487
  limit: int | None = None,
453
488
  ) -> list[SessionMeta]:
454
- """Session metadata with aggregated token/cost stats."""
455
- time_clause, params = self._time_filter(since, until, col="m.data")
456
-
457
- sql = f"""
458
- SELECT
459
- s.id AS session_id,
460
- COALESCE(s.title, s.id) AS title,
461
- s.parent_id,
462
- MIN(json_extract(m.data, '$.time.created')) AS start_ms,
463
- MAX(json_extract(m.data, '$.time.created')) AS end_ms,
464
- COUNT(m.id) AS message_count,
465
- COALESCE(SUM(json_extract(m.data, '$.tokens.total')), 0) AS total_tokens,
466
- COALESCE(SUM(json_extract(m.data, '$.cost')), 0) AS total_cost,
467
- s.time_updated
468
- FROM session s
469
- LEFT JOIN message m ON m.session_id = s.id
470
- AND json_extract(m.data, '$.role') = 'assistant'
471
- AND json_extract(m.data, '$.tokens.total') IS NOT NULL
472
- {time_clause}
473
- GROUP BY s.id
474
- ORDER BY total_tokens DESC
475
- """
476
- if limit:
477
- sql += " LIMIT ?"
478
- params.append(limit)
489
+ """Session metadata with aggregated token/cost stats across v1 and v2 schemas."""
490
+ time_clause, params = self._time_filter(since, until, col="src.time_created_ms")
479
491
 
480
492
  conn = self._connect()
481
493
  try:
494
+ sessions_sql = self._sessions_meta_sql(conn)
495
+ source_sql = self._source_query(conn)
496
+ sql = f"""
497
+ SELECT
498
+ s.id AS session_id,
499
+ COALESCE(s.title, s.id) AS title,
500
+ s.parent_id,
501
+ MIN(src.time_created_ms) AS start_ms,
502
+ MAX(src.time_created_ms) AS end_ms,
503
+ COUNT(src.id) AS message_count,
504
+ COALESCE(SUM(src.total_tokens), 0) AS total_tokens,
505
+ COALESCE(SUM(src.cost), 0) AS total_cost,
506
+ s.time_updated
507
+ FROM ({sessions_sql}) s
508
+ LEFT JOIN ({source_sql}) src ON src.session_id = s.id
509
+ {time_clause}
510
+ GROUP BY s.id
511
+ ORDER BY total_tokens DESC
512
+ """
513
+ if limit:
514
+ sql += " LIMIT ?"
515
+ params.append(limit)
482
516
  rows = conn.execute(sql, params).fetchall()
483
517
  finally:
484
518
  conn.close()
@@ -520,22 +554,21 @@ class OpenCodeDB:
520
554
  until: datetime | None = None,
521
555
  ) -> dict[str, float]:
522
556
  """Per-model cache read ratio: cache_read / (input + cache_read)."""
523
- time_clause, params = self._time_filter(since, until)
524
-
525
- sql = f"""
526
- SELECT
527
- json_extract(data, '$.modelID') AS model,
528
- COALESCE(SUM(json_extract(data, '$.tokens.cache.read')), 0) AS cache_read,
529
- COALESCE(SUM(json_extract(data, '$.tokens.input')), 0) AS input_tokens
530
- FROM message
531
- WHERE json_extract(data, '$.role') = 'assistant'
532
- AND json_extract(data, '$.tokens.total') IS NOT NULL
533
- {time_clause}
534
- GROUP BY model
535
- """
557
+ time_clause, params = self._time_filter(since, until, col="src.time_created_ms")
536
558
 
537
559
  conn = self._connect()
538
560
  try:
561
+ source_sql = self._source_query(conn)
562
+ sql = f"""
563
+ SELECT
564
+ src.model AS model,
565
+ COALESCE(SUM(src.cache_read), 0) AS cache_read,
566
+ COALESCE(SUM(src.input_tokens), 0) AS input_tokens
567
+ FROM ({source_sql}) src
568
+ WHERE 1 = 1
569
+ {time_clause}
570
+ GROUP BY src.model
571
+ """
539
572
  rows = conn.execute(sql, params).fetchall()
540
573
  finally:
541
574
  conn.close()
@@ -556,22 +589,21 @@ class OpenCodeDB:
556
589
  until: datetime | None = None,
557
590
  ) -> dict[str, float]:
558
591
  """Per-model cost per 1,000 tokens."""
559
- time_clause, params = self._time_filter(since, until)
560
-
561
- sql = f"""
562
- SELECT
563
- json_extract(data, '$.modelID') AS model,
564
- COALESCE(SUM(json_extract(data, '$.cost')), 0) AS total_cost,
565
- COALESCE(SUM(json_extract(data, '$.tokens.total')), 0) AS total_tokens
566
- FROM message
567
- WHERE json_extract(data, '$.role') = 'assistant'
568
- AND json_extract(data, '$.tokens.total') IS NOT NULL
569
- {time_clause}
570
- GROUP BY model
571
- """
592
+ time_clause, params = self._time_filter(since, until, col="src.time_created_ms")
572
593
 
573
594
  conn = self._connect()
574
595
  try:
596
+ source_sql = self._source_query(conn)
597
+ sql = f"""
598
+ SELECT
599
+ src.model AS model,
600
+ COALESCE(SUM(src.cost), 0) AS total_cost,
601
+ COALESCE(SUM(src.total_tokens), 0) AS total_tokens
602
+ FROM ({source_sql}) src
603
+ WHERE 1 = 1
604
+ {time_clause}
605
+ GROUP BY src.model
606
+ """
575
607
  rows = conn.execute(sql, params).fetchall()
576
608
  finally:
577
609
  conn.close()
@@ -585,52 +617,84 @@ class OpenCodeDB:
585
617
  return result
586
618
 
587
619
  def tool_error_rates(self) -> dict[str, float]:
588
- """Per-tool error rate from the part table."""
589
- sql = """
590
- SELECT
591
- json_extract(data, '$.tool.name') AS tool_name,
592
- COUNT(*) AS total_calls,
593
- SUM(CASE WHEN json_extract(data, '$.state.status') = 'error'
594
- THEN 1 ELSE 0 END) AS error_count
595
- FROM part
596
- WHERE json_extract(data, '$.type') = 'tool'
597
- AND json_extract(data, '$.tool.name') IS NOT NULL
598
- GROUP BY tool_name
599
- """
620
+ """Per-tool error rate across v2 session_message and v1 part tables."""
621
+ totals: dict[str, int] = {}
622
+ errors: dict[str, int] = {}
623
+
624
+ def _record(name: str | None, status: str | None) -> None:
625
+ if not name:
626
+ return
627
+ totals[name] = totals.get(name, 0) + 1
628
+ if status == "error":
629
+ errors[name] = errors.get(name, 0) + 1
600
630
 
601
631
  conn = self._connect()
602
632
  try:
603
- rows = conn.execute(sql).fetchall()
633
+ tables = self._detect_tables(conn)
634
+ has_v2 = "session_message" in tables
635
+
636
+ if has_v2:
637
+ v2_rows = conn.execute(
638
+ "SELECT data FROM session_message WHERE type = 'assistant'"
639
+ ).fetchall()
640
+ for r in v2_rows:
641
+ try:
642
+ d = json.loads(r["data"])
643
+ except (json.JSONDecodeError, TypeError):
644
+ continue
645
+ for item in d.get("content") or []:
646
+ if isinstance(item, dict) and item.get("type") == "tool":
647
+ name = item.get("name")
648
+ if not name and isinstance(item.get("tool"), dict):
649
+ name = item["tool"].get("name")
650
+ state = item.get("state")
651
+ status = state.get("status") if isinstance(state, dict) else None
652
+ _record(name if isinstance(name, str) else None, status)
653
+
654
+ if "part" in tables:
655
+ dedup = "AND message_id NOT IN (SELECT id FROM session_message)" if has_v2 else ""
656
+ part_rows = conn.execute(
657
+ f"""
658
+ SELECT data FROM part
659
+ WHERE json_extract(data, '$.type') = 'tool'
660
+ {dedup}
661
+ """
662
+ ).fetchall()
663
+ for r in part_rows:
664
+ try:
665
+ d = json.loads(r["data"])
666
+ except (json.JSONDecodeError, TypeError):
667
+ continue
668
+ if not isinstance(d, dict):
669
+ continue
670
+ tool_val = d.get("tool")
671
+ name = tool_val.get("name") if isinstance(tool_val, dict) else tool_val
672
+ state = d.get("state")
673
+ status = state.get("status") if isinstance(state, dict) else None
674
+ _record(name if isinstance(name, str) else None, status)
604
675
  finally:
605
676
  conn.close()
606
677
 
607
- result: dict[str, float] = {}
608
- for r in rows:
609
- tool_name = r["tool_name"]
610
- total_calls = r["total_calls"]
611
- if tool_name and total_calls > 0:
612
- result[tool_name] = r["error_count"] / total_calls
613
- return result
678
+ return {name: errors.get(name, 0) / cnt for name, cnt in totals.items() if cnt > 0}
614
679
 
615
680
  def agent_delegation(self) -> dict[str, list[str]]:
616
- """Map parent session agents to their sub-agents."""
617
- sql = """
618
- SELECT
619
- json_extract(pm.data, '$.agent') AS parent_agent,
620
- json_extract(cm.data, '$.agent') AS child_agent
621
- FROM session s
622
- JOIN message cm ON cm.session_id = s.id
623
- AND json_extract(cm.data, '$.role') = 'assistant'
624
- AND json_extract(cm.data, '$.agent') IS NOT NULL
625
- JOIN message pm ON pm.session_id = s.parent_id
626
- AND json_extract(pm.data, '$.role') = 'assistant'
627
- AND json_extract(pm.data, '$.agent') IS NOT NULL
628
- WHERE s.parent_id IS NOT NULL
629
- GROUP BY parent_agent, child_agent
630
- """
631
-
681
+ """Map parent session agents to their sub-agents across v1 and v2."""
632
682
  conn = self._connect()
633
683
  try:
684
+ sessions_sql = self._sessions_meta_sql(conn)
685
+ source_sql = self._source_query(conn)
686
+ sql = f"""
687
+ SELECT
688
+ pm.agent AS parent_agent,
689
+ cm.agent AS child_agent
690
+ FROM ({sessions_sql}) s
691
+ JOIN ({source_sql}) cm ON cm.session_id = s.id
692
+ AND cm.agent IS NOT NULL
693
+ JOIN ({source_sql}) pm ON pm.session_id = s.parent_id
694
+ AND pm.agent IS NOT NULL
695
+ WHERE s.parent_id IS NOT NULL
696
+ GROUP BY parent_agent, child_agent
697
+ """
634
698
  rows = conn.execute(sql).fetchall()
635
699
  finally:
636
700
  conn.close()
@@ -644,50 +708,130 @@ class OpenCodeDB:
644
708
  return result
645
709
 
646
710
  def build_transcript(self, session_id: str, max_chars: int = 30000) -> str:
647
- """Flatten session parts into a text transcript for LLM analysis."""
648
- sql = """
649
- SELECT data FROM part
650
- WHERE session_id = ?
651
- ORDER BY time_created ASC
652
- """
653
-
711
+ """Flatten session parts and v2 messages into a text transcript for LLM analysis."""
654
712
  conn = self._connect()
655
713
  try:
656
- rows = conn.execute(sql, [session_id]).fetchall()
714
+ tables = self._detect_tables(conn)
715
+ has_v2 = "session_message" in tables
716
+ entries: list[tuple[int, int, str, int, str]] = []
717
+
718
+ if has_v2:
719
+ cols = self._table_cols(conn, "session_message")
720
+ seq_expr = "seq" if "seq" in cols else "0"
721
+ ts_expr = (
722
+ "CASE WHEN time_created > 1000000000000 THEN time_created "
723
+ "ELSE time_created * 1000 END"
724
+ if "time_created" in cols
725
+ else "0"
726
+ )
727
+ v2_rows = conn.execute(
728
+ f"""
729
+ SELECT id, type, {seq_expr} AS seq, {ts_expr} AS time_ms, data
730
+ FROM session_message
731
+ WHERE session_id = ?
732
+ """,
733
+ [session_id],
734
+ ).fetchall()
735
+ for r in v2_rows:
736
+ try:
737
+ d = json.loads(r["data"])
738
+ except (json.JSONDecodeError, TypeError):
739
+ continue
740
+ if not isinstance(d, dict):
741
+ continue
742
+ t_ms = int(r["time_ms"] or 0)
743
+ seq = int(r["seq"] or 0)
744
+ mid = str(r["id"])
745
+ if r["type"] == "user":
746
+ text = str(d.get("text", ""))[:500]
747
+ if text:
748
+ entries.append((t_ms, seq, mid, 0, f"[text]: {text}"))
749
+ elif r["type"] == "assistant":
750
+ for idx, item in enumerate(d.get("content") or []):
751
+ if not isinstance(item, dict):
752
+ continue
753
+ ptype = item.get("type", "")
754
+ if ptype == "text":
755
+ text = str(item.get("text", ""))[:500]
756
+ if text:
757
+ entries.append((t_ms, seq, mid, idx, f"[text]: {text}"))
758
+ elif ptype == "tool":
759
+ tool_name = item.get("name") or "unknown"
760
+ state_data = item.get("state", {})
761
+ if isinstance(state_data, dict):
762
+ status = state_data.get("status", "unknown")
763
+ tool_input = str(state_data.get("input", ""))[:200]
764
+ else:
765
+ status = "unknown"
766
+ tool_input = ""
767
+ entries.append(
768
+ (
769
+ t_ms,
770
+ seq,
771
+ mid,
772
+ idx,
773
+ f"[tool:{tool_name}] status:{status} input:{tool_input}",
774
+ )
775
+ )
776
+ elif ptype == "reasoning":
777
+ text = str(item.get("text", ""))[:200]
778
+ if text:
779
+ entries.append((t_ms, seq, mid, idx, f"[thinking]: {text}"))
780
+
781
+ if "part" in tables:
782
+ dedup = "AND message_id NOT IN (SELECT id FROM session_message)" if has_v2 else ""
783
+ rows = conn.execute(
784
+ f"""
785
+ SELECT id, time_created, data FROM part
786
+ WHERE session_id = ?
787
+ {dedup}
788
+ ORDER BY time_created ASC
789
+ """,
790
+ [session_id],
791
+ ).fetchall()
792
+ for r in rows:
793
+ try:
794
+ d = json.loads(r["data"])
795
+ except (json.JSONDecodeError, TypeError):
796
+ continue
797
+ t_ms = int(r["time_created"] or 0)
798
+ if t_ms and t_ms <= 1_000_000_000_000:
799
+ t_ms *= 1000
800
+ pid = str(r["id"])
801
+ part_type = d.get("type", "")
802
+ if part_type == "text":
803
+ text = d.get("text", "")[:500]
804
+ entries.append((t_ms, 0, pid, 0, f"[text]: {text}"))
805
+ elif part_type == "tool":
806
+ tool_data = d.get("tool", {})
807
+ if isinstance(tool_data, dict):
808
+ tool_name = tool_data.get("name", "unknown")
809
+ else:
810
+ tool_name = str(tool_data)
811
+ state_data = d.get("state", {})
812
+ if isinstance(state_data, dict):
813
+ status = state_data.get("status", "unknown")
814
+ tool_input = str(state_data.get("input", ""))[:200]
815
+ else:
816
+ status = "unknown"
817
+ tool_input = ""
818
+ entries.append(
819
+ (
820
+ t_ms,
821
+ 0,
822
+ pid,
823
+ 0,
824
+ f"[tool:{tool_name}] status:{status} input:{tool_input}",
825
+ )
826
+ )
827
+ elif part_type == "reasoning":
828
+ text = d.get("text", "")[:200]
829
+ entries.append((t_ms, 0, pid, 0, f"[thinking]: {text}"))
657
830
  finally:
658
831
  conn.close()
659
832
 
660
- parts: list[str] = []
661
- for r in rows:
662
- try:
663
- d = json.loads(r["data"])
664
- except (json.JSONDecodeError, TypeError):
665
- continue
666
-
667
- part_type = d.get("type", "")
668
- if part_type == "text":
669
- text = d.get("text", "")[:500]
670
- parts.append(f"[text]: {text}")
671
- elif part_type == "tool":
672
- tool_data = d.get("tool", {})
673
- if isinstance(tool_data, dict):
674
- tool_name = tool_data.get("name", "unknown")
675
- else:
676
- tool_name = str(tool_data)
677
- state_data = d.get("state", {})
678
- if isinstance(state_data, dict):
679
- status = state_data.get("status", "unknown")
680
- tool_input = str(state_data.get("input", ""))[:200]
681
- else:
682
- status = "unknown"
683
- tool_input = ""
684
- parts.append(f"[tool:{tool_name}] status:{status} input:{tool_input}")
685
- elif part_type == "reasoning":
686
- text = d.get("text", "")[:200]
687
- parts.append(f"[thinking]: {text}")
688
- # Skip: step-start, step-finish, compaction, file, patch, subtask
689
-
690
- transcript = "\n".join(parts)
833
+ entries.sort(key=lambda x: (x[0], x[1], x[2], x[3]))
834
+ transcript = "\n".join(x[4] for x in entries)
691
835
 
692
836
  if len(transcript) > max_chars:
693
837
  keep = int(max_chars * 0.4)
@@ -696,17 +840,61 @@ class OpenCodeDB:
696
840
  return transcript
697
841
 
698
842
  def session_user_messages(self, session_id: str) -> list[str]:
699
- """Return user text messages for a session."""
700
- sql = """
701
- SELECT json_extract(data, '$.text') AS text FROM part
702
- WHERE session_id = ? AND json_extract(data, '$.type') = 'text'
703
- ORDER BY time_created ASC
704
- """
705
-
843
+ """Return user text messages for a session across v1 and v2 schemas."""
706
844
  conn = self._connect()
707
845
  try:
708
- rows = conn.execute(sql, [session_id]).fetchall()
846
+ tables = self._detect_tables(conn)
847
+ has_v2 = "session_message" in tables
848
+ entries: list[tuple[int, int, str, str]] = []
849
+
850
+ if has_v2:
851
+ cols = self._table_cols(conn, "session_message")
852
+ seq_expr = "seq" if "seq" in cols else "0"
853
+ ts_expr = (
854
+ "CASE WHEN time_created > 1000000000000 THEN time_created "
855
+ "ELSE time_created * 1000 END"
856
+ if "time_created" in cols
857
+ else "0"
858
+ )
859
+ v2_rows = conn.execute(
860
+ f"""
861
+ SELECT id, {seq_expr} AS seq, {ts_expr} AS time_ms,
862
+ json_extract(data, '$.text') AS text
863
+ FROM session_message
864
+ WHERE session_id = ? AND type = 'user'
865
+ """,
866
+ [session_id],
867
+ ).fetchall()
868
+ for r in v2_rows:
869
+ if r["text"]:
870
+ entries.append(
871
+ (
872
+ int(r["time_ms"] or 0),
873
+ int(r["seq"] or 0),
874
+ str(r["id"]),
875
+ r["text"],
876
+ )
877
+ )
878
+
879
+ if "part" in tables:
880
+ dedup = "AND message_id NOT IN (SELECT id FROM session_message)" if has_v2 else ""
881
+ rows = conn.execute(
882
+ f"""
883
+ SELECT id, time_created, json_extract(data, '$.text') AS text FROM part
884
+ WHERE session_id = ? AND json_extract(data, '$.type') = 'text'
885
+ {dedup}
886
+ ORDER BY time_created ASC
887
+ """,
888
+ [session_id],
889
+ ).fetchall()
890
+ for r in rows:
891
+ if r["text"]:
892
+ t_ms = int(r["time_created"] or 0)
893
+ if t_ms and t_ms <= 1_000_000_000_000:
894
+ t_ms *= 1000
895
+ entries.append((t_ms, 0, str(r["id"]), r["text"]))
709
896
  finally:
710
897
  conn.close()
711
898
 
712
- return [r["text"] for r in rows if r["text"]]
899
+ entries.sort(key=lambda x: (x[0], x[1], x[2]))
900
+ return [x[3] for x in entries]