Commit 2c418f7
authored
feat: add list_sessions and get_session_messages top-level functions (#622)
Adds `list_sessions()` and `get_session_messages()` as top-level
functions, matching the TypeScript SDK's `listSessions()` and
`getSessionMessages()`.
These are **filesystem-reading implementations** (not CLI passthroughs)
— they scan `~/.claude/projects/` directly, same as the TS SDK.
## `list_sessions(directory=None, limit=None, include_worktrees=True) ->
list[SDKSessionInfo]`
- Scans project directories under `~/.claude/projects/` (or
`CLAUDE_CONFIG_DIR`)
- Reads head/tail 64KB of each `.jsonl` file (does not load entire large
transcripts)
- Extracts `session_id`, `summary`, `last_modified`, `file_size`,
`custom_title`, `first_prompt`, `git_branch`, `cwd`
- `include_worktrees=True` expands to active git worktree session dirs;
`False` filters them out
- Metadata-only sessions are dropped (no `'(session)'` placeholder)
## `get_session_messages(session_id, directory=None, limit=None,
offset=0) -> list[SessionMessage]`
- Reads one session's `.jsonl` fully
- Reconstructs the conversation chain via `parentUuid` backward
traversal (leaf → root, reversed)
- Handles branched transcripts (sidechains, edit history) by picking the
main-line leaf (non-sidechain, non-meta, highest file position)
- Filters to visible `user`/`assistant` messages only
- Returns `[]` for nonexistent/invalid session IDs (never raises)
<!-- CHANGELOG:START -->
- Add `list_sessions()` and `get_session_messages()` top-level functions
- Add `SDKSessionInfo` and `SessionMessage` dataclasses
<!-- CHANGELOG:END -->
## Test plan
- Unit: 59 tests covering path sanitization, JSONL head/tail parsing,
parentUuid chain reconstruction, main-chain leaf selection, visibility
filtering, limit/offset pagination
- E2E `list_sessions`: verified against 637 real sessions — all shape
checks pass, `include_worktrees` expansion confirmed on a 16-worktree
repo (270 → 274 sessions), nonexistent dir → clean `[]`
- E2E `get_session_messages`: 8 real sessions (~14MB JSONL) — chain
reconstruction proven (0 broken links across 1,581 entries), 254-branch
session correctly walks main-line, isMeta filtering verified, pagination
matches exact slicing1 parent 9af27d7 commit 2c418f7
4 files changed
Lines changed: 2072 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
| 16 | + | |
16 | 17 | | |
17 | 18 | | |
18 | 19 | | |
| |||
59 | 60 | | |
60 | 61 | | |
61 | 62 | | |
| 63 | + | |
| 64 | + | |
62 | 65 | | |
63 | 66 | | |
64 | 67 | | |
| |||
402 | 405 | | |
403 | 406 | | |
404 | 407 | | |
| 408 | + | |
| 409 | + | |
| 410 | + | |
| 411 | + | |
| 412 | + | |
405 | 413 | | |
406 | 414 | | |
407 | 415 | | |
| |||
0 commit comments