ctxtree 0.1.0 → 0.2.1
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.
- package/README.md +48 -21
- package/ctxtree.py +684 -187
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -14,28 +14,45 @@ and opens the rest when it needs to. Nothing is summarized away: every part open
|
|
|
14
14
|
## Install
|
|
15
15
|
|
|
16
16
|
```sh
|
|
17
|
-
|
|
18
|
-
npx ctxtree #
|
|
17
|
+
pipx install ctxtree # recommended
|
|
18
|
+
npx ctxtree # nothing to install; needs Node, and Python 3.8 or newer (on Windows, use pipx)
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
+
If you use uv, `uvx ctxtree` runs it without installing it. In Claude Code 2.1.275 or newer, the plugin adds the history skill, `/ctxtree:where` and the start-up hook, and
|
|
22
|
+
brings its own copy of ctxtree for Claude:
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
/plugin install ctxtree --marketplace ctxtree/ctxtree
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
No pipx yet? `brew install pipx` on a Mac, `sudo apt install pipx` on Ubuntu or Debian, then `pipx ensurepath`. A plain
|
|
29
|
+
`pip install ctxtree` works inside a virtual environment; many systems (Ubuntu 24.04, Homebrew's Python) block it
|
|
30
|
+
outside one. Step by step, with pictures: https://ctxtree.com/install/
|
|
31
|
+
|
|
21
32
|
## Use
|
|
22
33
|
|
|
23
|
-
In a project folder, type `ctxtree`. It says what your last Claude Code session there was doing,
|
|
24
|
-
|
|
34
|
+
In a project folder, type `ctxtree`. It says what your last Claude Code session there was doing, and which way back is
|
|
35
|
+
cheaper right now, at list price:
|
|
25
36
|
|
|
26
37
|
```
|
|
27
38
|
api: your last session here (3f9a1c02) was active Nov 30 14:02, 3 hours ago.
|
|
28
39
|
The task: "move the billing webhooks to the new queue"
|
|
29
|
-
Its cache has cooled. Going back to it re-caches its whole window: 612k tokens, about $4.90 at list price.
|
|
30
|
-
Starting fresh from the folded view instead: about 52k tokens, about $0.42 at list price, with every word still reachable.
|
|
31
40
|
|
|
32
|
-
|
|
33
|
-
ctxtree
|
|
34
|
-
|
|
41
|
+
Cheaper now: start fresh from the folded view: about 52k tokens, about $0.42 at list price, with every word still reachable.
|
|
42
|
+
ctxtree resume
|
|
43
|
+
Going back instead re-caches its whole window: 612k tokens, about $4.90 at list price.
|
|
44
|
+
|
|
45
|
+
ctxtree show read the folded view yourself
|
|
46
|
+
ctxtree level see or change how much it holds (now auto)
|
|
35
47
|
```
|
|
36
48
|
|
|
37
|
-
`ctxtree resume` starts Claude Code there, told to read the folded view first
|
|
38
|
-
session in the folder you're in, unless you give a session id (or its
|
|
49
|
+
`ctxtree resume` starts Claude Code there, told to read the folded view first (`--upto t21` starts again from before
|
|
50
|
+
turn 21). Every command works on the newest session in the folder you're in, unless you give a session id (or its
|
|
51
|
+
first 6 characters); `ctxtree <id>` shows that session's card. To see what cooled caches cost you lately:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
ctxtree report
|
|
55
|
+
```
|
|
39
56
|
|
|
40
57
|
The rest, mostly for the agent in the new session:
|
|
41
58
|
|
|
@@ -45,19 +62,26 @@ ctxtree open t21.3 # e3 a stretch of work, t21 a turn, t21.3 one tool
|
|
|
45
62
|
ctxtree search --here 'queue' # every session in this folder from the last 30 days
|
|
46
63
|
ctxtree status --json # warm or cooled, and what each way back costs, read fast from the end of each log
|
|
47
64
|
ctxtree check --all # prove nothing is lost: every tool call and result opens to exactly what the log holds
|
|
65
|
+
ctxtree statusline # for Claude Code's status line: minutes left on the cache, then both prices
|
|
66
|
+
ctxtree mcp # search, open, show and report as an MCP server, for any MCP client
|
|
67
|
+
ctxtree titles # name each stretch of work in a few words (opt-in: asks Claude Haiku, see below)
|
|
48
68
|
```
|
|
49
69
|
|
|
70
|
+
With the Claude Code plugin, it also works without a command: after a compaction Claude is told the dropped turns still
|
|
71
|
+
open word for word, and after `/clear` on a big session the fresh one is pointed at the folded map of the one you
|
|
72
|
+
cleared. Codex CLI sessions work too: give ctxtree a Codex session's id.
|
|
73
|
+
|
|
50
74
|
**How much the opening holds** works like Claude Code's effort setting. `auto`, the default, holds the current task
|
|
51
75
|
word for word and a map of the rest, about 8k to 24k tokens. `low`, `medium`, `high`, `xhigh` and `max` hold about 2k,
|
|
52
|
-
8k, 24k, 64k tokens, or every turn; a size such as `30k` works too. `ctxtree level
|
|
53
|
-
|
|
76
|
+
8k, 24k, 64k tokens, or every turn; a size such as `30k` works too. `ctxtree level` shows what each would hold for
|
|
77
|
+
the session here; `ctxtree level high` saves one.
|
|
54
78
|
|
|
55
79
|
## Does it work?
|
|
56
80
|
|
|
57
81
|
In two small blind tests on five real sessions, an agent was asked 50 questions about earlier work.
|
|
58
82
|
|
|
59
|
-
- **Working from the folded view, with `search` and `open`:** 49 answered right, at a fifth
|
|
60
|
-
resuming.
|
|
83
|
+
- **Working from the folded view, with `search` and `open`:** 49 answered right, at about a fifth of the cost of
|
|
84
|
+
resuming, in total ($3.39 against about $17 at list price).
|
|
61
85
|
- **Resuming the old session:** 32 answered right. That was all 20 where nothing had been compacted, and 12 of 30 where
|
|
62
86
|
compaction had dropped the older work.
|
|
63
87
|
|
|
@@ -65,14 +89,17 @@ It's a small sample, so treat it as a sign, not a proof.
|
|
|
65
89
|
|
|
66
90
|
## What it touches
|
|
67
91
|
|
|
68
|
-
- **It reads** Claude Code's session logs in `~/.claude/projects` and
|
|
69
|
-
|
|
92
|
+
- **It reads** Claude Code's session logs in `~/.claude/projects` (and Codex's in `~/.codex/sessions`, when you name
|
|
93
|
+
one) and prints. It sends nothing anywhere, except `ctxtree titles`, which you run yourself: it sends each stretch of
|
|
94
|
+
work's opening words and a few tool calls, masked, to Claude Haiku through your own `claude` command.
|
|
95
|
+
- **It writes** a few small things:
|
|
70
96
|
- the level you save, in `~/.config/ctxtree/config`
|
|
71
|
-
- the opening message for `resume`, in `~/.local/state/ctxtree/`, readable by you only
|
|
72
|
-
- the sizes of fresh starts, in `~/.cache/ctxtree/`
|
|
97
|
+
- the opening message for `resume` and `/clear`, in `~/.local/state/ctxtree/`, readable by you only
|
|
98
|
+
- the sizes of fresh starts, and titles if you ask for them, in `~/.cache/ctxtree/`
|
|
99
|
+
- **It masks** anything shaped like a key or token in the views it prints or writes; `open` still gives the exact text.
|
|
73
100
|
- **It never watches** what you type.
|
|
74
|
-
- **Limits:** it knows Claude Code's log
|
|
75
|
-
the tool call that started it. Prices are list prices for current Claude models.
|
|
101
|
+
- **Limits:** it knows Claude Code's and Codex CLI's log formats. It leaves out sub-agents' own steps; each one's result
|
|
102
|
+
shows as the tool call that started it. Prices are list prices for current Claude models.
|
|
76
103
|
|
|
77
104
|
## License
|
|
78
105
|
|
package/ctxtree.py
CHANGED
|
@@ -1,28 +1,28 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
2
|
"""ctxtree: a folded, lossless view of a Claude Code session, opened on demand.
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
ctxtree
|
|
8
|
-
ctxtree
|
|
9
|
-
ctxtree
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
ctxtree
|
|
13
|
-
ctxtree
|
|
14
|
-
ctxtree
|
|
15
|
-
ctxtree
|
|
16
|
-
ctxtree
|
|
17
|
-
ctxtree
|
|
18
|
-
ctxtree
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
session in this folder
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
before turn N.
|
|
4
|
+
For you:
|
|
5
|
+
ctxtree where your last session here left off, and the cheaper way back
|
|
6
|
+
ctxtree resume [--upto tN] start a new Claude Code session from the folded view (or from before turn N)
|
|
7
|
+
ctxtree level [L] how much the folded view holds: see what each level would hold, or save one
|
|
8
|
+
ctxtree report [--days N] how often you went back to a cooled session lately, and what that cost
|
|
9
|
+
ctxtree titles [SESSION] name each stretch of work in a few words (asks Claude Haiku: opt-in, sends excerpts)
|
|
10
|
+
|
|
11
|
+
For Claude and other tools:
|
|
12
|
+
ctxtree show [--opening] the folded view: the map, then recent turns word for word (or the exact opening)
|
|
13
|
+
ctxtree open NODE e3 an episode, t12 a turn, t12.3 one tool call with its full input and output
|
|
14
|
+
ctxtree search PATTERN where a word or regex appears, in words and tool output alike
|
|
15
|
+
ctxtree status [--json] warm or cooled, and what each way back costs, read fast
|
|
16
|
+
ctxtree hook for the Claude Code plugin's SessionStart hook (reads its JSON on stdin)
|
|
17
|
+
ctxtree statusline a line for Claude Code's status line: the cache's minutes left, then both prices
|
|
18
|
+
ctxtree mcp search, open, show and report as an MCP server on stdio, for any MCP client
|
|
19
|
+
ctxtree check [--all] prove nothing is lost: every tool call and result opens to exactly what the log holds
|
|
20
|
+
|
|
21
|
+
Each command works on the newest session in this folder unless you name another: its id, its first 6 or more
|
|
22
|
+
characters, or its .jsonl file (`ctxtree <id>` shows that session's card). Codex CLI sessions work too, named by
|
|
23
|
+
their id (from ~/.codex/sessions). Inside a Claude Code session, the newest
|
|
24
|
+
session means the newest other than that one. search --here looks through every session in this folder. show, open,
|
|
25
|
+
search and resume take --upto tN to see a session as it stood before turn N.
|
|
26
26
|
|
|
27
27
|
The level works like effort. auto, the default, holds the current task word for word and a map of the rest, between
|
|
28
28
|
8k and 24k tokens. Or pick low, medium, high, xhigh or max (about 2k, 8k, 24k, 64k tokens, or every turn), or a size
|
|
@@ -30,7 +30,7 @@ such as 30k. --level beats CTXTREE_LEVEL, which beats the level saved with `ctxt
|
|
|
30
30
|
"""
|
|
31
31
|
import argparse, glob, json, os, re, shlex, shutil, subprocess, sys, time
|
|
32
32
|
|
|
33
|
-
__version__ = "0.1
|
|
33
|
+
__version__ = "0.2.1"
|
|
34
34
|
from datetime import datetime
|
|
35
35
|
|
|
36
36
|
ROOT = os.path.expanduser("~/.claude/projects")
|
|
@@ -40,17 +40,55 @@ START = 30000 # tokens a new Claude Code session holds before anything is said,
|
|
|
40
40
|
CHARS = 4 # characters a token, roughly
|
|
41
41
|
COMMIT = re.compile(r"(^|[\s;&|(])git\s+(-\S+\s+(\S+\s+)?)*commit\b")
|
|
42
42
|
HERE = os.path.realpath(__file__)
|
|
43
|
-
#
|
|
44
|
-
|
|
43
|
+
# Run by npx: ctxtree is on the PATH only until npx exits
|
|
44
|
+
NPX = os.environ.get("npm_lifecycle_event") == "npx"
|
|
45
|
+
# Run by the Claude Code plugin's launcher, whose folder is on Claude's PATH but not on the person's
|
|
46
|
+
PLUGIN_BIN = os.environ.get("CTXTREE_PLUGIN_BIN")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def installed():
|
|
50
|
+
"""A ctxtree the person can type: on the PATH, and not the plugin's own launcher"""
|
|
51
|
+
skip = os.path.realpath(PLUGIN_BIN) if PLUGIN_BIN else None
|
|
52
|
+
dirs = [d for d in os.environ.get("PATH", "").split(os.pathsep) if d and os.path.realpath(d) != skip]
|
|
53
|
+
return shutil.which("ctxtree", path=os.pathsep.join(dirs))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# The command that runs this file: on Windows, python (python3 is often missing there) and the full path (no ~)
|
|
57
|
+
FULL = ("python \"%s\"" % HERE) if os.name == "nt" else "python3 " + HERE.replace(os.path.expanduser("~"), "~", 1)
|
|
58
|
+
# How an agent runs this: plain ctxtree when it's on its PATH (installed, or the plugin's), else this file in full
|
|
59
|
+
ME = "ctxtree" if (PLUGIN_BIN or installed()) and not NPX else FULL
|
|
60
|
+
# How a person runs it again
|
|
61
|
+
YOU = "npx ctxtree" if NPX else "ctxtree" if installed() else FULL
|
|
45
62
|
# The slider's fixed notches: about how many tokens the opening message may hold (max: every turn, tool calls folded)
|
|
46
63
|
FIXED = (("low", 2000), ("medium", 8000), ("high", 24000), ("xhigh", 64000), ("max", None))
|
|
47
64
|
NAMES = ("auto",) + tuple(n for n, _ in FIXED)
|
|
48
65
|
# $ per million tokens, list prices (Nov 2026): written to a one-hour cache (coming back to a cooled window, or starting
|
|
49
66
|
# fresh), and read from it (coming back while it's warm)
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
67
|
+
# List prices, $ per million tokens: input, output, cache read, 5-minute cache write, 1-hour cache write (Nov 2026)
|
|
68
|
+
PRICES = {"claude-fable-5-2": (8, 40, 0.20, 10, 16), "claude-fable-5-1": (10, 50, 0.25, 12.5, 20),
|
|
69
|
+
"claude-opus-5-5": (4, 20, 0.20, 5, 8), "claude-opus-5": (5, 25, 0.50, 6.25, 10),
|
|
70
|
+
"claude-opus-4-8": (5, 25, 0.50, 6.25, 10), "claude-sonnet-5-5": (2, 10, 0.10, 2.5, 4),
|
|
71
|
+
"claude-sonnet-5": (2, 10, 0.20, 2.5, 4), "claude-haiku-5-5": (0.10, 0.50, 0.01, 0.125, 0.20),
|
|
72
|
+
"claude-haiku-4-5": (1, 5, 0.10, 1.25, 2)}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def prices(model):
|
|
76
|
+
"""A model's list prices, also for a dated name such as claude-haiku-4-5-20251001; None for one it doesn't know"""
|
|
77
|
+
model = model or ""
|
|
78
|
+
return PRICES.get(model) or next((p for k, p in PRICES.items() if model.startswith(k + "-")), None)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class _Rate(dict):
|
|
82
|
+
def __init__(self, i):
|
|
83
|
+
super().__init__()
|
|
84
|
+
self.i = i
|
|
85
|
+
|
|
86
|
+
def get(self, model, default=None):
|
|
87
|
+
p = prices(model)
|
|
88
|
+
return p[self.i] if p else default
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
WRITE, READ = _Rate(4), _Rate(2) # what re-caching a window costs (an hour's cache), and re-reading it
|
|
54
92
|
|
|
55
93
|
|
|
56
94
|
def text_of(content):
|
|
@@ -115,84 +153,153 @@ class Turn:
|
|
|
115
153
|
return [x for k, x in self.items if k == "call"]
|
|
116
154
|
|
|
117
155
|
|
|
156
|
+
CODEX = os.path.expanduser("~/.codex/sessions")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def entries(path, codex=None):
|
|
160
|
+
"""A session log's entries with their line numbers. A Codex CLI log is translated as it's read, one entry for each of
|
|
161
|
+
its lines, into the shape Claude Code writes, so everything else reads both; `codex` collects its id, model and
|
|
162
|
+
window."""
|
|
163
|
+
state = codex if codex is not None else {}
|
|
164
|
+
with open(path, encoding="utf-8", errors="replace") as f:
|
|
165
|
+
for line_no, line in enumerate(f, 1):
|
|
166
|
+
try:
|
|
167
|
+
e = json.loads(line)
|
|
168
|
+
except ValueError:
|
|
169
|
+
continue
|
|
170
|
+
if not isinstance(e, dict):
|
|
171
|
+
continue
|
|
172
|
+
if line_no == 1 and isinstance(e.get("payload"), dict) and e.get("type") in ("session_meta", "turn_context"):
|
|
173
|
+
state["codex"] = True
|
|
174
|
+
if state.get("codex"):
|
|
175
|
+
e = from_codex(e, state)
|
|
176
|
+
if e is None:
|
|
177
|
+
continue
|
|
178
|
+
yield line_no, e
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def from_codex(e, state):
|
|
182
|
+
kind, p = e.get("type"), e.get("payload") if isinstance(e.get("payload"), dict) else {}
|
|
183
|
+
stamp_ = {"timestamp": e.get("timestamp"), "cwd": state.get("cwd")}
|
|
184
|
+
if kind in ("session_meta", "turn_context"):
|
|
185
|
+
state["id"] = state.get("id") or p.get("id")
|
|
186
|
+
state["cwd"], state["model"] = p.get("cwd") or state.get("cwd"), p.get("model") or state.get("model")
|
|
187
|
+
return None
|
|
188
|
+
if kind == "compacted":
|
|
189
|
+
return {"type": "system", "subtype": "compact_boundary", "timestamp": e.get("timestamp")}
|
|
190
|
+
if kind == "event_msg" and p.get("type") == "user_message":
|
|
191
|
+
return dict(stamp_, type="user", origin={"kind": "human"}, promptSource="typed",
|
|
192
|
+
message={"role": "user", "content": p.get("message") or ""})
|
|
193
|
+
if kind == "event_msg" and p.get("type") == "token_count":
|
|
194
|
+
last = ((p.get("info") or {}).get("last_token_usage") or {})
|
|
195
|
+
state["window"] = last.get("input_tokens") or state.get("window") # Codex counts cached input inside it
|
|
196
|
+
return None
|
|
197
|
+
if kind != "response_item":
|
|
198
|
+
return None
|
|
199
|
+
item = p.get("type")
|
|
200
|
+
if item == "agent_message": # a message from another agent, such as the task a worker was given: not you
|
|
201
|
+
words = p.get("content") if isinstance(p.get("content"), str) else "".join(
|
|
202
|
+
c.get("text") or "" for c in p.get("content") or [] if isinstance(c, dict))
|
|
203
|
+
return dict(stamp_, type="user", promptSource="sdk", message={"role": "user", "content": words})
|
|
204
|
+
reply = lambda content: dict(stamp_, type="assistant", message={
|
|
205
|
+
"id": p.get("id") or p.get("call_id"), "role": "assistant", "model": state.get("model"), "content": content})
|
|
206
|
+
if item == "message" and p.get("role") == "assistant":
|
|
207
|
+
return reply([{"type": "text", "text": "".join(c.get("text") or "" for c in p.get("content") or []
|
|
208
|
+
if isinstance(c, dict))}])
|
|
209
|
+
if item in ("function_call", "custom_tool_call"):
|
|
210
|
+
args = p.get("arguments") if item == "function_call" else {"input": p.get("input")}
|
|
211
|
+
if isinstance(args, str):
|
|
212
|
+
try:
|
|
213
|
+
args = json.loads(args)
|
|
214
|
+
except ValueError:
|
|
215
|
+
args = {"arguments": args}
|
|
216
|
+
return reply([{"type": "tool_use", "id": p.get("call_id"), "name": p.get("name") or item,
|
|
217
|
+
"input": args if isinstance(args, dict) else {"arguments": args}}])
|
|
218
|
+
if item in ("function_call_output", "custom_tool_call_output"):
|
|
219
|
+
out = p.get("output")
|
|
220
|
+
return dict(stamp_, type="user", message={"role": "user", "content": [
|
|
221
|
+
{"type": "tool_result", "tool_use_id": p.get("call_id"),
|
|
222
|
+
"content": out if isinstance(out, str) else json.dumps(out)}]})
|
|
223
|
+
return None
|
|
224
|
+
|
|
225
|
+
|
|
118
226
|
class Session:
|
|
119
227
|
def __init__(self, path):
|
|
120
228
|
self.path, self.id = path, os.path.basename(path)[:-len(".jsonl")]
|
|
121
229
|
self.turns, self.orphans, self.cwd, self.chars, self.window, self.model = [], 0, None, 0, 0, None
|
|
122
230
|
calls, seen, compacted, cur = {}, set(), False, None
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
who = starter(e)
|
|
142
|
-
if who:
|
|
143
|
-
cur = Turn(len(self.turns) + 1, who, text_of(content), line_no, t)
|
|
144
|
-
cur.after_compact, compacted = compacted, False
|
|
145
|
-
self.turns.append(cur)
|
|
146
|
-
self.chars += len(cur.words)
|
|
147
|
-
continue
|
|
148
|
-
if cur and t:
|
|
149
|
-
cur.t1 = max(cur.t1 or t, t)
|
|
150
|
-
results = [x for x in content if isinstance(x, dict) and x.get("type") == "tool_result"] \
|
|
151
|
-
if isinstance(content, list) else []
|
|
152
|
-
for x in results:
|
|
153
|
-
body = text_of(x.get("content"))
|
|
154
|
-
self.chars += len(body)
|
|
155
|
-
c = calls.get(x.get("tool_use_id"))
|
|
156
|
-
if c is None:
|
|
157
|
-
self.orphans += 1
|
|
158
|
-
continue
|
|
159
|
-
c.result, c.result_line, c.error = body, line_no, bool(x.get("is_error"))
|
|
160
|
-
if c.name == "Bash" and not c.error and COMMIT.search(str(c.args.get("command", ""))):
|
|
161
|
-
c.turn.commits += 1
|
|
162
|
-
if not results and cur:
|
|
163
|
-
words = text_of(content)
|
|
164
|
-
if words.strip():
|
|
165
|
-
cur.notes.append((line_no, words))
|
|
166
|
-
self.chars += len(words)
|
|
167
|
-
continue
|
|
168
|
-
if cur is None: # a session that starts with the agent, as a resumed one can
|
|
169
|
-
cur = Turn(1, "start", "", line_no, t)
|
|
231
|
+
codex = {}
|
|
232
|
+
for line_no, e in entries(path, codex):
|
|
233
|
+
if e.get("isSidechain"):
|
|
234
|
+
continue
|
|
235
|
+
self.cwd = self.cwd or e.get("cwd")
|
|
236
|
+
kind, t = e.get("type"), when(e)
|
|
237
|
+
if kind == "system" and e.get("subtype") == "compact_boundary":
|
|
238
|
+
compacted = True
|
|
239
|
+
continue
|
|
240
|
+
if kind not in ("user", "assistant"):
|
|
241
|
+
continue
|
|
242
|
+
message = e.get("message") if isinstance(e.get("message"), dict) else {}
|
|
243
|
+
content = message.get("content")
|
|
244
|
+
if kind == "user":
|
|
245
|
+
who = starter(e)
|
|
246
|
+
if who:
|
|
247
|
+
cur = Turn(len(self.turns) + 1, who, text_of(content), line_no, t)
|
|
248
|
+
cur.after_compact, compacted = compacted, False
|
|
170
249
|
self.turns.append(cur)
|
|
171
|
-
|
|
250
|
+
self.chars += len(cur.words)
|
|
251
|
+
continue
|
|
252
|
+
if cur and t:
|
|
172
253
|
cur.t1 = max(cur.t1 or t, t)
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
self.
|
|
178
|
-
|
|
179
|
-
if
|
|
254
|
+
results = [x for x in content if isinstance(x, dict) and x.get("type") == "tool_result"] \
|
|
255
|
+
if isinstance(content, list) else []
|
|
256
|
+
for x in results:
|
|
257
|
+
body = text_of(x.get("content"))
|
|
258
|
+
self.chars += len(body)
|
|
259
|
+
c = calls.get(x.get("tool_use_id"))
|
|
260
|
+
if c is None:
|
|
261
|
+
self.orphans += 1
|
|
180
262
|
continue
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
263
|
+
c.result, c.result_line, c.error = body, line_no, bool(x.get("is_error"))
|
|
264
|
+
if c.name == "Bash" and not c.error and COMMIT.search(str(c.args.get("command", ""))):
|
|
265
|
+
c.turn.commits += 1
|
|
266
|
+
if not results and cur:
|
|
267
|
+
words = text_of(content)
|
|
268
|
+
if words.strip():
|
|
269
|
+
cur.notes.append((line_no, words))
|
|
270
|
+
self.chars += len(words)
|
|
271
|
+
continue
|
|
272
|
+
if cur is None: # a session that starts with the agent, as a resumed one can
|
|
273
|
+
cur = Turn(1, "start", "", line_no, t)
|
|
274
|
+
self.turns.append(cur)
|
|
275
|
+
if t:
|
|
276
|
+
cur.t1 = max(cur.t1 or t, t)
|
|
277
|
+
usage = message.get("usage") if isinstance(message.get("usage"), dict) else {}
|
|
278
|
+
if usage and message.get("model") != "<synthetic>": # tokens the window held at the last reply
|
|
279
|
+
self.window = sum(usage.get(k) or 0 for k in
|
|
280
|
+
("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
|
|
281
|
+
self.model = message.get("model") or self.model
|
|
282
|
+
for x in content if isinstance(content, list) else []:
|
|
283
|
+
if not isinstance(x, dict):
|
|
284
|
+
continue
|
|
285
|
+
if x.get("type") == "text" and (x.get("text") or "").strip():
|
|
286
|
+
key = (message.get("id"), x["text"])
|
|
287
|
+
if key not in seen:
|
|
288
|
+
seen.add(key)
|
|
289
|
+
cur.items.append(("text", x["text"]))
|
|
290
|
+
self.chars += len(x["text"])
|
|
291
|
+
elif x.get("type") == "tool_use" and x.get("id") not in calls:
|
|
292
|
+
args = x.get("input") if isinstance(x.get("input"), dict) else {}
|
|
293
|
+
c = Call(x.get("id"), x.get("name") or "?", args, line_no, cur)
|
|
294
|
+
calls[c.id] = c
|
|
295
|
+
cur.items.append(("call", c))
|
|
296
|
+
self.chars += len(json.dumps(args, ensure_ascii=False))
|
|
297
|
+
elif x.get("type") == "thinking":
|
|
298
|
+
self.chars += len(x.get("thinking") or "")
|
|
299
|
+
|
|
300
|
+
if codex.get("id"): # a Codex CLI log: its id, window and model come from its own fields
|
|
301
|
+
self.id, self.window = codex["id"], codex.get("window") or self.window
|
|
302
|
+
self.model = codex.get("model") or self.model
|
|
196
303
|
def episodes(self):
|
|
197
304
|
"""Turns split into stretches of work: a new one after a pause, a compaction or a commit"""
|
|
198
305
|
eps, prev = [], None
|
|
@@ -296,7 +403,7 @@ def render_turn(turn, notes=False):
|
|
|
296
403
|
return "\n".join(out)
|
|
297
404
|
|
|
298
405
|
|
|
299
|
-
def episode_line(i, turns):
|
|
406
|
+
def episode_line(i, turns, title=None):
|
|
300
407
|
files, commits = [], sum(t.commits for t in turns)
|
|
301
408
|
for t in turns:
|
|
302
409
|
for c in t.calls():
|
|
@@ -310,7 +417,9 @@ def episode_line(i, turns):
|
|
|
310
417
|
parts.append("edited " + ", ".join(files[:5]) + (" and %d more" % (len(files) - 5) if len(files) > 5 else ""))
|
|
311
418
|
if commits:
|
|
312
419
|
parts.append("%d commit%s" % (commits, "" if commits == 1 else "s"))
|
|
313
|
-
|
|
420
|
+
if title: # a name from `ctxtree titles`; the exact words follow it, so the map still quotes the session
|
|
421
|
+
parts.insert(1, title)
|
|
422
|
+
return " · ".join(parts) + ' · "%s"' % one_line(heading_words(task_of(turns)), 100 if not title else 70)
|
|
314
423
|
|
|
315
424
|
|
|
316
425
|
def budget(level, s=None):
|
|
@@ -341,7 +450,7 @@ def level_in_force(flag=None):
|
|
|
341
450
|
if os.environ.get("CTXTREE_LEVEL"):
|
|
342
451
|
return os.environ["CTXTREE_LEVEL"]
|
|
343
452
|
try:
|
|
344
|
-
with open(config_path()) as f:
|
|
453
|
+
with open(config_path(), encoding="utf-8") as f:
|
|
345
454
|
for line in f:
|
|
346
455
|
key, _, value = line.partition("=")
|
|
347
456
|
if key.strip() == "level" and value.strip():
|
|
@@ -360,6 +469,18 @@ def slider(level, s=None):
|
|
|
360
469
|
return "\n".join(out)
|
|
361
470
|
|
|
362
471
|
|
|
472
|
+
def levels_table(s, current):
|
|
473
|
+
"""What each level's opening would hold for a session"""
|
|
474
|
+
eps = len(s.episodes())
|
|
475
|
+
rows = ["%-8s %8s %-30s %s" % ("level", "opening", "turns word for word", "episodes on the map")]
|
|
476
|
+
for name in NAMES:
|
|
477
|
+
text, n, cut, mapped = prime(s, budget(name, s))
|
|
478
|
+
rows.append("%-8s %7.1fk %-30s %d of %d" % (
|
|
479
|
+
"[%s]" % name if name == current else name, len(text) / (CHARS * 1000),
|
|
480
|
+
"%d of %d%s" % (n, len(s.turns), ", the oldest cut" if cut else ""), mapped, eps))
|
|
481
|
+
return "\n".join(rows)
|
|
482
|
+
|
|
483
|
+
|
|
363
484
|
def tokens_for(flag, s=None):
|
|
364
485
|
"""The level in force and its tokens; a bad level ends the run with the reason"""
|
|
365
486
|
level = level_in_force(flag)
|
|
@@ -387,7 +508,8 @@ def fold(s, tokens):
|
|
|
387
508
|
% (s.id[:8], short(s.cwd), stamp(start), stamp(end), len(s.turns), len(eps)),
|
|
388
509
|
"Folded, nothing lost. Open a node with `%s open %s <node>`: e3 is an episode, t12 a turn, t12.3 one tool "
|
|
389
510
|
"call with its full input and output." % (ME, s.id[:8])]
|
|
390
|
-
|
|
511
|
+
named = load_titles(s.id)
|
|
512
|
+
lines_ = [episode_line(i, ep, named.get(span(ep))) for i, ep in enumerate(eps, 1)]
|
|
391
513
|
if tokens is None:
|
|
392
514
|
body = ["", "## Map"] + lines_ + ["", "## Every turn"] + [render_turn(t) for t in s.turns]
|
|
393
515
|
return "\n".join(out + body), len(s.turns), False, len(lines_)
|
|
@@ -476,7 +598,8 @@ def prime(s, tokens=8000):
|
|
|
476
598
|
|
|
477
599
|
|
|
478
600
|
def live():
|
|
479
|
-
"""The sessions running on this machine now, from runwatch: session id -> its row.
|
|
601
|
+
"""The sessions running on this machine now, from runwatch (an optional session watcher): session id -> its row.
|
|
602
|
+
Empty without it."""
|
|
480
603
|
exe = shutil.which("runwatch") or os.path.expanduser("~/.local/bin/runwatch")
|
|
481
604
|
try:
|
|
482
605
|
out = subprocess.run([exe, "ps", "--json", "--here"], capture_output=True, text=True, timeout=8).stdout
|
|
@@ -496,17 +619,38 @@ def where_it_runs(row):
|
|
|
496
619
|
return "in the background"
|
|
497
620
|
|
|
498
621
|
|
|
499
|
-
def
|
|
500
|
-
"
|
|
622
|
+
def usd(amount):
|
|
623
|
+
return ", about $%.2f at list price" % amount if amount is not None else ""
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def ways_back(s, level, now=None, opening=None):
|
|
627
|
+
"""The two ways back to a session, and which is cheaper now: straight back (a re-read while the cache is warm, a
|
|
628
|
+
re-cache of the whole window once it has cooled) or a fresh start from the folded view."""
|
|
629
|
+
now = now or time.time()
|
|
630
|
+
if opening is None:
|
|
631
|
+
opening = len(prime(s, budget(level, s))[0]) // CHARS
|
|
632
|
+
left = TTL - (now - s.last_active())
|
|
633
|
+
write, read = WRITE.get(s.model or ""), READ.get(s.model or "")
|
|
634
|
+
rate = read if left > 0 else write
|
|
635
|
+
fresh = start_tokens(os.path.dirname(s.path)) + opening
|
|
636
|
+
back_usd = s.window * rate / 1e6 if rate else None
|
|
637
|
+
fresh_usd = fresh * write / 1e6 if write else None
|
|
638
|
+
back_first = back_usd < fresh_usd if back_usd is not None and fresh_usd is not None else left > 0
|
|
639
|
+
return {"warm_minutes": int(left // 60 + 1) if left > 0 else 0, "back_usd": back_usd, "fresh": fresh,
|
|
640
|
+
"fresh_usd": fresh_usd, "back_first": back_first}
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def card(s, level, running=None, named=False):
|
|
644
|
+
"""Where you left off, in plain words, and what each way back costs. `running` is live()'s answer; `named` when the
|
|
645
|
+
session was asked for by id, so its commands name it too."""
|
|
501
646
|
now, last = time.time(), s.last_active()
|
|
502
|
-
|
|
647
|
+
eps = s.episodes()
|
|
648
|
+
# the latest stretch of work you spoke in: an agent left running can end on stretches of background notices
|
|
649
|
+
mine = next((ep for ep in reversed(eps) if any(t.who == "you" for t in ep)), eps[-1] if eps else None)
|
|
650
|
+
task = task_of(mine) if mine else None
|
|
651
|
+
me = (lambda verb: "%s %s %s" % (YOU, verb, s.id[:8])) if named else (lambda verb: "%s %s" % (YOU, verb))
|
|
503
652
|
latest = next((t for t in reversed(s.turns) if t.who == "you"), None)
|
|
504
653
|
opening = len(prime(s, budget(level, s))[0]) // CHARS
|
|
505
|
-
price = WRITE.get(s.model or "")
|
|
506
|
-
|
|
507
|
-
def cost(tokens):
|
|
508
|
-
return ", about $%.2f at list price" % (tokens * price / 1e6) if price else ""
|
|
509
|
-
|
|
510
654
|
out = ["%s: your last session here (%s) was active %s, %s." % (
|
|
511
655
|
os.path.basename(s.cwd or "?"), s.id[:8], stamp(last), ago(now - last))]
|
|
512
656
|
if task:
|
|
@@ -518,21 +662,24 @@ def card(s, level, running=None):
|
|
|
518
662
|
state = {"working": "working on it right now", "needs-input": "waiting for you",
|
|
519
663
|
"done": "done and waiting for your next message"}.get(row.get("state"), row.get("state") or "open")
|
|
520
664
|
out.append("It's still open %s, %s." % (where_it_runs(row), state))
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
665
|
+
w = ways_back(s, level, now, opening)
|
|
666
|
+
if not s.window:
|
|
667
|
+
out += ["", " %s start a new session from the folded view" % me("resume")]
|
|
668
|
+
elif w["back_first"]:
|
|
669
|
+
out += ["", "Cheaper now: go straight back while its cache is warm, about %d more minutes%s."
|
|
670
|
+
% (w["warm_minutes"], ": about $%.2f to re-read %dk tokens" % (w["back_usd"], s.window // 1000)
|
|
671
|
+
if w["back_usd"] is not None else ""),
|
|
672
|
+
" " + ("switch to it %s" % where_it_runs(row) if row else "claude --resume %s" % s.id),
|
|
673
|
+
"Starting fresh from the folded view instead: about %dk tokens%s." % (w["fresh"] // 1000, usd(w["fresh_usd"]))]
|
|
674
|
+
else:
|
|
675
|
+
out += ["", "Cheaper now: start fresh from the folded view: about %dk tokens%s, with every word still reachable."
|
|
676
|
+
% (w["fresh"] // 1000, usd(w["fresh_usd"])),
|
|
677
|
+
" " + me("resume"),
|
|
678
|
+
"Going back instead %s: %dk tokens%s." % (
|
|
679
|
+
"re-caches its whole window" if w["warm_minutes"] <= 0 else "re-reads its window",
|
|
680
|
+
s.window // 1000, usd(w["back_usd"]))]
|
|
681
|
+
out += ["", " %s read the folded view yourself" % me("show"),
|
|
682
|
+
" %s level see or change how much it holds (now %s)" % (YOU, level)]
|
|
536
683
|
return "\n".join(out)
|
|
537
684
|
|
|
538
685
|
|
|
@@ -570,6 +717,59 @@ def tail(path, size=262144):
|
|
|
570
717
|
return info
|
|
571
718
|
|
|
572
719
|
|
|
720
|
+
def span(turns):
|
|
721
|
+
return "%s-%s" % (turns[0].node, turns[-1].node)
|
|
722
|
+
|
|
723
|
+
|
|
724
|
+
def titles_file():
|
|
725
|
+
return os.path.join(os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "ctxtree", "titles.json")
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def load_titles(sid):
|
|
729
|
+
try:
|
|
730
|
+
with open(titles_file(), encoding="utf-8") as f:
|
|
731
|
+
return json.load(f).get(sid, {})
|
|
732
|
+
except (OSError, ValueError):
|
|
733
|
+
return {}
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def make_titles(s, run=None):
|
|
737
|
+
"""Names for a session's stretches of work, a few words each, from Claude (Haiku) through your own claude command:
|
|
738
|
+
one call for every stretch not yet named. Opt-in: it sends each stretch's opening words and a few tool calls,
|
|
739
|
+
masked. Returns (the titles, how many were new, the call's usage)."""
|
|
740
|
+
have = load_titles(s.id)
|
|
741
|
+
todo = [(i, ep) for i, ep in enumerate(s.episodes(), 1) if span(ep) not in have]
|
|
742
|
+
if not todo:
|
|
743
|
+
return have, 0, {}
|
|
744
|
+
blocks = []
|
|
745
|
+
for i, ep in todo:
|
|
746
|
+
said = [one_line(heading_words(t), 200) for t in ep if t.who == "you"][:5]
|
|
747
|
+
calls = [gist(c) for t in ep for c in t.calls()][:8]
|
|
748
|
+
blocks.append("## e%d\n%s" % (i, masked("\n".join(said + calls))[:1500]))
|
|
749
|
+
ask = ("Each block below is a stretch of work from a coding session. Give each a title of 3 to 6 plain words that "
|
|
750
|
+
"says what was done. Reply with JSON only: an object from the block's name (e1, e2, ...) to its title.\n\n"
|
|
751
|
+
+ "\n\n".join(blocks))
|
|
752
|
+
run = run or (lambda text: subprocess.run(
|
|
753
|
+
# no tools and no MCP servers: with tools off, Claude Code sends every MCP tool's full description instead of
|
|
754
|
+
# loading them on demand (measured here: 247k tokens for a two-word prompt, 4.5k without them)
|
|
755
|
+
["claude", "-p", "--model", "claude-haiku-5-5", "--no-session-persistence", "--tools", "", "--strict-mcp-config",
|
|
756
|
+
"--mcp-config", '{"mcpServers":{}}', "--output-format", "json"], input=text, capture_output=True, text=True, timeout=300, cwd=os.path.expanduser("~")).stdout)
|
|
757
|
+
reply = json.loads(run(ask))
|
|
758
|
+
text = reply.get("result") or ""
|
|
759
|
+
got = json.loads(text[text.index("{"):text.rindex("}") + 1])
|
|
760
|
+
new = {span(ep): one_line(str(got["e%d" % i]), 60) for i, ep in todo if got.get("e%d" % i)}
|
|
761
|
+
try:
|
|
762
|
+
with open(titles_file(), encoding="utf-8") as f:
|
|
763
|
+
everything = json.load(f)
|
|
764
|
+
except (OSError, ValueError):
|
|
765
|
+
everything = {}
|
|
766
|
+
everything.setdefault(s.id, {}).update(new)
|
|
767
|
+
os.makedirs(os.path.dirname(titles_file()), exist_ok=True)
|
|
768
|
+
with open(titles_file(), "w", encoding="utf-8") as f:
|
|
769
|
+
json.dump(everything, f)
|
|
770
|
+
return everything[s.id], len(new), reply.get("usage") or {}
|
|
771
|
+
|
|
772
|
+
|
|
573
773
|
def cache_file():
|
|
574
774
|
home = os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache")
|
|
575
775
|
return os.path.join(home, "ctxtree", "openings-v2.json")
|
|
@@ -582,7 +782,7 @@ def start_tokens(folder):
|
|
|
582
782
|
sizes = []
|
|
583
783
|
for path in sorted(glob.glob(os.path.join(folder, "*.jsonl")), key=os.path.getmtime, reverse=True)[:12]:
|
|
584
784
|
try:
|
|
585
|
-
with open(path, errors="replace") as f:
|
|
785
|
+
with open(path, encoding="utf-8", errors="replace") as f:
|
|
586
786
|
for line in f:
|
|
587
787
|
if '"usage"' not in line:
|
|
588
788
|
continue
|
|
@@ -607,7 +807,7 @@ def opening_tokens(path, level):
|
|
|
607
807
|
size and level, so a session that has stopped changing is read in full once. The file keeps only numbers."""
|
|
608
808
|
key, st = os.path.realpath(path), os.stat(path)
|
|
609
809
|
try:
|
|
610
|
-
with open(cache_file()) as f:
|
|
810
|
+
with open(cache_file(), encoding="utf-8") as f:
|
|
611
811
|
known = json.load(f)
|
|
612
812
|
except (OSError, ValueError):
|
|
613
813
|
known = {}
|
|
@@ -618,7 +818,7 @@ def opening_tokens(path, level):
|
|
|
618
818
|
known = {k: v for k, v in known.items() if os.path.exists(k)}
|
|
619
819
|
known[key] = [st.st_size, int(st.st_mtime), level, tokens]
|
|
620
820
|
os.makedirs(os.path.dirname(cache_file()), mode=0o700, exist_ok=True)
|
|
621
|
-
with open(cache_file() + ".new", "w") as f:
|
|
821
|
+
with open(cache_file() + ".new", "w", encoding="utf-8") as f:
|
|
622
822
|
json.dump(known, f)
|
|
623
823
|
os.replace(cache_file() + ".new", cache_file())
|
|
624
824
|
return tokens
|
|
@@ -646,7 +846,8 @@ def status_of(path, level, now=None):
|
|
|
646
846
|
def hook(event, now=None):
|
|
647
847
|
"""What the plugin's SessionStart hook says, if anything. Resuming a big session whose cache has cooled: a word to
|
|
648
848
|
you about the cheaper way back. Starting a new session where the last one has cooled: a note for Claude that the
|
|
649
|
-
earlier work is kept and how to search it.
|
|
849
|
+
earlier work is kept and how to search it. After a compaction: that every compacted turn still opens. After /clear
|
|
850
|
+
on a big session: its folded map, for Claude to read if the work carries on. Otherwise nothing."""
|
|
650
851
|
now = now or time.time()
|
|
651
852
|
if event.get("source") == "resume":
|
|
652
853
|
tokens, path = event.get("context_tokens") or 0, event.get("transcript_path") or ""
|
|
@@ -655,8 +856,19 @@ def hook(event, now=None):
|
|
|
655
856
|
return {"systemMessage": "Picking this session up re-caches %dk tokens%s. To start fresh from its folded "
|
|
656
857
|
"history instead (about %dk tokens, every word still reachable), quit and run: "
|
|
657
858
|
"%s resume %s" % (tokens // 1000, ", about $%.2f" % usd if usd else "",
|
|
658
|
-
fresh // 1000,
|
|
859
|
+
fresh // 1000, YOU, os.path.basename(path)[:8])}
|
|
659
860
|
return None
|
|
861
|
+
if event.get("source") == "compact":
|
|
862
|
+
sid = (event.get("session_id") or os.path.basename(event.get("transcript_path") or "")[:-len(".jsonl")])[:8]
|
|
863
|
+
if not sid:
|
|
864
|
+
return None
|
|
865
|
+
note = ("This session was just compacted, but nothing before it is lost: every turn and tool call is kept word "
|
|
866
|
+
"for word. When a detail matters (a decision and its reason, an error, a number), find it with "
|
|
867
|
+
"`%s search %s '<regex>'` and open the node a hit names with `%s open %s <node>` rather than trusting "
|
|
868
|
+
"the summary; `%s show %s` maps the session." % (ME, sid, ME, sid, ME, sid))
|
|
869
|
+
return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": note}}
|
|
870
|
+
if event.get("source") == "clear":
|
|
871
|
+
return after_clear(event, now)
|
|
660
872
|
if event.get("source") != "startup":
|
|
661
873
|
return None
|
|
662
874
|
folder = os.path.join(ROOT, folder_key(os.path.abspath(event.get("cwd") or os.getcwd())))
|
|
@@ -675,48 +887,92 @@ def hook(event, now=None):
|
|
|
675
887
|
return {"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": note}}
|
|
676
888
|
|
|
677
889
|
|
|
890
|
+
def after_clear(event, now):
|
|
891
|
+
"""After /clear: if the session just cleared here was big, its folded map, ready for the fresh session to read if
|
|
892
|
+
the next message carries on that work. Nothing is read unless it's needed."""
|
|
893
|
+
found = [p for p in here(event.get("cwd")) if os.path.basename(p)[:-len(".jsonl")] != event.get("session_id")]
|
|
894
|
+
if not found:
|
|
895
|
+
return None
|
|
896
|
+
i = tail(found[0])
|
|
897
|
+
if now - i["last"] > 600 or i["window"] < 100000: # cleared just now, and big enough to be worth carrying over
|
|
898
|
+
return None
|
|
899
|
+
s = Session(found[0])
|
|
900
|
+
path = write_opening(s, budget(level_in_force(), s))
|
|
901
|
+
task = task_of(next((ep for ep in reversed(s.episodes()) if any(t.who == "you" for t in ep)), s.turns))
|
|
902
|
+
note = ("The user just ran /clear on session %s here (%dk tokens; its task: \"%s\"). If their next message carries "
|
|
903
|
+
"on that work, read %s first: a folded, lossless map of it, with how to open any part word for word. If they "
|
|
904
|
+
"are starting something new, ignore it." % (s.id[:8], i["window"] // 1000, one_line(heading_words(task), 120),
|
|
905
|
+
path))
|
|
906
|
+
return {"systemMessage": "ctxtree: the folded map of the session you cleared is ready, if you carry on with it.",
|
|
907
|
+
"hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": note}}
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
SECRETS = re.compile("|".join([
|
|
911
|
+
r"sk-ant-[A-Za-z0-9_\-]{20,}", r"\bsk-(?:proj-)?[A-Za-z0-9]{20,}", r"\bgh[pousr]_[A-Za-z0-9]{30,}",
|
|
912
|
+
r"\bgithub_pat_[A-Za-z0-9_]{40,}", r"\bAKIA[0-9A-Z]{16}\b", r"\bxox[abprs]-[A-Za-z0-9\-]{10,}",
|
|
913
|
+
r"\b[rs]k_live_[A-Za-z0-9]{20,}", r"\bAIza[0-9A-Za-z_\-]{35}\b", r"\bnpm_[A-Za-z0-9]{36}\b",
|
|
914
|
+
r"\bpypi-[A-Za-z0-9_\-]{50,}", r"\beyJ[A-Za-z0-9_\-]{10,}\.eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}",
|
|
915
|
+
r"-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)",
|
|
916
|
+
r"(?i:(?<=password=)|(?<=secret=)|(?<=token=))[^\s'\"&]{8,}"]))
|
|
917
|
+
|
|
918
|
+
|
|
919
|
+
def masked(text):
|
|
920
|
+
"""A view with anything shaped like a key, token or private key masked. open still gives the exact text."""
|
|
921
|
+
return SECRETS.sub("[masked: open its node for the exact text]", text)
|
|
922
|
+
|
|
923
|
+
|
|
924
|
+
def write_opening(s, tokens):
|
|
925
|
+
"""The opening message, in a file only you can read (it can be bigger than a command line holds)"""
|
|
926
|
+
path = os.path.join(state_dir(), "opening-%s.md" % s.id[:8])
|
|
927
|
+
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w", encoding="utf-8") as f:
|
|
928
|
+
f.write(masked(prime(s, tokens)[0]))
|
|
929
|
+
os.chmod(path, 0o600)
|
|
930
|
+
return path
|
|
931
|
+
|
|
932
|
+
|
|
678
933
|
def state_dir():
|
|
679
934
|
d = os.path.join(os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "ctxtree")
|
|
680
935
|
os.makedirs(d, mode=0o700, exist_ok=True)
|
|
681
936
|
return d
|
|
682
937
|
|
|
683
938
|
|
|
684
|
-
def resume(s, tokens, dry=False):
|
|
939
|
+
def resume(s, tokens, dry=False, upto=None, level=None):
|
|
685
940
|
"""Start Claude Code in the session's folder, told to read the folded view first. The view goes in a private file
|
|
686
941
|
(it can be bigger than a command line holds)."""
|
|
687
|
-
path =
|
|
688
|
-
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
|
|
689
|
-
f.write(prime(s, tokens)[0])
|
|
690
|
-
os.chmod(path, 0o600)
|
|
942
|
+
path = write_opening(s, tokens)
|
|
691
943
|
ask = ("Read %s first, all of it: it is a folded view of an earlier session in this folder (%s), whose work you are "
|
|
692
|
-
"picking up. Then say in two lines where it left off, and wait for my next message."
|
|
944
|
+
"picking up%s. Then say in two lines where it left off, and wait for my next message."
|
|
945
|
+
% (path, s.id[:8], " from before turn %s" % upto if upto else ""))
|
|
693
946
|
folder = s.cwd if s.cwd and os.path.isdir(s.cwd) else os.getcwd()
|
|
694
947
|
if dry:
|
|
695
948
|
print("cd %s && claude %s" % (shlex.quote(folder), shlex.quote(ask)))
|
|
696
949
|
return 0
|
|
697
950
|
if not shutil.which("claude"):
|
|
698
951
|
sys.exit("claude isn't on your PATH. The opening is in %s" % path)
|
|
952
|
+
w = ways_back(s, level or "auto", opening=len(open(path, encoding="utf-8").read()) // CHARS)
|
|
953
|
+
if s.window and w["fresh_usd"] is not None and w["back_usd"] is not None:
|
|
954
|
+
print("Starting fresh: about %dk tokens, $%.2f at list price, against $%.2f to go back%s." % (
|
|
955
|
+
w["fresh"] // 1000, w["fresh_usd"], w["back_usd"],
|
|
956
|
+
" (it's still warm, so going back was the cheaper way)" if w["back_first"] else ""))
|
|
699
957
|
os.chdir(folder)
|
|
958
|
+
if os.name == "nt": # Windows has no exec: run Claude Code as a child, and end when it ends
|
|
959
|
+
sys.exit(subprocess.call([shutil.which("claude"), ask]))
|
|
700
960
|
os.execvp("claude", ["claude", ask])
|
|
701
961
|
|
|
702
962
|
|
|
703
963
|
def check(s):
|
|
704
964
|
"""Every tool call and every tool result in the file opens, and opens to exactly the text the file holds"""
|
|
705
965
|
uses, results = set(), {}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
if
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
if isinstance(x, dict) and x.get("type") == "tool_use":
|
|
717
|
-
uses.add(x.get("id"))
|
|
718
|
-
elif isinstance(x, dict) and x.get("type") == "tool_result":
|
|
719
|
-
results[x.get("tool_use_id")] = (line_no, text_of(x.get("content")))
|
|
966
|
+
codex = {}
|
|
967
|
+
for line_no, e in entries(s.path, codex):
|
|
968
|
+
if e.get("isSidechain") or e.get("type") not in ("user", "assistant"):
|
|
969
|
+
continue
|
|
970
|
+
content = (e.get("message") or {}).get("content") if isinstance(e.get("message"), dict) else None
|
|
971
|
+
for x in content if isinstance(content, list) else []:
|
|
972
|
+
if isinstance(x, dict) and x.get("type") == "tool_use":
|
|
973
|
+
uses.add(x.get("id"))
|
|
974
|
+
elif isinstance(x, dict) and x.get("type") == "tool_result":
|
|
975
|
+
results[x.get("tool_use_id")] = (line_no, text_of(x.get("content")))
|
|
720
976
|
calls = {c.id: c for t in s.turns for c in t.calls()}
|
|
721
977
|
missing = uses - set(calls)
|
|
722
978
|
unopened = [k for k in results if k not in calls]
|
|
@@ -751,6 +1007,8 @@ def find_session(arg):
|
|
|
751
1007
|
if arg.endswith(".jsonl") and os.path.exists(arg):
|
|
752
1008
|
return arg
|
|
753
1009
|
found = glob.glob(os.path.join(ROOT, "*", glob.escape(arg) + "*.jsonl")) if len(arg) >= 6 else []
|
|
1010
|
+
if not found and len(arg) >= 6: # a Codex CLI session, by the id at the end of its file's name
|
|
1011
|
+
found = glob.glob(os.path.join(CODEX, "**", "*" + glob.escape(arg) + "*.jsonl"), recursive=True)
|
|
754
1012
|
return found[0] if len(found) == 1 else None
|
|
755
1013
|
|
|
756
1014
|
|
|
@@ -771,16 +1029,24 @@ def recent_paths(days, project=None):
|
|
|
771
1029
|
|
|
772
1030
|
|
|
773
1031
|
def main(argv):
|
|
774
|
-
|
|
1032
|
+
if argv[:1] in (["-h"], ["--help"]):
|
|
1033
|
+
print(__doc__.strip())
|
|
1034
|
+
return 0
|
|
1035
|
+
head, rest = __doc__.split("\n\n", 1)
|
|
1036
|
+
ap = argparse.ArgumentParser(prog="ctxtree", description=head, epilog=rest,
|
|
1037
|
+
formatter_class=argparse.RawDescriptionHelpFormatter, usage="ctxtree [COMMAND] [SESSION]")
|
|
775
1038
|
ap.add_argument("--version", action="version", version="ctxtree " + __version__)
|
|
776
|
-
sub = ap.add_subparsers(dest="verb")
|
|
1039
|
+
sub = ap.add_subparsers(dest="verb", metavar="COMMAND")
|
|
777
1040
|
upto = argparse.ArgumentParser(add_help=False)
|
|
778
1041
|
upto.add_argument("--upto", help="see the session only as it stood before this turn, such as t29")
|
|
779
1042
|
lv = argparse.ArgumentParser(add_help=False)
|
|
780
1043
|
lv.add_argument("--level", help="auto, low, medium, high, xhigh, max, or a size such as 30k (tokens)")
|
|
781
|
-
for verb, parents in (("show", [upto, lv]), ("prime", [upto, lv]), ("levels", [upto])):
|
|
782
|
-
sub.add_parser(verb, parents=parents)
|
|
783
|
-
|
|
1044
|
+
for verb, parents in (("card", [upto, lv]), ("show", [upto, lv]), ("prime", [upto, lv]), ("levels", [upto])):
|
|
1045
|
+
p = sub.add_parser(verb, parents=parents)
|
|
1046
|
+
p.add_argument("session", nargs="?")
|
|
1047
|
+
if verb == "show":
|
|
1048
|
+
p.add_argument("--opening", action="store_true", help="the exact opening message a new session gets")
|
|
1049
|
+
p = sub.add_parser("resume", parents=[lv, upto])
|
|
784
1050
|
p.add_argument("session", nargs="?")
|
|
785
1051
|
p.add_argument("--dry-run", action="store_true", help="write the opening and print the command, but don't start")
|
|
786
1052
|
sub.add_parser("open", parents=[upto]).add_argument("args", nargs="+", metavar="[SESSION] NODE")
|
|
@@ -796,10 +1062,18 @@ def main(argv):
|
|
|
796
1062
|
p.add_argument("--days", type=float, default=7)
|
|
797
1063
|
p.add_argument("--project")
|
|
798
1064
|
p.add_argument("--min", type=float, default=1.0, help="leave out sessions under this many million characters")
|
|
1065
|
+
sub.add_parser("titles").add_argument("session", nargs="?")
|
|
1066
|
+
sub.add_parser("statusline")
|
|
1067
|
+
sub.add_parser("mcp")
|
|
1068
|
+
p = sub.add_parser("report")
|
|
1069
|
+
p.add_argument("--days", type=float, default=7)
|
|
1070
|
+
p.add_argument("--json", action="store_true")
|
|
799
1071
|
p = sub.add_parser("check")
|
|
800
1072
|
p.add_argument("session", nargs="*")
|
|
801
1073
|
p.add_argument("--all", action="store_true")
|
|
802
1074
|
p.add_argument("--days", type=float, default=7)
|
|
1075
|
+
if argv and not argv[0].startswith("-") and argv[0] not in sub.choices:
|
|
1076
|
+
argv = ["card"] + list(argv) # ctxtree <session>: that session's card
|
|
803
1077
|
a = ap.parse_args(argv)
|
|
804
1078
|
|
|
805
1079
|
if a.verb == "hook":
|
|
@@ -827,21 +1101,17 @@ def main(argv):
|
|
|
827
1101
|
if left <= 0 and r["cold_usd"] is not None and r["fresh_usd"] is not None else ""))
|
|
828
1102
|
return 0
|
|
829
1103
|
if a.verb == "search" and a.here:
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
for path in paths:
|
|
835
|
-
hits += ["%s %s" % (os.path.basename(path)[:8], h) for h in search(Session(path), a.args[-1], most=20)
|
|
836
|
-
if not h.startswith("…")]
|
|
837
|
-
print("\n".join(hits[:60]) + ("\n… and %d more" % (len(hits) - 60) if len(hits) > 60 else "")
|
|
838
|
-
if hits else "nothing matches")
|
|
1104
|
+
print(search_here(os.getcwd(), a.args[-1]))
|
|
1105
|
+
return 0
|
|
1106
|
+
if a.verb == "mcp":
|
|
1107
|
+
mcp(sys.stdin, sys.stdout)
|
|
839
1108
|
return 0
|
|
840
1109
|
if a.verb == "sessions":
|
|
841
1110
|
level = level_in_force()
|
|
842
1111
|
print("Opening at level %s. words: every turn folded, as a share of the whole history." % level)
|
|
843
1112
|
print("%-8s %-16s %-12s %5s %8s %7s %7s %7s" %
|
|
844
1113
|
("session", "folder", "last", "turns", "history", "words", "window", "opening"))
|
|
1114
|
+
shown = 0
|
|
845
1115
|
for path in recent_paths(a.days, a.project):
|
|
846
1116
|
s = Session(path)
|
|
847
1117
|
if s.chars < a.min * 1e6 or not s.turns:
|
|
@@ -850,6 +1120,9 @@ def main(argv):
|
|
|
850
1120
|
s.id[:8], os.path.basename(s.cwd or "?")[:16], stamp(os.path.getmtime(path)), len(s.turns),
|
|
851
1121
|
s.chars / 1e6, 100 * len(fold(s, None)[0]) / s.chars, s.window / 1e3,
|
|
852
1122
|
len(prime(s, tokens_for(level, s)[1])[0]) / (CHARS * 1000)))
|
|
1123
|
+
shown += 1
|
|
1124
|
+
if not shown:
|
|
1125
|
+
print("(none yet: no session in the last %d days has a history over %gM characters)" % (a.days, a.min))
|
|
853
1126
|
return 0
|
|
854
1127
|
if a.verb == "level":
|
|
855
1128
|
if a.name:
|
|
@@ -858,7 +1131,7 @@ def main(argv):
|
|
|
858
1131
|
except ValueError as e:
|
|
859
1132
|
sys.exit(str(e))
|
|
860
1133
|
os.makedirs(os.path.dirname(config_path()), exist_ok=True)
|
|
861
|
-
with open(config_path(), "w") as f:
|
|
1134
|
+
with open(config_path(), "w", encoding="utf-8") as f:
|
|
862
1135
|
f.write("# ctxtree: how much the opening message holds. auto, low, medium, high, xhigh, max or a "
|
|
863
1136
|
"size such as 30k.\nlevel = %s\n" % a.name)
|
|
864
1137
|
print(slider(a.name))
|
|
@@ -867,21 +1140,34 @@ def main(argv):
|
|
|
867
1140
|
level = level_in_force()
|
|
868
1141
|
source = "CTXTREE_LEVEL" if os.environ.get("CTXTREE_LEVEL") else \
|
|
869
1142
|
short(config_path(), 120) if os.path.exists(config_path()) else "the default"
|
|
870
|
-
|
|
871
|
-
s = Session(
|
|
1143
|
+
found = here()
|
|
1144
|
+
s = Session(found[0]) if found else None
|
|
872
1145
|
print(slider(level, s))
|
|
873
|
-
|
|
1146
|
+
if s is not None:
|
|
1147
|
+
print("\nWhat each would hold for the session here (%s):\n%s" % (s.id[:8], levels_table(s, level)))
|
|
1148
|
+
print("\nFrom %s. Change it with: %s level <%s|30k>" % (source, YOU, "|".join(NAMES)))
|
|
1149
|
+
return 0
|
|
1150
|
+
if a.verb == "statusline":
|
|
1151
|
+
try:
|
|
1152
|
+
print(statusline(json.loads(sys.stdin.read() or "{}")))
|
|
1153
|
+
except Exception: # noqa: BLE001 - a status line must never show an error
|
|
1154
|
+
print("")
|
|
1155
|
+
return 0
|
|
1156
|
+
if a.verb == "report":
|
|
1157
|
+
r = report(a.days)
|
|
1158
|
+
print(json.dumps(r) if a.json else say_report(r))
|
|
874
1159
|
return 0
|
|
875
1160
|
if a.verb == "check":
|
|
876
1161
|
paths = recent_paths(a.days) if a.all else [locate(x) for x in a.session] or [newest_here()]
|
|
877
1162
|
bad = 0
|
|
878
1163
|
for path in paths:
|
|
879
|
-
|
|
1164
|
+
s = Session(path)
|
|
1165
|
+
r = check(s)
|
|
880
1166
|
lost = r["missing_calls"] + r["unopened_results"] + r["wrong_results"]
|
|
881
1167
|
bad += lost > 0
|
|
882
1168
|
if lost or not a.all:
|
|
883
1169
|
print("%s %d calls, %d results: %d calls missing, %d results that don't open, %d that open wrong"
|
|
884
|
-
% (
|
|
1170
|
+
% (s.id[:8], r["calls"], r["results"], r["missing_calls"],
|
|
885
1171
|
r["unopened_results"], r["wrong_results"]))
|
|
886
1172
|
print("%d of %d sessions lossless" % (len(paths) - bad, len(paths)))
|
|
887
1173
|
return 1 if bad else 0
|
|
@@ -893,33 +1179,41 @@ def main(argv):
|
|
|
893
1179
|
session, rest = (a.args[0], a.args[1]) if len(a.args) == 2 else (None, a.args[0])
|
|
894
1180
|
else:
|
|
895
1181
|
session = getattr(a, "session", None)
|
|
1182
|
+
if a.verb in (None, "card") and session is None and not here():
|
|
1183
|
+
# The card has nothing to say yet; that isn't an error (and /ctxtree:where would fail on one)
|
|
1184
|
+
print("No Claude Code sessions for this folder yet. Run it in a folder where you've used Claude Code.")
|
|
1185
|
+
return 0
|
|
896
1186
|
s = Session(locate(session))
|
|
897
1187
|
if getattr(a, "upto", None):
|
|
898
1188
|
m = re.fullmatch(r"t(\d+)", a.upto)
|
|
899
1189
|
if not m:
|
|
900
1190
|
sys.exit("--upto takes a turn, such as t29")
|
|
901
1191
|
s.turns = s.turns[:int(m.group(1)) - 1]
|
|
902
|
-
if a.verb
|
|
903
|
-
print(card(s, level_in_force(), live()))
|
|
1192
|
+
if a.verb in (None, "card"):
|
|
1193
|
+
print(card(s, level_in_force(getattr(a, "level", None)), live(), named=session is not None))
|
|
904
1194
|
elif a.verb == "resume":
|
|
905
|
-
return resume(s, tokens_for(a.level, s)[1], a.dry_run)
|
|
906
|
-
elif a.verb == "show":
|
|
907
|
-
print(fold(s, tokens_for(a.level, s)[1])[0])
|
|
908
|
-
elif a.verb
|
|
909
|
-
print(prime(s, tokens_for(a.level, s)[1])[0])
|
|
1195
|
+
return resume(s, tokens_for(a.level, s)[1], a.dry_run, a.upto, level_in_force(a.level))
|
|
1196
|
+
elif a.verb == "show" and not a.opening:
|
|
1197
|
+
print(masked(fold(s, tokens_for(a.level, s)[1])[0]))
|
|
1198
|
+
elif a.verb in ("show", "prime"):
|
|
1199
|
+
print(masked(prime(s, tokens_for(a.level, s)[1])[0]))
|
|
910
1200
|
elif a.verb == "levels":
|
|
911
|
-
|
|
912
|
-
print("%-8s %8s %-30s %s" % ("level", "opening", "turns word for word", "episodes on the map"))
|
|
913
|
-
for name in NAMES:
|
|
914
|
-
text, n, cut, mapped = prime(s, budget(name, s))
|
|
915
|
-
print("%-8s %7.1fk %-30s %d of %d" % (
|
|
916
|
-
"[%s]" % name if name == current else name, len(text) / (CHARS * 1000),
|
|
917
|
-
"%d of %d%s" % (n, len(s.turns), ", the oldest cut" if cut else ""), mapped, eps))
|
|
1201
|
+
print(levels_table(s, level_in_force()))
|
|
918
1202
|
if not a.upto:
|
|
919
1203
|
print("Its window held %dk tokens at the last reply: what coming back after a lapse re-caches."
|
|
920
1204
|
% (s.window // 1000))
|
|
921
1205
|
elif a.verb == "search":
|
|
922
|
-
print("\n".join(search(s, rest)) or "nothing matches")
|
|
1206
|
+
print(masked("\n".join(search(s, rest))) or "nothing matches")
|
|
1207
|
+
elif a.verb == "titles":
|
|
1208
|
+
if not shutil.which("claude"):
|
|
1209
|
+
sys.exit("titles asks Claude through your claude command, and it isn't on your PATH")
|
|
1210
|
+
titles, new, usage = make_titles(s)
|
|
1211
|
+
print("Named %d stretch%s of work (%d named in all)%s." % (
|
|
1212
|
+
new, "" if new == 1 else "es", len(titles), ", with %dk tokens in and %d out on Haiku" % (
|
|
1213
|
+
(usage.get("input_tokens", 0) + usage.get("cache_creation_input_tokens", 0)
|
|
1214
|
+
+ usage.get("cache_read_input_tokens", 0)) // 1000, usage.get("output_tokens", 0)) if usage else ""))
|
|
1215
|
+
for i, ep in enumerate(s.episodes(), 1):
|
|
1216
|
+
print(episode_line(i, ep, titles.get(span(ep))))
|
|
923
1217
|
else:
|
|
924
1218
|
out = open_node(s, rest)
|
|
925
1219
|
if out is None:
|
|
@@ -928,11 +1222,214 @@ def main(argv):
|
|
|
928
1222
|
return 0
|
|
929
1223
|
|
|
930
1224
|
|
|
1225
|
+
def statusline(info, now=None):
|
|
1226
|
+
"""One line for Claude Code's status line, from the JSON it passes: how long the cache stays warm, and near the end
|
|
1227
|
+
what each way back will cost. Reads nothing while there's time left, since a status line runs often."""
|
|
1228
|
+
now = now or time.time()
|
|
1229
|
+
cache = info.get("prompt_cache") if isinstance(info.get("prompt_cache"), dict) else {}
|
|
1230
|
+
expires, tokens = cache.get("expires_at"), cache.get("recache_tokens_if_cold")
|
|
1231
|
+
if not expires or not tokens:
|
|
1232
|
+
return ""
|
|
1233
|
+
left = expires - now
|
|
1234
|
+
if left > 600:
|
|
1235
|
+
return "cache warm %dm" % (left // 60)
|
|
1236
|
+
model = info.get("model")
|
|
1237
|
+
model = model.get("id") if isinstance(model, dict) else model
|
|
1238
|
+
write, path = WRITE.get(model), info.get("transcript_path") or ""
|
|
1239
|
+
back = "$%.2f" % (tokens * write / 1e6) if write else "%dk tokens" % (tokens // 1000)
|
|
1240
|
+
fresh = ""
|
|
1241
|
+
if write and os.path.exists(path):
|
|
1242
|
+
f = start_tokens(os.path.dirname(path)) + opening_tokens(path, level_in_force())
|
|
1243
|
+
fresh = ", /clear starts fresh for $%.2f" % (f * write / 1e6)
|
|
1244
|
+
if left > 0:
|
|
1245
|
+
return "cache cools in %dm: then %s to come back%s" % (left // 60 + 1, back, fresh)
|
|
1246
|
+
return "cache cooled: the next message re-caches %s%s" % (back, fresh)
|
|
1247
|
+
|
|
1248
|
+
|
|
1249
|
+
def search_here(cwd, pattern, days=30):
|
|
1250
|
+
"""Every session in a folder from the last `days`, newest first, searched; each hit names its session and node"""
|
|
1251
|
+
folder = os.path.join(ROOT, folder_key(os.path.abspath(cwd)))
|
|
1252
|
+
paths = [p for p in sorted(glob.glob(os.path.join(folder, "*.jsonl")), key=os.path.getmtime, reverse=True)
|
|
1253
|
+
if os.path.getsize(p) > 2000 and os.path.getmtime(p) > time.time() - days * 86400][:15]
|
|
1254
|
+
hits = []
|
|
1255
|
+
for path in paths:
|
|
1256
|
+
hits += ["%s %s" % (os.path.basename(path)[:8], h) for h in search(Session(path), pattern, most=20)
|
|
1257
|
+
if not h.startswith("…")]
|
|
1258
|
+
return masked("\n".join(hits[:60]) + ("\n… and %d more" % (len(hits) - 60) if len(hits) > 60 else "")
|
|
1259
|
+
if hits else "nothing matches")
|
|
1260
|
+
|
|
1261
|
+
|
|
1262
|
+
MCP_TOOLS = [
|
|
1263
|
+
{"name": "search", "description": "Search a folder's Claude Code sessions from the last 30 days, word for word, "
|
|
1264
|
+
"including turns that were compacted away. Each hit starts with its session's id and node; open a node with the "
|
|
1265
|
+
"open tool.", "inputSchema": {"type": "object", "required": ["pattern"], "properties": {
|
|
1266
|
+
"pattern": {"type": "string", "description": "a word or regular expression"},
|
|
1267
|
+
"folder": {"type": "string", "description": "the project folder; the server's own folder if left out"}}}},
|
|
1268
|
+
{"name": "open", "description": "One part of a session, word for word: e3 an episode, t12 a turn, t12.3 one tool "
|
|
1269
|
+
"call with its full input and output.", "inputSchema": {"type": "object", "required": ["session", "node"],
|
|
1270
|
+
"properties": {
|
|
1271
|
+
"session": {"type": "string", "description": "a session id, or its first 6 or more characters"},
|
|
1272
|
+
"node": {"type": "string", "description": "e3, t12 or t12.3"}}}},
|
|
1273
|
+
{"name": "show", "description": "A session folded: a map of its work, then its last turns word for word. The newest "
|
|
1274
|
+
"session in the folder if no session is given.", "inputSchema": {"type": "object", "properties": {
|
|
1275
|
+
"session": {"type": "string"}, "folder": {"type": "string"},
|
|
1276
|
+
"opening": {"type": "boolean", "description": "the exact opening message a new session would get"}}}},
|
|
1277
|
+
{"name": "report", "description": "How often sessions were picked up after their cache had cooled lately, and what "
|
|
1278
|
+
"that cost at list price.", "inputSchema": {"type": "object", "properties": {"days": {"type": "number"}}}},
|
|
1279
|
+
]
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
def session_id(value):
|
|
1283
|
+
"""A session as an MCP client names it: an id or its start, never a path, so a client can't point it at other files"""
|
|
1284
|
+
value = str(value or "")
|
|
1285
|
+
if not re.fullmatch(r"[0-9A-Za-z-]{6,64}", value):
|
|
1286
|
+
raise ValueError("give a session id, or its first 6 or more characters")
|
|
1287
|
+
return value
|
|
1288
|
+
|
|
1289
|
+
|
|
1290
|
+
def mcp_call(name, args):
|
|
1291
|
+
if name == "search":
|
|
1292
|
+
return search_here(args.get("folder") or os.getcwd(), args["pattern"])
|
|
1293
|
+
if name == "open":
|
|
1294
|
+
out = open_node(Session(locate(session_id(args["session"]))), args["node"])
|
|
1295
|
+
if out is None:
|
|
1296
|
+
raise ValueError("no node %r: try e1 (an episode), t1 (a turn) or t1.1 (a tool call)" % args["node"])
|
|
1297
|
+
return out
|
|
1298
|
+
if name == "show":
|
|
1299
|
+
found = [locate(session_id(args["session"]))] if args.get("session") else here(args.get("folder"))
|
|
1300
|
+
if not found:
|
|
1301
|
+
raise ValueError("no Claude Code sessions for that folder")
|
|
1302
|
+
s = Session(found[0])
|
|
1303
|
+
tokens = budget(level_in_force(), s)
|
|
1304
|
+
return masked(prime(s, tokens)[0] if args.get("opening") else fold(s, tokens)[0])
|
|
1305
|
+
if name == "report":
|
|
1306
|
+
return say_report(report(float(args.get("days") or 7)))
|
|
1307
|
+
raise ValueError("no tool %r" % name)
|
|
1308
|
+
|
|
1309
|
+
|
|
1310
|
+
def mcp(stdin, stdout):
|
|
1311
|
+
"""ctxtree as an MCP server on stdio: search, open, show and report. A tool that fails answers with an error; the
|
|
1312
|
+
server keeps going."""
|
|
1313
|
+
for line in stdin:
|
|
1314
|
+
try:
|
|
1315
|
+
msg = json.loads(line)
|
|
1316
|
+
except ValueError:
|
|
1317
|
+
continue
|
|
1318
|
+
if not isinstance(msg, dict) or msg.get("id") is None:
|
|
1319
|
+
continue # a notification: nothing to answer
|
|
1320
|
+
method, params = msg.get("method"), msg.get("params") or {}
|
|
1321
|
+
if method == "initialize":
|
|
1322
|
+
result = {"protocolVersion": params.get("protocolVersion") or "2025-06-18", "capabilities": {"tools": {}},
|
|
1323
|
+
"serverInfo": {"name": "ctxtree", "version": __version__}}
|
|
1324
|
+
elif method == "tools/list":
|
|
1325
|
+
result = {"tools": MCP_TOOLS}
|
|
1326
|
+
elif method == "tools/call":
|
|
1327
|
+
try:
|
|
1328
|
+
text, failed = mcp_call(params.get("name"), params.get("arguments") or {}), False
|
|
1329
|
+
except (SystemExit, ValueError, KeyError, OSError, re.error) as e:
|
|
1330
|
+
text, failed = str(e) or type(e).__name__, True
|
|
1331
|
+
result = {"content": [{"type": "text", "text": text}], "isError": failed}
|
|
1332
|
+
elif method == "ping":
|
|
1333
|
+
result = {}
|
|
1334
|
+
else:
|
|
1335
|
+
stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg["id"],
|
|
1336
|
+
"error": {"code": -32601, "message": "no method %s" % method}}) + "\n")
|
|
1337
|
+
stdout.flush()
|
|
1338
|
+
continue
|
|
1339
|
+
stdout.write(json.dumps({"jsonrpc": "2.0", "id": msg["id"], "result": result}) + "\n")
|
|
1340
|
+
stdout.flush()
|
|
1341
|
+
|
|
1342
|
+
|
|
1343
|
+
def report(days=7, root=None, now=None):
|
|
1344
|
+
"""Every time a session was picked up after its cache had cooled, over the last `days`: how often, what re-caching
|
|
1345
|
+
cost against reading a warm cache, and the share of all usage that was, at list price. A cache lapsed when a reply
|
|
1346
|
+
came after the cache's life (an hour if the last write asked for one, else 5 minutes) and read much less from it
|
|
1347
|
+
than the reply before had left there."""
|
|
1348
|
+
now, root = now or time.time(), root or ROOT
|
|
1349
|
+
since = now - days * 86400
|
|
1350
|
+
spend, lapses = 0.0, []
|
|
1351
|
+
for path in glob.glob(os.path.join(root, "*", "*.jsonl")):
|
|
1352
|
+
if os.path.getmtime(path) < since:
|
|
1353
|
+
continue
|
|
1354
|
+
replies, order, folder, after_compact = {}, [], None, False
|
|
1355
|
+
with open(path, encoding="utf-8", errors="replace") as f:
|
|
1356
|
+
for line in f:
|
|
1357
|
+
if '"assistant"' not in line and '"compact_boundary"' not in line:
|
|
1358
|
+
continue
|
|
1359
|
+
try:
|
|
1360
|
+
e = json.loads(line)
|
|
1361
|
+
except ValueError:
|
|
1362
|
+
continue
|
|
1363
|
+
if not isinstance(e, dict) or e.get("isSidechain"):
|
|
1364
|
+
continue
|
|
1365
|
+
if isinstance(e.get("cwd"), str) and not folder:
|
|
1366
|
+
folder = os.path.basename(e["cwd"].rstrip("/"))
|
|
1367
|
+
if e.get("type") == "system" and e.get("subtype") == "compact_boundary":
|
|
1368
|
+
after_compact = True
|
|
1369
|
+
continue
|
|
1370
|
+
m = e.get("message") if isinstance(e.get("message"), dict) else {}
|
|
1371
|
+
if e.get("type") != "assistant":
|
|
1372
|
+
continue
|
|
1373
|
+
mid = m.get("id") or e.get("uuid")
|
|
1374
|
+
if mid not in replies:
|
|
1375
|
+
replies[mid] = {"t": when(e), "usage": {}, "model": None, "compacted": after_compact}
|
|
1376
|
+
after_compact = False
|
|
1377
|
+
order.append(mid)
|
|
1378
|
+
if isinstance(m.get("usage"), dict):
|
|
1379
|
+
replies[mid]["usage"] = m["usage"]
|
|
1380
|
+
replies[mid]["model"] = m.get("model") or replies[mid]["model"]
|
|
1381
|
+
last = None
|
|
1382
|
+
for mid in order:
|
|
1383
|
+
r = replies[mid]
|
|
1384
|
+
u, t, p = r["usage"], r["t"], prices(r["model"])
|
|
1385
|
+
if not u or t is None or not p:
|
|
1386
|
+
continue
|
|
1387
|
+
num = lambda k: u.get(k) if isinstance(u.get(k), (int, float)) else 0
|
|
1388
|
+
made = u.get("cache_creation") if isinstance(u.get("cache_creation"), dict) else {}
|
|
1389
|
+
write, read = num("cache_creation_input_tokens"), num("cache_read_input_tokens")
|
|
1390
|
+
hour = min(write, made.get("ephemeral_1h_input_tokens") or 0)
|
|
1391
|
+
size = num("input_tokens") + read + write
|
|
1392
|
+
if t >= since:
|
|
1393
|
+
spend += (num("input_tokens") * p[0] + num("output_tokens") * p[1] + read * p[2]
|
|
1394
|
+
+ (write - hour) * p[3] + hour * p[4]) / 1e6
|
|
1395
|
+
if last and t >= since and not r["compacted"]:
|
|
1396
|
+
gone = last["size"] - read
|
|
1397
|
+
if t - last["t"] > (3600 if last["hour"] else 300) and gone >= 2000 and gone * 20 > last["size"]:
|
|
1398
|
+
lapses.append({"folder": folder or "?", "t": t, "tokens": gone,
|
|
1399
|
+
"usd": gone * ((p[4] if last["hour"] else p[3]) - p[2]) / 1e6})
|
|
1400
|
+
last = {"t": t, "size": size, "hour": hour > 0 if write else (last["hour"] if last else False)}
|
|
1401
|
+
lapses.sort(key=lambda x: -x["usd"])
|
|
1402
|
+
return {"days": days, "spend_usd": spend, "lapses": len(lapses), "lapse_usd": sum(x["usd"] for x in lapses),
|
|
1403
|
+
"biggest": lapses[:3]}
|
|
1404
|
+
|
|
1405
|
+
|
|
1406
|
+
def say_report(r):
|
|
1407
|
+
if not r["spend_usd"]:
|
|
1408
|
+
return "No Claude Code use in the last %g days to report on." % r["days"]
|
|
1409
|
+
share = 100 * r["lapse_usd"] / r["spend_usd"]
|
|
1410
|
+
out = ["Last %g days, at list price (on a Claude plan, this is usage against your limits, not a bill):" % r["days"],
|
|
1411
|
+
" Claude Code used about $%s of tokens." % format(round(r["spend_usd"]), ","),
|
|
1412
|
+
" %d time%s, you went back to a session after its cache had cooled. Reading %s back in cost about $%s"
|
|
1413
|
+
" more than a warm cache would have: %.0f%% of the total." % (
|
|
1414
|
+
r["lapses"], "" if r["lapses"] == 1 else "s", "it" if r["lapses"] == 1 else "those",
|
|
1415
|
+
format(round(r["lapse_usd"]), ","), share)]
|
|
1416
|
+
if r["biggest"]:
|
|
1417
|
+
out.append(" The biggest:")
|
|
1418
|
+
out += [" %-18s %5dk tokens about %-8s %s" % (x["folder"][:18], x["tokens"] // 1000, "$%.2f" % x["usd"],
|
|
1419
|
+
stamp(x["t"])) for x in r["biggest"]]
|
|
1420
|
+
out += ["", "Next time, type ctxtree in the folder first: it says when starting fresh from the folded view is "
|
|
1421
|
+
"the cheaper way."]
|
|
1422
|
+
return "\n".join(out)
|
|
1423
|
+
|
|
1424
|
+
|
|
931
1425
|
def entry():
|
|
932
1426
|
"""The ctxtree command"""
|
|
933
1427
|
import signal
|
|
934
1428
|
if hasattr(signal, "SIGPIPE"):
|
|
935
1429
|
signal.signal(signal.SIGPIPE, signal.SIG_DFL) # piped into head: stop quietly
|
|
1430
|
+
for stream in (sys.stdout, sys.stderr): # a console that can't show a character gets a ? instead of an error
|
|
1431
|
+
if hasattr(stream, "reconfigure"):
|
|
1432
|
+
stream.reconfigure(errors="replace")
|
|
936
1433
|
sys.exit(main(sys.argv[1:]))
|
|
937
1434
|
|
|
938
1435
|
|