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/db.py ADDED
@@ -0,0 +1,712 @@
1
+ """SQLite query layer for OpenCode's database."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sqlite3
7
+ from dataclasses import dataclass, field
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from ._opencode_cli import get_db_path
13
+
14
+
15
+ def _default_db_path() -> Path:
16
+ """Resolve the OpenCode database path per platform."""
17
+ return get_db_path()
18
+
19
+
20
+ @dataclass
21
+ class TokenStats:
22
+ input: int = 0
23
+ output: int = 0
24
+ reasoning: int = 0
25
+ cache_read: int = 0
26
+ cache_write: int = 0
27
+ total: int = 0
28
+
29
+
30
+ @dataclass
31
+ class UsageRow:
32
+ """A single aggregated usage row."""
33
+
34
+ label: str
35
+ calls: int = 0
36
+ tokens: TokenStats = field(default_factory=TokenStats)
37
+ cost: float = 0.0
38
+ detail: str | None = None
39
+
40
+
41
+ @dataclass
42
+ class SessionMeta:
43
+ """Metadata about a user session."""
44
+
45
+ session_id: str
46
+ title: str
47
+ parent_id: str | None
48
+ start_time: datetime
49
+ duration_minutes: float
50
+ message_count: int
51
+ user_message_count: int
52
+ total_tokens: int
53
+ total_cost: float
54
+ agents: list[str]
55
+ models: list[str]
56
+ tool_counts: dict[str, int]
57
+ tool_errors: int
58
+
59
+
60
+ class OpenCodeDB:
61
+ """Read-only access to the OpenCode SQLite database."""
62
+
63
+ def __init__(self, db_path: Path | str | None = None) -> None:
64
+ self.path = Path(db_path) if db_path else _default_db_path()
65
+ if not self.path.exists():
66
+ raise FileNotFoundError(
67
+ f"OpenCode database not found at {self.path}\nSet OPENCODE_DB env var to override."
68
+ )
69
+
70
+ def _connect(self) -> sqlite3.Connection:
71
+ conn = sqlite3.connect(f"file:{self.path}?mode=ro", uri=True)
72
+ conn.row_factory = sqlite3.Row
73
+ return conn
74
+
75
+ def _detect_tables(self, conn) -> set[str]:
76
+ """Return the set of user table names in the database."""
77
+ rows = conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
78
+ return {r["name"] for r in rows}
79
+
80
+ def _source_query(self, conn) -> str:
81
+ """Return normalized assistant SQL SELECT across v1, v2, or mixed schemas."""
82
+ tables = self._detect_tables(conn)
83
+ has_v1 = "message" in tables
84
+ has_v2 = "session_message" in tables
85
+
86
+ parts: list[str] = []
87
+
88
+ if has_v2:
89
+ parts.append("""
90
+ SELECT
91
+ id,
92
+ session_id,
93
+ CASE
94
+ WHEN time_created > 1000000000000 THEN time_created
95
+ ELSE time_created * 1000
96
+ END AS time_created_ms,
97
+ json_extract(data, '$.agent') AS agent,
98
+ json_extract(data, '$.model.id') AS model,
99
+ json_extract(data, '$.model.providerID') AS provider,
100
+ COALESCE(json_extract(data, '$.tokens.input'), 0) AS input_tokens,
101
+ COALESCE(json_extract(data, '$.tokens.output'), 0) AS output_tokens,
102
+ COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS reasoning_tokens,
103
+ COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS cache_read,
104
+ COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS cache_write,
105
+ (COALESCE(json_extract(data, '$.tokens.input'), 0) +
106
+ COALESCE(json_extract(data, '$.tokens.output'), 0) +
107
+ COALESCE(json_extract(data, '$.tokens.reasoning'), 0)) AS total_tokens,
108
+ COALESCE(json_extract(data, '$.cost'), 0) AS cost
109
+ FROM session_message
110
+ WHERE type = 'assistant'
111
+ AND (COALESCE(json_extract(data, '$.tokens.input'), 0) +
112
+ COALESCE(json_extract(data, '$.tokens.output'), 0) +
113
+ COALESCE(json_extract(data, '$.tokens.reasoning'), 0)) > 0
114
+ """)
115
+
116
+ if has_v1:
117
+ dedup_clause = "AND id NOT IN (SELECT id FROM session_message)" if has_v2 else ""
118
+ parts.append(f"""
119
+ SELECT
120
+ id,
121
+ session_id,
122
+ json_extract(data, '$.time.created') AS time_created_ms,
123
+ json_extract(data, '$.agent') AS agent,
124
+ json_extract(data, '$.modelID') AS model,
125
+ json_extract(data, '$.providerID') AS provider,
126
+ COALESCE(json_extract(data, '$.tokens.input'), 0) AS input_tokens,
127
+ COALESCE(json_extract(data, '$.tokens.output'), 0) AS output_tokens,
128
+ COALESCE(json_extract(data, '$.tokens.reasoning'), 0) AS reasoning_tokens,
129
+ COALESCE(json_extract(data, '$.tokens.cache.read'), 0) AS cache_read,
130
+ COALESCE(json_extract(data, '$.tokens.cache.write'), 0) AS cache_write,
131
+ COALESCE(json_extract(data, '$.tokens.total'), 0) AS total_tokens,
132
+ COALESCE(json_extract(data, '$.cost'), 0) AS cost
133
+ FROM message
134
+ WHERE json_extract(data, '$.role') = 'assistant'
135
+ AND json_extract(data, '$.tokens.total') IS NOT NULL
136
+ {dedup_clause}
137
+ """)
138
+
139
+ if not parts:
140
+ return """
141
+ SELECT
142
+ NULL AS id,
143
+ NULL AS session_id,
144
+ 0 AS time_created_ms,
145
+ NULL AS agent,
146
+ NULL AS model,
147
+ NULL AS provider,
148
+ 0 AS input_tokens,
149
+ 0 AS output_tokens,
150
+ 0 AS reasoning_tokens,
151
+ 0 AS cache_read,
152
+ 0 AS cache_write,
153
+ 0 AS total_tokens,
154
+ 0.0 AS cost
155
+ WHERE 1 = 0
156
+ """
157
+
158
+ return " UNION ALL ".join(parts)
159
+
160
+ def _sessions_query(self, conn) -> str:
161
+ """Return the SQL SELECT for normalized session (id, title)."""
162
+ tables = self._detect_tables(conn)
163
+ has_v1 = "session" in tables
164
+ has_v2 = "session_v2" in tables
165
+
166
+ if has_v2 and has_v1:
167
+ return """
168
+ SELECT id, title FROM session_v2
169
+ UNION
170
+ SELECT id, title FROM session WHERE id NOT IN (SELECT id FROM session_v2)
171
+ """
172
+ if has_v2:
173
+ return "SELECT id, title FROM session_v2"
174
+ if has_v1:
175
+ return "SELECT id, title FROM session"
176
+ return "SELECT NULL AS id, NULL AS title WHERE 1 = 0"
177
+
178
+ # ── query helpers ─────────────────────────────────────────────
179
+
180
+ def _time_filter(
181
+ self,
182
+ since: datetime | None,
183
+ until: datetime | None = None,
184
+ *,
185
+ col: str = "src.time_created_ms",
186
+ ) -> tuple[str, list[Any]]:
187
+ """Return WHERE clause fragments and params for time filtering."""
188
+ clauses: list[str] = []
189
+ params: list[Any] = []
190
+ if since is not None:
191
+ ts_ms = int(since.timestamp() * 1000)
192
+ clauses.append(f"AND {col} >= ?")
193
+ params.append(ts_ms)
194
+ if until is not None:
195
+ ts_ms = int(until.timestamp() * 1000)
196
+ clauses.append(f"AND {col} < ?")
197
+ params.append(ts_ms)
198
+ return " ".join(clauses), params
199
+
200
+ def _base_query(
201
+ self,
202
+ group_expr: str,
203
+ since: datetime | None = None,
204
+ until: datetime | None = None,
205
+ order: str = "total_tokens DESC",
206
+ limit: int | None = None,
207
+ ) -> list[UsageRow]:
208
+ conn = self._connect()
209
+ try:
210
+ source_sql = self._source_query(conn)
211
+ time_clause, params = self._time_filter(since, until, col="src.time_created_ms")
212
+
213
+ sql = f"""
214
+ SELECT
215
+ {group_expr} AS label,
216
+ COUNT(*) AS calls,
217
+ COALESCE(SUM(src.input_tokens), 0) AS input_tokens,
218
+ COALESCE(SUM(src.output_tokens), 0) AS output_tokens,
219
+ COALESCE(SUM(src.reasoning_tokens), 0) AS reasoning_tokens,
220
+ COALESCE(SUM(src.cache_read), 0) AS cache_read,
221
+ COALESCE(SUM(src.cache_write), 0) AS cache_write,
222
+ COALESCE(SUM(src.total_tokens), 0) AS total_tokens,
223
+ COALESCE(SUM(src.cost), 0) AS cost
224
+ FROM ({source_sql}) src
225
+ WHERE 1 = 1
226
+ {time_clause}
227
+ GROUP BY label
228
+ ORDER BY {order}
229
+ """
230
+ if limit:
231
+ sql += " LIMIT ?"
232
+ params.append(limit)
233
+
234
+ rows = conn.execute(sql, params).fetchall()
235
+ finally:
236
+ conn.close()
237
+
238
+ return [
239
+ UsageRow(
240
+ label=r["label"] or "(unknown)",
241
+ calls=r["calls"],
242
+ tokens=TokenStats(
243
+ input=r["input_tokens"],
244
+ output=r["output_tokens"],
245
+ reasoning=r["reasoning_tokens"],
246
+ cache_read=r["cache_read"],
247
+ cache_write=r["cache_write"],
248
+ total=r["total_tokens"],
249
+ ),
250
+ cost=r["cost"],
251
+ )
252
+ for r in rows
253
+ ]
254
+
255
+ # ── public API ────────────────────────────────────────────────
256
+
257
+ def daily(
258
+ self,
259
+ since: datetime | None = None,
260
+ until: datetime | None = None,
261
+ limit: int | None = None,
262
+ ) -> list[UsageRow]:
263
+ return self._base_query(
264
+ group_expr=("date(src.time_created_ms / 1000, 'unixepoch', 'localtime')"),
265
+ since=since,
266
+ until=until,
267
+ order="label DESC",
268
+ limit=limit,
269
+ )
270
+
271
+ def by_model(
272
+ self,
273
+ since: datetime | None = None,
274
+ until: datetime | None = None,
275
+ limit: int | None = None,
276
+ ) -> list[UsageRow]:
277
+ return self._base_query(
278
+ group_expr="src.model",
279
+ since=since,
280
+ until=until,
281
+ limit=limit,
282
+ )
283
+
284
+ def by_agent(
285
+ self,
286
+ since: datetime | None = None,
287
+ until: datetime | None = None,
288
+ limit: int | None = None,
289
+ ) -> list[UsageRow]:
290
+ """Group by agent x model, showing which model each agent uses."""
291
+ conn = self._connect()
292
+ try:
293
+ source_sql = self._source_query(conn)
294
+ time_clause, params = self._time_filter(since, until, col="src.time_created_ms")
295
+
296
+ sql = f"""
297
+ SELECT
298
+ src.agent AS agent,
299
+ src.model AS model,
300
+ COUNT(*) AS calls,
301
+ COALESCE(SUM(src.input_tokens), 0) AS input_tokens,
302
+ COALESCE(SUM(src.output_tokens), 0) AS output_tokens,
303
+ COALESCE(SUM(src.reasoning_tokens), 0) AS reasoning_tokens,
304
+ COALESCE(SUM(src.cache_read), 0) AS cache_read,
305
+ COALESCE(SUM(src.cache_write), 0) AS cache_write,
306
+ COALESCE(SUM(src.total_tokens), 0) AS total_tokens,
307
+ COALESCE(SUM(src.cost), 0) AS cost
308
+ FROM ({source_sql}) src
309
+ WHERE 1 = 1
310
+ {time_clause}
311
+ GROUP BY src.agent, src.model
312
+ ORDER BY agent, total_tokens DESC
313
+ """
314
+ if limit:
315
+ sql += " LIMIT ?"
316
+ params.append(limit)
317
+
318
+ rows = conn.execute(sql, params).fetchall()
319
+ finally:
320
+ conn.close()
321
+
322
+ return [
323
+ UsageRow(
324
+ label=r["agent"] or "(unknown)",
325
+ calls=r["calls"],
326
+ tokens=TokenStats(
327
+ input=r["input_tokens"],
328
+ output=r["output_tokens"],
329
+ reasoning=r["reasoning_tokens"],
330
+ cache_read=r["cache_read"],
331
+ cache_write=r["cache_write"],
332
+ total=r["total_tokens"],
333
+ ),
334
+ cost=r["cost"],
335
+ detail=r["model"],
336
+ )
337
+ for r in rows
338
+ ]
339
+
340
+ def by_provider(
341
+ self,
342
+ since: datetime | None = None,
343
+ until: datetime | None = None,
344
+ limit: int | None = None,
345
+ ) -> list[UsageRow]:
346
+ return self._base_query(
347
+ group_expr="src.provider",
348
+ since=since,
349
+ until=until,
350
+ limit=limit,
351
+ )
352
+
353
+ def by_session(
354
+ self,
355
+ since: datetime | None = None,
356
+ until: datetime | None = None,
357
+ limit: int | None = None,
358
+ ) -> list[UsageRow]:
359
+ """Group by session, using session title as label."""
360
+ conn = self._connect()
361
+ try:
362
+ source_sql = self._source_query(conn)
363
+ sessions_sql = self._sessions_query(conn)
364
+ time_clause, params = self._time_filter(since, until, col="src.time_created_ms")
365
+
366
+ sql = f"""
367
+ SELECT
368
+ COALESCE(s.title, src.session_id) AS label,
369
+ COUNT(*) AS calls,
370
+ COALESCE(SUM(src.input_tokens), 0) AS input_tokens,
371
+ COALESCE(SUM(src.output_tokens), 0) AS output_tokens,
372
+ COALESCE(SUM(src.reasoning_tokens), 0) AS reasoning_tokens,
373
+ COALESCE(SUM(src.cache_read), 0) AS cache_read,
374
+ COALESCE(SUM(src.cache_write), 0) AS cache_write,
375
+ COALESCE(SUM(src.total_tokens), 0) AS total_tokens,
376
+ COALESCE(SUM(src.cost), 0) AS cost
377
+ FROM ({source_sql}) src
378
+ LEFT JOIN ({sessions_sql}) s ON src.session_id = s.id
379
+ WHERE 1 = 1
380
+ {time_clause}
381
+ GROUP BY src.session_id
382
+ ORDER BY total_tokens DESC
383
+ """
384
+ if limit:
385
+ sql += " LIMIT ?"
386
+ params.append(limit)
387
+
388
+ rows = conn.execute(sql, params).fetchall()
389
+ finally:
390
+ conn.close()
391
+
392
+ return [
393
+ UsageRow(
394
+ label=r["label"] or "(untitled)",
395
+ calls=r["calls"],
396
+ tokens=TokenStats(
397
+ input=r["input_tokens"],
398
+ output=r["output_tokens"],
399
+ reasoning=r["reasoning_tokens"],
400
+ cache_read=r["cache_read"],
401
+ cache_write=r["cache_write"],
402
+ total=r["total_tokens"],
403
+ ),
404
+ cost=r["cost"],
405
+ )
406
+ for r in rows
407
+ ]
408
+
409
+ def totals(
410
+ self,
411
+ since: datetime | None = None,
412
+ until: datetime | None = None,
413
+ ) -> UsageRow:
414
+ """Return a single aggregated row for the period."""
415
+ rows = self._base_query(
416
+ group_expr="'total'",
417
+ since=since,
418
+ until=until,
419
+ )
420
+ if rows:
421
+ return rows[0]
422
+ return UsageRow(label="total")
423
+
424
+ def to_dicts(self, rows: list[UsageRow]) -> list[dict[str, Any]]:
425
+ """Serialize rows for JSON output."""
426
+ result = []
427
+ for r in rows:
428
+ d: dict[str, Any] = {
429
+ "label": r.label,
430
+ "calls": r.calls,
431
+ "tokens": {
432
+ "input": r.tokens.input,
433
+ "output": r.tokens.output,
434
+ "reasoning": r.tokens.reasoning,
435
+ "cache_read": r.tokens.cache_read,
436
+ "cache_write": r.tokens.cache_write,
437
+ "total": r.tokens.total,
438
+ },
439
+ "cost": round(r.cost, 4),
440
+ }
441
+ if r.detail is not None:
442
+ d["model"] = r.detail
443
+ result.append(d)
444
+ return result
445
+
446
+ # ── insights queries ─────────────────────────────────────────
447
+
448
+ def session_meta(
449
+ self,
450
+ since: datetime | None = None,
451
+ until: datetime | None = None,
452
+ limit: int | None = None,
453
+ ) -> 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)
479
+
480
+ conn = self._connect()
481
+ try:
482
+ rows = conn.execute(sql, params).fetchall()
483
+ finally:
484
+ conn.close()
485
+
486
+ result: list[SessionMeta] = []
487
+ for r in rows:
488
+ start_ms = r["start_ms"]
489
+ end_ms = r["end_ms"]
490
+ if start_ms is not None:
491
+ start_time = datetime.fromtimestamp(start_ms / 1000).astimezone()
492
+ else:
493
+ start_time = datetime.min.replace(tzinfo=datetime.now().astimezone().tzinfo)
494
+ if start_ms is not None and end_ms is not None:
495
+ duration_minutes = (end_ms - start_ms) / 60000
496
+ else:
497
+ duration_minutes = 0.0
498
+ result.append(
499
+ SessionMeta(
500
+ session_id=r["session_id"],
501
+ title=r["title"] or r["session_id"],
502
+ parent_id=r["parent_id"],
503
+ start_time=start_time,
504
+ duration_minutes=duration_minutes,
505
+ message_count=r["message_count"],
506
+ user_message_count=0,
507
+ total_tokens=r["total_tokens"],
508
+ total_cost=r["total_cost"],
509
+ agents=[],
510
+ models=[],
511
+ tool_counts={},
512
+ tool_errors=0,
513
+ )
514
+ )
515
+ return result
516
+
517
+ def cache_efficiency(
518
+ self,
519
+ since: datetime | None = None,
520
+ until: datetime | None = None,
521
+ ) -> dict[str, float]:
522
+ """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
+ """
536
+
537
+ conn = self._connect()
538
+ try:
539
+ rows = conn.execute(sql, params).fetchall()
540
+ finally:
541
+ conn.close()
542
+
543
+ result: dict[str, float] = {}
544
+ for r in rows:
545
+ model = r["model"]
546
+ cache_read = r["cache_read"]
547
+ input_tokens = r["input_tokens"]
548
+ denominator = input_tokens + cache_read
549
+ if model and denominator > 0:
550
+ result[model] = cache_read / denominator
551
+ return result
552
+
553
+ def cost_per_1k_tokens(
554
+ self,
555
+ since: datetime | None = None,
556
+ until: datetime | None = None,
557
+ ) -> dict[str, float]:
558
+ """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
+ """
572
+
573
+ conn = self._connect()
574
+ try:
575
+ rows = conn.execute(sql, params).fetchall()
576
+ finally:
577
+ conn.close()
578
+
579
+ result: dict[str, float] = {}
580
+ for r in rows:
581
+ model = r["model"]
582
+ total_tokens = r["total_tokens"]
583
+ if model and total_tokens > 0:
584
+ result[model] = r["total_cost"] / total_tokens * 1000
585
+ return result
586
+
587
+ 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
+ """
600
+
601
+ conn = self._connect()
602
+ try:
603
+ rows = conn.execute(sql).fetchall()
604
+ finally:
605
+ conn.close()
606
+
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
614
+
615
+ 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
+
632
+ conn = self._connect()
633
+ try:
634
+ rows = conn.execute(sql).fetchall()
635
+ finally:
636
+ conn.close()
637
+
638
+ result: dict[str, list[str]] = {}
639
+ for r in rows:
640
+ parent = r["parent_agent"]
641
+ child = r["child_agent"]
642
+ if parent and child:
643
+ result.setdefault(parent, []).append(child)
644
+ return result
645
+
646
+ 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
+
654
+ conn = self._connect()
655
+ try:
656
+ rows = conn.execute(sql, [session_id]).fetchall()
657
+ finally:
658
+ conn.close()
659
+
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)
691
+
692
+ if len(transcript) > max_chars:
693
+ keep = int(max_chars * 0.4)
694
+ transcript = transcript[:keep] + "\n[...truncated...]\n" + transcript[-keep:]
695
+
696
+ return transcript
697
+
698
+ 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
+
706
+ conn = self._connect()
707
+ try:
708
+ rows = conn.execute(sql, [session_id]).fetchall()
709
+ finally:
710
+ conn.close()
711
+
712
+ return [r["text"] for r in rows if r["text"]]