@alexgreensh/token-optimizer 5.13.51 → 5.13.53
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.
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
"name": "token-optimizer",
|
|
14
14
|
"source": "./",
|
|
15
15
|
"description": "Audit, fix, and monitor Claude Code context window usage. Find the ghost tokens.",
|
|
16
|
-
"version": "5.13.
|
|
16
|
+
"version": "5.13.53",
|
|
17
17
|
"author": {
|
|
18
18
|
"name": "Alex Greenshpun",
|
|
19
19
|
"url": "https://linkedin.com/in/alexgreensh"
|
|
@@ -55,7 +55,7 @@
|
|
|
55
55
|
"name": "token-optimizer-cowork",
|
|
56
56
|
"source": "./cowork/token-optimizer",
|
|
57
57
|
"description": "Token Optimizer for Claude Cowork \u2014 full skills + Cowork-native hooks (beta). Install THIS in Cowork; the standard token-optimizer entry is for desktop Claude Code.",
|
|
58
|
-
"version": "5.13.
|
|
58
|
+
"version": "5.13.53",
|
|
59
59
|
"author": {
|
|
60
60
|
"name": "Alex Greenshpun",
|
|
61
61
|
"url": "https://linkedin.com/in/alexgreensh"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@alexgreensh/token-optimizer",
|
|
3
|
-
"version": "5.13.
|
|
3
|
+
"version": "5.13.53",
|
|
4
4
|
"description": "Token Optimizer for Claude Code cloud sessions: the real plugin, installed by your cloud environment's setup script.",
|
|
5
5
|
"license": "PolyForm-Noncommercial-1.0.0",
|
|
6
6
|
"author": "Alex Greenshpun (https://linkedin.com/in/alexgreensh)",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: token-dashboard
|
|
3
|
-
description: Answers what a past session cost ("the
|
|
3
|
+
description: Answers what a past session cost ("the Garden session yesterday", a session id) with a priced number, and opens the Token Optimizer dashboard when asked to see it.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Token Optimizer Dashboard
|
|
@@ -62,11 +62,11 @@ if [ -z "$MEASURE_PY" ]; then echo "[Error] measure.py not found. Is Token Optim
|
|
|
62
62
|
export TOKEN_OPTIMIZER_RUNTIME="$RUNTIME"
|
|
63
63
|
```
|
|
64
64
|
|
|
65
|
-
2. **A cost question** ("what did the
|
|
65
|
+
2. **A cost question** ("what did the Garden session yesterday cost?", "how much were my TR sync sessions?", "cost of session <id>"): run this instead of steps 3-4.
|
|
66
66
|
```bash
|
|
67
67
|
python3 "$MEASURE_PY" session-cost <the user's words> --json
|
|
68
68
|
```
|
|
69
|
-
- Pass the user's own words (`
|
|
69
|
+
- Pass the user's own words (`garden yesterday`, `tr sync`, an id or its first 8 characters). Names match topic, slug and project, case-insensitively, and all of them must match; `today`, `yesterday` and `YYYY-MM-DD` set the day. Add `--days N` for "this week" (default 30), `--limit N` to list more.
|
|
70
70
|
- Answer from `sessions[]`: date, topic, `cost_usd.total`, the main-thread and subagent split when subagents ran, `cost_usd.on_date` when a day was asked and the session ran over several days, and `partial_reason` when set. Several matches: give `total_cost_usd` and list them, asking which one only when it changes the answer.
|
|
71
71
|
- State `basis` in one line: API list prices, so on a subscription it is what the work would have cost, not a bill.
|
|
72
72
|
- No match: say so, show `closest[]`, and pass on `note` (a session is collected when it ends).
|
|
@@ -96,7 +96,7 @@ import shutil
|
|
|
96
96
|
from collections import deque
|
|
97
97
|
from contextlib import contextmanager, nullcontext
|
|
98
98
|
from datetime import datetime, timedelta, timezone
|
|
99
|
-
from pathlib import Path
|
|
99
|
+
from pathlib import Path, PureWindowsPath
|
|
100
100
|
try:
|
|
101
101
|
import tomllib
|
|
102
102
|
except ImportError: # pragma: no cover - Python < 3.11 fallback
|
|
@@ -1908,9 +1908,14 @@ def _resolve_session_model(session_id=None):
|
|
|
1908
1908
|
if session_id:
|
|
1909
1909
|
session_id = sanitize_session_id(session_id)
|
|
1910
1910
|
try:
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1911
|
+
# The session id names its transcript exactly; find it wherever it
|
|
1912
|
+
# lives rather than trusting a cwd lookup that can guess another
|
|
1913
|
+
# project's dir (#265).
|
|
1914
|
+
candidate = next(iter(sorted((CLAUDE_DIR / "projects").glob(f"*/{session_id}.jsonl"))), None)
|
|
1915
|
+
if candidate is None:
|
|
1916
|
+
projects_dir = find_projects_dir()
|
|
1917
|
+
candidate = projects_dir / f"{session_id}.jsonl" if projects_dir else None
|
|
1918
|
+
if candidate is not None:
|
|
1914
1919
|
if candidate.exists():
|
|
1915
1920
|
counts = {}
|
|
1916
1921
|
with open(candidate, "r", encoding="utf-8", errors="replace") as f:
|
|
@@ -2215,34 +2220,87 @@ def _encode_project_dir_name(path_str):
|
|
|
2215
2220
|
return re.sub(r"[^A-Za-z0-9]", "-", str(path_str))
|
|
2216
2221
|
|
|
2217
2222
|
|
|
2223
|
+
# MSIX-packaged apps (the Claude desktop app on Windows) get a virtualized
|
|
2224
|
+
# %APPDATA%: after any `cd` in Git Bash the Win32 cwd is the physical
|
|
2225
|
+
# ...\\AppData\\Local\\Packages\\<pkg>\\LocalCache\\Roaming\\... path, while Claude Code
|
|
2226
|
+
# names project dirs from the logical ...\\AppData\\Roaming\\... path (#265).
|
|
2227
|
+
_MSIX_REDIRECT_RE = re.compile(
|
|
2228
|
+
r"^(?P<home>[A-Za-z]:[\\/]Users[\\/][^\\/]+)[\\/]AppData[\\/]Local[\\/]Packages[\\/]"
|
|
2229
|
+
r"[^\\/]+[\\/]LocalCache[\\/](?P<kind>Roaming|Local)(?P<rest>(?:[\\/].*)?)$",
|
|
2230
|
+
re.IGNORECASE,
|
|
2231
|
+
)
|
|
2232
|
+
|
|
2233
|
+
|
|
2234
|
+
def _unvirtualize_msix_path(path_str):
|
|
2235
|
+
"""Map an MSIX physical LocalCache path back to the logical AppData path."""
|
|
2236
|
+
text = str(path_str)
|
|
2237
|
+
m = _MSIX_REDIRECT_RE.match(text)
|
|
2238
|
+
if not m:
|
|
2239
|
+
return text
|
|
2240
|
+
sep = "\\" if "\\" in text else "/"
|
|
2241
|
+
return f"{m.group('home')}{sep}AppData{sep}{m.group('kind')}{m.group('rest')}"
|
|
2242
|
+
|
|
2243
|
+
|
|
2218
2244
|
def cwd_to_project_dir_name():
|
|
2219
2245
|
"""Convert cwd to Claude Code project directory name format.
|
|
2220
2246
|
|
|
2221
2247
|
e.g. /Users/alex/my project -> -Users-alex-my-project
|
|
2222
2248
|
D:\\Code\\my app -> D--Code-my-app (Windows)
|
|
2223
2249
|
"""
|
|
2224
|
-
return _encode_project_dir_name(Path.cwd())
|
|
2250
|
+
return _encode_project_dir_name(_unvirtualize_msix_path(Path.cwd()))
|
|
2251
|
+
|
|
2252
|
+
|
|
2253
|
+
def _project_dir_from_transcript(projects_base, transcript_path):
|
|
2254
|
+
"""The project dir holding a transcript, when it lives under projects_base."""
|
|
2255
|
+
if not transcript_path:
|
|
2256
|
+
return None
|
|
2257
|
+
try:
|
|
2258
|
+
rel = Path(transcript_path).resolve().relative_to(projects_base.resolve())
|
|
2259
|
+
except (OSError, ValueError, RuntimeError):
|
|
2260
|
+
return None
|
|
2261
|
+
if len(rel.parts) < 2:
|
|
2262
|
+
return None
|
|
2263
|
+
candidate = projects_base / rel.parts[0]
|
|
2264
|
+
return candidate if candidate.is_dir() else None
|
|
2265
|
+
|
|
2225
2266
|
|
|
2267
|
+
def find_projects_dir(cwd=None, transcript_path=None):
|
|
2268
|
+
"""Find the Claude Code projects directory for this session.
|
|
2226
2269
|
|
|
2227
|
-
|
|
2228
|
-
|
|
2270
|
+
Most reliable first: the hook payload's transcript_path (its parent is the
|
|
2271
|
+
project dir by construction), then the payload cwd, then the process cwd,
|
|
2272
|
+
then $CLAUDE_PROJECT_DIR, each with MSIX paths mapped back to the logical
|
|
2273
|
+
AppData path (#265). Only then the most-recently-modified guess.
|
|
2274
|
+
"""
|
|
2229
2275
|
projects_base = CLAUDE_DIR / "projects"
|
|
2230
2276
|
if not projects_base.exists():
|
|
2231
2277
|
return None
|
|
2232
2278
|
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
if expected_dir.exists():
|
|
2237
|
-
return expected_dir
|
|
2279
|
+
from_transcript = _project_dir_from_transcript(projects_base, transcript_path)
|
|
2280
|
+
if from_transcript is not None:
|
|
2281
|
+
return from_transcript
|
|
2238
2282
|
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2283
|
+
bases = []
|
|
2284
|
+
if cwd:
|
|
2285
|
+
bases.append(cwd)
|
|
2286
|
+
try:
|
|
2287
|
+
bases.append(Path.cwd())
|
|
2288
|
+
except OSError:
|
|
2289
|
+
pass
|
|
2290
|
+
if os.environ.get("CLAUDE_PROJECT_DIR"):
|
|
2291
|
+
bases.append(os.environ["CLAUDE_PROJECT_DIR"])
|
|
2292
|
+
|
|
2293
|
+
for base in bases:
|
|
2294
|
+
for text in dict.fromkeys((_unvirtualize_msix_path(base), str(base))):
|
|
2295
|
+
expected_dir = projects_base / _encode_project_dir_name(text)
|
|
2296
|
+
if expected_dir.exists():
|
|
2297
|
+
return expected_dir
|
|
2298
|
+
# The user may be in a subdirectory of the project.
|
|
2299
|
+
path_cls = PureWindowsPath if re.match(r"^[A-Za-z]:[\\/]", text) else Path
|
|
2300
|
+
for parent in list(path_cls(text).parents)[:5]:
|
|
2301
|
+
parent_dir = projects_base / _encode_project_dir_name(parent)
|
|
2302
|
+
if parent_dir.exists():
|
|
2303
|
+
return parent_dir
|
|
2246
2304
|
|
|
2247
2305
|
# Last resort: most recently modified (with warning)
|
|
2248
2306
|
dirs = [d for d in projects_base.iterdir() if d.is_dir()]
|
|
@@ -25956,7 +26014,7 @@ def _price_session_row(sr, pricing_tier):
|
|
|
25956
26014
|
|
|
25957
26015
|
|
|
25958
26016
|
# ---------------------------------------------------------------------------
|
|
25959
|
-
# session-cost: "what did the
|
|
26017
|
+
# session-cost: "what did the Garden session yesterday cost?" answered from
|
|
25960
26018
|
# trends.db, priced by _price_session_row (the dashboard's own number). Strictly
|
|
25961
26019
|
# read-only: the DB is opened mode=ro (WAL readers never block a writer) and,
|
|
25962
26020
|
# only if that open fails, immutable=1. Nothing here creates, migrates or
|
|
@@ -37268,7 +37326,8 @@ def compute_quality_score(quality_data, session_id=None):
|
|
|
37268
37326
|
elif _worst_key == "context_fill_degradation":
|
|
37269
37327
|
top_drag = {
|
|
37270
37328
|
"key": "context_fill",
|
|
37271
|
-
"label": f"{round(
|
|
37329
|
+
"label": (f"{round(model_fill * 100)}% context fill ({round(fill_pct * 100)}% of the way to auto-compact)"
|
|
37330
|
+
if compact_window_reduced else f"{round(fill_pct * 100)}% context fill"),
|
|
37272
37331
|
"points": round(_worst_pts, 1),
|
|
37273
37332
|
}
|
|
37274
37333
|
elif _worst_key == "compaction_depth":
|
|
@@ -37319,8 +37378,8 @@ def compute_quality_score(quality_data, session_id=None):
|
|
|
37319
37378
|
_cfd_detail = f"{round(fill_pct * 100)}% fill, {band_name.lower()} ({curve_name})"
|
|
37320
37379
|
if compact_window_reduced:
|
|
37321
37380
|
_cfd_detail = (
|
|
37322
|
-
f"{round(
|
|
37323
|
-
f"({round(
|
|
37381
|
+
f"{round(model_fill * 100)}% of model window "
|
|
37382
|
+
f"({round(fill_pct * 100)}% of the way to auto-compact), "
|
|
37324
37383
|
f"{band_name.lower()} ({curve_name})"
|
|
37325
37384
|
)
|
|
37326
37385
|
|
|
@@ -40859,7 +40918,7 @@ def compact_capture(transcript_path=None, session_id=None, trigger="auto", cwd=N
|
|
|
40859
40918
|
lines.append("## Context Quality")
|
|
40860
40919
|
lines.append(
|
|
40861
40920
|
f"- Score: {quality_summary.get('grade', '?')} ({quality_summary.get('score', '?')}/100)"
|
|
40862
|
-
f" | Fill: {cfd.get('fill_pct',
|
|
40921
|
+
f" | Fill: {_format_context_fill(cfd.get('fill_pct'), cfd)}"
|
|
40863
40922
|
f" | Model: {cfd.get('model') or quality_summary.get('model') or 'unknown'}"
|
|
40864
40923
|
)
|
|
40865
40924
|
if cfd.get("quality_curve"):
|
|
@@ -43015,7 +43074,7 @@ def _continuity_prompt_hint(prompt_text="", session_id=None, cwd=None, max_age_m
|
|
|
43015
43074
|
if quality:
|
|
43016
43075
|
lines.append(
|
|
43017
43076
|
f"- Prior context quality: {quality.get('grade', '?')} "
|
|
43018
|
-
f"({quality.get('score', '?')}/100), fill {quality.get('breakdown', {}).get('context_fill_degradation', {}).get('fill_pct', '
|
|
43077
|
+
f"({quality.get('score', '?')}/100), fill {_format_context_fill(quality.get('breakdown', {}).get('context_fill_degradation', {}).get('fill_pct'), quality.get('breakdown', {}).get('context_fill_degradation', {}))}"
|
|
43019
43078
|
)
|
|
43020
43079
|
# Per-item relevance filter: a checkpoint that passed the
|
|
43021
43080
|
# same-project gate may still carry session-wide Key Decisions / Files that
|
|
@@ -43694,7 +43753,7 @@ def checkpoint_trigger(milestone=None, session_id=None, transcript_path=None, qu
|
|
|
43694
43753
|
transcript_path=str(filepath),
|
|
43695
43754
|
session_id=session_id,
|
|
43696
43755
|
trigger=trigger,
|
|
43697
|
-
fill_pct=result
|
|
43756
|
+
fill_pct=_model_window_fill(result),
|
|
43698
43757
|
quality_score=result.get("score"),
|
|
43699
43758
|
)
|
|
43700
43759
|
if not cp_path:
|
|
@@ -45868,8 +45927,11 @@ def _maybe_fresh_session_nudge(result, cache_path, quality_data, quiet=False):
|
|
|
45868
45927
|
saved_str = f"~{saved // 1000}K" if saved >= 1000 else f"~{saved}"
|
|
45869
45928
|
usd = _fresh_session_savings_usd(saved, session_id)
|
|
45870
45929
|
cost_str = f" (~${usd:.2f})" if usd >= 0.01 else ""
|
|
45930
|
+
# Share of the model window: what the user's meter shows (see _format_context_fill).
|
|
45931
|
+
shown = _model_window_fill(result)
|
|
45932
|
+
shown = shown if isinstance(shown, (int, float)) else fill_pct
|
|
45871
45933
|
return (
|
|
45872
|
-
f"[Token Optimizer] {int(
|
|
45934
|
+
f"[Token Optimizer] {int(shown)}% full, quality {score}. "
|
|
45873
45935
|
f"Fresh session reclaims {saved_str}{cost_str}. "
|
|
45874
45936
|
f"Checkpoint saved, say \"continue this\"."
|
|
45875
45937
|
)
|
|
@@ -56533,6 +56595,43 @@ def _format_reduced_window_note(cached, model_window, model_size):
|
|
|
56533
56595
|
return f" (of {_format_window_size(compact)} compact window, {share}{model_size} model window{origin})"
|
|
56534
56596
|
|
|
56535
56597
|
|
|
56598
|
+
def _format_context_fill(fill_pct, cached):
|
|
56599
|
+
"""The fill phrase every model-facing message uses, e.g. "38% of 1M window".
|
|
56600
|
+
|
|
56601
|
+
Leads with the share of the MODEL window: the number the user's own context
|
|
56602
|
+
meter shows. With a reduced compact window the compact share follows as
|
|
56603
|
+
distance to auto-compact. Models quote the first number they read; leading
|
|
56604
|
+
with the compact share made sessions report "76% full" and offer handovers
|
|
56605
|
+
at 38% real fill.
|
|
56606
|
+
"""
|
|
56607
|
+
cached = cached or {}
|
|
56608
|
+
try:
|
|
56609
|
+
model_window = int(cached.get("model_context_window") or 0)
|
|
56610
|
+
compact = int(cached.get("compact_window") or 0)
|
|
56611
|
+
except (TypeError, ValueError, OverflowError):
|
|
56612
|
+
model_window = compact = 0
|
|
56613
|
+
model_fill = cached.get("model_fill_pct")
|
|
56614
|
+
if (cached.get("compact_window_reduced") and 0 < compact < model_window
|
|
56615
|
+
and isinstance(fill_pct, (int, float))):
|
|
56616
|
+
if not isinstance(model_fill, (int, float)):
|
|
56617
|
+
model_fill = fill_pct * compact / model_window
|
|
56618
|
+
source = _safe_note_text(cached.get("compact_window_source"), extra="=.[]'", limit=64)
|
|
56619
|
+
origin = f", source: {source}" if source else ""
|
|
56620
|
+
return (f"{model_fill:.0f}% of {_format_window_size(model_window)} window "
|
|
56621
|
+
f"(auto-compact at {_format_window_size(compact)}, {fill_pct:.0f}% of the way there{origin})")
|
|
56622
|
+
if not isinstance(fill_pct, (int, float)):
|
|
56623
|
+
return "?%"
|
|
56624
|
+
return f"{fill_pct:.0f}%{_format_window_note(cached)}"
|
|
56625
|
+
|
|
56626
|
+
|
|
56627
|
+
def _model_window_fill(result):
|
|
56628
|
+
"""Share of the model window for display; fill_pct when no reduction applies."""
|
|
56629
|
+
result = result or {}
|
|
56630
|
+
if result.get("compact_window_reduced") and isinstance(result.get("model_fill_pct"), (int, float)):
|
|
56631
|
+
return result["model_fill_pct"]
|
|
56632
|
+
return result.get("fill_pct")
|
|
56633
|
+
|
|
56634
|
+
|
|
56536
56635
|
def _format_window_note(cached):
|
|
56537
56636
|
"""Render the denominator and its origin, e.g. " (1M window, source: default 1M)".
|
|
56538
56637
|
|
|
@@ -56865,7 +56964,7 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
56865
56964
|
if fill_pct >= 90:
|
|
56866
56965
|
if not quiet:
|
|
56867
56966
|
sys.stderr.write(
|
|
56868
|
-
f"[Token Optimizer] Context at {fill_pct
|
|
56967
|
+
f"[Token Optimizer] Context at {_format_context_fill(fill_pct, cached)} — consider /compact or /clear. "
|
|
56869
56968
|
f"Verbosity nudge suppressed to avoid adding tokens.\n"
|
|
56870
56969
|
)
|
|
56871
56970
|
return ""
|
|
@@ -56894,7 +56993,7 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
56894
56993
|
# the Sonnet figure as the product number.
|
|
56895
56994
|
if fill_pct >= 75:
|
|
56896
56995
|
nudge = (
|
|
56897
|
-
f"[Token Optimizer] Context {fill_pct
|
|
56996
|
+
f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, resource health {score:.0f}/100. "
|
|
56898
56997
|
"Answer in a focused and spartan way, as if the user has ADHD. Cut everything "
|
|
56899
56998
|
"that is not the answer itself. Think as long as you need, and size code, "
|
|
56900
56999
|
"diffs and file contents to the task."
|
|
@@ -56902,7 +57001,7 @@ def run_verbosity_steer(transcript_path=None, quiet=True, session_id=None):
|
|
|
56902
57001
|
elif (fill_pct >= _VERBOSITY_NUDGE_MIN_FILL
|
|
56903
57002
|
and session_efficiency < _VERBOSITY_NUDGE_EFFICIENCY_THRESHOLD):
|
|
56904
57003
|
nudge = (
|
|
56905
|
-
f"[Token Optimizer] Context {fill_pct
|
|
57004
|
+
f"[Token Optimizer] Context {_format_context_fill(fill_pct, cached)}, "
|
|
56906
57005
|
f"session efficiency {session_efficiency:.0f}/100. "
|
|
56907
57006
|
"Answer in a focused and spartan way, as if the user has ADHD. "
|
|
56908
57007
|
"Think as long as you need, and size code, diffs and file contents to the task."
|
|
@@ -59324,7 +59423,7 @@ if __name__ == "__main__":
|
|
|
59324
59423
|
quiet = "--quiet" in args or "-q" in args
|
|
59325
59424
|
archive_result(quiet=quiet)
|
|
59326
59425
|
elif args[0] == "session-cost":
|
|
59327
|
-
# "What did the
|
|
59426
|
+
# "What did the Garden session yesterday cost?" Read-only; see session_cost_main.
|
|
59328
59427
|
sys.exit(session_cost_main(args[1:]))
|
|
59329
59428
|
elif args[0] == "expand":
|
|
59330
59429
|
# Retrieve archived tool result
|
|
@@ -59507,7 +59606,7 @@ if __name__ == "__main__":
|
|
|
59507
59606
|
print(" python3 measure.py attention-optimize --apply # Apply reordering (backup + write)")
|
|
59508
59607
|
print(" python3 measure.py archive-result # PostToolUse hook: archive large tool results")
|
|
59509
59608
|
print(" python3 measure.py archive-result --quiet # Silent mode (suppress stderr)")
|
|
59510
|
-
print(" python3 measure.py session-cost
|
|
59609
|
+
print(" python3 measure.py session-cost garden --date yesterday # What a session cost, in your words (read-only)")
|
|
59511
59610
|
print(" python3 measure.py session-cost --id UUID --json # One session by id, machine-readable")
|
|
59512
59611
|
print(" python3 measure.py expand TOOL_USE_ID # Retrieve archived tool result")
|
|
59513
59612
|
print(" python3 measure.py expand TOOL_USE_ID --session SID # Retrieve from specific session")
|