@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.
- 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_doctor.py +78 -1
- package/skills/token-optimizer/scripts/codex_install.py +379 -41
- 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 +258 -16
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +229 -9
- 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 +76 -9
- package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
- package/skills/token-optimizer/scripts/measure.py +1340 -321
- 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,116 @@ 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 _stale_files(plugin_dir: Path) -> list[str]:
|
|
365
|
+
"""Installed plugin files that differ from this checkout's copies."""
|
|
366
|
+
import hashlib # noqa: PLC0415
|
|
367
|
+
|
|
368
|
+
here = Path(__file__).resolve().parent
|
|
369
|
+
stale = []
|
|
370
|
+
for name in _COPIED_RUNTIME_MODULES:
|
|
371
|
+
src, dst = here / name, plugin_dir / name
|
|
372
|
+
try:
|
|
373
|
+
if src.is_file() and dst.is_file() and \
|
|
374
|
+
hashlib.sha256(src.read_bytes()).digest() != hashlib.sha256(dst.read_bytes()).digest():
|
|
375
|
+
stale.append(name)
|
|
376
|
+
except OSError:
|
|
377
|
+
continue
|
|
378
|
+
for name in ("__init__.py", "plugin.yaml"):
|
|
379
|
+
src, dst = _repo_root() / "hermes" / name, plugin_dir / name
|
|
380
|
+
try:
|
|
381
|
+
if src.is_file() and dst.is_file() and src.read_bytes() != dst.read_bytes():
|
|
382
|
+
stale.append(name)
|
|
383
|
+
except OSError:
|
|
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)
|
|
394
|
+
if stale:
|
|
395
|
+
return [_check("WARN", "Installed copy up to date",
|
|
396
|
+
f"differs from this checkout: {', '.join(stale)}; re-run: python3 hermes_install.py")]
|
|
397
|
+
return [_check("OK", "Installed copy up to date", "plugin files match this checkout")]
|
|
398
|
+
|
|
399
|
+
|
|
221
400
|
def _bridge_smoke_check() -> list[dict[str, str]]:
|
|
222
401
|
"""Run the installed bridge's __main__ smoke test.
|
|
223
402
|
|
|
@@ -277,12 +456,7 @@ def _activation_check() -> list[dict[str, str]]:
|
|
|
277
456
|
importable, else a conservative text scan).
|
|
278
457
|
"""
|
|
279
458
|
hermes_root = hermes_home()
|
|
280
|
-
cfg =
|
|
281
|
-
for name in _CONFIG_NAMES:
|
|
282
|
-
candidate = hermes_root / name
|
|
283
|
-
if candidate.exists():
|
|
284
|
-
cfg = candidate
|
|
285
|
-
break
|
|
459
|
+
cfg = _config_path(hermes_root)
|
|
286
460
|
|
|
287
461
|
snippet_hint = f"add to Hermes config:\n{_ACTIVATION_SNIPPET}"
|
|
288
462
|
|
|
@@ -298,6 +472,27 @@ def _activation_check() -> list[dict[str, str]]:
|
|
|
298
472
|
except OSError as exc:
|
|
299
473
|
return [_check("WARN", "Plugin activation", f"could not read {cfg}: {exc}")]
|
|
300
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?"""
|
|
301
496
|
enabled = False
|
|
302
497
|
try:
|
|
303
498
|
import yaml # type: ignore[import] # noqa: PLC0415
|
|
@@ -310,16 +505,59 @@ def _activation_check() -> list[dict[str, str]]:
|
|
|
310
505
|
enabled = _PLUGIN_NAME in [str(x).strip() for x in listed]
|
|
311
506
|
except Exception: # noqa: BLE001 — PyYAML absent or unparseable; fall back to text scan
|
|
312
507
|
enabled = _activation_text_scan(text)
|
|
508
|
+
return enabled
|
|
313
509
|
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
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)]
|
|
323
561
|
|
|
324
562
|
|
|
325
563
|
def _activation_text_scan(text: str) -> bool:
|
|
@@ -429,7 +667,11 @@ def run_checks() -> list[dict[str, str]]:
|
|
|
429
667
|
checks.extend(_plugin_dir_checks())
|
|
430
668
|
checks.extend(_plugin_yaml_checks())
|
|
431
669
|
checks.extend(_bridge_smoke_check())
|
|
670
|
+
checks.extend(_registration_checks())
|
|
671
|
+
checks.extend(_engine_checks())
|
|
672
|
+
checks.extend(_freshness_checks())
|
|
432
673
|
checks.extend(_activation_check())
|
|
674
|
+
checks.extend(_profile_checks())
|
|
433
675
|
checks.extend(_state_db_checks())
|
|
434
676
|
checks.append(_dashboard_port_check())
|
|
435
677
|
return checks
|
|
@@ -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
|
|
@@ -116,6 +118,44 @@ def _locate_measure_py() -> Path | None:
|
|
|
116
118
|
return None
|
|
117
119
|
|
|
118
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
|
+
|
|
119
159
|
# ---------------------------------------------------------------------------
|
|
120
160
|
# Internal subprocess helper
|
|
121
161
|
# ---------------------------------------------------------------------------
|
|
@@ -137,8 +177,7 @@ def _run_measure(args: list[str], *, capture_output: bool = True, timeout: int =
|
|
|
137
177
|
encoding="utf-8",
|
|
138
178
|
errors="replace",
|
|
139
179
|
timeout=timeout,
|
|
140
|
-
env=
|
|
141
|
-
"PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
|
|
180
|
+
env=_child_env(),
|
|
142
181
|
creationflags=_NO_WINDOW,
|
|
143
182
|
)
|
|
144
183
|
if result.returncode != 0 and result.stderr:
|
|
@@ -164,6 +203,7 @@ def _run_measure(args: list[str], *, capture_output: bool = True, timeout: int =
|
|
|
164
203
|
def run_rollup(
|
|
165
204
|
session_id: str = "", platform: str = "hermes", reason: str = "",
|
|
166
205
|
context_tokens: int | None = None,
|
|
206
|
+
skills: dict | None = None,
|
|
167
207
|
) -> None:
|
|
168
208
|
"""Write a session rollup to TO's trends.db.
|
|
169
209
|
|
|
@@ -196,11 +236,15 @@ def run_rollup(
|
|
|
196
236
|
cmd += ["--reason", reason]
|
|
197
237
|
if context_tokens is not None and context_tokens > 0:
|
|
198
238
|
cmd += ["--context-tokens", str(int(context_tokens))]
|
|
239
|
+
if skills:
|
|
240
|
+
try:
|
|
241
|
+
cmd += ["--skills-json", json.dumps(skills, ensure_ascii=True)]
|
|
242
|
+
except (TypeError, ValueError):
|
|
243
|
+
pass
|
|
199
244
|
try:
|
|
200
245
|
_proc = spawn_detached(
|
|
201
246
|
cmd,
|
|
202
|
-
env=
|
|
203
|
-
"PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
|
|
247
|
+
env=_child_env(),
|
|
204
248
|
stdout=subprocess.DEVNULL,
|
|
205
249
|
stderr=subprocess.DEVNULL,
|
|
206
250
|
)
|
|
@@ -215,9 +259,7 @@ def run_rollup(
|
|
|
215
259
|
try:
|
|
216
260
|
spawn_detached(
|
|
217
261
|
[sys.executable, str(measure_py), "dashboard", "--quiet"],
|
|
218
|
-
env=
|
|
219
|
-
"TOKEN_OPTIMIZER_INTERACTIVE": "1",
|
|
220
|
-
"PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
|
|
262
|
+
env=_child_env(TOKEN_OPTIMIZER_INTERACTIVE="1"),
|
|
221
263
|
stdout=subprocess.DEVNULL,
|
|
222
264
|
stderr=subprocess.DEVNULL,
|
|
223
265
|
)
|
|
@@ -256,8 +298,7 @@ def run_dashboard(session_id: str = "", port: int = DASHBOARD_PORT) -> None:
|
|
|
256
298
|
try:
|
|
257
299
|
_proc = spawn_detached(
|
|
258
300
|
args,
|
|
259
|
-
env=
|
|
260
|
-
"PYTHONUTF8": "1", "PYTHONIOENCODING": "utf-8"},
|
|
301
|
+
env=_child_env(),
|
|
261
302
|
stdout=subprocess.DEVNULL,
|
|
262
303
|
stderr=subprocess.DEVNULL,
|
|
263
304
|
)
|
|
@@ -270,6 +311,185 @@ def run_dashboard(session_id: str = "", port: int = DASHBOARD_PORT) -> None:
|
|
|
270
311
|
print("[Token Optimizer] Could not open dashboard: spawn failed")
|
|
271
312
|
|
|
272
313
|
|
|
314
|
+
# ---------------------------------------------------------------------------
|
|
315
|
+
# Per-tool engines and session continuity (parity with Claude Code / Codex)
|
|
316
|
+
# ---------------------------------------------------------------------------
|
|
317
|
+
#
|
|
318
|
+
# The plugin runs in the Hermes process. Every engine call below runs in a
|
|
319
|
+
# short child process (the same scripts Claude Code's hooks run), so a slow or
|
|
320
|
+
# broken engine can never stall or crash Hermes. All helpers fail open: they
|
|
321
|
+
# return None / "" on any problem and the caller keeps the original output.
|
|
322
|
+
|
|
323
|
+
def scripts_dir() -> Path | None:
|
|
324
|
+
"""Directory holding measure.py and the engine scripts, or None."""
|
|
325
|
+
measure_py = _locate_measure_py()
|
|
326
|
+
return measure_py.parent if measure_py is not None else None
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _run_json(cmd: list[str], payload: dict, timeout: float) -> str:
|
|
330
|
+
"""Run ``cmd`` with ``payload`` as JSON on stdin; return stdout ("" on failure)."""
|
|
331
|
+
try:
|
|
332
|
+
data = json.dumps(payload, ensure_ascii=False, default=str)
|
|
333
|
+
except (TypeError, ValueError):
|
|
334
|
+
return ""
|
|
335
|
+
try:
|
|
336
|
+
result = subprocess.run(
|
|
337
|
+
cmd,
|
|
338
|
+
input=data,
|
|
339
|
+
capture_output=True,
|
|
340
|
+
text=True,
|
|
341
|
+
encoding="utf-8",
|
|
342
|
+
errors="replace",
|
|
343
|
+
timeout=max(0.1, float(timeout)),
|
|
344
|
+
env=_child_env(),
|
|
345
|
+
creationflags=_NO_WINDOW,
|
|
346
|
+
)
|
|
347
|
+
except subprocess.TimeoutExpired:
|
|
348
|
+
logger.debug("[hermes_hook_bridge] %s timed out", cmd[1:3])
|
|
349
|
+
return ""
|
|
350
|
+
except Exception as exc:
|
|
351
|
+
logger.debug("[hermes_hook_bridge] %s error: %s", cmd[1:3], exc)
|
|
352
|
+
return ""
|
|
353
|
+
return result.stdout or ""
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _last_json_object(text: str) -> dict | None:
|
|
357
|
+
for line in reversed((text or "").strip().splitlines()):
|
|
358
|
+
line = line.strip()
|
|
359
|
+
if line.startswith("{"):
|
|
360
|
+
try:
|
|
361
|
+
obj = json.loads(line)
|
|
362
|
+
except ValueError:
|
|
363
|
+
continue
|
|
364
|
+
if isinstance(obj, dict):
|
|
365
|
+
return obj
|
|
366
|
+
return None
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def run_tool_hooks(event: str, payload: dict, timeout: float = 8.0) -> dict | None:
|
|
370
|
+
"""Run ``hermes_tool_hooks.py <event>`` on a Claude-Code-shaped payload.
|
|
371
|
+
|
|
372
|
+
Returns the normalized result dict, or None when nothing applies or on any
|
|
373
|
+
failure (missing script, timeout, bad output).
|
|
374
|
+
"""
|
|
375
|
+
sdir = scripts_dir()
|
|
376
|
+
if sdir is None:
|
|
377
|
+
return None
|
|
378
|
+
script = sdir / "hermes_tool_hooks.py"
|
|
379
|
+
if not script.is_file():
|
|
380
|
+
return None
|
|
381
|
+
out = _run_json([sys.executable, str(script), event], payload, timeout)
|
|
382
|
+
return _last_json_object(out)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def redaction_patterns(timeout: float = 10.0) -> list[str]:
|
|
386
|
+
"""Credential regexes for Hermes's redactor, loaded under the Hermes runtime."""
|
|
387
|
+
res = run_tool_hooks("redaction-patterns", {}, timeout=timeout)
|
|
388
|
+
pats = res.get("patterns") if isinstance(res, dict) else None
|
|
389
|
+
return [p for p in (pats or []) if isinstance(p, str)]
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def run_measure_context(args: list[str], payload: dict, timeout: float = 10.0) -> str:
|
|
393
|
+
"""Run a measure.py hook subcommand and return its additionalContext text.
|
|
394
|
+
|
|
395
|
+
Used for ``compact-restore`` and ``prompt-continuity``, which read a hook
|
|
396
|
+
payload on stdin and answer with a hookSpecificOutput envelope.
|
|
397
|
+
"""
|
|
398
|
+
measure_py = _locate_measure_py()
|
|
399
|
+
if measure_py is None:
|
|
400
|
+
return ""
|
|
401
|
+
out = _run_json([sys.executable, str(measure_py), *args], payload, timeout)
|
|
402
|
+
obj = _last_json_object(out)
|
|
403
|
+
if not obj:
|
|
404
|
+
return ""
|
|
405
|
+
hso = obj.get("hookSpecificOutput")
|
|
406
|
+
ctx = hso.get("additionalContext") if isinstance(hso, dict) else None
|
|
407
|
+
return ctx.strip() if isinstance(ctx, str) else ""
|
|
408
|
+
|
|
409
|
+
|
|
410
|
+
def run_turn_context(payload: dict, timeout: float = 10.0) -> dict | None:
|
|
411
|
+
"""Run ``measure.py hermes-turn-context``: continuity pointer, prior-session
|
|
412
|
+
hint and lean-output nudge for one Hermes turn, in one child process."""
|
|
413
|
+
measure_py = _locate_measure_py()
|
|
414
|
+
if measure_py is None:
|
|
415
|
+
return None
|
|
416
|
+
out = _run_json([sys.executable, str(measure_py), "hermes-turn-context"], payload, timeout)
|
|
417
|
+
obj = _last_json_object(out)
|
|
418
|
+
return obj if isinstance(obj, dict) else None
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def spawn_checkpoint(
|
|
422
|
+
session_id: str, trigger: str, *, fill_pct: float | None = None, cwd: str | None = None,
|
|
423
|
+
) -> bool:
|
|
424
|
+
"""Write a checkpoint for a Hermes session in the background.
|
|
425
|
+
|
|
426
|
+
Fire-and-forget ``measure.py hermes-checkpoint``; returns True when the
|
|
427
|
+
child was started. Never blocks the Hermes turn.
|
|
428
|
+
"""
|
|
429
|
+
if not session_id or not trigger:
|
|
430
|
+
return False
|
|
431
|
+
measure_py = _locate_measure_py()
|
|
432
|
+
if measure_py is None:
|
|
433
|
+
return False
|
|
434
|
+
cmd = [sys.executable, str(measure_py), "hermes-checkpoint", "--quiet",
|
|
435
|
+
"--session", str(session_id), "--trigger", str(trigger)]
|
|
436
|
+
if fill_pct is not None:
|
|
437
|
+
cmd += ["--fill-pct", f"{float(fill_pct):.1f}"]
|
|
438
|
+
if cwd:
|
|
439
|
+
cmd += ["--cwd", str(cwd)]
|
|
440
|
+
try:
|
|
441
|
+
proc = spawn_detached(
|
|
442
|
+
cmd,
|
|
443
|
+
env=_child_env(),
|
|
444
|
+
stdout=subprocess.DEVNULL,
|
|
445
|
+
stderr=subprocess.DEVNULL,
|
|
446
|
+
)
|
|
447
|
+
except Exception as exc:
|
|
448
|
+
logger.debug("[hermes_hook_bridge] spawn_checkpoint error: %s", exc)
|
|
449
|
+
return False
|
|
450
|
+
return proc is not None
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def run_command_text(args: list[str], timeout: int = 20) -> str:
|
|
454
|
+
"""Run a read-only measure.py command for the slash command; return stdout."""
|
|
455
|
+
return _run_measure(list(args), capture_output=True, timeout=timeout)
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
def to_claude_payload(
|
|
459
|
+
tool_name: str,
|
|
460
|
+
args: Any,
|
|
461
|
+
*,
|
|
462
|
+
session_id: str,
|
|
463
|
+
tool_call_id: str = "",
|
|
464
|
+
result: Any = None,
|
|
465
|
+
cwd: str = "",
|
|
466
|
+
) -> list[dict]:
|
|
467
|
+
"""Translate a Hermes tool call into Claude-Code-shaped hook payloads.
|
|
468
|
+
|
|
469
|
+
One Hermes call can map to several (a multi-file patch), so a list is
|
|
470
|
+
returned. Tool output, when given, goes in ``tool_response``.
|
|
471
|
+
"""
|
|
472
|
+
try:
|
|
473
|
+
from hermes_session import hermes_tool_to_claude
|
|
474
|
+
except Exception:
|
|
475
|
+
return []
|
|
476
|
+
out = []
|
|
477
|
+
for cc_name, cc_input in hermes_tool_to_claude(tool_name, args):
|
|
478
|
+
payload: dict = {
|
|
479
|
+
"hook_event_name": "PostToolUse" if result is not None else "PreToolUse",
|
|
480
|
+
"tool_name": cc_name,
|
|
481
|
+
"tool_input": cc_input,
|
|
482
|
+
"session_id": session_id,
|
|
483
|
+
"tool_use_id": tool_call_id,
|
|
484
|
+
}
|
|
485
|
+
if cwd:
|
|
486
|
+
payload["cwd"] = cwd
|
|
487
|
+
if result is not None:
|
|
488
|
+
payload["tool_response"] = result
|
|
489
|
+
out.append(payload)
|
|
490
|
+
return out
|
|
491
|
+
|
|
492
|
+
|
|
273
493
|
if __name__ == "__main__":
|
|
274
494
|
try:
|
|
275
495
|
from utf8_io import enforce_utf8_io
|