agent-chat-reader 0.1.0__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.
- agent_chat_reader/__init__.py +7 -0
- agent_chat_reader/claude.py +167 -0
- agent_chat_reader/cli.py +183 -0
- agent_chat_reader/codex.py +151 -0
- agent_chat_reader/models.py +25 -0
- agent_chat_reader/output.py +69 -0
- agent_chat_reader/py.typed +0 -0
- agent_chat_reader-0.1.0.dist-info/METADATA +109 -0
- agent_chat_reader-0.1.0.dist-info/RECORD +12 -0
- agent_chat_reader-0.1.0.dist-info/WHEEL +4 -0
- agent_chat_reader-0.1.0.dist-info/entry_points.txt +2 -0
- agent_chat_reader-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""Claude Code session reader."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from agent_chat_reader.models import SessionMeta, Turn
|
|
9
|
+
|
|
10
|
+
CLAUDE_PROJECTS = Path.home() / ".claude" / "projects"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _decode_project_path(dirname: str) -> str:
|
|
14
|
+
"""Decode '-home-ali' -> '/home/ali'."""
|
|
15
|
+
return dirname.replace("-", "/")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _session_title(path: Path) -> str:
|
|
19
|
+
"""Return the last ai-title from a Claude session file."""
|
|
20
|
+
last_title = ""
|
|
21
|
+
with path.open() as fh:
|
|
22
|
+
for raw in fh:
|
|
23
|
+
try:
|
|
24
|
+
rec = json.loads(raw.strip())
|
|
25
|
+
if rec.get("type") == "ai-title":
|
|
26
|
+
t = rec.get("aiTitle", "").strip()
|
|
27
|
+
if t:
|
|
28
|
+
last_title = t
|
|
29
|
+
except Exception:
|
|
30
|
+
pass
|
|
31
|
+
return last_title
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _extract_user_text(content: str | list) -> str | None: # type: ignore[type-arg]
|
|
35
|
+
"""Extract real user text; return None for tool-result carriers."""
|
|
36
|
+
if isinstance(content, str):
|
|
37
|
+
return content.strip() or None
|
|
38
|
+
if isinstance(content, list):
|
|
39
|
+
has_tool_result = any(
|
|
40
|
+
b.get("type") == "tool_result" for b in content if isinstance(b, dict)
|
|
41
|
+
)
|
|
42
|
+
if has_tool_result:
|
|
43
|
+
return None
|
|
44
|
+
text = " ".join(
|
|
45
|
+
b.get("text", "")
|
|
46
|
+
for b in content
|
|
47
|
+
if isinstance(b, dict) and b.get("type") == "text"
|
|
48
|
+
).strip()
|
|
49
|
+
return text or None
|
|
50
|
+
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def list_sessions() -> list[SessionMeta]:
|
|
54
|
+
"""List all Claude Code sessions, sorted by most recent first."""
|
|
55
|
+
if not CLAUDE_PROJECTS.exists():
|
|
56
|
+
return []
|
|
57
|
+
results = []
|
|
58
|
+
for proj_dir in CLAUDE_PROJECTS.iterdir():
|
|
59
|
+
if not proj_dir.is_dir():
|
|
60
|
+
continue
|
|
61
|
+
for f in proj_dir.glob("*.jsonl"):
|
|
62
|
+
stat = f.stat()
|
|
63
|
+
results.append(
|
|
64
|
+
SessionMeta(
|
|
65
|
+
source="claude",
|
|
66
|
+
id=f.stem,
|
|
67
|
+
path=f,
|
|
68
|
+
mtime=stat.st_mtime,
|
|
69
|
+
size_kb=stat.st_size // 1024,
|
|
70
|
+
title=_session_title(f) or "(untitled)",
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
return sorted(results, key=lambda s: s.mtime, reverse=True)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def read_turns(
|
|
77
|
+
path: Path,
|
|
78
|
+
*,
|
|
79
|
+
verbose: bool = False,
|
|
80
|
+
include_subagents: bool = False,
|
|
81
|
+
tail: int | None = None,
|
|
82
|
+
) -> list[Turn]:
|
|
83
|
+
"""Read conversation turns from a Claude Code session file.
|
|
84
|
+
|
|
85
|
+
Args:
|
|
86
|
+
path: Path to the session JSONL file.
|
|
87
|
+
verbose: If True, append brief tool call summaries to assistant turns.
|
|
88
|
+
include_subagents: If True, include sidechain (sub-agent) turns.
|
|
89
|
+
tail: If set, return only turns from the last N user messages onward.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
List of Turn namedtuples in conversation order.
|
|
93
|
+
"""
|
|
94
|
+
turns: list[Turn] = []
|
|
95
|
+
|
|
96
|
+
with path.open() as fh:
|
|
97
|
+
for raw in fh:
|
|
98
|
+
stripped = raw.strip()
|
|
99
|
+
if not stripped:
|
|
100
|
+
continue
|
|
101
|
+
try:
|
|
102
|
+
rec = json.loads(stripped)
|
|
103
|
+
t = rec.get("type", "")
|
|
104
|
+
is_sidechain = rec.get("isSidechain", False)
|
|
105
|
+
ts: str = rec.get("timestamp", "")
|
|
106
|
+
|
|
107
|
+
if not include_subagents and is_sidechain:
|
|
108
|
+
continue
|
|
109
|
+
|
|
110
|
+
if t == "user":
|
|
111
|
+
content = rec.get("message", {}).get("content", "")
|
|
112
|
+
text = _extract_user_text(content)
|
|
113
|
+
if text:
|
|
114
|
+
turns.append(Turn("USER", text, ts))
|
|
115
|
+
|
|
116
|
+
elif t == "assistant":
|
|
117
|
+
blocks = rec.get("message", {}).get("content", [])
|
|
118
|
+
if not isinstance(blocks, list):
|
|
119
|
+
continue
|
|
120
|
+
text_parts = []
|
|
121
|
+
tool_parts = []
|
|
122
|
+
for block in blocks:
|
|
123
|
+
if not isinstance(block, dict):
|
|
124
|
+
continue
|
|
125
|
+
btype = block.get("type", "")
|
|
126
|
+
if btype == "text":
|
|
127
|
+
t_text = block.get("text", "").strip()
|
|
128
|
+
if t_text:
|
|
129
|
+
text_parts.append(t_text)
|
|
130
|
+
elif btype == "tool_use" and verbose:
|
|
131
|
+
tool_parts.append(_format_tool_call(block))
|
|
132
|
+
|
|
133
|
+
full_text = "\n".join(text_parts).strip()
|
|
134
|
+
if tool_parts and verbose:
|
|
135
|
+
full_text = (full_text + "\n" + " ".join(tool_parts)).strip()
|
|
136
|
+
if full_text:
|
|
137
|
+
turns.append(Turn("CLAUDE", full_text, ts))
|
|
138
|
+
|
|
139
|
+
except Exception:
|
|
140
|
+
pass
|
|
141
|
+
|
|
142
|
+
return _apply_tail(turns, tail)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _format_tool_call(block: dict) -> str: # type: ignore[type-arg]
|
|
146
|
+
"""Format a tool_use block as a short bracketed summary."""
|
|
147
|
+
name = block.get("name", "?")
|
|
148
|
+
inp = block.get("input", {})
|
|
149
|
+
if name == "Bash":
|
|
150
|
+
desc = inp.get("description", inp.get("command", ""))[:60]
|
|
151
|
+
elif name in ("Read", "Edit", "Write"):
|
|
152
|
+
desc = str(inp.get("file_path", ""))
|
|
153
|
+
elif name == "Agent":
|
|
154
|
+
desc = str(inp.get("description", ""))[:60]
|
|
155
|
+
else:
|
|
156
|
+
desc = str(next(iter(inp.values()), ""))[:60]
|
|
157
|
+
return f"[{name}: {desc}]"
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _apply_tail(turns: list[Turn], tail: int | None) -> list[Turn]:
|
|
161
|
+
"""Trim to the last N user-message turns and everything after."""
|
|
162
|
+
if tail is None:
|
|
163
|
+
return turns
|
|
164
|
+
user_indices = [i for i, t in enumerate(turns) if t.role == "USER"]
|
|
165
|
+
if tail >= len(user_indices):
|
|
166
|
+
return turns
|
|
167
|
+
return turns[user_indices[-tail]:]
|
agent_chat_reader/cli.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Command-line entry point for agent-chat-reader."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from agent_chat_reader import __version__, claude, codex
|
|
10
|
+
from agent_chat_reader.models import SessionMeta
|
|
11
|
+
from agent_chat_reader.output import print_find_result, print_session_list, print_turn
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _find_session(session_id: str) -> tuple[Path, str] | None:
|
|
15
|
+
"""Locate a session file by ID fragment, returning (path, source)."""
|
|
16
|
+
p = Path(session_id)
|
|
17
|
+
if p.exists():
|
|
18
|
+
source = "codex" if ".codex" in str(p) else "claude"
|
|
19
|
+
return p, source
|
|
20
|
+
|
|
21
|
+
codex_matches = list(codex.CODEX_SESSIONS.rglob(f"*{session_id}*.jsonl"))
|
|
22
|
+
if codex_matches:
|
|
23
|
+
return sorted(codex_matches)[-1], "codex"
|
|
24
|
+
|
|
25
|
+
claude_matches = list(claude.CLAUDE_PROJECTS.rglob(f"*{session_id}*.jsonl"))
|
|
26
|
+
if claude_matches:
|
|
27
|
+
return sorted(claude_matches)[-1], "claude"
|
|
28
|
+
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def cmd_list(
|
|
33
|
+
*,
|
|
34
|
+
source_filter: str | None,
|
|
35
|
+
include_subagents: bool,
|
|
36
|
+
limit: int,
|
|
37
|
+
) -> int:
|
|
38
|
+
"""List recent sessions from both sources."""
|
|
39
|
+
sessions: list[SessionMeta] = []
|
|
40
|
+
if source_filter != "claude":
|
|
41
|
+
sessions += codex.list_sessions(include_subagents=include_subagents)
|
|
42
|
+
if source_filter != "codex":
|
|
43
|
+
sessions += claude.list_sessions()
|
|
44
|
+
|
|
45
|
+
sessions = sorted(sessions, key=lambda s: s.mtime, reverse=True)[:limit]
|
|
46
|
+
print_session_list(sessions)
|
|
47
|
+
return 0
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def cmd_find(
|
|
51
|
+
keyword: str,
|
|
52
|
+
*,
|
|
53
|
+
source_filter: str | None,
|
|
54
|
+
include_subagents: bool,
|
|
55
|
+
) -> int:
|
|
56
|
+
"""Search sessions for a keyword."""
|
|
57
|
+
sessions: list[SessionMeta] = []
|
|
58
|
+
if source_filter != "claude":
|
|
59
|
+
sessions += codex.list_sessions(include_subagents=include_subagents)
|
|
60
|
+
if source_filter != "codex":
|
|
61
|
+
sessions += claude.list_sessions()
|
|
62
|
+
|
|
63
|
+
sessions = sorted(sessions, key=lambda s: s.mtime, reverse=True)
|
|
64
|
+
keyword_lower = keyword.lower()
|
|
65
|
+
found_any = False
|
|
66
|
+
|
|
67
|
+
for s in sessions:
|
|
68
|
+
try:
|
|
69
|
+
if s.source == "codex":
|
|
70
|
+
turns = codex.read_turns(s.path)
|
|
71
|
+
else:
|
|
72
|
+
turns = claude.read_turns(s.path)
|
|
73
|
+
except Exception:
|
|
74
|
+
continue
|
|
75
|
+
|
|
76
|
+
hits = [
|
|
77
|
+
(t.role, t.text[:120].replace("\n", " "))
|
|
78
|
+
for t in turns
|
|
79
|
+
if keyword_lower in t.text.lower()
|
|
80
|
+
]
|
|
81
|
+
if hits:
|
|
82
|
+
found_any = True
|
|
83
|
+
print_find_result(s, hits)
|
|
84
|
+
|
|
85
|
+
if not found_any:
|
|
86
|
+
print(f"No sessions found containing {keyword!r}")
|
|
87
|
+
return 0
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def cmd_read(
|
|
91
|
+
session_id: str,
|
|
92
|
+
*,
|
|
93
|
+
verbose: bool,
|
|
94
|
+
include_subagents: bool,
|
|
95
|
+
tail: int | None,
|
|
96
|
+
) -> int:
|
|
97
|
+
"""Read a specific session as clean conversation."""
|
|
98
|
+
result = _find_session(session_id)
|
|
99
|
+
if result is None:
|
|
100
|
+
print(f"Session not found: {session_id}", file=sys.stderr)
|
|
101
|
+
return 1
|
|
102
|
+
|
|
103
|
+
path, source = result
|
|
104
|
+
size_kb = path.stat().st_size // 1024
|
|
105
|
+
print(f"Source: {source.upper()} | {path.name} | {size_kb}KB")
|
|
106
|
+
|
|
107
|
+
if source == "codex":
|
|
108
|
+
turns = codex.read_turns(path, tail=tail)
|
|
109
|
+
else:
|
|
110
|
+
turns = claude.read_turns(
|
|
111
|
+
path, verbose=verbose, include_subagents=include_subagents, tail=tail
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
if not turns:
|
|
115
|
+
print("(no conversation turns found)")
|
|
116
|
+
return 0
|
|
117
|
+
|
|
118
|
+
for turn in turns:
|
|
119
|
+
print_turn(turn)
|
|
120
|
+
|
|
121
|
+
print(f"\n{'─'*60}")
|
|
122
|
+
print(f"Total turns: {len(turns)}")
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main(argv: list[str] | None = None) -> int:
|
|
127
|
+
"""Run the agent-chat-reader command-line interface."""
|
|
128
|
+
p = argparse.ArgumentParser(
|
|
129
|
+
prog="agent-chat-reader",
|
|
130
|
+
description="Read and search Codex CLI and Claude Code chat history.",
|
|
131
|
+
)
|
|
132
|
+
p.add_argument(
|
|
133
|
+
"--version", action="version", version=f"agent-chat-reader {__version__}",
|
|
134
|
+
)
|
|
135
|
+
p.add_argument("session", nargs="?", help="Session ID or file path to read")
|
|
136
|
+
p.add_argument("--list", "-l", action="store_true", help="List recent sessions")
|
|
137
|
+
p.add_argument(
|
|
138
|
+
"--find", "-f", metavar="KEYWORD", help="Search sessions for keyword",
|
|
139
|
+
)
|
|
140
|
+
p.add_argument("--source", choices=["codex", "claude"], help="Filter to one source")
|
|
141
|
+
p.add_argument(
|
|
142
|
+
"--verbose", "-v", action="store_true",
|
|
143
|
+
help="Include tool call summaries (Claude sessions)",
|
|
144
|
+
)
|
|
145
|
+
p.add_argument(
|
|
146
|
+
"--tail", "-n", type=int, metavar="N", help="Show only the last N user turns",
|
|
147
|
+
)
|
|
148
|
+
p.add_argument(
|
|
149
|
+
"--include-subagents", action="store_true",
|
|
150
|
+
help="Include guardian/subagent sessions",
|
|
151
|
+
)
|
|
152
|
+
p.add_argument(
|
|
153
|
+
"--limit", type=int, default=40, help="Max sessions for --list (default: 40)",
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
args = p.parse_args(argv)
|
|
157
|
+
|
|
158
|
+
if args.list:
|
|
159
|
+
return cmd_list(
|
|
160
|
+
source_filter=args.source,
|
|
161
|
+
include_subagents=args.include_subagents,
|
|
162
|
+
limit=args.limit,
|
|
163
|
+
)
|
|
164
|
+
if args.find:
|
|
165
|
+
return cmd_find(
|
|
166
|
+
args.find,
|
|
167
|
+
source_filter=args.source,
|
|
168
|
+
include_subagents=args.include_subagents,
|
|
169
|
+
)
|
|
170
|
+
if args.session:
|
|
171
|
+
return cmd_read(
|
|
172
|
+
args.session,
|
|
173
|
+
verbose=args.verbose,
|
|
174
|
+
include_subagents=args.include_subagents,
|
|
175
|
+
tail=args.tail,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
p.print_help()
|
|
179
|
+
return 0
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if __name__ == "__main__":
|
|
183
|
+
sys.exit(main())
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Codex CLI session reader."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from agent_chat_reader.models import SessionMeta, Turn
|
|
9
|
+
|
|
10
|
+
CODEX_SESSIONS = Path.home() / ".codex" / "sessions"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def is_subagent(path: Path) -> bool:
|
|
14
|
+
"""Return True if this Codex session is a guardian/subagent session."""
|
|
15
|
+
with path.open() as fh:
|
|
16
|
+
for raw in fh:
|
|
17
|
+
try:
|
|
18
|
+
rec = json.loads(raw.strip())
|
|
19
|
+
if rec.get("type") == "session_meta":
|
|
20
|
+
payload = rec.get("payload", {})
|
|
21
|
+
if payload.get("thread_source") == "subagent":
|
|
22
|
+
return True
|
|
23
|
+
source = payload.get("source", {})
|
|
24
|
+
return isinstance(source, dict) and "subagent" in source
|
|
25
|
+
except Exception:
|
|
26
|
+
pass
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _first_user_message(path: Path) -> str:
|
|
31
|
+
"""Return the first user message text, truncated to 80 chars."""
|
|
32
|
+
with path.open() as fh:
|
|
33
|
+
for raw in fh:
|
|
34
|
+
try:
|
|
35
|
+
rec = json.loads(raw.strip())
|
|
36
|
+
if (
|
|
37
|
+
rec.get("type") == "event_msg"
|
|
38
|
+
and rec.get("payload", {}).get("type") == "user_message"
|
|
39
|
+
):
|
|
40
|
+
return rec["payload"].get("message", "").replace("\n", " ")[:80]
|
|
41
|
+
except Exception:
|
|
42
|
+
pass
|
|
43
|
+
return ""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _session_id_from_path(path: Path) -> str:
|
|
47
|
+
"""Extract the UUID from a rollout filename."""
|
|
48
|
+
name = path.stem.replace("rollout-", "")
|
|
49
|
+
parts = name.split("-")
|
|
50
|
+
# UUID is the last 5 hyphen-groups (8-4-4-4-12)
|
|
51
|
+
return "-".join(parts[-5:]) if len(parts) >= 5 else name
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def list_sessions(*, include_subagents: bool = False) -> list[SessionMeta]:
|
|
55
|
+
"""List all Codex sessions, sorted by most recent first."""
|
|
56
|
+
if not CODEX_SESSIONS.exists():
|
|
57
|
+
return []
|
|
58
|
+
files = sorted(
|
|
59
|
+
CODEX_SESSIONS.rglob("*.jsonl"),
|
|
60
|
+
key=lambda f: f.stat().st_mtime,
|
|
61
|
+
reverse=True,
|
|
62
|
+
)
|
|
63
|
+
results = []
|
|
64
|
+
for f in files:
|
|
65
|
+
if not include_subagents and is_subagent(f):
|
|
66
|
+
continue
|
|
67
|
+
stat = f.stat()
|
|
68
|
+
results.append(
|
|
69
|
+
SessionMeta(
|
|
70
|
+
source="codex",
|
|
71
|
+
id=_session_id_from_path(f),
|
|
72
|
+
path=f,
|
|
73
|
+
mtime=stat.st_mtime,
|
|
74
|
+
size_kb=stat.st_size // 1024,
|
|
75
|
+
title=_first_user_message(f),
|
|
76
|
+
)
|
|
77
|
+
)
|
|
78
|
+
return results
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def read_turns(path: Path, *, tail: int | None = None) -> list[Turn]:
|
|
82
|
+
"""Read conversation turns from a Codex session file.
|
|
83
|
+
|
|
84
|
+
Extracts user messages, agent commentary (event_msg/agent_message), and
|
|
85
|
+
full assistant responses (response_item). Adjacent duplicate text between
|
|
86
|
+
agent_message and response_item records is deduplicated.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
path: Path to the session JSONL file.
|
|
90
|
+
tail: If set, return only turns from the last N user messages onward.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
List of Turn namedtuples in conversation order.
|
|
94
|
+
"""
|
|
95
|
+
turns: list[Turn] = []
|
|
96
|
+
last_assistant_text: str | None = None
|
|
97
|
+
|
|
98
|
+
with path.open() as fh:
|
|
99
|
+
for raw in fh:
|
|
100
|
+
stripped = raw.strip()
|
|
101
|
+
if not stripped:
|
|
102
|
+
continue
|
|
103
|
+
try:
|
|
104
|
+
rec = json.loads(stripped)
|
|
105
|
+
t = rec.get("type", "")
|
|
106
|
+
pt = rec.get("payload", {}).get("type", "")
|
|
107
|
+
ts: str = rec.get("timestamp", "")
|
|
108
|
+
|
|
109
|
+
if t == "event_msg" and pt == "user_message":
|
|
110
|
+
msg = rec["payload"].get("message", "").strip()
|
|
111
|
+
if msg:
|
|
112
|
+
turns.append(Turn("USER", msg, ts))
|
|
113
|
+
last_assistant_text = None
|
|
114
|
+
|
|
115
|
+
elif t == "event_msg" and pt == "agent_message":
|
|
116
|
+
msg = rec["payload"].get("message", "").strip()
|
|
117
|
+
if msg and msg != last_assistant_text:
|
|
118
|
+
turns.append(Turn("AGENT", msg, ts))
|
|
119
|
+
last_assistant_text = msg
|
|
120
|
+
|
|
121
|
+
elif t == "response_item":
|
|
122
|
+
role = rec.get("payload", {}).get("role", "")
|
|
123
|
+
if role == "assistant":
|
|
124
|
+
content = rec.get("payload", {}).get("content", [])
|
|
125
|
+
text = ""
|
|
126
|
+
if isinstance(content, str):
|
|
127
|
+
text = content.strip()
|
|
128
|
+
elif isinstance(content, list):
|
|
129
|
+
text = "\n".join(
|
|
130
|
+
b.get("text", "")
|
|
131
|
+
for b in content
|
|
132
|
+
if isinstance(b, dict) and b.get("type") == "text"
|
|
133
|
+
).strip()
|
|
134
|
+
if text and text != last_assistant_text:
|
|
135
|
+
turns.append(Turn("AGENT", text, ts))
|
|
136
|
+
last_assistant_text = text
|
|
137
|
+
|
|
138
|
+
except Exception:
|
|
139
|
+
pass
|
|
140
|
+
|
|
141
|
+
return _apply_tail(turns, tail)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _apply_tail(turns: list[Turn], tail: int | None) -> list[Turn]:
|
|
145
|
+
"""Trim to the last N user-message turns and everything after."""
|
|
146
|
+
if tail is None:
|
|
147
|
+
return turns
|
|
148
|
+
user_indices = [i for i, t in enumerate(turns) if t.role == "USER"]
|
|
149
|
+
if tail >= len(user_indices):
|
|
150
|
+
return turns
|
|
151
|
+
return turns[user_indices[-tail]:]
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Shared data models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import NamedTuple
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Turn(NamedTuple):
|
|
10
|
+
"""A single conversation turn."""
|
|
11
|
+
|
|
12
|
+
role: str # "USER" | "AGENT" | "CLAUDE"
|
|
13
|
+
text: str
|
|
14
|
+
timestamp: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class SessionMeta(NamedTuple):
|
|
18
|
+
"""Metadata for a single chat session."""
|
|
19
|
+
|
|
20
|
+
source: str # "codex" | "claude"
|
|
21
|
+
id: str
|
|
22
|
+
path: Path
|
|
23
|
+
mtime: float
|
|
24
|
+
size_kb: int
|
|
25
|
+
title: str
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Output formatting helpers."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import textwrap
|
|
6
|
+
from datetime import datetime
|
|
7
|
+
|
|
8
|
+
from agent_chat_reader.models import SessionMeta, Turn
|
|
9
|
+
|
|
10
|
+
_MAX_TURN_LEN = 3000
|
|
11
|
+
_WRAP_THRESHOLD = 400
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def fmt_ts(ts_str: str) -> str:
|
|
15
|
+
"""Format an ISO timestamp to a short local time string."""
|
|
16
|
+
if not ts_str:
|
|
17
|
+
return ""
|
|
18
|
+
try:
|
|
19
|
+
dt = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
|
|
20
|
+
return dt.astimezone().strftime("%Y-%m-%d %H:%M")
|
|
21
|
+
except ValueError:
|
|
22
|
+
return ts_str[:16]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def fmt_mtime(mtime: float) -> str:
|
|
26
|
+
"""Format a Unix mtime float to a short local time string."""
|
|
27
|
+
return datetime.fromtimestamp(mtime).strftime("%Y-%m-%d %H:%M") # noqa: DTZ006
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def print_turn(turn: Turn) -> None:
|
|
31
|
+
"""Print a single conversation turn with a header rule."""
|
|
32
|
+
ts_str = f" {fmt_ts(turn.timestamp)}" if turn.timestamp else ""
|
|
33
|
+
print(f"\n{'─'*60}")
|
|
34
|
+
print(f"[{turn.role}]{ts_str}")
|
|
35
|
+
print("─" * 60)
|
|
36
|
+
text = turn.text
|
|
37
|
+
if len(text) <= _WRAP_THRESHOLD:
|
|
38
|
+
print(textwrap.fill(text, width=100))
|
|
39
|
+
else:
|
|
40
|
+
print(text[:_MAX_TURN_LEN] + ("…" if len(text) > _MAX_TURN_LEN else ""))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def print_session_list(sessions: list[SessionMeta]) -> None:
|
|
44
|
+
"""Print a formatted table of sessions."""
|
|
45
|
+
print(f"{'SRC':<6} {'DATE':<16} {'SIZE':>7} {'ID':<36} TITLE")
|
|
46
|
+
print("─" * 100)
|
|
47
|
+
for s in sessions:
|
|
48
|
+
src = s.source
|
|
49
|
+
date = fmt_mtime(s.mtime)
|
|
50
|
+
size = f"{s.size_kb}KB"
|
|
51
|
+
title = (s.title or "(no title)")[:55]
|
|
52
|
+
print(f"{src:<6} {date:<16} {size:>7} {s.id:<36} {title}")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def print_find_result(
|
|
56
|
+
session: SessionMeta,
|
|
57
|
+
hits: list[tuple[str, str]],
|
|
58
|
+
*,
|
|
59
|
+
max_hits: int = 4,
|
|
60
|
+
) -> None:
|
|
61
|
+
"""Print a single session's find results."""
|
|
62
|
+
print(f"\n{'='*70}")
|
|
63
|
+
print(f"[{session.source.upper()}] {session.id} {fmt_mtime(session.mtime)}")
|
|
64
|
+
if session.title:
|
|
65
|
+
print(f' "{session.title[:60]}"')
|
|
66
|
+
for role, snippet in hits[:max_hits]:
|
|
67
|
+
print(f" [{role}] {snippet!r}")
|
|
68
|
+
if len(hits) > max_hits:
|
|
69
|
+
print(f" ... and {len(hits) - max_hits} more matches")
|
|
File without changes
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agent-chat-reader
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read and search Codex CLI and Claude Code chat history from the terminal.
|
|
5
|
+
Project-URL: Homepage, https://github.com/alik-git/agent-chat-reader
|
|
6
|
+
Project-URL: Repository, https://github.com/alik-git/agent-chat-reader
|
|
7
|
+
Project-URL: Issues, https://github.com/alik-git/agent-chat-reader/issues
|
|
8
|
+
Author-email: Ali K <alikgithb@gmail.com>
|
|
9
|
+
Maintainer-email: Ali K <alikgithb@gmail.com>
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: ai-agents,chat-history,claude,cli,codex,developer-tools
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Environment :: Console
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.11
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
23
|
+
Requires-Dist: mypy>=1.15; extra == 'dev'
|
|
24
|
+
Requires-Dist: pre-commit>=4.0; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff>=0.11; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# agent-chat-reader
|
|
30
|
+
|
|
31
|
+
Read and search [Codex CLI](https://github.com/openai/codex) and [Claude Code](https://claude.ai/code) chat history from the terminal.
|
|
32
|
+
|
|
33
|
+
Useful for AI agents that need to recall what was discussed or decided in past sessions, without manually parsing noisy JSONL files.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
uv tool install agent-chat-reader
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Or for development:
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
git clone https://github.com/alik-git/agent-chat-reader
|
|
45
|
+
cd agent-chat-reader
|
|
46
|
+
uv sync --extra dev
|
|
47
|
+
uv run agent-chat-reader --help
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Usage
|
|
51
|
+
|
|
52
|
+
**List recent sessions** (both Codex and Claude Code, sorted by recency):
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
agent-chat-reader --list
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
**Search across all sessions** for a keyword:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
agent-chat-reader --find "sim2sim"
|
|
62
|
+
agent-chat-reader --find "policy_interface" --source codex
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
**Read a specific session** by UUID prefix:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
agent-chat-reader 019eaecb
|
|
69
|
+
agent-chat-reader 1bfc739b --verbose # include tool call summaries
|
|
70
|
+
agent-chat-reader 019eaecb --tail 5 # last 5 user turns only
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## What it filters out
|
|
74
|
+
|
|
75
|
+
The raw JSONL files are very noisy. This tool extracts only:
|
|
76
|
+
|
|
77
|
+
- **Codex**: `user_message` events, `agent_message` events, and full `response_item` assistant text. Guardian/subagent sessions (auto-approval bots) are hidden by default.
|
|
78
|
+
- **Claude Code**: real user turns (not tool-result carriers), and assistant text blocks (not thinking blocks or tool calls). Sidechain sub-agent turns are hidden by default.
|
|
79
|
+
|
|
80
|
+
Use `--include-subagents` to see everything.
|
|
81
|
+
|
|
82
|
+
## Options
|
|
83
|
+
|
|
84
|
+
| Flag | Description |
|
|
85
|
+
|------|-------------|
|
|
86
|
+
| `--list` / `-l` | List recent sessions from both sources |
|
|
87
|
+
| `--find KEYWORD` / `-f` | Search all sessions for a keyword |
|
|
88
|
+
| `--source codex\|claude` | Filter to one source |
|
|
89
|
+
| `--verbose` / `-v` | Include brief tool call summaries (Claude sessions) |
|
|
90
|
+
| `--tail N` / `-n N` | Show only the last N user turns of a session |
|
|
91
|
+
| `--include-subagents` | Include guardian/subagent sessions |
|
|
92
|
+
| `--limit N` | Max sessions shown by `--list` (default: 40) |
|
|
93
|
+
|
|
94
|
+
## Session storage locations
|
|
95
|
+
|
|
96
|
+
| Agent | Path |
|
|
97
|
+
|-------|------|
|
|
98
|
+
| Codex CLI | `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` |
|
|
99
|
+
| Claude Code | `~/.claude/projects/*/*.jsonl` |
|
|
100
|
+
|
|
101
|
+
## Development
|
|
102
|
+
|
|
103
|
+
```bash
|
|
104
|
+
uv run ruff format --check .
|
|
105
|
+
uv run ruff check .
|
|
106
|
+
uv run mypy
|
|
107
|
+
uv run pytest
|
|
108
|
+
uv build
|
|
109
|
+
```
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
agent_chat_reader/__init__.py,sha256=wZ7hNNuZynG9J-57C6yx4DdBHB0c4d2JULdhbcgv1Ck,148
|
|
2
|
+
agent_chat_reader/claude.py,sha256=R1FFJAHqpCCpXwF66OVE2Z_OOlmuRJVJB4MX_95e8GA,5629
|
|
3
|
+
agent_chat_reader/cli.py,sha256=w_Glfqj8UbgKnlQregqrhrssB84x-5qINAWCNoKy5uA,5289
|
|
4
|
+
agent_chat_reader/codex.py,sha256=Jt5PPgvqrA4QNLrmpd-6CuKIBXcK-wdS_CLs6YgN_U4,5339
|
|
5
|
+
agent_chat_reader/models.py,sha256=GR6hBuecMDpBnDZhtu5FKSDU7ZPC-EcKwt4-TUt7oBQ,455
|
|
6
|
+
agent_chat_reader/output.py,sha256=Xe4Kq46t0kMQad6h3MeAvd3GUfPseEFuCTKBp7nbdQE,2127
|
|
7
|
+
agent_chat_reader/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
8
|
+
agent_chat_reader-0.1.0.dist-info/METADATA,sha256=WNYSKl3p_K6j-hdq20_zEF0hKRojJmgs_pC-YjttxZ0,3478
|
|
9
|
+
agent_chat_reader-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
10
|
+
agent_chat_reader-0.1.0.dist-info/entry_points.txt,sha256=tZ7fDCX48KbBC4Myq_iHpUGLsNL2b3mb4VgcNt8hl-0,65
|
|
11
|
+
agent_chat_reader-0.1.0.dist-info/licenses/LICENSE,sha256=tR8qNVMEuTuQ451Je9XMooqw5lrRSrgUj-Oc9HIwcWc,1051
|
|
12
|
+
agent_chat_reader-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ali K
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR Ali KS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|