@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.
Files changed (30) 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_compact_prompt.py +93 -9
  11. package/skills/token-optimizer/scripts/codex_doctor.py +134 -16
  12. package/skills/token-optimizer/scripts/codex_install.py +436 -26
  13. package/skills/token-optimizer/scripts/codex_session.py +38 -8
  14. package/skills/token-optimizer/scripts/copilot_doctor.py +129 -6
  15. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +62 -14
  16. package/skills/token-optimizer/scripts/copilot_install.py +56 -4
  17. package/skills/token-optimizer/scripts/detectors/cache_instability.py +18 -4
  18. package/skills/token-optimizer/scripts/deterministic_candidates.py +55 -15
  19. package/skills/token-optimizer/scripts/devin_source.py +1 -1
  20. package/skills/token-optimizer/scripts/hermes_doctor.py +177 -1
  21. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +190 -0
  22. package/skills/token-optimizer/scripts/hermes_install.py +43 -0
  23. package/skills/token-optimizer/scripts/hermes_session.py +133 -0
  24. package/skills/token-optimizer/scripts/hermes_state.py +58 -0
  25. package/skills/token-optimizer/scripts/hermes_tool_hooks.py +291 -0
  26. package/skills/token-optimizer/scripts/measure.py +1442 -325
  27. package/skills/token-optimizer/scripts/plugin_env.py +18 -0
  28. package/skills/token-optimizer/scripts/recovery_output.py +15 -2
  29. package/skills/token-optimizer/scripts/refetch_fingerprint.py +36 -1
  30. package/skills/token-optimizer/scripts/runtime_env.py +5 -1
@@ -412,6 +412,64 @@ def session_token_totals(session_id: str) -> dict[str, Any]:
412
412
  }
413
413
 
414
414
 
415
+ # Message columns the checkpoint builder reads. Content-bearing columns are
416
+ # capped per row so one huge tool result cannot balloon a checkpoint read.
417
+ _MESSAGE_COLUMNS = ("id", "role", "content", "tool_call_id", "tool_calls", "tool_name", "timestamp")
418
+ _MESSAGE_TEXT_CAP = 20_000
419
+ _MAX_MESSAGE_ROWS = 2_000
420
+
421
+
422
+ def session_messages(
423
+ session_id: str, *, limit: int = 500, live: bool = True
424
+ ) -> list[dict[str, Any]]:
425
+ """Return the last ``limit`` message rows of a session, oldest first.
426
+
427
+ Read-only, like every reader here. Rows are returned whether or not Hermes
428
+ has since compacted them away (``active``/``compacted`` are ignored on
429
+ purpose): a pre-compaction checkpoint must see what the model saw. Each row
430
+ is a dict with ``role``, ``content``, ``tool_calls`` (raw JSON text),
431
+ ``tool_name``, ``tool_call_id`` and ``timestamp``; text is capped per row.
432
+
433
+ ``live=True`` (default) opens the WAL-visible view so a checkpoint written
434
+ during a live session sees the latest turns. Never raises: an absent,
435
+ locked, or unexpected DB yields an empty list.
436
+ """
437
+ if not session_id:
438
+ return []
439
+ db = state_db_path()
440
+ if not db.exists():
441
+ return []
442
+ limit = max(1, min(int(limit or 1), _MAX_MESSAGE_ROWS))
443
+ try:
444
+ with _ro_connect(db, immutable=not live) as conn:
445
+ available = _table_columns(conn, "messages")
446
+ if not available or "session_id" not in available or "role" not in available:
447
+ return []
448
+ cols = [c for c in _MESSAGE_COLUMNS if c in available]
449
+ order = "id" if "id" in available else ("timestamp" if "timestamp" in available else "rowid")
450
+ sql = (
451
+ f"SELECT {', '.join(cols)} FROM messages WHERE session_id = ? "
452
+ f"ORDER BY {order} DESC LIMIT ?"
453
+ )
454
+ rows = conn.execute(sql, (session_id, limit)).fetchall()
455
+ except (sqlite3.Error, OSError) as exc:
456
+ logger.debug("[hermes_state] session_messages(%r) error: %s", session_id, exc)
457
+ return []
458
+ out: list[dict[str, Any]] = []
459
+ for row in reversed(rows):
460
+ item: dict[str, Any] = {}
461
+ for col in cols:
462
+ try:
463
+ val = row[col]
464
+ except (IndexError, KeyError):
465
+ val = None
466
+ if isinstance(val, str) and len(val) > _MESSAGE_TEXT_CAP:
467
+ val = val[:_MESSAGE_TEXT_CAP]
468
+ item[col] = val
469
+ out.append(item)
470
+ return out
471
+
472
+
415
473
  def db_status() -> dict[str, Any]:
416
474
  """Lightweight presence/readability report for the doctor."""
417
475
  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())