@alexgreensh/token-optimizer 5.13.52 → 5.13.54
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.54",
|
|
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.54",
|
|
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.54",
|
|
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)",
|
|
@@ -11,22 +11,50 @@ import json
|
|
|
11
11
|
import sys
|
|
12
12
|
import threading
|
|
13
13
|
|
|
14
|
+
# The wait for the first byte, and the longest pause allowed while a payload is
|
|
15
|
+
# still arriving. A host that opens stdin and then goes silent costs at most this.
|
|
14
16
|
_STDIN_TIMEOUT = 0.5
|
|
17
|
+
# Hard ceiling for the whole read. A multi-MB tool result can take longer than
|
|
18
|
+
# _STDIN_TIMEOUT to stream on a loaded machine; reading stops only when the host
|
|
19
|
+
# goes quiet or this ceiling is reached, never mid-stream at the first 0.5 s.
|
|
20
|
+
_STDIN_TOTAL_CAP = 5.0
|
|
15
21
|
|
|
16
22
|
|
|
17
23
|
def _read_stdin_windows(timeout: float = _STDIN_TIMEOUT, max_bytes: int = 1_048_576) -> str:
|
|
18
|
-
|
|
24
|
+
import time
|
|
25
|
+
chunks = []
|
|
26
|
+
state = {"done": False, "last": time.monotonic()}
|
|
19
27
|
|
|
20
28
|
def _reader() -> None:
|
|
21
29
|
try:
|
|
22
|
-
|
|
30
|
+
buf = sys.stdin.buffer
|
|
31
|
+
read = getattr(buf, "read1", buf.read)
|
|
32
|
+
total = 0
|
|
33
|
+
while total < max_bytes:
|
|
34
|
+
chunk = read(min(65536, max_bytes - total))
|
|
35
|
+
if not chunk:
|
|
36
|
+
break
|
|
37
|
+
chunks.append(chunk)
|
|
38
|
+
total += len(chunk)
|
|
39
|
+
state["last"] = time.monotonic()
|
|
23
40
|
except Exception:
|
|
24
41
|
pass
|
|
42
|
+
state["done"] = True
|
|
25
43
|
|
|
26
44
|
t = threading.Thread(target=_reader, daemon=True)
|
|
27
45
|
t.start()
|
|
28
|
-
|
|
29
|
-
|
|
46
|
+
start = time.monotonic()
|
|
47
|
+
# Keep waiting while bytes keep arriving; give up after `timeout` of silence
|
|
48
|
+
# or at the total ceiling. A partial payload is not valid JSON, so a cut-off
|
|
49
|
+
# read degrades to {} exactly as a timeout always did.
|
|
50
|
+
while not state["done"]:
|
|
51
|
+
t.join(0.05)
|
|
52
|
+
now = time.monotonic()
|
|
53
|
+
if now - state["last"] >= timeout or now - start >= _STDIN_TOTAL_CAP:
|
|
54
|
+
break
|
|
55
|
+
if not state["done"]:
|
|
56
|
+
return ""
|
|
57
|
+
return b"".join(chunks).decode("utf-8", errors="replace")
|
|
30
58
|
|
|
31
59
|
|
|
32
60
|
def read_stdin_hook_input(max_bytes: int = 1_048_576) -> dict:
|
|
@@ -49,14 +77,12 @@ def read_stdin_hook_input(max_bytes: int = 1_048_576) -> dict:
|
|
|
49
77
|
import os
|
|
50
78
|
import select
|
|
51
79
|
import time
|
|
52
|
-
#
|
|
53
|
-
#
|
|
54
|
-
#
|
|
55
|
-
#
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
remaining = deadline - time.monotonic()
|
|
59
|
-
if remaining <= 0 or not select.select([sys.stdin], [], [], remaining)[0]:
|
|
80
|
+
# Two clocks: the first byte must arrive within _STDIN_TIMEOUT, and
|
|
81
|
+
# after that each pause may last up to _STDIN_TIMEOUT, all inside
|
|
82
|
+
# one _STDIN_TOTAL_CAP deadline set BEFORE the first select. A
|
|
83
|
+
# payload still streaming is never cut off at the first 0.5 s.
|
|
84
|
+
deadline = time.monotonic() + _STDIN_TOTAL_CAP
|
|
85
|
+
if not select.select([sys.stdin], [], [], _STDIN_TIMEOUT)[0]:
|
|
60
86
|
return {}
|
|
61
87
|
try:
|
|
62
88
|
fd = sys.stdin.fileno()
|
|
@@ -68,15 +94,15 @@ def read_stdin_hook_input(max_bytes: int = 1_048_576) -> dict:
|
|
|
68
94
|
# host that writes a partial payload and holds the pipe open
|
|
69
95
|
# defeats the timeout. Read what is actually available in a loop
|
|
70
96
|
# bounded by the same deadline, assembling chunked payloads
|
|
71
|
-
# without ever blocking past _STDIN_TIMEOUT.
|
|
97
|
+
# without ever blocking on a silent pipe past _STDIN_TIMEOUT.
|
|
72
98
|
chunks = []
|
|
73
99
|
total = 0
|
|
74
100
|
while total < max_bytes:
|
|
75
101
|
remaining = deadline - time.monotonic()
|
|
76
102
|
if remaining <= 0:
|
|
77
103
|
break
|
|
78
|
-
if not select.select([sys.stdin], [], [], remaining)[0]:
|
|
79
|
-
break #
|
|
104
|
+
if not select.select([sys.stdin], [], [], min(_STDIN_TIMEOUT, remaining))[0]:
|
|
105
|
+
break # the host went quiet: take what arrived
|
|
80
106
|
chunk = os.read(fd, max_bytes - total)
|
|
81
107
|
if not chunk:
|
|
82
108
|
break # EOF: host closed stdin, payload complete
|
|
@@ -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()]
|
|
@@ -34846,6 +34904,15 @@ def setup_daemon(dry_run=False, uninstall=False, this_install_only=False, latch_
|
|
|
34846
34904
|
# the quality-bar install path. Skipped on dry-run (side-effect-free).
|
|
34847
34905
|
if not dry_run:
|
|
34848
34906
|
_set_daemon_disabled(False)
|
|
34907
|
+
# Every platform's uninstall leaves a permanent tombstone the daemon
|
|
34908
|
+
# obeys forever; an explicit install is what clears it. Done here, not
|
|
34909
|
+
# per installer: only the launchd installer cleared it, so on Windows
|
|
34910
|
+
# and Linux `setup-daemon` after `--uninstall` left the daemon dead.
|
|
34911
|
+
try:
|
|
34912
|
+
if DAEMON_THRASH_BREADCRUMB.exists():
|
|
34913
|
+
DAEMON_THRASH_BREADCRUMB.unlink()
|
|
34914
|
+
except OSError:
|
|
34915
|
+
pass
|
|
34849
34916
|
if system == "Darwin":
|
|
34850
34917
|
_installed_ok = _install_launchd_daemon(dry_run=dry_run, effective_host=effective_host)
|
|
34851
34918
|
elif system == "Windows":
|
|
@@ -36045,7 +36112,20 @@ def _heal_windows_console_flash():
|
|
|
36045
36112
|
if _daemon_resurrection_blocked() is not None:
|
|
36046
36113
|
return False
|
|
36047
36114
|
healed_shim = _heal_windows_launcher_shim()
|
|
36048
|
-
healed_task =
|
|
36115
|
+
healed_task = False
|
|
36116
|
+
# Reading the task's action costs a `schtasks /Query`. A healthy install
|
|
36117
|
+
# needs no heal, so look at most once per ensure-throttle window instead of
|
|
36118
|
+
# on every SessionStart. Stamped before the read, like the heal throttle.
|
|
36119
|
+
try:
|
|
36120
|
+
last = float(_read_config_flag("last_windows_task_action_check", 0) or 0)
|
|
36121
|
+
except (TypeError, ValueError):
|
|
36122
|
+
last = 0.0
|
|
36123
|
+
if time.time() - last >= _daemon_ensure_throttle_seconds():
|
|
36124
|
+
try:
|
|
36125
|
+
_write_config_flag("last_windows_task_action_check", int(time.time()))
|
|
36126
|
+
except Exception:
|
|
36127
|
+
pass
|
|
36128
|
+
healed_task = _heal_windows_task_action(stop_first=True, throttle=True)
|
|
36049
36129
|
return bool(healed_shim or healed_task)
|
|
36050
36130
|
|
|
36051
36131
|
|