@alexgreensh/token-optimizer 5.13.57 → 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.
Files changed (29) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/hooks/hooks.json +16 -16
  4. package/hooks/python-launcher.sh +10 -0
  5. package/hooks/stop_runner.py +27 -4
  6. package/hooks/windows-launcher.py +57 -3
  7. package/package.json +1 -1
  8. package/skills/fleet-auditor/scripts/shared.py +29 -1
  9. package/skills/token-optimizer/pricing/prices.json +13 -1
  10. package/skills/token-optimizer/scripts/codex_doctor.py +78 -1
  11. package/skills/token-optimizer/scripts/codex_install.py +379 -41
  12. package/skills/token-optimizer/scripts/codex_session.py +38 -8
  13. package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
  14. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
  15. package/skills/token-optimizer/scripts/copilot_install.py +56 -4
  16. package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
  17. package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
  18. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  19. package/skills/token-optimizer/scripts/hermes_doctor.py +258 -16
  20. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +229 -9
  21. package/skills/token-optimizer/scripts/hermes_install.py +43 -0
  22. package/skills/token-optimizer/scripts/hermes_session.py +133 -0
  23. package/skills/token-optimizer/scripts/hermes_state.py +76 -9
  24. package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
  25. package/skills/token-optimizer/scripts/measure.py +1340 -321
  26. package/skills/token-optimizer/scripts/plugin_env.py +18 -0
  27. package/skills/token-optimizer/scripts/recovery_output.py +15 -2
  28. package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
  29. package/skills/token-optimizer/scripts/runtime_env.py +5 -1
@@ -61,6 +61,20 @@ _RUNTIME_MODULES = (
61
61
  "spawn_utils.py",
62
62
  )
63
63
 
64
+ # Engine scripts the plugin runs as child processes from THIS checkout (found
65
+ # through the measure-path locator, never copied, so they update with the
66
+ # checkout). Checked up front: a checkout missing one would install a plugin
67
+ # with that feature silently off.
68
+ _ENGINE_SCRIPTS = (
69
+ "hermes_tool_hooks.py",
70
+ "bash_compress_hook.py",
71
+ "archive_result.py",
72
+ "context_intel.py",
73
+ "read_cache.py",
74
+ "refetch_guard.py",
75
+ "credential_patterns.py",
76
+ )
77
+
64
78
  # Plain-text locator file written into the plugin dir: one line, the absolute
65
79
  # path to the canonical measure.py. hermes_hook_bridge._locate_measure_py reads
66
80
  # it. We do NOT copy measure.py itself (version-drift risk — nothing refreshes a
@@ -420,6 +434,12 @@ def install(
420
434
  "It must sit next to hermes_install.py for the plugin to import it."
421
435
  )
422
436
  runtime_srcs.append(src)
437
+ missing_engines = [name for name in _ENGINE_SCRIPTS if not (scripts_dir / name).is_file()]
438
+ if missing_engines:
439
+ raise ValueError(
440
+ f"Token Optimizer engine scripts missing from {scripts_dir}: "
441
+ f"{', '.join(missing_engines)}. Update the checkout, then re-run the installer."
442
+ )
423
443
 
424
444
  hermes_root = hermes_home()
425
445
  install_dir = _plugin_install_dir(hermes_root)
@@ -450,6 +470,7 @@ def install(
450
470
  "plugin_dir": str(install_dir),
451
471
  "hermes_home": str(hermes_root),
452
472
  "files": listed_files,
473
+ "hooks": _declared_hooks(payload / "plugin.yaml"),
453
474
  "dry_run": dry_run,
454
475
  }
455
476
 
@@ -531,6 +552,26 @@ def install(
531
552
  return install_dir, "installed", details
532
553
 
533
554
 
555
+ def _declared_hooks(manifest: Path) -> list[str]:
556
+ """Hook names listed in plugin.yaml (simple text read; no PyYAML needed)."""
557
+ hooks: list[str] = []
558
+ try:
559
+ lines = manifest.read_text(encoding="utf-8").splitlines()
560
+ except OSError:
561
+ return hooks
562
+ in_hooks = False
563
+ for raw in lines:
564
+ stripped = raw.strip()
565
+ if not stripped or stripped.startswith("#"):
566
+ continue
567
+ if not raw[:1].isspace():
568
+ in_hooks = stripped in ("hooks:", "provides_hooks:")
569
+ continue
570
+ if in_hooks and stripped.startswith("- "):
571
+ hooks.append(stripped[2:].strip().strip("'\""))
572
+ return hooks
573
+
574
+
534
575
  def _activation_dry_run_note(hermes_root: Path, enable: bool) -> str:
535
576
  cfg = _config_path(hermes_root)
536
577
  if enable:
@@ -653,6 +694,8 @@ def main(argv: list[str] | None = None) -> int:
653
694
  prefix = "Would update" if args.dry_run else "Updated"
654
695
  n_files = len(details.get("files", []))
655
696
  print(f"[Token Optimizer] {prefix} {install_dir} ({action}; {n_files} files)")
697
+ if details.get("hooks"):
698
+ print(f"[Token Optimizer] Hooks: {len(details['hooks'])} ({', '.join(details['hooks'])})")
656
699
  if "activation" in details:
657
700
  print(f"[Token Optimizer] {details['activation']}")
658
701
  # v5.11.1: print the activation note on ALL uninstall outcomes,
@@ -672,6 +672,139 @@ def normalize_session(row: dict[str, Any], *, context_tokens: int | None = None)
672
672
  }
673
673
 
674
674
 
675
+ # ---------------------------------------------------------------------------
676
+ # Checkpoint support: Hermes messages -> Claude-Code-shaped transcript records
677
+ # ---------------------------------------------------------------------------
678
+ #
679
+ # The shared checkpoint engine (measure.compact_capture) reads a Claude Code
680
+ # JSONL transcript. Hermes keeps its transcript in state.db instead, so we
681
+ # translate the message rows into the record shape that engine reads. Only the
682
+ # fields the engine looks at are produced: user text, assistant text, and
683
+ # tool_use blocks named like their Claude Code equivalents so file edits,
684
+ # reads, todos and delegated agents land in the right checkpoint sections.
685
+
686
+ # Progressive checkpoint fill bands and edit-batch thresholds. Mirrors of
687
+ # measure._PROGRESSIVE_BANDS / _EDIT_BATCH_*_THRESHOLD (pinned by a test) so
688
+ # the in-process Hermes plugin can decide when to checkpoint without importing
689
+ # the 60K-line measure module into the Hermes host.
690
+ PROGRESSIVE_BANDS = (20, 35, 50, 65, 80)
691
+ EDIT_BATCH_WRITE_THRESHOLD = 4
692
+ EDIT_BATCH_FILE_THRESHOLD = 3
693
+
694
+ # Hermes read_file's default line limit (tools/file_operations_common.py).
695
+ HERMES_DEFAULT_READ_LIMIT = 2000
696
+
697
+ _PATCH_FILE_RE = re.compile(r"^\*\*\* (?:Update|Add|Delete) File:\s*(.+?)\s*$", re.MULTILINE)
698
+
699
+
700
+ def _json_or(value: Any, default: Any) -> Any:
701
+ if isinstance(value, (dict, list)):
702
+ return value
703
+ if isinstance(value, str) and value.strip()[:1] in ("{", "["):
704
+ try:
705
+ import json as _json
706
+
707
+ return _json.loads(value)
708
+ except ValueError:
709
+ return default
710
+ return default
711
+
712
+
713
+ def _text_of(content: Any) -> str:
714
+ """Plain text of a Hermes message content (string or list of parts)."""
715
+ parsed = _json_or(content, None) if isinstance(content, str) else content
716
+ if isinstance(parsed, list):
717
+ parts = []
718
+ for part in parsed:
719
+ if isinstance(part, str):
720
+ parts.append(part)
721
+ elif isinstance(part, dict) and isinstance(part.get("text"), str):
722
+ parts.append(part["text"])
723
+ return "\n".join(p for p in parts if p)
724
+ return content if isinstance(content, str) else ""
725
+
726
+
727
+ def hermes_tool_to_claude(name: str, args: Any) -> list[tuple[str, dict]]:
728
+ """Map one Hermes tool call to Claude Code (name, input) pairs.
729
+
730
+ Returns a list because one Hermes call can stand for several Claude Code
731
+ calls (a multi-file patch, a delegate_task batch). Unknown tools keep their
732
+ Hermes name, so the checkpoint engine simply ignores them.
733
+ """
734
+ args = args if isinstance(args, dict) else {}
735
+ name = str(name or "")
736
+ if name == "read_file":
737
+ # Hermes: offset is 1-indexed (default 1), limit defaults to 2000 lines.
738
+ # Claude Code: offset/limit absent (0) means "the whole file". Map the
739
+ # Hermes defaults to absent so a plain read counts as a full read.
740
+ inp: dict = {"file_path": str(args.get("path") or "")}
741
+ offset = _safe_int(args.get("offset"), 0)
742
+ limit = _safe_int(args.get("limit"), 0)
743
+ if offset > 1:
744
+ inp["offset"] = offset
745
+ if limit > 0 and limit != HERMES_DEFAULT_READ_LIMIT:
746
+ inp["limit"] = limit
747
+ return [("Read", inp)]
748
+ if name == "write_file":
749
+ return [("Write", {"file_path": str(args.get("path") or "")})]
750
+ if name == "patch":
751
+ path = args.get("path")
752
+ if isinstance(path, str) and path:
753
+ return [("Edit", {"file_path": path})]
754
+ body = args.get("patch")
755
+ if isinstance(body, str):
756
+ return [("Edit", {"file_path": p}) for p in _PATCH_FILE_RE.findall(body)]
757
+ return []
758
+ if name == "terminal":
759
+ return [("Bash", {"command": str(args.get("command") or "")})]
760
+ if name == "todo_list":
761
+ todos = args.get("todos")
762
+ return [("TodoWrite", {"todos": todos if isinstance(todos, list) else []})]
763
+ if name == "delegate_task":
764
+ tasks = args.get("tasks")
765
+ if not isinstance(tasks, list):
766
+ tasks = [args]
767
+ out = []
768
+ for task in tasks:
769
+ if isinstance(task, dict):
770
+ goal = str(task.get("goal") or "")
771
+ out.append(("Agent", {"subagent_type": "delegate_task", "description": goal}))
772
+ return out
773
+ return [(name, args)]
774
+
775
+
776
+ def messages_to_transcript_records(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
777
+ """Translate Hermes message rows into Claude-Code-shaped transcript records.
778
+
779
+ ``tool`` and ``system`` rows are skipped: tool output is not task text and
780
+ must not become the checkpoint's "active task". Never raises.
781
+ """
782
+ records: list[dict[str, Any]] = []
783
+ for msg in messages or []:
784
+ if not isinstance(msg, dict):
785
+ continue
786
+ role = msg.get("role")
787
+ if role == "user":
788
+ text = _text_of(msg.get("content"))
789
+ if text.strip():
790
+ records.append({"type": "user", "message": {"role": "user", "content": text}})
791
+ elif role == "assistant":
792
+ blocks: list[dict[str, Any]] = []
793
+ text = _text_of(msg.get("content"))
794
+ if text.strip():
795
+ blocks.append({"type": "text", "text": text})
796
+ for call in _json_or(msg.get("tool_calls"), []) or []:
797
+ if not isinstance(call, dict):
798
+ continue
799
+ fn = call.get("function") if isinstance(call.get("function"), dict) else call
800
+ tool_args = _json_or(fn.get("arguments"), fn.get("arguments") or {})
801
+ for cc_name, cc_input in hermes_tool_to_claude(fn.get("name"), tool_args):
802
+ blocks.append({"type": "tool_use", "name": cc_name, "input": cc_input})
803
+ if blocks:
804
+ records.append({"type": "assistant", "message": {"role": "assistant", "content": blocks}})
805
+ return records
806
+
807
+
675
808
  if __name__ == "__main__":
676
809
  import json
677
810
  import sys as _sys
@@ -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:
@@ -412,6 +421,64 @@ def session_token_totals(session_id: str) -> dict[str, Any]:
412
421
  }
413
422
 
414
423
 
424
+ # Message columns the checkpoint builder reads. Content-bearing columns are
425
+ # capped per row so one huge tool result cannot balloon a checkpoint read.
426
+ _MESSAGE_COLUMNS = ("id", "role", "content", "tool_call_id", "tool_calls", "tool_name", "timestamp")
427
+ _MESSAGE_TEXT_CAP = 20_000
428
+ _MAX_MESSAGE_ROWS = 2_000
429
+
430
+
431
+ def session_messages(
432
+ session_id: str, *, limit: int = 500, live: bool = True
433
+ ) -> list[dict[str, Any]]:
434
+ """Return the last ``limit`` message rows of a session, oldest first.
435
+
436
+ Read-only, like every reader here. Rows are returned whether or not Hermes
437
+ has since compacted them away (``active``/``compacted`` are ignored on
438
+ purpose): a pre-compaction checkpoint must see what the model saw. Each row
439
+ is a dict with ``role``, ``content``, ``tool_calls`` (raw JSON text),
440
+ ``tool_name``, ``tool_call_id`` and ``timestamp``; text is capped per row.
441
+
442
+ ``live=True`` (default) opens the WAL-visible view so a checkpoint written
443
+ during a live session sees the latest turns. Never raises: an absent,
444
+ locked, or unexpected DB yields an empty list.
445
+ """
446
+ if not session_id:
447
+ return []
448
+ db = state_db_path()
449
+ if not db.exists():
450
+ return []
451
+ limit = max(1, min(int(limit or 1), _MAX_MESSAGE_ROWS))
452
+ try:
453
+ with _ro_connect(db, immutable=not live) as conn:
454
+ available = _table_columns(conn, "messages")
455
+ if not available or "session_id" not in available or "role" not in available:
456
+ return []
457
+ cols = [c for c in _MESSAGE_COLUMNS if c in available]
458
+ order = "id" if "id" in available else ("timestamp" if "timestamp" in available else "rowid")
459
+ sql = (
460
+ f"SELECT {', '.join(cols)} FROM messages WHERE session_id = ? "
461
+ f"ORDER BY {order} DESC LIMIT ?"
462
+ )
463
+ rows = conn.execute(sql, (session_id, limit)).fetchall()
464
+ except (sqlite3.Error, OSError) as exc:
465
+ logger.debug("[hermes_state] session_messages(%r) error: %s", session_id, exc)
466
+ return []
467
+ out: list[dict[str, Any]] = []
468
+ for row in reversed(rows):
469
+ item: dict[str, Any] = {}
470
+ for col in cols:
471
+ try:
472
+ val = row[col]
473
+ except (IndexError, KeyError):
474
+ val = None
475
+ if isinstance(val, str) and len(val) > _MESSAGE_TEXT_CAP:
476
+ val = val[:_MESSAGE_TEXT_CAP]
477
+ item[col] = val
478
+ out.append(item)
479
+ return out
480
+
481
+
415
482
  def db_status() -> dict[str, Any]:
416
483
  """Lightweight presence/readability report for the doctor."""
417
484
  db = state_db_path()
@@ -0,0 +1,291 @@
1
+ #!/usr/bin/env python3
2
+ """Hermes tool-hook dispatcher for Token Optimizer.
3
+
4
+ The Hermes plugin (``hermes/__init__.py``) runs inside the Hermes process. To
5
+ keep that process clean, every per-tool engine call happens here, in a short
6
+ child process, fed one Claude-Code-shaped payload on stdin. The engines are the
7
+ SAME ones the Claude Code PostToolUse / PreToolUse hooks run; this file only
8
+ routes a payload to them and normalizes what they print. No engine logic lives
9
+ here.
10
+
11
+ python3 hermes_tool_hooks.py post-tool < payload.json
12
+ python3 hermes_tool_hooks.py pre-tool < payload.json
13
+ python3 hermes_tool_hooks.py clear-reads < payload.json
14
+ python3 hermes_tool_hooks.py redaction-patterns
15
+
16
+ Output is ONE JSON object on stdout (or nothing):
17
+
18
+ post-tool: {"replacement": str | null, "notes": [str, ...]}
19
+ pre-tool: {"block": str | null, "notes": [str, ...]}
20
+ clear-reads: {}
21
+ redaction-patterns: {"patterns": [str, ...]}
22
+
23
+ Engines run here (post-tool), by Claude Code tool name:
24
+ - bash_compress_hook (Bash): output compression, cross-turn dedup, loop
25
+ detection (thrash guard), archive + expand pointer, savings logging.
26
+ - archive_result (Bash|Read|Glob|Grep|Agent|mcp__*): archive large
27
+ results; MCP results are replaced by a preview + expand pointer.
28
+ - context_intel (most tools): activity mode + decision extraction.
29
+ - read_cache --invalidate (Edit|Write): keep delta reads correct after edits.
30
+
31
+ The Claude Code runner's quality-cache tick is deliberately NOT run: with no
32
+ transcript for Hermes it would fall back to the most recently modified Claude
33
+ Code transcript and score the wrong session.
34
+
35
+ Fail-open everywhere: any error prints nothing and exits 0, so the caller keeps
36
+ the original tool output.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import io
42
+ import json
43
+ import os
44
+ import re
45
+ import sys
46
+ from contextlib import redirect_stdout
47
+ from pathlib import Path
48
+
49
+ _SCRIPT_DIR = Path(__file__).resolve().parent
50
+ if str(_SCRIPT_DIR) not in sys.path:
51
+ sys.path.insert(0, str(_SCRIPT_DIR))
52
+
53
+ # Same cap the Claude Code PostToolUse runner uses (archive_result's limit).
54
+ _STDIN_MAX_BYTES = 5_242_880 + 262_144
55
+
56
+ # Matchers copied from hooks/posttooluse_runner.py (searched, not anchored).
57
+ _MATCH_BASH_COMPRESS = re.compile("Bash")
58
+ _MATCH_ARCHIVE = re.compile("Bash|PowerShell|Read|Glob|Grep|Agent|mcp__.*")
59
+ _MATCH_CONTEXT_INTEL = re.compile(
60
+ "Bash|PowerShell|Read|Grep|Glob|Edit|Write|MultiEdit|NotebookEdit|mcp__.*"
61
+ )
62
+ _MATCH_READ_INVALIDATE = re.compile("Edit|Write|MultiEdit|NotebookEdit")
63
+
64
+
65
+ def _read_payload() -> dict:
66
+ try:
67
+ from hook_io import read_stdin_hook_input
68
+
69
+ data = read_stdin_hook_input(_STDIN_MAX_BYTES)
70
+ except Exception:
71
+ return {}
72
+ return data if isinstance(data, dict) else {}
73
+
74
+
75
+ def _share_payload(payload: dict) -> None:
76
+ """Every engine reads stdin through hook_io; hand them all this payload."""
77
+
78
+ def _shared(max_bytes=None, *_a, **_kw):
79
+ return dict(payload)
80
+
81
+ try:
82
+ import hook_io
83
+
84
+ hook_io.read_stdin_hook_input = _shared
85
+ except Exception:
86
+ pass
87
+
88
+
89
+ def _rebind(module) -> None:
90
+ """Re-patch a module that bound read_stdin_hook_input at import time."""
91
+ try:
92
+ if hasattr(module, "read_stdin_hook_input"):
93
+ import hook_io
94
+
95
+ module.read_stdin_hook_input = hook_io.read_stdin_hook_input
96
+ except Exception:
97
+ pass
98
+
99
+
100
+ def _capture(fn, *args, **kwargs) -> str:
101
+ """Run one engine, return what it printed. Never raises."""
102
+ buf = io.StringIO()
103
+ try:
104
+ with redirect_stdout(buf):
105
+ fn(*args, **kwargs)
106
+ except BaseException: # SystemExit included: an engine must not end the dispatcher
107
+ pass
108
+ return buf.getvalue()
109
+
110
+
111
+ def _json_objects(text: str) -> list[dict]:
112
+ """Parse every JSON object line an engine printed."""
113
+ out: list[dict] = []
114
+ for line in (text or "").splitlines():
115
+ line = line.strip()
116
+ if not line.startswith("{"):
117
+ continue
118
+ try:
119
+ obj = json.loads(line)
120
+ except ValueError:
121
+ continue
122
+ if isinstance(obj, dict):
123
+ out.append(obj)
124
+ return out
125
+
126
+
127
+ def _collect(objs: list[dict], result: dict) -> None:
128
+ """Fold Claude Code hook envelopes into the normalized result."""
129
+ for obj in objs:
130
+ hso = obj.get("hookSpecificOutput")
131
+ if isinstance(hso, dict):
132
+ updated = hso.get("updatedToolOutput")
133
+ if isinstance(updated, dict) and isinstance(updated.get("stdout"), str):
134
+ text = updated["stdout"]
135
+ stderr = updated.get("stderr")
136
+ if isinstance(stderr, str) and stderr:
137
+ text = f"{text}\n{stderr}" if text else stderr
138
+ result["replacement"] = text
139
+ mcp = hso.get("updatedMCPToolOutput")
140
+ if isinstance(mcp, str):
141
+ result["replacement"] = mcp
142
+ ctx = hso.get("additionalContext")
143
+ if isinstance(ctx, str) and ctx.strip():
144
+ result["notes"].append(ctx.strip())
145
+ if hso.get("permissionDecision") == "deny":
146
+ reason = hso.get("permissionDecisionReason")
147
+ if isinstance(reason, str) and reason.strip():
148
+ result["block"] = reason.strip()
149
+ msg = obj.get("systemMessage")
150
+ if isinstance(msg, str) and msg.strip():
151
+ result["notes"].append(msg.strip())
152
+
153
+
154
+ def _bash_compress_enabled() -> bool:
155
+ """The same switch every other bridge honours (env var or dashboard)."""
156
+ try:
157
+ from plugin_env import is_v5_flag_enabled
158
+
159
+ return bool(is_v5_flag_enabled("v5_bash_compress", "TOKEN_OPTIMIZER_BASH_COMPRESS", default=True))
160
+ except Exception:
161
+ return True
162
+
163
+
164
+ def run_post_tool(payload: dict) -> dict:
165
+ result: dict = {"replacement": None, "notes": []}
166
+ tool_name = str(payload.get("tool_name") or "")
167
+ if not tool_name or not payload.get("session_id"):
168
+ return result
169
+ _share_payload(payload)
170
+
171
+ if _MATCH_BASH_COMPRESS.search(tool_name):
172
+ import bash_compress_hook
173
+
174
+ if not _bash_compress_enabled():
175
+ # The user turned compression off (env or dashboard toggle). Keep
176
+ # loop detection: the hook's nudge-only mode skips the compression
177
+ # compute and still reports reruns.
178
+ os.environ["TOKEN_OPTIMIZER_NO_UPDATED_TOOL_OUTPUT"] = "1"
179
+ _rebind(bash_compress_hook)
180
+ _collect(_json_objects(_capture(bash_compress_hook.main)), result)
181
+ if _MATCH_ARCHIVE.search(tool_name) and result["replacement"] is None:
182
+ # Bash output already compressed and archived by bash_compress_hook
183
+ # never needs a second archive copy; everything else goes through.
184
+ import archive_result
185
+
186
+ _rebind(archive_result)
187
+ _collect(_json_objects(_capture(archive_result.archive_result, quiet=True)), result)
188
+ if _MATCH_CONTEXT_INTEL.search(tool_name):
189
+ import context_intel
190
+
191
+ _rebind(context_intel)
192
+ _capture(context_intel.handle_post_tool_use)
193
+ if _MATCH_READ_INVALIDATE.search(tool_name):
194
+ import read_cache
195
+
196
+ _capture(read_cache.handle_invalidate, dict(payload), True)
197
+ return result
198
+
199
+
200
+ def run_pre_tool(payload: dict) -> dict:
201
+ result: dict = {"block": None, "notes": []}
202
+ tool_name = str(payload.get("tool_name") or "")
203
+ if not tool_name:
204
+ return result
205
+ _share_payload(payload)
206
+
207
+ if tool_name == "Read":
208
+ import read_cache
209
+
210
+ _rebind(read_cache)
211
+ saved_argv = sys.argv
212
+ try:
213
+ sys.argv = ["read_cache.py", "--quiet"]
214
+ _collect(_json_objects(_capture(read_cache.main)), result)
215
+ finally:
216
+ sys.argv = saved_argv
217
+ elif tool_name.startswith("mcp__"):
218
+ import refetch_guard
219
+
220
+ _rebind(refetch_guard)
221
+ _collect(_json_objects(_capture(refetch_guard.refetch_guard)), result)
222
+ return result
223
+
224
+
225
+ def run_clear_reads(payload: dict) -> dict:
226
+ if not payload.get("session_id"):
227
+ return {}
228
+ import read_cache
229
+
230
+ _capture(read_cache.handle_clear_compacted, dict(payload), True)
231
+ return {}
232
+
233
+
234
+ def run_redaction_patterns(_payload: dict) -> dict:
235
+ """Credential regexes (built-in + the user's custom file for this runtime).
236
+
237
+ The plugin hands these to Hermes's own redactor. Loaded here, under the
238
+ Hermes runtime, so the custom pattern file is the one the engines use.
239
+ A broken custom file contributes nothing; the built-ins still go.
240
+ """
241
+ import credential_patterns
242
+
243
+ compiled = list(getattr(credential_patterns, "PATTERNS_ONLY", []))
244
+ try:
245
+ compiled += [pat for _, pat in credential_patterns.get_custom_patterns()]
246
+ except Exception:
247
+ pass
248
+ seen: list[str] = []
249
+ for pat in compiled:
250
+ text = getattr(pat, "pattern", None)
251
+ if isinstance(text, str) and text not in seen:
252
+ seen.append(text)
253
+ return {"patterns": seen}
254
+
255
+
256
+ _HANDLERS = {
257
+ "post-tool": run_post_tool,
258
+ "pre-tool": run_pre_tool,
259
+ "clear-reads": run_clear_reads,
260
+ "redaction-patterns": run_redaction_patterns,
261
+ }
262
+ # Events that need no stdin payload.
263
+ _NO_PAYLOAD = frozenset({"redaction-patterns"})
264
+
265
+
266
+ def main(argv: list[str] | None = None) -> int:
267
+ args = list(sys.argv[1:] if argv is None else argv)
268
+ if not args or args[0] not in _HANDLERS:
269
+ return 0
270
+ os.environ.setdefault("TOKEN_OPTIMIZER_RUNTIME", "hermes")
271
+ try:
272
+ from utf8_io import enforce_utf8_io
273
+
274
+ enforce_utf8_io()
275
+ except Exception:
276
+ pass
277
+ payload = {} if args[0] in _NO_PAYLOAD else _read_payload()
278
+ if not payload and args[0] not in _NO_PAYLOAD:
279
+ return 0
280
+ try:
281
+ out = _HANDLERS[args[0]](payload)
282
+ except Exception:
283
+ return 0
284
+ if out:
285
+ sys.stdout.write(json.dumps(out))
286
+ sys.stdout.flush()
287
+ return 0
288
+
289
+
290
+ if __name__ == "__main__":
291
+ sys.exit(main())