@alexgreensh/token-optimizer 5.13.59 → 5.13.60

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.59",
16
+ "version": "5.13.60",
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.59",
58
+ "version": "5.13.60",
59
59
  "author": {
60
60
  "name": "Alex Greenshpun",
61
61
  "url": "https://linkedin.com/in/alexgreensh"
@@ -7,7 +7,7 @@
7
7
  },
8
8
  "homepage": "https://github.com/alexgreensh/token-optimizer",
9
9
  "repository": "https://github.com/alexgreensh/token-optimizer",
10
- "version": "5.13.59",
10
+ "version": "5.13.60",
11
11
  "license": "PolyForm-Noncommercial-1.0.0",
12
12
  "keywords": [
13
13
  "token",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexgreensh/token-optimizer",
3
- "version": "5.13.59",
3
+ "version": "5.13.60",
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)",
@@ -361,13 +361,10 @@ def _engine_checks() -> list[dict[str, str]]:
361
361
  return [_check("OK", "Engine scripts", f"{len(REQUIRED_ENGINE_SCRIPTS)} present in {sdir}")]
362
362
 
363
363
 
364
- def _freshness_checks() -> list[dict[str, str]]:
365
- """WARN when the installed copies or plugin version lag the checkout."""
364
+ def _stale_files(plugin_dir: Path) -> list[str]:
365
+ """Installed plugin files that differ from this checkout's copies."""
366
366
  import hashlib # noqa: PLC0415
367
367
 
368
- plugin_dir = _plugin_install_dir(hermes_home())
369
- if not plugin_dir.is_dir():
370
- return []
371
368
  here = Path(__file__).resolve().parent
372
369
  stale = []
373
370
  for name in _COPIED_RUNTIME_MODULES:
@@ -385,6 +382,15 @@ def _freshness_checks() -> list[dict[str, str]]:
385
382
  stale.append(name)
386
383
  except OSError:
387
384
  continue
385
+ return stale
386
+
387
+
388
+ def _freshness_checks() -> list[dict[str, str]]:
389
+ """WARN when the installed copies or plugin version lag the checkout."""
390
+ plugin_dir = _plugin_install_dir(hermes_home())
391
+ if not plugin_dir.is_dir():
392
+ return []
393
+ stale = _stale_files(plugin_dir)
388
394
  if stale:
389
395
  return [_check("WARN", "Installed copy up to date",
390
396
  f"differs from this checkout: {', '.join(stale)}; re-run: python3 hermes_install.py")]
@@ -450,12 +456,7 @@ def _activation_check() -> list[dict[str, str]]:
450
456
  importable, else a conservative text scan).
451
457
  """
452
458
  hermes_root = hermes_home()
453
- cfg = None
454
- for name in _CONFIG_NAMES:
455
- candidate = hermes_root / name
456
- if candidate.exists():
457
- cfg = candidate
458
- break
459
+ cfg = _config_path(hermes_root)
459
460
 
460
461
  snippet_hint = f"add to Hermes config:\n{_ACTIVATION_SNIPPET}"
461
462
 
@@ -471,6 +472,27 @@ def _activation_check() -> list[dict[str, str]]:
471
472
  except OSError as exc:
472
473
  return [_check("WARN", "Plugin activation", f"could not read {cfg}: {exc}")]
473
474
 
475
+ if _config_enables_plugin(text):
476
+ # v5.11.1: use the full path, not just the basename, so the OK
477
+ # message is unambiguous about which config was checked.
478
+ return [_check("OK", "Plugin activation", f"token-optimizer allow-listed in {cfg}")]
479
+ return [_check(
480
+ "WARN",
481
+ "Plugin activation",
482
+ f"token-optimizer not under plugins.enabled in {cfg}; {snippet_hint}",
483
+ )]
484
+
485
+
486
+ def _config_path(hermes_root: Path) -> Path | None:
487
+ for name in _CONFIG_NAMES:
488
+ candidate = hermes_root / name
489
+ if candidate.exists():
490
+ return candidate
491
+ return None
492
+
493
+
494
+ def _config_enables_plugin(text: str) -> bool:
495
+ """Is token-optimizer listed under plugins.enabled in this config text?"""
474
496
  enabled = False
475
497
  try:
476
498
  import yaml # type: ignore[import] # noqa: PLC0415
@@ -483,16 +505,59 @@ def _activation_check() -> list[dict[str, str]]:
483
505
  enabled = _PLUGIN_NAME in [str(x).strip() for x in listed]
484
506
  except Exception: # noqa: BLE001 — PyYAML absent or unparseable; fall back to text scan
485
507
  enabled = _activation_text_scan(text)
508
+ return enabled
486
509
 
487
- if enabled:
488
- # v5.11.1: use the full path, not just the basename, so the OK
489
- # message is unambiguous about which config was checked.
490
- return [_check("OK", "Plugin activation", f"token-optimizer allow-listed in {cfg}")]
491
- return [_check(
492
- "WARN",
493
- "Plugin activation",
494
- f"token-optimizer not under plugins.enabled in {cfg}; {snippet_hint}",
495
- )]
510
+
511
+ def _profile_homes(home: Path) -> list[tuple[str, Path]]:
512
+ """Every Hermes profile next to ``home``: the root home plus profiles/<name>.
513
+
514
+ Empty for a single-profile setup (no profiles directory), so the doctor
515
+ only talks about profiles to people who have them.
516
+ """
517
+ root = home.parent.parent if home.parent.name == "profiles" else home
518
+ profiles_dir = root / "profiles"
519
+ try:
520
+ named = sorted(
521
+ (d.name, d) for d in profiles_dir.iterdir() if d.is_dir() and not d.is_symlink()
522
+ )
523
+ except OSError:
524
+ return []
525
+ if not named:
526
+ return []
527
+ return [("default", root), *named]
528
+
529
+
530
+ def _profile_checks() -> list[dict[str, str]]:
531
+ """One line per Hermes profile: is the plugin installed, enabled, current?
532
+
533
+ With gateway.multiplex_profiles one gateway runs every profile's hooks,
534
+ and each profile only reports into its own dashboard when the plugin is
535
+ installed and allow-listed THERE. A profile left on an older install keeps
536
+ the old behavior, so name it.
537
+ """
538
+ profiles = _profile_homes(hermes_home())
539
+ if not profiles:
540
+ return []
541
+ states: list[str] = []
542
+ fixes: list[str] = []
543
+ for name, root in profiles:
544
+ if not (_plugin_install_dir(root) / "__init__.py").is_file():
545
+ states.append(f"{name}: not installed")
546
+ continue
547
+ cfg = _config_path(root)
548
+ try:
549
+ enabled = cfg is not None and _config_enables_plugin(cfg.read_text(encoding="utf-8"))
550
+ except OSError:
551
+ enabled = False
552
+ stale = _stale_files(_plugin_install_dir(root))
553
+ problems = ([] if enabled else ["not enabled"]) + (["out of date"] if stale else [])
554
+ states.append(f"{name}: {', '.join(problems) if problems else 'installed, enabled, current'}")
555
+ if problems:
556
+ fixes.append(f"HERMES_HOME={root} python3 measure.py hermes-install --enable")
557
+ detail = "; ".join(states)
558
+ if fixes:
559
+ return [_check("WARN", "Hermes profiles", f"{detail}. Fix: " + " ; ".join(fixes))]
560
+ return [_check("OK", "Hermes profiles", detail)]
496
561
 
497
562
 
498
563
  def _activation_text_scan(text: str) -> bool:
@@ -606,6 +671,7 @@ def run_checks() -> list[dict[str, str]]:
606
671
  checks.extend(_engine_checks())
607
672
  checks.extend(_freshness_checks())
608
673
  checks.extend(_activation_check())
674
+ checks.extend(_profile_checks())
609
675
  checks.extend(_state_db_checks())
610
676
  checks.append(_dashboard_port_check())
611
677
  return checks
@@ -118,6 +118,44 @@ def _locate_measure_py() -> Path | None:
118
118
  return None
119
119
 
120
120
 
121
+ # ---------------------------------------------------------------------------
122
+ # Active Hermes profile home
123
+ # ---------------------------------------------------------------------------
124
+ #
125
+ # One Hermes process can serve several profiles (gateway.multiplex_profiles,
126
+ # cron ticking every profile's jobs, the desktop app). Hermes binds the profile
127
+ # a hook runs for with a context-local override that
128
+ # hermes_constants.get_hermes_home() reads; os.environ["HERMES_HOME"] keeps
129
+ # naming the LAUNCH profile. Every child below therefore gets the active
130
+ # profile's home in HERMES_HOME, so it reads that profile's state.db and writes
131
+ # that profile's trends.db, checkpoints, archive and read cache. Outside Hermes
132
+ # (or on a Hermes without the override) this is the env var, as before.
133
+
134
+ _HERMES_ENV = {"TOKEN_OPTIMIZER_RUNTIME": "hermes", "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
135
+
136
+
137
+ def active_hermes_home() -> str:
138
+ """Home of the Hermes profile the current hook runs for ("" = default)."""
139
+ try:
140
+ from hermes_constants import get_hermes_home # noqa: PLC0415
141
+
142
+ home = get_hermes_home()
143
+ if home:
144
+ return str(Path(home).expanduser())
145
+ except Exception:
146
+ pass
147
+ return os.environ.get("HERMES_HOME", "").strip()
148
+
149
+
150
+ def _child_env(**extra: str) -> dict:
151
+ """Environment for a child engine process, pinned to the active profile."""
152
+ env = {**os.environ, **_HERMES_ENV, **extra}
153
+ home = active_hermes_home()
154
+ if home:
155
+ env["HERMES_HOME"] = home
156
+ return env
157
+
158
+
121
159
  # ---------------------------------------------------------------------------
122
160
  # Internal subprocess helper
123
161
  # ---------------------------------------------------------------------------
@@ -139,8 +177,7 @@ def _run_measure(args: list[str], *, capture_output: bool = True, timeout: int =
139
177
  encoding="utf-8",
140
178
  errors="replace",
141
179
  timeout=timeout,
142
- env={**os.environ, "TOKEN_OPTIMIZER_RUNTIME": "hermes",
143
- "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
180
+ env=_child_env(),
144
181
  creationflags=_NO_WINDOW,
145
182
  )
146
183
  if result.returncode != 0 and result.stderr:
@@ -207,8 +244,7 @@ def run_rollup(
207
244
  try:
208
245
  _proc = spawn_detached(
209
246
  cmd,
210
- env={**os.environ, "TOKEN_OPTIMIZER_RUNTIME": "hermes",
211
- "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
247
+ env=_child_env(),
212
248
  stdout=subprocess.DEVNULL,
213
249
  stderr=subprocess.DEVNULL,
214
250
  )
@@ -223,9 +259,7 @@ def run_rollup(
223
259
  try:
224
260
  spawn_detached(
225
261
  [sys.executable, str(measure_py), "dashboard", "--quiet"],
226
- env={**os.environ, "TOKEN_OPTIMIZER_RUNTIME": "hermes",
227
- "TOKEN_OPTIMIZER_INTERACTIVE": "1",
228
- "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
262
+ env=_child_env(TOKEN_OPTIMIZER_INTERACTIVE="1"),
229
263
  stdout=subprocess.DEVNULL,
230
264
  stderr=subprocess.DEVNULL,
231
265
  )
@@ -264,8 +298,7 @@ def run_dashboard(session_id: str = "", port: int = DASHBOARD_PORT) -> None:
264
298
  try:
265
299
  _proc = spawn_detached(
266
300
  args,
267
- env={**os.environ, "TOKEN_OPTIMIZER_RUNTIME": "hermes",
268
- "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
301
+ env=_child_env(),
269
302
  stdout=subprocess.DEVNULL,
270
303
  stderr=subprocess.DEVNULL,
271
304
  )
@@ -287,9 +320,6 @@ def run_dashboard(session_id: str = "", port: int = DASHBOARD_PORT) -> None:
287
320
  # broken engine can never stall or crash Hermes. All helpers fail open: they
288
321
  # return None / "" on any problem and the caller keeps the original output.
289
322
 
290
- _HERMES_ENV = {"TOKEN_OPTIMIZER_RUNTIME": "hermes", "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
291
-
292
-
293
323
  def scripts_dir() -> Path | None:
294
324
  """Directory holding measure.py and the engine scripts, or None."""
295
325
  measure_py = _locate_measure_py()
@@ -311,7 +341,7 @@ def _run_json(cmd: list[str], payload: dict, timeout: float) -> str:
311
341
  encoding="utf-8",
312
342
  errors="replace",
313
343
  timeout=max(0.1, float(timeout)),
314
- env={**os.environ, **_HERMES_ENV},
344
+ env=_child_env(),
315
345
  creationflags=_NO_WINDOW,
316
346
  )
317
347
  except subprocess.TimeoutExpired:
@@ -410,7 +440,7 @@ def spawn_checkpoint(
410
440
  try:
411
441
  proc = spawn_detached(
412
442
  cmd,
413
- env={**os.environ, **_HERMES_ENV},
443
+ env=_child_env(),
414
444
  stdout=subprocess.DEVNULL,
415
445
  stderr=subprocess.DEVNULL,
416
446
  )
@@ -177,9 +177,15 @@ def _is_safe_home_dir_relaxed(path: Path) -> bool:
177
177
  return False
178
178
 
179
179
 
180
- def hermes_home() -> Path:
181
- """Return the Hermes data directory, safely honoring HERMES_HOME when valid."""
182
- raw = os.environ.get(_HERMES_HOME_ENV, "").strip()
180
+ def hermes_home(home: str | os.PathLike | None = None) -> Path:
181
+ """Return the Hermes data directory, safely honoring HERMES_HOME when valid.
182
+
183
+ ``home`` names a profile home explicitly (the Hermes plugin passes the
184
+ profile whose hook is running: in a multiplexed gateway os.environ holds
185
+ the launch profile's HERMES_HOME, not the active one). It goes through the
186
+ same safety checks as the env var.
187
+ """
188
+ raw = str(home).strip() if home else os.environ.get(_HERMES_HOME_ENV, "").strip()
183
189
  if raw:
184
190
  candidate = Path(raw).expanduser()
185
191
  if _is_safe_home_dir(candidate):
@@ -197,9 +203,9 @@ def hermes_home() -> Path:
197
203
  return Path.home() / _DEFAULT_HERMES_DIR
198
204
 
199
205
 
200
- def state_db_path() -> Path:
201
- """Return the canonical path to Hermes's state.db."""
202
- return hermes_home() / _DB_NAME
206
+ def state_db_path(home: str | os.PathLike | None = None) -> Path:
207
+ """Return the canonical path to Hermes's state.db (of ``home`` when given)."""
208
+ return hermes_home(home) / _DB_NAME
203
209
 
204
210
 
205
211
  # ---------------------------------------------------------------------------
@@ -293,7 +299,9 @@ def _row_to_dict(row: sqlite3.Row, available_cols: set[str]) -> dict[str, Any]:
293
299
  # Public API
294
300
  # ---------------------------------------------------------------------------
295
301
 
296
- def get_session(session_id: str, *, live: bool = False) -> dict[str, Any] | None:
302
+ def get_session(
303
+ session_id: str, *, live: bool = False, home: str | os.PathLike | None = None,
304
+ ) -> dict[str, Any] | None:
297
305
  """Return a single session row as a dict, or None when not found.
298
306
 
299
307
  Absent DB or locked DB returns None gracefully. Missing columns in the
@@ -302,11 +310,12 @@ def get_session(session_id: str, *, live: bool = False) -> dict[str, Any] | None
302
310
  ``live=True`` opens the DB WAL-visible (plain ``mode=ro``) so a probe
303
311
  running alongside a live Hermes session sees writes that are committed but
304
312
  not yet checkpointed. The default keeps the immutable snapshot view used
305
- for collecting already-ended sessions.
313
+ for collecting already-ended sessions. ``home`` reads that profile's
314
+ state.db instead of the one HERMES_HOME names.
306
315
  """
307
316
  if not session_id:
308
317
  return None
309
- db = state_db_path()
318
+ db = state_db_path(home) if home else state_db_path()
310
319
  if not db.exists():
311
320
  return None
312
321
  try:
@@ -24716,6 +24716,36 @@ def hermes_checkpoint(session_id, trigger="stop", fill_pct=None, cwd=None):
24716
24716
  pass
24717
24717
 
24718
24718
 
24719
+ _HERMES_PROFILE_HELP = (
24720
+ "\nProfiles: reads and writes the Hermes home in HERMES_HOME (default ~/.hermes).\n"
24721
+ "For a profile: HERMES_HOME=~/.hermes/profiles/<name> measure.py <command>"
24722
+ )
24723
+ _HERMES_SUBCOMMAND_HELP = {
24724
+ "hermes-rollup": (
24725
+ "usage: measure.py hermes-rollup [--quiet] [--session ID] [--platform P] [--reason R]\n"
24726
+ " [--context-tokens N] [--skills-json JSON]\n\n"
24727
+ "Ingest the last 90 days of Hermes sessions from state.db into trends.db.\n"
24728
+ "Run by the Hermes plugin at session end; safe to run by hand (idempotent).\n"
24729
+ "--session, --platform and --reason are accepted for the plugin's call shape;\n"
24730
+ "every recent session is collected either way." + _HERMES_PROFILE_HELP
24731
+ ),
24732
+ "hermes-checkpoint": (
24733
+ "usage: measure.py hermes-checkpoint --session ID [--trigger T] [--fill-pct N]\n"
24734
+ " [--cwd DIR] [--quiet]\n\n"
24735
+ "Write a checkpoint for a Hermes session from its state.db messages." + _HERMES_PROFILE_HELP
24736
+ ),
24737
+ "hermes-turn-context": (
24738
+ "usage: measure.py hermes-turn-context < payload.json\n\n"
24739
+ "Per-turn context for the Hermes plugin (continuity pointer, prior-session hint,\n"
24740
+ "lean-output nudge). Reads one JSON payload on stdin, prints one JSON object." + _HERMES_PROFILE_HELP
24741
+ ),
24742
+ "hermes-summary": (
24743
+ "usage: measure.py hermes-summary [--days N] [--quiet] [--session ID]\n\n"
24744
+ "Ingest recent Hermes sessions, then print usage trends." + _HERMES_PROFILE_HELP
24745
+ ),
24746
+ }
24747
+
24748
+
24719
24749
  def _hermes_checkpoint_cli(args):
24720
24750
  """``hermes-checkpoint --session <id> [--trigger T] [--fill-pct N] [--cwd DIR] [--quiet]``."""
24721
24751
  sid = ""
@@ -28139,7 +28169,7 @@ def usage_trends(days=30, as_json=False):
28139
28169
 
28140
28170
  print(f"\nUSAGE TRENDS (last {days} days)")
28141
28171
  print("=" * 55)
28142
- print(f"\n Sessions: {session_count} | Avg duration: {avg_dur:.0f} min | Avg tokens/session: {_fmt_tokens(avg_in)} in / {_fmt_tokens(avg_out)} out")
28172
+ print(f"\n Sessions: {session_count} | Avg duration: {avg_dur:.0f} min | Avg tokens/session: {_fmt_tokens(avg_in)} in (incl. cache reads) / {_fmt_tokens(avg_out)} out")
28143
28173
 
28144
28174
  skill_sessions = trends["skills"]["used"]
28145
28175
  installed_count = trends["skills"]["installed_count"]
@@ -28181,7 +28211,9 @@ def usage_trends(days=30, as_json=False):
28181
28211
 
28182
28212
  total_model_tokens = trends["model_mix"]
28183
28213
  if total_model_tokens:
28184
- print("\nMODEL MIX")
28214
+ # Model shares count fresh input + output (cache reads excluded), unlike
28215
+ # the per-session average above; say so, or the two read as contradictory.
28216
+ print("\nMODEL MIX (share of tokens, excl. cache reads)")
28185
28217
  grand_total = sum(total_model_tokens.values())
28186
28218
  for model, tokens in sorted(total_model_tokens.items(), key=lambda x: -x[1]):
28187
28219
  pct = tokens / grand_total * 100 if grand_total else 0
@@ -58521,6 +58553,10 @@ if __name__ == "__main__":
58521
58553
  elif args[0] == "hermes-install":
58522
58554
  import hermes_install
58523
58555
  sys.exit(hermes_install.main(args[1:]))
58556
+ elif args[0] in _HERMES_SUBCOMMAND_HELP and ("--help" in args[1:] or "-h" in args[1:]):
58557
+ # Print usage, never run: `hermes-rollup --help` used to start a rollup.
58558
+ print(_HERMES_SUBCOMMAND_HELP[args[0]])
58559
+ sys.exit(0)
58524
58560
  elif args[0] == "hermes-rollup":
58525
58561
  # Ingest recent Hermes sessions into trends.db. Called by the Hermes
58526
58562
  # plugin's on_session_end hook via hermes_hook_bridge.run_rollup().