@alexgreensh/token-optimizer 5.13.56 → 5.13.59
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/.claude-plugin/marketplace.json +2 -2
- package/.claude-plugin/plugin.json +1 -1
- package/hooks/hooks.json +16 -16
- package/hooks/python-launcher.sh +10 -0
- package/hooks/stop_runner.py +27 -4
- package/hooks/windows-launcher.py +57 -3
- package/package.json +1 -1
- package/skills/fleet-auditor/scripts/shared.py +29 -1
- package/skills/token-optimizer/pricing/prices.json +13 -1
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +93 -9
- package/skills/token-optimizer/scripts/codex_doctor.py +134 -16
- package/skills/token-optimizer/scripts/codex_install.py +436 -26
- package/skills/token-optimizer/scripts/codex_session.py +38 -8
- package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
- package/skills/token-optimizer/scripts/copilot_install.py +56 -4
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
- package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
- package/skills/token-optimizer/scripts/devin_source.py +1 -1
- package/skills/token-optimizer/scripts/hermes_doctor.py +177 -1
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +190 -0
- package/skills/token-optimizer/scripts/hermes_install.py +43 -0
- package/skills/token-optimizer/scripts/hermes_session.py +133 -0
- package/skills/token-optimizer/scripts/hermes_state.py +58 -0
- package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
- package/skills/token-optimizer/scripts/measure.py +1442 -325
- package/skills/token-optimizer/scripts/plugin_env.py +18 -0
- package/skills/token-optimizer/scripts/recovery_output.py +15 -2
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
- package/skills/token-optimizer/scripts/runtime_env.py +5 -1
|
@@ -47,13 +47,82 @@ REQUIRED_PLUGIN_FILES = (
|
|
|
47
47
|
_CONFIG_NAMES = ("config.yaml", "config.yml")
|
|
48
48
|
_ACTIVATION_SNIPPET = "plugins:\n enabled:\n - token-optimizer\n"
|
|
49
49
|
|
|
50
|
+
# Every hook the plugin registers (hermes/__init__.py HOOKS, hermes/plugin.yaml).
|
|
51
|
+
# A test pins all three lists together.
|
|
50
52
|
EXPECTED_HOOKS = {
|
|
51
53
|
"pre_llm_call",
|
|
52
54
|
"post_api_request",
|
|
53
|
-
"
|
|
55
|
+
"pre_tool_call",
|
|
56
|
+
"post_tool_call",
|
|
57
|
+
"transform_terminal_output",
|
|
58
|
+
"transform_tool_result",
|
|
59
|
+
"pre_auxiliary_call",
|
|
60
|
+
"post_compaction",
|
|
61
|
+
"api_request_error",
|
|
62
|
+
"subagent_start",
|
|
63
|
+
"subagent_stop",
|
|
64
|
+
"on_skill_lifecycle",
|
|
65
|
+
"on_session_start",
|
|
54
66
|
"on_session_end",
|
|
67
|
+
"on_session_finalize",
|
|
68
|
+
"on_session_reset",
|
|
69
|
+
"on_session_delete",
|
|
55
70
|
}
|
|
56
71
|
|
|
72
|
+
# Engine scripts the plugin runs from the checkout (found via measure-path).
|
|
73
|
+
# They are not copied into the plugin dir, so a checkout missing one silently
|
|
74
|
+
# switches that feature off; the doctor names it instead.
|
|
75
|
+
REQUIRED_ENGINE_SCRIPTS = (
|
|
76
|
+
"hermes_tool_hooks.py",
|
|
77
|
+
"bash_compress_hook.py",
|
|
78
|
+
"archive_result.py",
|
|
79
|
+
"context_intel.py",
|
|
80
|
+
"read_cache.py",
|
|
81
|
+
"refetch_guard.py",
|
|
82
|
+
"credential_patterns.py",
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
# Copied into the plugin dir by hermes_install; a copy older than the checkout
|
|
86
|
+
# means the plugin runs stale code until the installer is re-run.
|
|
87
|
+
_COPIED_RUNTIME_MODULES = (
|
|
88
|
+
"hermes_hook_bridge.py",
|
|
89
|
+
"hermes_state.py",
|
|
90
|
+
"hermes_session.py",
|
|
91
|
+
"runtime_env.py",
|
|
92
|
+
"spawn_utils.py",
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
# Loads the INSTALLED plugin in a child process with a stand-in Hermes context
|
|
96
|
+
# and prints what register() actually registered. A child keeps the plugin's
|
|
97
|
+
# sys.path change and module state out of the doctor.
|
|
98
|
+
_REGISTRATION_PROBE = r"""
|
|
99
|
+
import importlib.util, json, sys
|
|
100
|
+
plugin_dir = sys.argv[1]
|
|
101
|
+
spec = importlib.util.spec_from_file_location("to_hermes_doctor_probe", plugin_dir + "/__init__.py")
|
|
102
|
+
module = importlib.util.module_from_spec(spec)
|
|
103
|
+
spec.loader.exec_module(module)
|
|
104
|
+
|
|
105
|
+
class Ctx:
|
|
106
|
+
def __init__(self):
|
|
107
|
+
self.hooks, self.commands, self.cli, self.patterns = [], [], [], 0
|
|
108
|
+
def register_hook(self, name, callback, **kw):
|
|
109
|
+
if not callable(callback):
|
|
110
|
+
raise TypeError(name)
|
|
111
|
+
self.hooks.append(name)
|
|
112
|
+
def register_command(self, name, *a, **k):
|
|
113
|
+
self.commands.append(name)
|
|
114
|
+
def register_cli_command(self, name, *a, **k):
|
|
115
|
+
self.cli.append(name)
|
|
116
|
+
def register_redaction_patterns(self, patterns):
|
|
117
|
+
self.patterns = len(list(patterns))
|
|
118
|
+
return self.patterns
|
|
119
|
+
|
|
120
|
+
ctx = Ctx()
|
|
121
|
+
module.register(ctx)
|
|
122
|
+
print(json.dumps({"hooks": ctx.hooks, "commands": ctx.commands, "cli": ctx.cli,
|
|
123
|
+
"patterns": ctx.patterns}))
|
|
124
|
+
"""
|
|
125
|
+
|
|
57
126
|
SKILL_INSTALL_FILES = (
|
|
58
127
|
"SKILL.md",
|
|
59
128
|
"scripts/hermes_install.py",
|
|
@@ -218,6 +287,110 @@ def _plugin_yaml_checks() -> list[dict[str, str]]:
|
|
|
218
287
|
return checks
|
|
219
288
|
|
|
220
289
|
|
|
290
|
+
def _registration_checks() -> list[dict[str, str]]:
|
|
291
|
+
"""Load the installed plugin and check every expected hook is registered.
|
|
292
|
+
|
|
293
|
+
Reports each hook by name, so a Hermes user can see exactly which Token
|
|
294
|
+
Optimizer features are live.
|
|
295
|
+
"""
|
|
296
|
+
plugin_dir = _plugin_install_dir(hermes_home())
|
|
297
|
+
init = plugin_dir / "__init__.py"
|
|
298
|
+
if not init.is_file():
|
|
299
|
+
return [_check("FAIL", "Registered hooks", f"{init} not found; re-run: python3 hermes_install.py")]
|
|
300
|
+
if init.is_symlink():
|
|
301
|
+
return [_check("FAIL", "Registered hooks", f"{init} is a symlink; re-run hermes_install.py")]
|
|
302
|
+
try:
|
|
303
|
+
result = subprocess.run(
|
|
304
|
+
[sys.executable, "-c", _REGISTRATION_PROBE, str(plugin_dir)],
|
|
305
|
+
capture_output=True,
|
|
306
|
+
text=True,
|
|
307
|
+
encoding="utf-8",
|
|
308
|
+
errors="replace",
|
|
309
|
+
timeout=30,
|
|
310
|
+
creationflags=_NO_WINDOW,
|
|
311
|
+
)
|
|
312
|
+
except (subprocess.TimeoutExpired, OSError) as exc:
|
|
313
|
+
return [_check("WARN", "Registered hooks", f"could not load the plugin: {exc}")]
|
|
314
|
+
data = None
|
|
315
|
+
for line in reversed((result.stdout or "").strip().splitlines()):
|
|
316
|
+
try:
|
|
317
|
+
data = json.loads(line)
|
|
318
|
+
break
|
|
319
|
+
except ValueError:
|
|
320
|
+
continue
|
|
321
|
+
if not isinstance(data, dict):
|
|
322
|
+
err = (result.stderr or "").strip().splitlines()
|
|
323
|
+
return [_check("FAIL", "Registered hooks",
|
|
324
|
+
f"plugin failed to register: {err[-1] if err else 'no output'}")]
|
|
325
|
+
registered = set(data.get("hooks") or [])
|
|
326
|
+
missing = sorted(EXPECTED_HOOKS - registered)
|
|
327
|
+
checks: list[dict[str, str]] = []
|
|
328
|
+
if missing:
|
|
329
|
+
checks.append(_check("FAIL", "Registered hooks",
|
|
330
|
+
f"{len(EXPECTED_HOOKS) - len(missing)}/{len(EXPECTED_HOOKS)}; "
|
|
331
|
+
f"not registered: {', '.join(missing)}; re-run: python3 hermes_install.py"))
|
|
332
|
+
else:
|
|
333
|
+
checks.append(_check("OK", "Registered hooks",
|
|
334
|
+
f"{len(EXPECTED_HOOKS)}/{len(EXPECTED_HOOKS)}: {', '.join(sorted(registered & EXPECTED_HOOKS))}"))
|
|
335
|
+
if "token-optimizer" in (data.get("commands") or []):
|
|
336
|
+
checks.append(_check("OK", "Slash command", "/token-optimizer registered"))
|
|
337
|
+
else:
|
|
338
|
+
checks.append(_check("WARN", "Slash command", "/token-optimizer not registered"))
|
|
339
|
+
patterns = int(data.get("patterns") or 0)
|
|
340
|
+
if patterns:
|
|
341
|
+
checks.append(_check("OK", "Credential redaction", f"{patterns} patterns shared with Hermes's redactor"))
|
|
342
|
+
else:
|
|
343
|
+
checks.append(_check("WARN", "Credential redaction",
|
|
344
|
+
"no patterns registered (TOKEN_OPTIMIZER_HERMES_REDACTION=0, or credential_patterns.py not found)"))
|
|
345
|
+
return checks
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _engine_checks() -> list[dict[str, str]]:
|
|
349
|
+
"""The checkout the plugin points at must hold every engine script."""
|
|
350
|
+
plugin_dir = _plugin_install_dir(hermes_home())
|
|
351
|
+
locator = plugin_dir / "measure-path"
|
|
352
|
+
try:
|
|
353
|
+
measure_py = Path(locator.read_text(encoding="utf-8").strip())
|
|
354
|
+
except (OSError, ValueError):
|
|
355
|
+
return [_check("FAIL", "Engine scripts", f"cannot read {locator}; re-run: python3 hermes_install.py")]
|
|
356
|
+
sdir = measure_py.parent
|
|
357
|
+
missing = [name for name in REQUIRED_ENGINE_SCRIPTS if not (sdir / name).is_file()]
|
|
358
|
+
if missing:
|
|
359
|
+
return [_check("FAIL", "Engine scripts",
|
|
360
|
+
f"missing in {sdir}: {', '.join(missing)}; update the Token Optimizer checkout")]
|
|
361
|
+
return [_check("OK", "Engine scripts", f"{len(REQUIRED_ENGINE_SCRIPTS)} present in {sdir}")]
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _freshness_checks() -> list[dict[str, str]]:
|
|
365
|
+
"""WARN when the installed copies or plugin version lag the checkout."""
|
|
366
|
+
import hashlib # noqa: PLC0415
|
|
367
|
+
|
|
368
|
+
plugin_dir = _plugin_install_dir(hermes_home())
|
|
369
|
+
if not plugin_dir.is_dir():
|
|
370
|
+
return []
|
|
371
|
+
here = Path(__file__).resolve().parent
|
|
372
|
+
stale = []
|
|
373
|
+
for name in _COPIED_RUNTIME_MODULES:
|
|
374
|
+
src, dst = here / name, plugin_dir / name
|
|
375
|
+
try:
|
|
376
|
+
if src.is_file() and dst.is_file() and \
|
|
377
|
+
hashlib.sha256(src.read_bytes()).digest() != hashlib.sha256(dst.read_bytes()).digest():
|
|
378
|
+
stale.append(name)
|
|
379
|
+
except OSError:
|
|
380
|
+
continue
|
|
381
|
+
for name in ("__init__.py", "plugin.yaml"):
|
|
382
|
+
src, dst = _repo_root() / "hermes" / name, plugin_dir / name
|
|
383
|
+
try:
|
|
384
|
+
if src.is_file() and dst.is_file() and src.read_bytes() != dst.read_bytes():
|
|
385
|
+
stale.append(name)
|
|
386
|
+
except OSError:
|
|
387
|
+
continue
|
|
388
|
+
if stale:
|
|
389
|
+
return [_check("WARN", "Installed copy up to date",
|
|
390
|
+
f"differs from this checkout: {', '.join(stale)}; re-run: python3 hermes_install.py")]
|
|
391
|
+
return [_check("OK", "Installed copy up to date", "plugin files match this checkout")]
|
|
392
|
+
|
|
393
|
+
|
|
221
394
|
def _bridge_smoke_check() -> list[dict[str, str]]:
|
|
222
395
|
"""Run the installed bridge's __main__ smoke test.
|
|
223
396
|
|
|
@@ -429,6 +602,9 @@ def run_checks() -> list[dict[str, str]]:
|
|
|
429
602
|
checks.extend(_plugin_dir_checks())
|
|
430
603
|
checks.extend(_plugin_yaml_checks())
|
|
431
604
|
checks.extend(_bridge_smoke_check())
|
|
605
|
+
checks.extend(_registration_checks())
|
|
606
|
+
checks.extend(_engine_checks())
|
|
607
|
+
checks.extend(_freshness_checks())
|
|
432
608
|
checks.extend(_activation_check())
|
|
433
609
|
checks.extend(_state_db_checks())
|
|
434
610
|
checks.append(_dashboard_port_check())
|
|
@@ -20,11 +20,13 @@ Either way, Path(__file__).parent / "measure.py" resolves correctly.
|
|
|
20
20
|
|
|
21
21
|
from __future__ import annotations
|
|
22
22
|
|
|
23
|
+
import json
|
|
23
24
|
import logging
|
|
24
25
|
import os
|
|
25
26
|
import subprocess
|
|
26
27
|
import sys
|
|
27
28
|
from pathlib import Path
|
|
29
|
+
from typing import Any
|
|
28
30
|
|
|
29
31
|
from runtime_env import runtime_home
|
|
30
32
|
from spawn_utils import spawn_detached
|
|
@@ -164,6 +166,7 @@ def _run_measure(args: list[str], *, capture_output: bool = True, timeout: int =
|
|
|
164
166
|
def run_rollup(
|
|
165
167
|
session_id: str = "", platform: str = "hermes", reason: str = "",
|
|
166
168
|
context_tokens: int | None = None,
|
|
169
|
+
skills: dict | None = None,
|
|
167
170
|
) -> None:
|
|
168
171
|
"""Write a session rollup to TO's trends.db.
|
|
169
172
|
|
|
@@ -196,6 +199,11 @@ def run_rollup(
|
|
|
196
199
|
cmd += ["--reason", reason]
|
|
197
200
|
if context_tokens is not None and context_tokens > 0:
|
|
198
201
|
cmd += ["--context-tokens", str(int(context_tokens))]
|
|
202
|
+
if skills:
|
|
203
|
+
try:
|
|
204
|
+
cmd += ["--skills-json", json.dumps(skills, ensure_ascii=True)]
|
|
205
|
+
except (TypeError, ValueError):
|
|
206
|
+
pass
|
|
199
207
|
try:
|
|
200
208
|
_proc = spawn_detached(
|
|
201
209
|
cmd,
|
|
@@ -270,6 +278,188 @@ def run_dashboard(session_id: str = "", port: int = DASHBOARD_PORT) -> None:
|
|
|
270
278
|
print("[Token Optimizer] Could not open dashboard: spawn failed")
|
|
271
279
|
|
|
272
280
|
|
|
281
|
+
# ---------------------------------------------------------------------------
|
|
282
|
+
# Per-tool engines and session continuity (parity with Claude Code / Codex)
|
|
283
|
+
# ---------------------------------------------------------------------------
|
|
284
|
+
#
|
|
285
|
+
# The plugin runs in the Hermes process. Every engine call below runs in a
|
|
286
|
+
# short child process (the same scripts Claude Code's hooks run), so a slow or
|
|
287
|
+
# broken engine can never stall or crash Hermes. All helpers fail open: they
|
|
288
|
+
# return None / "" on any problem and the caller keeps the original output.
|
|
289
|
+
|
|
290
|
+
_HERMES_ENV = {"TOKEN_OPTIMIZER_RUNTIME": "hermes", "PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"}
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def scripts_dir() -> Path | None:
|
|
294
|
+
"""Directory holding measure.py and the engine scripts, or None."""
|
|
295
|
+
measure_py = _locate_measure_py()
|
|
296
|
+
return measure_py.parent if measure_py is not None else None
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _run_json(cmd: list[str], payload: dict, timeout: float) -> str:
|
|
300
|
+
"""Run ``cmd`` with ``payload`` as JSON on stdin; return stdout ("" on failure)."""
|
|
301
|
+
try:
|
|
302
|
+
data = json.dumps(payload, ensure_ascii=False, default=str)
|
|
303
|
+
except (TypeError, ValueError):
|
|
304
|
+
return ""
|
|
305
|
+
try:
|
|
306
|
+
result = subprocess.run(
|
|
307
|
+
cmd,
|
|
308
|
+
input=data,
|
|
309
|
+
capture_output=True,
|
|
310
|
+
text=True,
|
|
311
|
+
encoding="utf-8",
|
|
312
|
+
errors="replace",
|
|
313
|
+
timeout=max(0.1, float(timeout)),
|
|
314
|
+
env={**os.environ, **_HERMES_ENV},
|
|
315
|
+
creationflags=_NO_WINDOW,
|
|
316
|
+
)
|
|
317
|
+
except subprocess.TimeoutExpired:
|
|
318
|
+
logger.debug("[hermes_hook_bridge] %s timed out", cmd[1:3])
|
|
319
|
+
return ""
|
|
320
|
+
except Exception as exc:
|
|
321
|
+
logger.debug("[hermes_hook_bridge] %s error: %s", cmd[1:3], exc)
|
|
322
|
+
return ""
|
|
323
|
+
return result.stdout or ""
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _last_json_object(text: str) -> dict | None:
|
|
327
|
+
for line in reversed((text or "").strip().splitlines()):
|
|
328
|
+
line = line.strip()
|
|
329
|
+
if line.startswith("{"):
|
|
330
|
+
try:
|
|
331
|
+
obj = json.loads(line)
|
|
332
|
+
except ValueError:
|
|
333
|
+
continue
|
|
334
|
+
if isinstance(obj, dict):
|
|
335
|
+
return obj
|
|
336
|
+
return None
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def run_tool_hooks(event: str, payload: dict, timeout: float = 8.0) -> dict | None:
|
|
340
|
+
"""Run ``hermes_tool_hooks.py <event>`` on a Claude-Code-shaped payload.
|
|
341
|
+
|
|
342
|
+
Returns the normalized result dict, or None when nothing applies or on any
|
|
343
|
+
failure (missing script, timeout, bad output).
|
|
344
|
+
"""
|
|
345
|
+
sdir = scripts_dir()
|
|
346
|
+
if sdir is None:
|
|
347
|
+
return None
|
|
348
|
+
script = sdir / "hermes_tool_hooks.py"
|
|
349
|
+
if not script.is_file():
|
|
350
|
+
return None
|
|
351
|
+
out = _run_json([sys.executable, str(script), event], payload, timeout)
|
|
352
|
+
return _last_json_object(out)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def redaction_patterns(timeout: float = 10.0) -> list[str]:
|
|
356
|
+
"""Credential regexes for Hermes's redactor, loaded under the Hermes runtime."""
|
|
357
|
+
res = run_tool_hooks("redaction-patterns", {}, timeout=timeout)
|
|
358
|
+
pats = res.get("patterns") if isinstance(res, dict) else None
|
|
359
|
+
return [p for p in (pats or []) if isinstance(p, str)]
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def run_measure_context(args: list[str], payload: dict, timeout: float = 10.0) -> str:
|
|
363
|
+
"""Run a measure.py hook subcommand and return its additionalContext text.
|
|
364
|
+
|
|
365
|
+
Used for ``compact-restore`` and ``prompt-continuity``, which read a hook
|
|
366
|
+
payload on stdin and answer with a hookSpecificOutput envelope.
|
|
367
|
+
"""
|
|
368
|
+
measure_py = _locate_measure_py()
|
|
369
|
+
if measure_py is None:
|
|
370
|
+
return ""
|
|
371
|
+
out = _run_json([sys.executable, str(measure_py), *args], payload, timeout)
|
|
372
|
+
obj = _last_json_object(out)
|
|
373
|
+
if not obj:
|
|
374
|
+
return ""
|
|
375
|
+
hso = obj.get("hookSpecificOutput")
|
|
376
|
+
ctx = hso.get("additionalContext") if isinstance(hso, dict) else None
|
|
377
|
+
return ctx.strip() if isinstance(ctx, str) else ""
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def run_turn_context(payload: dict, timeout: float = 10.0) -> dict | None:
|
|
381
|
+
"""Run ``measure.py hermes-turn-context``: continuity pointer, prior-session
|
|
382
|
+
hint and lean-output nudge for one Hermes turn, in one child process."""
|
|
383
|
+
measure_py = _locate_measure_py()
|
|
384
|
+
if measure_py is None:
|
|
385
|
+
return None
|
|
386
|
+
out = _run_json([sys.executable, str(measure_py), "hermes-turn-context"], payload, timeout)
|
|
387
|
+
obj = _last_json_object(out)
|
|
388
|
+
return obj if isinstance(obj, dict) else None
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def spawn_checkpoint(
|
|
392
|
+
session_id: str, trigger: str, *, fill_pct: float | None = None, cwd: str | None = None,
|
|
393
|
+
) -> bool:
|
|
394
|
+
"""Write a checkpoint for a Hermes session in the background.
|
|
395
|
+
|
|
396
|
+
Fire-and-forget ``measure.py hermes-checkpoint``; returns True when the
|
|
397
|
+
child was started. Never blocks the Hermes turn.
|
|
398
|
+
"""
|
|
399
|
+
if not session_id or not trigger:
|
|
400
|
+
return False
|
|
401
|
+
measure_py = _locate_measure_py()
|
|
402
|
+
if measure_py is None:
|
|
403
|
+
return False
|
|
404
|
+
cmd = [sys.executable, str(measure_py), "hermes-checkpoint", "--quiet",
|
|
405
|
+
"--session", str(session_id), "--trigger", str(trigger)]
|
|
406
|
+
if fill_pct is not None:
|
|
407
|
+
cmd += ["--fill-pct", f"{float(fill_pct):.1f}"]
|
|
408
|
+
if cwd:
|
|
409
|
+
cmd += ["--cwd", str(cwd)]
|
|
410
|
+
try:
|
|
411
|
+
proc = spawn_detached(
|
|
412
|
+
cmd,
|
|
413
|
+
env={**os.environ, **_HERMES_ENV},
|
|
414
|
+
stdout=subprocess.DEVNULL,
|
|
415
|
+
stderr=subprocess.DEVNULL,
|
|
416
|
+
)
|
|
417
|
+
except Exception as exc:
|
|
418
|
+
logger.debug("[hermes_hook_bridge] spawn_checkpoint error: %s", exc)
|
|
419
|
+
return False
|
|
420
|
+
return proc is not None
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def run_command_text(args: list[str], timeout: int = 20) -> str:
|
|
424
|
+
"""Run a read-only measure.py command for the slash command; return stdout."""
|
|
425
|
+
return _run_measure(list(args), capture_output=True, timeout=timeout)
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
def to_claude_payload(
|
|
429
|
+
tool_name: str,
|
|
430
|
+
args: Any,
|
|
431
|
+
*,
|
|
432
|
+
session_id: str,
|
|
433
|
+
tool_call_id: str = "",
|
|
434
|
+
result: Any = None,
|
|
435
|
+
cwd: str = "",
|
|
436
|
+
) -> list[dict]:
|
|
437
|
+
"""Translate a Hermes tool call into Claude-Code-shaped hook payloads.
|
|
438
|
+
|
|
439
|
+
One Hermes call can map to several (a multi-file patch), so a list is
|
|
440
|
+
returned. Tool output, when given, goes in ``tool_response``.
|
|
441
|
+
"""
|
|
442
|
+
try:
|
|
443
|
+
from hermes_session import hermes_tool_to_claude
|
|
444
|
+
except Exception:
|
|
445
|
+
return []
|
|
446
|
+
out = []
|
|
447
|
+
for cc_name, cc_input in hermes_tool_to_claude(tool_name, args):
|
|
448
|
+
payload: dict = {
|
|
449
|
+
"hook_event_name": "PostToolUse" if result is not None else "PreToolUse",
|
|
450
|
+
"tool_name": cc_name,
|
|
451
|
+
"tool_input": cc_input,
|
|
452
|
+
"session_id": session_id,
|
|
453
|
+
"tool_use_id": tool_call_id,
|
|
454
|
+
}
|
|
455
|
+
if cwd:
|
|
456
|
+
payload["cwd"] = cwd
|
|
457
|
+
if result is not None:
|
|
458
|
+
payload["tool_response"] = result
|
|
459
|
+
out.append(payload)
|
|
460
|
+
return out
|
|
461
|
+
|
|
462
|
+
|
|
273
463
|
if __name__ == "__main__":
|
|
274
464
|
try:
|
|
275
465
|
from utf8_io import enforce_utf8_io
|
|
@@ -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
|