-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
1319 lines (1200 loc) · 46 KB
/
Copy pathdatabase.py
File metadata and controls
1319 lines (1200 loc) · 46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
SQLite layer with thread-safe writes, thread-local read pool, and versioned migrations.
Cost stored as INTEGER micro-dollars (1 USD = 1,000,000 microusd).
This eliminates float accumulation drift entirely.
"""
import json
import logging
import os
import re
import sqlite3
import threading
import time
from contextlib import contextmanager
from datetime import datetime, timedelta, timezone
from pathlib import Path
logger = logging.getLogger(__name__)
DB_PATH = Path(
os.environ.get(
'DASHBOARD_DB_PATH',
str(Path.home() / '.codex' / 'dashboard.db'),
)
)
_write_lock = threading.Lock()
_read_local = threading.local() # per-thread cached read connection
_READ_CONN_TTL = 300 # seconds before recycling a cached read connection
_READ_EPOCH = 0 # incremented after writes so readers reopen snapshots
MICRO = 1_000_000 # 1 USD = 1M micro-dollars
SCHEMA_VERSION = 18 # bump on every schema change
_CODEX_FTS_TOKEN_RE = re.compile(r'[\w가-힣]+', re.UNICODE)
def _esc_like(value: str) -> str:
return value.replace('\\', '\\\\').replace('%', r'\%').replace('_', r'\_')
def _configure(conn: sqlite3.Connection) -> None:
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
conn.execute("PRAGMA busy_timeout=5000")
conn.execute("PRAGMA foreign_keys=ON")
# Incremental auto-vacuum lets /api/admin/retention reclaim space without
# a full VACUUM rewrite. First-time switch from NONE only takes effect
# after a one-shot VACUUM, so a brand-new DB inherits it immediately.
conn.execute("PRAGMA auto_vacuum=INCREMENTAL")
def _new_connection() -> sqlite3.Connection:
conn = sqlite3.connect(str(DB_PATH), check_same_thread=False, timeout=30)
_configure(conn)
return conn
@contextmanager
def read_db():
"""Reuses a single sqlite3.Connection per OS thread (PRAGMAs are set once).
Connections older than ``_READ_CONN_TTL`` seconds are closed and recreated
to prevent stale WAL snapshots from accumulating indefinitely.
"""
conn = getattr(_read_local, 'conn', None)
conn_epoch = getattr(_read_local, 'conn_epoch', -1)
if (
conn is None
or conn_epoch != _READ_EPOCH
or (time.time() - getattr(_read_local, 'conn_time', 0)) > _READ_CONN_TTL
):
if conn is not None:
try:
conn.close()
except sqlite3.Error:
logger.debug("stale read connection close failed", exc_info=True)
conn = _new_connection()
_read_local.conn = conn
_read_local.conn_time = time.time()
_read_local.conn_epoch = _READ_EPOCH
try:
yield conn
except sqlite3.Error:
try:
conn.close()
except sqlite3.Error:
logger.debug("failed read connection close failed", exc_info=True)
_read_local.conn = None
_read_local.conn_epoch = -1
raise
@contextmanager
def write_db():
"""Single-writer context. Always opens a fresh connection to avoid
interleaving with any read connection cached on the same thread."""
global _READ_EPOCH
with _write_lock:
conn = _new_connection()
try:
conn.execute("BEGIN IMMEDIATE")
yield conn
conn.commit()
_READ_EPOCH += 1
except Exception:
conn.rollback()
raise
finally:
conn.close()
_CODEX_BOOTSTRAP_SCHEMA = '''
CREATE TABLE IF NOT EXISTS file_watch_state (
file_path TEXT PRIMARY KEY,
last_line INTEGER DEFAULT 0,
last_modified REAL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS plan_config (
id INTEGER PRIMARY KEY CHECK (id = 1),
daily_cost_limit REAL DEFAULT 50.0,
weekly_cost_limit REAL DEFAULT 300.0,
reset_hour INTEGER DEFAULT 0,
reset_weekday INTEGER DEFAULT 0,
timezone_offset INTEGER DEFAULT 9,
timezone_name TEXT DEFAULT 'Asia/Seoul'
);
INSERT OR IGNORE INTO plan_config (id) VALUES (1);
CREATE TABLE IF NOT EXISTS remote_nodes (
node_id TEXT PRIMARY KEY,
label TEXT,
ingest_key_hash TEXT NOT NULL,
last_seen TEXT,
session_count INTEGER DEFAULT 0,
message_count INTEGER DEFAULT 0,
created_at TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
);
CREATE TABLE IF NOT EXISTS admin_audit (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now')),
action TEXT NOT NULL,
actor_ip TEXT,
status TEXT NOT NULL DEFAULT 'ok',
detail TEXT
);
CREATE INDEX IF NOT EXISTS idx_admin_audit_ts
ON admin_audit(ts DESC);
CREATE TABLE IF NOT EXISTS app_config (
key TEXT PRIMARY KEY,
value TEXT NOT NULL,
updated_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
);
'''
# v15: Codex-native project/session/message store with message-first FTS.
_MIGRATE_V15_CODEX = '''
CREATE TABLE IF NOT EXISTS codex_projects (
project_path TEXT PRIMARY KEY,
project_name TEXT NOT NULL,
created_at TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now')),
updated_at TEXT DEFAULT (strftime('%Y-%m-%dT%H:%M:%SZ','now'))
);
CREATE TABLE IF NOT EXISTS codex_sessions (
id TEXT PRIMARY KEY,
project_path TEXT NOT NULL REFERENCES codex_projects(project_path) ON DELETE CASCADE,
session_name TEXT,
created_at TEXT,
updated_at TEXT,
model TEXT,
cwd TEXT,
source_node TEXT DEFAULT 'local',
pinned INTEGER DEFAULT 0,
final_stop_reason TEXT DEFAULT '',
tags TEXT DEFAULT '',
message_count INTEGER DEFAULT 0,
user_message_count INTEGER DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_codex_sessions_project_path ON codex_sessions(project_path);
CREATE INDEX IF NOT EXISTS idx_codex_sessions_updated_at ON codex_sessions(updated_at);
CREATE INDEX IF NOT EXISTS idx_codex_sessions_source_node ON codex_sessions(source_node);
CREATE TABLE IF NOT EXISTS codex_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL REFERENCES codex_sessions(id) ON DELETE CASCADE,
message_uuid TEXT UNIQUE,
parent_uuid TEXT,
role TEXT,
content TEXT,
content_preview TEXT,
timestamp TEXT,
model TEXT
);
CREATE INDEX IF NOT EXISTS idx_codex_messages_session_id ON codex_messages(session_id);
CREATE INDEX IF NOT EXISTS idx_codex_messages_timestamp ON codex_messages(timestamp);
CREATE VIRTUAL TABLE IF NOT EXISTS codex_messages_fts USING fts5(
content_preview,
content='codex_messages',
content_rowid='id',
tokenize='unicode61 remove_diacritics 0'
);
CREATE TRIGGER IF NOT EXISTS codex_messages_fts_ai AFTER INSERT ON codex_messages BEGIN
INSERT INTO codex_messages_fts(rowid, content_preview)
VALUES (new.id, COALESCE(new.content_preview, ''));
END;
CREATE TRIGGER IF NOT EXISTS codex_messages_fts_ad AFTER DELETE ON codex_messages BEGIN
INSERT INTO codex_messages_fts(codex_messages_fts, rowid, content_preview)
VALUES ('delete', old.id, COALESCE(old.content_preview, ''));
END;
CREATE TRIGGER IF NOT EXISTS codex_messages_fts_au AFTER UPDATE OF content_preview ON codex_messages BEGIN
INSERT INTO codex_messages_fts(codex_messages_fts, rowid, content_preview)
VALUES ('delete', old.id, COALESCE(old.content_preview, ''));
INSERT INTO codex_messages_fts(rowid, content_preview)
VALUES (new.id, COALESCE(new.content_preview, ''));
END;
'''
def _get_user_version(conn: sqlite3.Connection) -> int:
row = conn.execute("PRAGMA user_version").fetchone()
return int(row[0]) if row else 0
def _set_user_version(conn: sqlite3.Connection, v: int) -> None:
conn.execute(f"PRAGMA user_version = {int(v)}")
def _ensure_column(conn: sqlite3.Connection, table: str, col: str, decl: str) -> None:
cols = [r[1] for r in conn.execute(f"PRAGMA table_info({table})")]
if col not in cols:
logger.info("Adding column %s.%s", table, col)
conn.execute(f"ALTER TABLE {table} ADD COLUMN {col} {decl}")
def _backfill_codex_fts(conn: sqlite3.Connection) -> None:
total = conn.execute("SELECT COUNT(*) FROM codex_messages").fetchone()[0]
logger.info("Rebuilding Codex FTS index (%d rows) …", total)
conn.execute("INSERT INTO codex_messages_fts(codex_messages_fts) VALUES('rebuild')")
logger.info("Codex FTS rebuild complete")
def _ensure_codex_project(conn: sqlite3.Connection, project_path: str, project_name: str) -> None:
now = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
conn.execute(
'''
INSERT INTO codex_projects (project_path, project_name, created_at, updated_at)
VALUES (?, ?, ?, ?)
ON CONFLICT(project_path) DO UPDATE SET
project_name = excluded.project_name,
updated_at = excluded.updated_at
''',
(project_path, project_name, now, now),
)
def _ensure_codex_session(
conn: sqlite3.Connection,
session_id: str,
project_path: str,
session_name: str = '',
created_at: str = '',
updated_at: str = '',
cwd: str = '',
model: str | None = None,
source_node: str = 'local',
) -> None:
conn.execute(
'''
INSERT INTO codex_sessions
(id, project_path, session_name, created_at, updated_at, cwd, model, source_node)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET
project_path = excluded.project_path,
session_name = COALESCE(NULLIF(excluded.session_name, ''), codex_sessions.session_name),
created_at = COALESCE(NULLIF(excluded.created_at, ''), codex_sessions.created_at),
updated_at = COALESCE(NULLIF(excluded.updated_at, ''), codex_sessions.updated_at),
cwd = COALESCE(NULLIF(excluded.cwd, ''), codex_sessions.cwd),
model = COALESCE(NULLIF(excluded.model, ''), codex_sessions.model),
source_node = COALESCE(NULLIF(excluded.source_node, ''), codex_sessions.source_node, 'local')
''',
(session_id, project_path, session_name, created_at, updated_at, cwd, model or '', source_node or 'local'),
)
def store_codex_message(
*,
project_path: str,
project_name: str,
session_id: str,
session_name: str = '',
role: str,
content: str = '',
content_preview: str = '',
timestamp: str = '',
message_uuid: str | None = None,
parent_uuid: str = '',
model: str = '',
cwd: str = '',
source_node: str = 'local',
) -> int:
"""Persist a Codex message plus its project/session context."""
preview = content_preview or content[:240]
with write_db() as conn:
_ensure_codex_project(conn, project_path, project_name or Path(project_path).name or project_path)
_ensure_codex_session(
conn,
session_id,
project_path,
session_name,
timestamp,
timestamp,
cwd,
model,
source_node,
)
cur = conn.execute(
'''
INSERT OR IGNORE INTO codex_messages
(session_id, message_uuid, parent_uuid, role, content, content_preview, timestamp, model)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''',
(session_id, message_uuid, parent_uuid, role, content, preview, timestamp, model),
)
if cur.rowcount > 0:
conn.execute(
'''
UPDATE codex_sessions
SET message_count = COALESCE(message_count, 0) + 1,
user_message_count = COALESCE(user_message_count, 0) + ?
WHERE id = ?
''',
(1 if role == 'user' else 0, session_id),
)
return int(cur.lastrowid)
def search_codex_messages(
query: str,
limit: int = 20,
project: str = '',
role: str = '',
) -> list[sqlite3.Row]:
"""Search Codex messages joined with session/project context."""
if not query.strip():
return []
select_sql = '''
SELECT
m.id AS message_id,
m.session_id,
m.message_uuid,
m.parent_uuid,
m.role,
m.content AS body,
m.content_preview,
m.content_preview AS body_text,
m.timestamp AS created_at,
m.model,
s.session_name AS session_title,
s.created_at AS session_created_at,
s.updated_at AS session_updated_at,
p.project_path,
p.project_name
FROM codex_messages m
JOIN codex_sessions s ON s.id = m.session_id
JOIN codex_projects p ON p.project_path = s.project_path
'''
filters: list[str] = []
base_params: list[object] = []
if project:
filters.append('(p.project_name = ? OR p.project_path = ?)')
base_params.extend([project, project])
if role:
filters.append('m.role = ?')
base_params.append(role)
tokens = [t for t in _CODEX_FTS_TOKEN_RE.findall(query) if len(t) >= 2]
fts_query = ' '.join(f'"{token}"' for token in tokens)
def _like_search(conn: sqlite3.Connection) -> list[sqlite3.Row]:
like_sql = select_sql
like_filters = list(filters)
like_filters.append("(m.content_preview LIKE ? ESCAPE '\\' OR m.content LIKE ? ESCAPE '\\')")
like_sql += ' WHERE ' + ' AND '.join(like_filters)
like_sql += ' ORDER BY m.timestamp DESC, m.id DESC LIMIT ?'
like_value = f"%{_esc_like(query)}%"
params = [*base_params, like_value, like_value, limit]
return list(conn.execute(like_sql, params).fetchall())
with read_db() as conn:
if not fts_query:
return _like_search(conn)
sql = '''
SELECT
m.id AS message_id,
m.session_id,
m.message_uuid,
m.parent_uuid,
m.role,
m.content AS body,
m.content_preview,
m.content_preview AS body_text,
m.timestamp AS created_at,
m.model,
s.session_name AS session_title,
s.created_at AS session_created_at,
s.updated_at AS session_updated_at,
p.project_path,
p.project_name
FROM codex_messages_fts f
JOIN codex_messages m ON m.id = f.rowid
JOIN codex_sessions s ON s.id = m.session_id
JOIN codex_projects p ON p.project_path = s.project_path
WHERE codex_messages_fts MATCH ?
'''
params: list[object] = [fts_query, *base_params]
if filters:
sql += ' AND ' + ' AND '.join(filters)
sql += ' ORDER BY bm25(codex_messages_fts), m.timestamp DESC, m.id DESC LIMIT ?'
params.append(limit)
try:
return list(conn.execute(sql, params).fetchall())
except sqlite3.OperationalError:
return _like_search(conn)
def get_codex_message_context(message_id: int, window: int = 2) -> dict | None:
"""Return neighboring Codex messages around one message."""
with read_db() as conn:
current = conn.execute(
'''
SELECT id AS message_id, session_id, role,
content_preview AS body_text, timestamp AS created_at
FROM codex_messages
WHERE id = ?
''',
(message_id,),
).fetchone()
if not current:
return None
before = conn.execute(
'''
SELECT * FROM (
SELECT id AS message_id, session_id, role,
content_preview AS body_text, timestamp AS created_at
FROM codex_messages
WHERE session_id = ?
AND (timestamp < ? OR (timestamp = ? AND id < ?))
ORDER BY timestamp DESC, id DESC
LIMIT ?
)
ORDER BY created_at ASC, message_id ASC
''',
(
current['session_id'],
current['created_at'],
current['created_at'],
current['message_id'],
window,
),
).fetchall()
after = conn.execute(
'''
SELECT id AS message_id, session_id, role,
content_preview AS body_text, timestamp AS created_at
FROM codex_messages
WHERE session_id = ?
AND (timestamp > ? OR (timestamp = ? AND id > ?))
ORDER BY timestamp ASC, id ASC
LIMIT ?
''',
(
current['session_id'],
current['created_at'],
current['created_at'],
current['message_id'],
window,
),
).fetchall()
return {
'session_id': current['session_id'],
'current': dict(current),
'before': [dict(row) for row in before],
'after': [dict(row) for row in after],
}
def _decode_codex_payload(content: str) -> dict:
if not content:
return {}
try:
value = json.loads(content)
except (TypeError, ValueError):
return {}
return value if isinstance(value, dict) else {}
def get_codex_session_replay(session_id: str) -> dict | None:
"""Return ordered replay events for a Codex session."""
with read_db() as conn:
session = conn.execute(
'''
SELECT s.id AS session_id, s.session_name AS session_title,
s.created_at, s.updated_at, p.project_name, p.project_path
FROM codex_sessions s
JOIN codex_projects p ON p.project_path = s.project_path
WHERE s.id = ?
''',
(session_id,),
).fetchone()
if not session:
return None
rows = conn.execute(
'''
SELECT id AS message_id, role, content, content_preview, timestamp, model
FROM codex_messages
WHERE session_id = ?
ORDER BY timestamp ASC, message_id ASC
''',
(session_id,),
).fetchall()
events: list[dict] = []
for row in rows:
payload = _decode_codex_payload(row['content'])
event = {
'message_id': row['message_id'],
'timestamp': row['timestamp'],
'model': row['model'],
'payload': payload,
}
if row['role'] == 'tool':
event.update({
'kind': 'tool_call',
'tool_name': payload.get('name', ''),
'body_text': row['content_preview'],
})
elif row['role'] == 'agent':
event.update({
'kind': 'agent_run',
'agent_name': payload.get('agent_name', ''),
'status': payload.get('status', ''),
'body_text': row['content_preview'],
})
else:
event.update({
'kind': 'message',
'role': row['role'],
'body_text': row['content_preview'],
})
events.append(event)
payload = dict(session)
payload['events'] = events
return payload
def list_codex_sessions(limit: int = 50) -> dict:
"""Return recent Codex sessions suitable for replay launching."""
with read_db() as conn:
rows = conn.execute(
'''
SELECT s.id AS session_id,
s.session_name AS session_title,
p.project_name,
s.message_count,
s.user_message_count,
s.updated_at AS last_activity_at
FROM codex_sessions s
JOIN codex_projects p ON p.project_path = s.project_path
ORDER BY s.updated_at DESC, s.id DESC
LIMIT ?
''',
(limit,),
).fetchall()
total = conn.execute('SELECT COUNT(*) AS c FROM codex_sessions').fetchone()['c']
role_rows = conn.execute(
'''
SELECT session_id, role, COUNT(*) AS count
FROM codex_messages
GROUP BY session_id, role
'''
).fetchall()
role_counts: dict[str, dict[str, int]] = {}
for row in role_rows:
role_counts.setdefault(row['session_id'], {})[row['role']] = int(row['count'] or 0)
sessions = []
for row in rows:
session = dict(row)
session['message_count'] = int(session['message_count'] or 0)
session['user_message_count'] = int(session['user_message_count'] or 0)
session['role_counts'] = role_counts.get(session['session_id'], {})
session['replay_url'] = f"/api/sessions/{session['session_id']}/replay"
sessions.append(session)
return {'sessions': sessions, 'total': int(total or 0)}
def get_codex_timeline_summary(
limit: int = 200,
date_from: str | None = None,
date_to: str | None = None,
) -> dict:
"""Return recent Codex events in a compact timeline-friendly shape."""
where = ''
params: list[object] = []
if date_from:
where += ' AND m.timestamp >= ?'
params.append(date_from)
if date_to:
where += ' AND m.timestamp <= ?'
params.append(date_to if len(date_to) > 10 else date_to + 'T23:59:59Z')
with read_db() as conn:
rows = conn.execute(
f'''
SELECT m.id AS message_id,
m.session_id,
m.role,
m.content,
m.content_preview,
m.timestamp,
s.session_name,
p.project_name
FROM codex_messages m
JOIN codex_sessions s ON s.id = m.session_id
JOIN codex_projects p ON p.project_path = s.project_path
WHERE 1=1 {where}
ORDER BY m.timestamp DESC, m.id DESC
LIMIT ?
''',
(*params, limit),
).fetchall()
totals = conn.execute(
f'''
SELECT COUNT(*) AS total,
COUNT(DISTINCT session_id) AS sessions
FROM codex_messages
WHERE 1=1 {where.replace('m.timestamp', 'timestamp')}
''',
params,
).fetchone()
session_rows = conn.execute(
f'''
SELECT m.session_id,
s.session_name AS session_title,
p.project_name,
COUNT(*) AS event_count,
MAX(m.timestamp) AS last_activity_at
FROM codex_messages m
JOIN codex_sessions s ON s.id = m.session_id
JOIN codex_projects p ON p.project_path = s.project_path
WHERE 1=1 {where}
GROUP BY m.session_id, s.session_name, p.project_name
ORDER BY last_activity_at DESC, m.session_id DESC
LIMIT ?
''',
(*params, limit),
).fetchall()
items: list[dict] = []
for row in rows:
payload = _decode_codex_payload(row['content'])
label = row['role']
kind = 'message'
if row['role'] == 'tool':
kind = 'tool_call'
label = payload.get('name', '') or 'tool'
elif row['role'] == 'agent':
kind = 'agent_run'
label = payload.get('agent_name', '') or 'agent'
items.append({
'message_id': row['message_id'],
'session_id': row['session_id'],
'session_title': row['session_name'],
'project_name': row['project_name'],
'timestamp': row['timestamp'],
'kind': kind,
'label': label,
'body_text': row['content_preview'] or '',
})
return {
'items': items,
'total': int(totals['total'] or 0),
'sessions': int(totals['sessions'] or 0),
'session_summaries': [
{
'session_id': row['session_id'],
'session_title': row['session_title'],
'project_name': row['project_name'],
'event_count': int(row['event_count'] or 0),
'last_activity_at': row['last_activity_at'],
}
for row in session_rows
],
}
def get_codex_usage_summary() -> dict:
"""Return compact Codex usage totals for summary widgets."""
with read_db() as conn:
totals = conn.execute(
'''
SELECT COUNT(*) AS messages,
COUNT(DISTINCT m.session_id) AS sessions,
COUNT(DISTINCT s.project_path) AS projects,
MAX(m.timestamp) AS latest_activity_at
FROM codex_messages m
JOIN codex_sessions s ON s.id = m.session_id
'''
).fetchone()
by_role = conn.execute(
'''
SELECT role, COUNT(*) AS count
FROM codex_messages
GROUP BY role
ORDER BY role
'''
).fetchall()
top_sessions = conn.execute(
'''
SELECT s.id AS session_id,
s.session_name AS session_title,
p.project_name,
s.message_count,
s.updated_at AS last_activity_at
FROM codex_sessions s
JOIN codex_projects p ON p.project_path = s.project_path
ORDER BY s.message_count DESC, s.updated_at DESC, s.id DESC
LIMIT 10
'''
).fetchall()
return {
'sessions': int(totals['sessions'] or 0),
'messages': int(totals['messages'] or 0),
'projects': int(totals['projects'] or 0),
'latest_activity_at': totals['latest_activity_at'],
'by_role': {row['role']: int(row['count'] or 0) for row in by_role},
'top_sessions': [
{
'session_id': row['session_id'],
'session_title': row['session_title'],
'project_name': row['project_name'],
'message_count': int(row['message_count'] or 0),
'last_activity_at': row['last_activity_at'],
}
for row in top_sessions
],
}
_CODEX_SESSIONS_SORT_MAP = {
'updated_at': 's.updated_at',
'created_at': 's.created_at',
'messages': 's.message_count',
'project': 'p.project_name',
'model': 's.model',
}
def list_codex_sessions_table(
*,
page: int = 1,
per_page: int = 25,
search: str = '',
sort: str = 'updated_at',
order: str = 'desc',
) -> dict:
sort_col = _CODEX_SESSIONS_SORT_MAP.get(sort, 's.updated_at')
order_sql = 'ASC' if str(order).lower() == 'asc' else 'DESC'
offset = (page - 1) * per_page
where = ''
params: list[object] = []
if search:
where = '''
WHERE (
p.project_name LIKE ? ESCAPE '\\'
OR s.cwd LIKE ? ESCAPE '\\'
OR s.session_name LIKE ? ESCAPE '\\'
OR s.id LIKE ? ESCAPE '\\'
)
'''
term = f'%{search.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")}%'
params.extend([term, term, term, term])
with read_db() as conn:
total = conn.execute(
f'''
SELECT COUNT(*)
FROM codex_sessions s
JOIN codex_projects p ON p.project_path = s.project_path
{where}
''',
params,
).fetchone()[0]
rows = conn.execute(
f'''
SELECT
s.id,
p.project_name,
s.project_path,
COALESCE(s.cwd, s.project_path) AS cwd,
COALESCE(NULLIF(s.model, ''), '(unknown)') AS model,
s.created_at,
s.updated_at,
0 AS total_input_tokens,
0 AS total_output_tokens,
0 AS total_cache_creation_tokens,
0 AS total_cache_read_tokens,
0.0 AS total_cost_usd,
s.message_count,
s.user_message_count,
COALESCE(s.pinned, 0) AS pinned,
0 AS is_subagent,
NULL AS parent_session_id,
'' AS agent_type,
'' AS agent_description,
'' AS version,
COALESCE(NULLIF(s.final_stop_reason, ''), '') AS final_stop_reason,
COALESCE(NULLIF(s.tags, ''), '') AS tags,
0 AS turn_duration_ms,
COALESCE(NULLIF(s.source_node, ''), 'local') AS source_node,
(julianday(COALESCE(NULLIF(s.updated_at,''), s.created_at)) - julianday(s.created_at)) * 86400.0 AS duration_seconds,
0 AS subagent_count,
0.0 AS subagent_cost,
COALESCE(NULLIF(s.session_name, ''), s.id) AS session_title
FROM codex_sessions s
JOIN codex_projects p ON p.project_path = s.project_path
{where}
ORDER BY {sort_col} {order_sql}, s.id DESC
LIMIT ? OFFSET ?
''',
(*params, per_page, offset),
).fetchall()
return {
'sessions': [dict(r) for r in rows],
'total': int(total or 0),
'page': page,
'per_page': per_page,
'pages': max(1, -(-int(total or 0) // per_page)),
'sort': sort,
'order': order_sql.lower(),
}
def get_codex_session_detail_row(session_id: str) -> dict | None:
with read_db() as conn:
row = conn.execute(
'''
SELECT
s.id,
p.project_name,
s.project_path,
COALESCE(s.cwd, s.project_path) AS cwd,
COALESCE(NULLIF(s.model, ''), '(unknown)') AS model,
s.created_at,
s.updated_at,
0 AS total_input_tokens,
0 AS total_output_tokens,
0 AS total_cache_creation_tokens,
0 AS total_cache_read_tokens,
0.0 AS total_cost_usd,
s.message_count,
s.user_message_count,
COALESCE(s.pinned, 0) AS pinned,
0 AS is_subagent,
NULL AS parent_session_id,
'' AS agent_type,
'' AS agent_description,
'' AS version,
COALESCE(NULLIF(s.final_stop_reason, ''), '') AS final_stop_reason,
COALESCE(NULLIF(s.tags, ''), '') AS tags,
0 AS turn_duration_ms,
COALESCE(NULLIF(s.source_node, ''), 'local') AS source_node,
(julianday(COALESCE(NULLIF(s.updated_at,''), s.created_at)) - julianday(s.created_at)) * 86400.0 AS duration_seconds,
0 AS subagent_count,
0.0 AS subagent_cost,
COALESCE(NULLIF(s.session_name, ''), s.id) AS session_title
FROM codex_sessions s
JOIN codex_projects p ON p.project_path = s.project_path
WHERE s.id = ?
''',
(session_id,),
).fetchone()
return dict(row) if row else None
def get_codex_session_messages_page(session_id: str, limit: int = 500, offset: int = 0) -> dict:
with read_db() as conn:
rows = conn.execute(
'''
SELECT
id,
message_uuid,
parent_uuid,
role,
content_preview,
content,
0 AS input_tokens,
0 AS output_tokens,
0 AS cache_creation_tokens,
0 AS cache_read_tokens,
0.0 AS cost_usd,
COALESCE(NULLIF(model, ''), '(unknown)') AS model,
timestamp,
'' AS git_branch,
0 AS is_sidechain,
'' AS stop_reason
FROM codex_messages
WHERE session_id = ?
ORDER BY timestamp ASC, id ASC
LIMIT ? OFFSET ?
''',
(session_id, limit, offset),
).fetchall()
total = conn.execute(
'SELECT COUNT(*) FROM codex_messages WHERE session_id = ?',
(session_id,),
).fetchone()[0]
return {'messages': [dict(r) for r in rows], 'total': int(total or 0), 'limit': limit, 'offset': offset}
def get_codex_message_position(session_id: str, message_id: int) -> dict | None:
with read_db() as conn:
current = conn.execute(
'''
SELECT id, timestamp
FROM codex_messages
WHERE id = ? AND session_id = ?
''',
(message_id, session_id),
).fetchone()
if not current:
return None
pos = conn.execute(
'''
SELECT COUNT(*)
FROM codex_messages
WHERE session_id = ?
AND (timestamp < ? OR (timestamp = ? AND id < ?))
''',
(session_id, current['timestamp'], current['timestamp'], current['id']),
).fetchone()[0]
total = conn.execute(
'SELECT COUNT(*) FROM codex_messages WHERE session_id = ?',
(session_id,),
).fetchone()[0]
return {'position': int(pos or 0), 'total': int(total or 0), 'message_id': message_id}
def get_codex_session_delete_preview(session_id: str) -> dict | None:
with read_db() as conn:
row = conn.execute(
'''
SELECT
s.id AS session_id,
p.project_name,
s.message_count
FROM codex_sessions s
JOIN codex_projects p ON p.project_path = s.project_path
WHERE s.id = ?
''',
(session_id,),
).fetchone()
return dict(row) if row else None
def delete_codex_session(session_id: str) -> dict:
with write_db() as conn:
preview = conn.execute(
'SELECT COUNT(*) AS messages_deleted FROM codex_messages WHERE session_id = ?',
(session_id,),
).fetchone()
deleted = conn.execute(
'DELETE FROM codex_sessions WHERE id = ?',
(session_id,),
).rowcount
close_thread_connections()
return {