@alexgreensh/token-optimizer 0.0.0-stage → 5.13.50

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 (161) hide show
  1. package/.claude-plugin/marketplace.json +76 -0
  2. package/.claude-plugin/plugin.json +21 -0
  3. package/LICENSE +130 -0
  4. package/LICENSE-SMALL-BUSINESS.md +62 -0
  5. package/PRIVACY.md +200 -0
  6. package/README.md +13 -2
  7. package/hooks/codex-hooks.json +4 -0
  8. package/hooks/hooks.json +182 -0
  9. package/hooks/module_runner.py +149 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +776 -0
  13. package/hooks/sessionstart_runner.py +629 -0
  14. package/hooks/stop_runner.py +408 -0
  15. package/hooks/userpromptsubmit_runner.py +722 -0
  16. package/hooks/windows-launcher.py +163 -0
  17. package/install-cloud.sh +23 -0
  18. package/package.json +29 -4
  19. package/skills/fleet-auditor/SKILL.md +150 -0
  20. package/skills/fleet-auditor/references/fleet-systems.md +167 -0
  21. package/skills/fleet-auditor/references/report-template.md +50 -0
  22. package/skills/fleet-auditor/references/waste-patterns.md +126 -0
  23. package/skills/fleet-auditor/scripts/fleet.py +3612 -0
  24. package/skills/fleet-auditor/scripts/shared.py +277 -0
  25. package/skills/resume-checkpoint/SKILL.md +52 -0
  26. package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
  27. package/skills/token-coach/SKILL.md +129 -0
  28. package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
  29. package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
  30. package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
  31. package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
  32. package/skills/token-coach/references/agentic-systems.md +147 -0
  33. package/skills/token-coach/references/coach-patterns.md +120 -0
  34. package/skills/token-coach/references/coaching-scripts.md +146 -0
  35. package/skills/token-coach/references/deterministic-stages.md +102 -0
  36. package/skills/token-coach/references/keepwarm-consent.md +48 -0
  37. package/skills/token-coach/references/quick-reference.md +155 -0
  38. package/skills/token-dashboard/SKILL.md +72 -0
  39. package/skills/token-optimizer/SKILL.md +150 -0
  40. package/skills/token-optimizer/assets/dashboard.html +7251 -0
  41. package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
  42. package/skills/token-optimizer/examples/hooks-starter.json +179 -0
  43. package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
  44. package/skills/token-optimizer/pricing/prices.json +695 -0
  45. package/skills/token-optimizer/references/agent-prompts.md +687 -0
  46. package/skills/token-optimizer/references/cli-reference.md +92 -0
  47. package/skills/token-optimizer/references/codex-workflow.md +188 -0
  48. package/skills/token-optimizer/references/cursor-workflow.md +74 -0
  49. package/skills/token-optimizer/references/error-recovery.md +37 -0
  50. package/skills/token-optimizer/references/implementation-playbook.md +416 -0
  51. package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
  52. package/skills/token-optimizer/references/opencode-workflow.md +72 -0
  53. package/skills/token-optimizer/references/optimization-checklist.md +714 -0
  54. package/skills/token-optimizer/references/phase0-setup.md +142 -0
  55. package/skills/token-optimizer/references/presentation-workflow.md +72 -0
  56. package/skills/token-optimizer/references/session-continuity.md +19 -0
  57. package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
  58. package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
  59. package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
  60. package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
  61. package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
  62. package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
  63. package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
  64. package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
  65. package/skills/token-optimizer/scripts/archive_result.py +1725 -0
  66. package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
  67. package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
  68. package/skills/token-optimizer/scripts/bash_hook.py +61 -0
  69. package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
  70. package/skills/token-optimizer/scripts/benchmark.py +1765 -0
  71. package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
  72. package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
  73. package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
  74. package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
  75. package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
  76. package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
  77. package/skills/token-optimizer/scripts/codex_install.py +810 -0
  78. package/skills/token-optimizer/scripts/codex_io.py +119 -0
  79. package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
  80. package/skills/token-optimizer/scripts/codex_models.py +34 -0
  81. package/skills/token-optimizer/scripts/codex_session.py +1186 -0
  82. package/skills/token-optimizer/scripts/codex_state.py +707 -0
  83. package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
  84. package/skills/token-optimizer/scripts/command_filters.py +386 -0
  85. package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
  86. package/skills/token-optimizer/scripts/compression_log.py +230 -0
  87. package/skills/token-optimizer/scripts/context_intel.py +331 -0
  88. package/skills/token-optimizer/scripts/context_pressure.py +115 -0
  89. package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
  90. package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
  91. package/skills/token-optimizer/scripts/copilot_install.py +277 -0
  92. package/skills/token-optimizer/scripts/copilot_session.py +496 -0
  93. package/skills/token-optimizer/scripts/copilot_state.py +569 -0
  94. package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
  95. package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
  96. package/skills/token-optimizer/scripts/cowork_install.py +380 -0
  97. package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
  98. package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
  99. package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
  100. package/skills/token-optimizer/scripts/cursor_install.py +423 -0
  101. package/skills/token-optimizer/scripts/cursor_session.py +303 -0
  102. package/skills/token-optimizer/scripts/cursor_state.py +348 -0
  103. package/skills/token-optimizer/scripts/delta_diff.py +110 -0
  104. package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
  105. package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
  106. package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
  107. package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
  108. package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
  109. package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
  110. package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
  111. package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
  112. package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
  113. package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
  114. package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
  115. package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
  116. package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
  117. package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
  118. package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
  119. package/skills/token-optimizer/scripts/devin_compress.py +790 -0
  120. package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
  121. package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
  122. package/skills/token-optimizer/scripts/devin_install.py +1086 -0
  123. package/skills/token-optimizer/scripts/devin_source.py +119 -0
  124. package/skills/token-optimizer/scripts/devin_state.py +330 -0
  125. package/skills/token-optimizer/scripts/devin_verify.py +67 -0
  126. package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
  127. package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
  128. package/skills/token-optimizer/scripts/grok_install.py +397 -0
  129. package/skills/token-optimizer/scripts/grok_session.py +317 -0
  130. package/skills/token-optimizer/scripts/grok_state.py +299 -0
  131. package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
  132. package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
  133. package/skills/token-optimizer/scripts/hermes_install.py +668 -0
  134. package/skills/token-optimizer/scripts/hermes_session.py +691 -0
  135. package/skills/token-optimizer/scripts/hermes_state.py +448 -0
  136. package/skills/token-optimizer/scripts/hook_io.py +120 -0
  137. package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
  138. package/skills/token-optimizer/scripts/injection.py +156 -0
  139. package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
  140. package/skills/token-optimizer/scripts/measure.py +58739 -0
  141. package/skills/token-optimizer/scripts/outline.py +53 -0
  142. package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
  143. package/skills/token-optimizer/scripts/plugin_env.py +562 -0
  144. package/skills/token-optimizer/scripts/py_trust.py +80 -0
  145. package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
  146. package/skills/token-optimizer/scripts/read_cache.py +2489 -0
  147. package/skills/token-optimizer/scripts/recovery_output.py +110 -0
  148. package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
  149. package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
  150. package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
  151. package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
  152. package/skills/token-optimizer/scripts/session_store.py +979 -0
  153. package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
  154. package/skills/token-optimizer/scripts/statusline.js +660 -0
  155. package/skills/token-optimizer/scripts/structure_map.py +2880 -0
  156. package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
  157. package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
  158. package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
  159. package/skills/token-optimizer/scripts/token_estimate.py +80 -0
  160. package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
  161. package/skills/token-optimizer/scripts/utf8_io.py +219 -0
@@ -0,0 +1,691 @@
1
+ #!/usr/bin/env python3
2
+ """Hermes session normalizer for Token Optimizer.
3
+
4
+ Converts a Hermes ``sessions`` row (as returned by ``hermes_state.py``) into
5
+ the same canonical dict shape that ``measure.py`` / the dashboard consume for
6
+ Codex and Claude Code sessions. The goal is that all downstream code can be
7
+ runtime-agnostic.
8
+
9
+ ## Key design decisions
10
+
11
+ **Cost:** Read from ``estimated_cost_usd`` in the sessions row. Hermes
12
+ pre-computes this value; if the column is NULL or ``cost_status`` is
13
+ ``'unknown'`` we fall back to TO's own ``_get_model_cost`` pricing on the
14
+ stored token counts. This mirrors the Codex session
15
+ normalizer's approach.
16
+
17
+ **Quality scoring:** Hermes does not provide per-message token granularity
18
+ (``messages.token_count`` is rarely populated). We therefore score from the
19
+ session-level fields only:
20
+
21
+ Active signals:
22
+ - Context fill (input_tokens vs model context window) — weight 0.40
23
+ - Message count risk — weight 0.35
24
+ - Output / input ratio — weight 0.25
25
+
26
+ Omitted signals (not weighted in the score):
27
+ - Cache hit rate (cache_read is present but unreliable on Hermes; included
28
+ as informational only; not wired into the score to avoid noise)
29
+ - Compaction events (the sessions row carries no successful-compaction
30
+ count. It does carry compression-health fields: failure cooldown, error,
31
+ fallback streak, ineffective count, recovery deadline — those gate the
32
+ nudge, not the quality score)
33
+ - API calls / turn ratio (api_call_count available; included as optional
34
+ compaction proxy in the grade dict but not in the weighted score because
35
+ Hermes call counts are not directly comparable to CC turns)
36
+
37
+ The grade thresholds reuse ``score_to_grade`` and ``score_to_band`` imported
38
+ from ``measure.py`` (same S/A/B/C/D/F scale).
39
+
40
+ **Model mapping:** ``model`` in Hermes sessions can be any model ID the user
41
+ configured (Claude, OpenAI, Gemini, etc.). We normalise it to a TO model
42
+ family for pricing and context-window lookup using the same helpers measure.py
43
+ exposes. Unknown models get a conservative 200 K context window and
44
+ ``cost_status='unknown'``.
45
+
46
+ **No Hermes imports:** This module is pure stdlib + measure.py helpers.
47
+ """
48
+
49
+ from __future__ import annotations
50
+
51
+ import logging
52
+ import re
53
+ import sys
54
+ from datetime import datetime, timezone
55
+ from pathlib import Path
56
+ from typing import Any
57
+
58
+ logger = logging.getLogger(__name__)
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # Lazy import of measure.py helpers (avoids circular import at module load;
62
+ # measure.py is the shared core and this adapter runs inside it or alongside).
63
+ # ---------------------------------------------------------------------------
64
+
65
+ _MEASURE_HELPERS_SENTINEL = object() # distinct from None: "not yet resolved"
66
+ _measure_helpers_result: Any = _MEASURE_HELPERS_SENTINEL
67
+
68
+
69
+ def _get_measure_helpers():
70
+ """Return (score_to_grade, score_to_band, _get_model_cost, _normalize_model_name).
71
+
72
+ Deferred so tests can import hermes_session without a full measure.py
73
+ bootstrap (e.g. when CLAUDE_PLUGIN_ROOT is unset). Result is cached ONLY
74
+ on success; a transient failure (measure.py not yet on sys.path) is retried
75
+ on the next call rather than permanently locked as None by lru_cache.
76
+ """
77
+ global _measure_helpers_result
78
+ if _measure_helpers_result is not _MEASURE_HELPERS_SENTINEL:
79
+ # Already resolved (either a tuple on success, or None stayed uncached
80
+ # on failure, so we always reach the try block again on failure).
81
+ return _measure_helpers_result
82
+ try:
83
+ # measure.py lives in the same scripts/ directory.
84
+ scripts_dir = Path(__file__).parent
85
+ if str(scripts_dir) not in sys.path:
86
+ sys.path.insert(0, str(scripts_dir))
87
+ import measure as _m # noqa: PLC0415
88
+
89
+ result = (
90
+ _m.score_to_grade,
91
+ _m.score_to_band,
92
+ _m._get_model_cost, # noqa: SLF001
93
+ _m._normalize_model_name, # noqa: SLF001
94
+ )
95
+ _measure_helpers_result = result # cache only on success
96
+ return result
97
+ except Exception as exc:
98
+ logger.debug("[hermes_session] measure.py helpers unavailable: %s", exc)
99
+ # Do NOT update the sentinel — allow retry on next call.
100
+ return None
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Constants
105
+ # ---------------------------------------------------------------------------
106
+
107
+ _UNKNOWN_MODEL = "unknown"
108
+
109
+ # Conservative context window used when model is unrecognised.
110
+ _DEFAULT_CONTEXT_WINDOW = 200_000
111
+
112
+ # Fail-safe window for an unrecognised *modern* Claude model with no parseable
113
+ # version. Too large only understates fill, whereas the 200K default cries
114
+ # "100% CRITICAL" wolf on a 1M model.
115
+ _LARGE_CONTEXT_WINDOW = 1_000_000
116
+
117
+ _CLAUDE_FAMILY_RE = re.compile(
118
+ r"(fable|mythos|opus|sonnet|haiku)(?:[-_.](\d+))?(?:[-_.](\d{1,2}))?(?!\d)")
119
+
120
+
121
+ def _claude_context_window(low: str):
122
+ """Claude window per Claude Code's model-config docs (checked 2026-10-10).
123
+
124
+ Fable, Sonnet 5+, Opus 4.7+ and Haiku 5.5 are 1M with no suffix; Sonnet
125
+ 4.6 / Opus 4.6 are 1M only as the ``[1m]`` variant (200K without); every
126
+ older Claude is 200K. None when ``low`` is not a Claude id.
127
+ """
128
+ if not (low.startswith("claude") or re.match(
129
+ r"^(fable|mythos|opus|sonnet|haiku)(?:[-_.]\d|$)", low)):
130
+ return None
131
+ one_m = "[1m]" in low or "1000k" in low
132
+ ident = re.sub(r"[-@]\d{8}$", "", low.replace("[1m]", ""))
133
+ if re.search(r"claude[-_]?[0-3]\b", ident) or re.search(
134
+ r"claude-\d(?:[-.]\d)?-(opus|sonnet|haiku)", ident):
135
+ return 200_000
136
+ m = _CLAUDE_FAMILY_RE.search(ident)
137
+ if not m:
138
+ return None
139
+ family, major_raw, minor_raw = m.groups()
140
+ if family in ("fable", "mythos"):
141
+ return 1_000_000
142
+ major = int(major_raw) if major_raw else None
143
+ minor = int(minor_raw) if minor_raw else 0
144
+ if family == "haiku":
145
+ if major is None:
146
+ return 200_000
147
+ return 1_000_000 if (major, minor) >= (5, 5) else 200_000
148
+ if major is None or major >= 5:
149
+ return 1_000_000
150
+ if major == 4 and family == "opus" and minor >= 7:
151
+ return 1_000_000
152
+ if major == 4 and minor == 6:
153
+ return 1_000_000 if one_m else 200_000
154
+ return 200_000
155
+
156
+
157
+ # Known Hermes model → approximate context window (tokens).
158
+ # Claude context windows; OpenAI/Gemini models handled via measure.py pricing.
159
+ _MODEL_CONTEXT_WINDOWS: dict[str, int] = {
160
+ # Claude ids resolve through _claude_context_window() (per-model doc table).
161
+ "gpt-4o": 128_000,
162
+ "gpt-4o-mini": 128_000,
163
+ "gpt-4.1": 1_047_576,
164
+ "gpt-4.1-mini": 1_047_576,
165
+ "gpt-4.1-nano": 1_047_576,
166
+ "gpt-5": 1_000_000,
167
+ "gpt-5.1": 1_000_000,
168
+ "o3": 200_000,
169
+ "o4-mini": 200_000,
170
+ "gemini-2.5-pro": 1_000_000,
171
+ "gemini-2.5-flash": 1_000_000,
172
+ "gemini-3-pro": 1_000_000,
173
+ "gemini-3-flash": 1_000_000,
174
+ }
175
+
176
+ # Signals active for Hermes (documented for operators / tests).
177
+ ACTIVE_QUALITY_SIGNALS = (
178
+ "context_fill", # input_tokens / model_context_window
179
+ "message_count", # risk from long session
180
+ "output_input_ratio", # productivity signal
181
+ )
182
+
183
+ OMITTED_QUALITY_SIGNALS = (
184
+ "cache_hit_rate", # cache_read present but unreliable in Hermes
185
+ "compaction_events", # no successful-compaction count in the sessions row
186
+ # (compression-health fields exist and gate the nudge)
187
+ "api_per_message", # api_call_count not directly comparable to CC turns
188
+ )
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # Model helpers
193
+ # ---------------------------------------------------------------------------
194
+
195
+ # Bedrock inference-profile ids are dot-qualified
196
+ # ("us.anthropic.claude-haiku-4-5", "global.anthropic.claude-sonnet-4-5"): a
197
+ # leading chain of known provider/region tokens. Mirror of measure.py's
198
+ # _DOTTED_PROVIDER_PREFIX_RE; dots are only cut on KNOWN tokens so versioned
199
+ # ids like "gpt-4.1" or "claude-3.5-sonnet" are never split.
200
+ _DOTTED_PROVIDER_PREFIX_RE = re.compile(
201
+ r"^(?:(?:anthropic|openai|google|gemini|vertex|bedrock|openrouter|gateway"
202
+ r"|litellm|azure|aws|amazon|us|us-gov|eu|ap|apac|au|ca|cn|global|jp|sa|me"
203
+ r"|af|il)\.)+")
204
+
205
+
206
+ def _context_window_for_model(model: str) -> int:
207
+ """Return the context window (tokens) for a Hermes model string."""
208
+ if not model or model == _UNKNOWN_MODEL:
209
+ return _DEFAULT_CONTEXT_WINDOW
210
+ low = model.lower().strip()
211
+ # Strip a provider prefix (e.g. "anthropic/claude-fable-5",
212
+ # "openrouter/anthropic/claude-sonnet-5", "us.anthropic.claude-haiku-4-5")
213
+ # so vendor-qualified ids resolve like their bare form instead of falling
214
+ # through to the default.
215
+ if "/" in low:
216
+ low = low.rsplit("/", 1)[-1]
217
+ low = _DOTTED_PROVIDER_PREFIX_RE.sub("", low)
218
+ claude = _claude_context_window(low)
219
+ if claude is not None:
220
+ return claude
221
+ # Direct lookup, then prefix match for versioned variants.
222
+ if low in _MODEL_CONTEXT_WINDOWS:
223
+ return _MODEL_CONTEXT_WINDOWS[low]
224
+ for key, window in _MODEL_CONTEXT_WINDOWS.items():
225
+ if low.startswith(key):
226
+ return window
227
+ if low.startswith("claude-") and not low.startswith(("claude-2", "claude-3")):
228
+ return _LARGE_CONTEXT_WINDOW
229
+ return _DEFAULT_CONTEXT_WINDOW
230
+
231
+
232
+ _PLAIN_46_RE = re.compile(r"(?:^|[^a-z])(?:opus|sonnet)[-_.]4[-_.]6(?!\d)")
233
+
234
+
235
+ def promote_window_for_observed_tokens(model: str, window: int, tokens) -> int:
236
+ """Opus/Sonnet 4.6 are 1M only as the ``[1m]`` variant, but runtimes record
237
+ the plain id. Tokens above the 200K window prove it is the 1M variant, so
238
+ widen instead of clamping to 100%. Any other model, or tokens that fit,
239
+ leave the window alone.
240
+ """
241
+ low = (model or "").lower()
242
+ if (window >= _LARGE_CONTEXT_WINDOW or "[1m]" in low or not _PLAIN_46_RE.search(low)):
243
+ return window
244
+ try:
245
+ if tokens is not None and float(tokens) > window:
246
+ return _LARGE_CONTEXT_WINDOW
247
+ except (TypeError, ValueError):
248
+ pass
249
+ return window
250
+
251
+
252
+ # Public alias so hermes/__init__.py can import the single source of truth.
253
+ context_window_for_model = _context_window_for_model
254
+
255
+
256
+ def _compute_cost_fallback(
257
+ model: str,
258
+ input_tokens: int,
259
+ output_tokens: int,
260
+ cache_read: int = 0,
261
+ cache_write: int = 0,
262
+ ) -> float:
263
+ """Compute USD cost via TO's pricing as a fallback when Hermes has no cost.
264
+
265
+ Returns 0.0 on any error (pricing unknown, measure.py unavailable).
266
+ """
267
+ helpers = _get_measure_helpers()
268
+ if helpers is None:
269
+ return 0.0
270
+ _score_to_grade, _score_to_band, _get_model_cost, _normalize_model_name = helpers
271
+ try:
272
+ return _get_model_cost(
273
+ model,
274
+ input_tokens,
275
+ output_tokens,
276
+ cache_read=cache_read,
277
+ cache_create=cache_write,
278
+ )
279
+ except Exception as exc:
280
+ logger.debug("[hermes_session] pricing fallback error for %r: %s", model, exc)
281
+ return 0.0
282
+
283
+
284
+ def _resolve_model_family(model: str) -> str:
285
+ """Return the TO model family label (opus/sonnet/haiku/unknown)."""
286
+ helpers = _get_measure_helpers()
287
+ if helpers is None:
288
+ return _UNKNOWN_MODEL
289
+ _score_to_grade, _score_to_band, _get_model_cost, _normalize_model_name = helpers
290
+ try:
291
+ family = _normalize_model_name(model)
292
+ return family or _UNKNOWN_MODEL
293
+ except Exception:
294
+ return _UNKNOWN_MODEL
295
+
296
+
297
+ # ---------------------------------------------------------------------------
298
+ # Quality scoring
299
+ # ---------------------------------------------------------------------------
300
+
301
+ # Distinguishes "caller did not opt in" from "opted in but occupancy is
302
+ # unavailable": callers that never pass ``context_tokens`` keep the lifetime
303
+ # fill their scores shipped with, while Hermes callers pass an explicit value
304
+ # (``None`` = measured-but-unavailable) to get live-occupancy scoring.
305
+ _LIVE_CONTEXT_UNSET: Any = object()
306
+
307
+
308
+ def compute_quality_score(
309
+ input_tokens: int,
310
+ output_tokens: int,
311
+ message_count: int,
312
+ model: str = _UNKNOWN_MODEL,
313
+ *,
314
+ context_window: int | None = None,
315
+ cache_read: int = 0,
316
+ context_tokens: int | None | object = _LIVE_CONTEXT_UNSET,
317
+ ) -> dict[str, Any]:
318
+ """Score Hermes session context quality from available session-level fields.
319
+
320
+ Two fill modes, chosen by whether the caller passes ``context_tokens``:
321
+
322
+ - Not passed (the Cursor/Copilot/Grok/Antigravity adapters): the legacy
323
+ lifetime fill numerator ``input_tokens + cache_read`` — both occupy the
324
+ same context window, so a session that read 160K cached tokens against
325
+ a 200K window is 80% full, not 0%.
326
+ - Passed (the Hermes path): live prompt occupancy only. Hermes session
327
+ rows store lifetime totals — every API call re-sends the prompt, so
328
+ summing them is never a context-window measurement — and only the
329
+ provider-reported latest prompt counts. A non-positive or non-numeric
330
+ value is "measured but unavailable": fill is omitted rather than
331
+ fabricated and the two remaining signals renormalize below.
332
+
333
+ Grade thresholds reuse measure.py's ``score_to_grade`` / ``score_to_band``
334
+ exactly.
335
+
336
+ Returns a dict with: score (0-100 int), grade (letter), band (label),
337
+ signals_active (list), signals_omitted (list).
338
+ """
339
+ ctx_win = context_window if context_window and context_window > 0 else _context_window_for_model(model)
340
+ # Only a live prompt reading proves a window; the legacy lifetime sum
341
+ # re-counts every call and exceeds any window by construction.
342
+ if context_tokens is not _LIVE_CONTEXT_UNSET:
343
+ ctx_win = promote_window_for_observed_tokens(model, ctx_win, context_tokens)
344
+
345
+ # Signal 1: Context fill (40% weight when present).
346
+ if context_tokens is _LIVE_CONTEXT_UNSET:
347
+ fill_available = True
348
+ fill_numerator = input_tokens + max(0, cache_read)
349
+ fill_ratio = min(1.0, max(0.0, fill_numerator / ctx_win)) if ctx_win > 0 else 0.0
350
+ context_source = "lifetime_tokens"
351
+ else:
352
+ fill_available = (
353
+ isinstance(context_tokens, (int, float))
354
+ and not isinstance(context_tokens, bool)
355
+ and context_tokens > 0
356
+ )
357
+ fill_ratio = min(1.0, max(0.0, context_tokens / ctx_win)) if fill_available and ctx_win > 0 else None
358
+ context_source = "provider_prompt_tokens" if fill_available else "unavailable"
359
+ if not fill_available:
360
+ fill_score = None
361
+ elif fill_ratio < 0.30:
362
+ fill_score = 100
363
+ elif fill_ratio < 0.50:
364
+ fill_score = 80
365
+ elif fill_ratio < 0.70:
366
+ fill_score = 55
367
+ elif fill_ratio < 0.85:
368
+ fill_score = 30
369
+ else:
370
+ fill_score = 10
371
+
372
+ # Signal 2: Message count risk (35% weight)
373
+ if message_count <= 20:
374
+ msg_score = 100
375
+ elif message_count <= 40:
376
+ msg_score = 80
377
+ elif message_count <= 60:
378
+ msg_score = 55
379
+ elif message_count <= 100:
380
+ msg_score = 30
381
+ else:
382
+ msg_score = 10
383
+
384
+ # Signal 3: Output / input ratio (25% weight)
385
+ if input_tokens > 0:
386
+ oi_ratio = output_tokens / input_tokens
387
+ else:
388
+ oi_ratio = 1.0
389
+ if oi_ratio >= 0.05:
390
+ oi_score = 100
391
+ elif oi_ratio >= 0.02:
392
+ oi_score = 70
393
+ elif oi_ratio >= 0.01:
394
+ oi_score = 40
395
+ else:
396
+ oi_score = 15
397
+
398
+ if fill_available:
399
+ weights = {"fill": 0.40, "message_count": 0.35, "output_input_ratio": 0.25}
400
+ raw = (
401
+ fill_score * weights["fill"]
402
+ + msg_score * weights["message_count"]
403
+ + oi_score * weights["output_input_ratio"]
404
+ )
405
+ else:
406
+ # Preserve the relative 35:25 weighting when occupancy is unavailable.
407
+ weights = {"fill": 0.0, "message_count": 7 / 12, "output_input_ratio": 5 / 12}
408
+ raw = msg_score * weights["message_count"] + oi_score * weights["output_input_ratio"]
409
+ final = int(round(min(100, max(0, raw))))
410
+
411
+ helpers = _get_measure_helpers()
412
+ if helpers:
413
+ score_to_grade, score_to_band = helpers[0], helpers[1]
414
+ grade = score_to_grade(final)
415
+ band = score_to_band(final)
416
+ else:
417
+ # Inline fallback thresholds matching measure.py exactly.
418
+ if final >= 90:
419
+ grade = "S"
420
+ elif final >= 80:
421
+ grade = "A"
422
+ elif final >= 70:
423
+ grade = "B"
424
+ elif final >= 55:
425
+ grade = "C"
426
+ elif final >= 40:
427
+ grade = "D"
428
+ else:
429
+ grade = "F"
430
+ if final >= 80:
431
+ band = "Good"
432
+ elif final >= 60:
433
+ band = "Fair"
434
+ elif final >= 40:
435
+ band = "Needs Work"
436
+ else:
437
+ band = "Poor"
438
+
439
+ return {
440
+ "score": final,
441
+ "grade": grade,
442
+ "band": band,
443
+ "fill_ratio": round(fill_ratio, 4) if fill_ratio is not None else None,
444
+ "context_window_used": ctx_win,
445
+ "context_source": context_source,
446
+ "signals_active": list(ACTIVE_QUALITY_SIGNALS if fill_available else ACTIVE_QUALITY_SIGNALS[1:]),
447
+ "signals_omitted": list(OMITTED_QUALITY_SIGNALS) + ([] if fill_available else ["context_fill"]),
448
+ "signal_scores": {
449
+ "fill": fill_score,
450
+ "message_count": msg_score,
451
+ "output_input_ratio": oi_score,
452
+ },
453
+ "signal_weights": weights,
454
+ }
455
+
456
+
457
+ # ---------------------------------------------------------------------------
458
+ # Session normalizer
459
+ # ---------------------------------------------------------------------------
460
+
461
+ def _parse_ts(value: Any) -> str | None:
462
+ """Convert a float epoch or ISO string to ISO-8601 string, or None."""
463
+ if value is None:
464
+ return None
465
+ try:
466
+ if isinstance(value, (int, float)):
467
+ return datetime.fromtimestamp(float(value), tz=timezone.utc).isoformat()
468
+ return str(value)
469
+ except (OSError, ValueError, OverflowError):
470
+ return None
471
+
472
+
473
+ def _safe_int(value: Any, default: int = 0) -> int:
474
+ try:
475
+ return int(float(value)) if value is not None else default
476
+ except (TypeError, ValueError, OverflowError):
477
+ return default
478
+
479
+
480
+ def normalize_session(row: dict[str, Any], *, context_tokens: int | None = None) -> dict[str, Any] | None:
481
+ """Normalize a Hermes sessions row into TO's canonical session shape.
482
+
483
+ Returns a dict matching the keys that ``measure.py`` / the dashboard
484
+ consume from Codex / Claude Code session data. Returns None when the
485
+ row is empty or has no meaningful activity (no tokens and no messages).
486
+
487
+ Cost strategy:
488
+ - If ``estimated_cost_usd`` is non-NULL → use it directly (cost_source
489
+ set to "hermes_estimated").
490
+ - If NULL / cost_status=="unknown" → compute via TO's _get_model_cost on
491
+ stored token counts (cost_source set to "to_pricing_fallback").
492
+
493
+ Quality:
494
+ Calls ``compute_quality_score`` with session-level fields. The quality
495
+ dict is embedded under the "quality" key.
496
+ """
497
+ if not row:
498
+ return None
499
+
500
+ model = str(row.get("model") or _UNKNOWN_MODEL).strip() or _UNKNOWN_MODEL
501
+ # M2: clamp all five token fields to non-negative so a corrupt/negative DB
502
+ # row can never produce a negative cost or fabricated savings.
503
+ input_tokens = max(0, _safe_int(row.get("input_tokens")))
504
+ output_tokens = max(0, _safe_int(row.get("output_tokens")))
505
+ cache_read = max(0, _safe_int(row.get("cache_read_tokens")))
506
+ cache_write = max(0, _safe_int(row.get("cache_write_tokens")))
507
+ reasoning = max(0, _safe_int(row.get("reasoning_tokens")))
508
+ message_count = _safe_int(row.get("message_count"))
509
+ tool_call_count = _safe_int(row.get("tool_call_count"))
510
+ api_call_count = _safe_int(row.get("api_call_count"))
511
+
512
+ # Reject completely empty sessions.
513
+ if input_tokens == 0 and output_tokens == 0 and message_count == 0:
514
+ return None
515
+
516
+ # Cost resolution.
517
+ raw_cost = row.get("estimated_cost_usd")
518
+ cost_status = str(row.get("cost_status") or "unknown").lower()
519
+
520
+ if raw_cost is not None and cost_status != "unknown":
521
+ try:
522
+ cost_usd = float(raw_cost)
523
+ used_cost_source = "hermes_estimated"
524
+ except (TypeError, ValueError):
525
+ cost_usd = None
526
+ used_cost_source = "unknown"
527
+ else:
528
+ cost_usd = None
529
+ used_cost_source = "unknown"
530
+
531
+ if cost_usd is None:
532
+ cost_usd = _compute_cost_fallback(model, input_tokens, output_tokens, cache_read, cache_write)
533
+ used_cost_source = "to_pricing_fallback"
534
+
535
+ # Model family for downstream model_usage breakdown.
536
+ model_family = _resolve_model_family(model)
537
+
538
+ # Context window for fill calculation.
539
+ ctx_window = promote_window_for_observed_tokens(
540
+ model, _context_window_for_model(model), context_tokens)
541
+
542
+ # M1: Align with the savings engine's convention.
543
+ #
544
+ # _session_token_vector (measure.py) assumes session_log.input_tokens already
545
+ # contains TOTAL billed input = fresh_input + cache_read + cache_write (same
546
+ # as the Claude Code / Codex convention: input_tokens from the API is the
547
+ # aggregate billed count). It then reconstructs each class via cache_hit_rate
548
+ # and cache_create_1h_tokens.
549
+ #
550
+ # Hermes DB stores input_tokens as FRESH-ONLY and cache tokens separately, so
551
+ # we must roll them up before writing to session_log:
552
+ # total_input_tokens = fresh_input + cache_read + cache_write
553
+ # total_cache_create_1h = cache_write (Hermes has no TTL split; use 1h)
554
+ # total_cache_create_5m = 0 (no 5-min TTL in Hermes)
555
+ # cache_hit_rate = cache_read / total_input_tokens
556
+ #
557
+ # This lets _session_token_vector reconstruct (fresh, cw, cr, out) accurately:
558
+ # cw = cache_create_1h = cache_write
559
+ # hit = cache_read / total_input
560
+ # cr = total_input * hit ≈ cache_read
561
+ # fi = total_input * (1 - hit) - cw ≈ fresh_input
562
+ total_input_for_savings = input_tokens + cache_read + cache_write
563
+ cache_hit_rate = cache_read / total_input_for_savings if total_input_for_savings > 0 else 0.0
564
+
565
+ # Duration.
566
+ started_at_raw = row.get("started_at")
567
+ ended_at_raw = row.get("ended_at")
568
+ duration_minutes = 0.0
569
+ if started_at_raw is not None and ended_at_raw is not None:
570
+ try:
571
+ duration_minutes = max(0.0, (float(ended_at_raw) - float(started_at_raw)) / 60.0)
572
+ except (TypeError, ValueError):
573
+ duration_minutes = 0.0
574
+
575
+ # Quality score from available signals only. The session counters remain
576
+ # useful for cost, but only the latest provider prompt can measure occupancy.
577
+ quality = compute_quality_score(
578
+ input_tokens=input_tokens,
579
+ output_tokens=output_tokens,
580
+ message_count=message_count,
581
+ model=model,
582
+ context_window=ctx_window,
583
+ cache_read=cache_read,
584
+ context_tokens=context_tokens,
585
+ )
586
+
587
+ # Topic: use title from Hermes if available. It is user text persisted to
588
+ # session_log — redact credentials, or drop if the redactor refuses.
589
+ title = str(row.get("title") or "").strip() or None
590
+ if title:
591
+ try:
592
+ from credential_patterns import redact_credentials
593
+ title = redact_credentials(title)
594
+ except Exception:
595
+ title = None
596
+
597
+ # model_usage / model_usage_breakdown: mirrors the Codex normalizer's shape.
598
+ # M1: billable uses the original fresh_input (input_tokens) + output so the
599
+ # model_usage key reflects actual API call volume, not the rolled-up total.
600
+ billable = input_tokens + output_tokens
601
+ model_key = model if model != _UNKNOWN_MODEL else "hermes"
602
+ model_usage = {model_key: billable}
603
+ model_usage_breakdown = {
604
+ model_key: {
605
+ "fresh_input": input_tokens,
606
+ "cache_read": cache_read,
607
+ "cache_create": cache_write,
608
+ "output": output_tokens + reasoning,
609
+ }
610
+ }
611
+
612
+ return {
613
+ # Identity
614
+ "slug": str(row.get("id") or ""),
615
+ "topic": title,
616
+ # Timestamps
617
+ "first_ts": _parse_ts(started_at_raw),
618
+ "last_ts": _parse_ts(ended_at_raw),
619
+ "duration_minutes": round(duration_minutes, 2),
620
+ # Token counts — engine convention: input = total billed (fresh+cr+cw).
621
+ # M1: total_input_tokens is the rolled-up total so _session_token_vector
622
+ # can reconstruct each class via cache_hit_rate + cache_create_1h.
623
+ "total_input_tokens": total_input_for_savings,
624
+ "total_output_tokens": output_tokens,
625
+ "total_cache_read": cache_read,
626
+ "total_cache_create": cache_write,
627
+ "total_cache_create_1h": cache_write, # M1: forward cache_write here
628
+ "total_cache_create_5m": 0, # no 5-min TTL in Hermes
629
+ # Context window (for fill %, dashboard)
630
+ "model_context_window": ctx_window,
631
+ # Cache efficiency
632
+ "cache_hit_rate": round(cache_hit_rate, 4),
633
+ # Cost
634
+ "cost_usd": round(cost_usd, 6),
635
+ "cost_source": used_cost_source,
636
+ # Model
637
+ "model": model,
638
+ "model_family": model_family if model_family != _UNKNOWN_MODEL else None,
639
+ "model_usage": model_usage,
640
+ "model_usage_breakdown": model_usage_breakdown,
641
+ # Activity counts
642
+ "message_count": message_count,
643
+ "api_calls": api_call_count,
644
+ "tool_calls": {"total": tool_call_count},
645
+ # Standard keys measure.py checks
646
+ "estimated": False, # token counts come directly from Hermes DB, not estimated
647
+ "token_source": "hermes_db",
648
+ "runtime": "hermes",
649
+ "version": None,
650
+ # Placeholders for signals Codex provides that Hermes does not.
651
+ "avg_call_gap_seconds": None,
652
+ "max_call_gap_seconds": None,
653
+ "p95_call_gap_seconds": None,
654
+ "rate_limits": None,
655
+ "effort": None,
656
+ "effort_breakdown": {},
657
+ "skills_used": {},
658
+ "subagents_used": {},
659
+ "tool_duration_p90_ms": None,
660
+ "task_duration_ms_max": None,
661
+ "ttft_ms_avg": None,
662
+ # Quality
663
+ "quality": quality,
664
+ "quality_score": quality["score"],
665
+ "quality_grade": quality["grade"],
666
+ "quality_band": quality["band"],
667
+ # Session metadata
668
+ "end_reason": str(row.get("end_reason") or ""),
669
+ "archived": bool(_safe_int(row.get("archived"))),
670
+ "cwd": row.get("cwd"),
671
+ "billing_provider": row.get("billing_provider"),
672
+ }
673
+
674
+
675
+ if __name__ == "__main__":
676
+ import json
677
+ import sys as _sys
678
+
679
+ # Quick smoke test against a fixture DB when run directly.
680
+ try:
681
+ from hermes_state import get_session # noqa: PLC0415
682
+
683
+ row = get_session("s-heavy")
684
+ if row:
685
+ norm = normalize_session(row)
686
+ print(json.dumps(norm, indent=2, default=str))
687
+ else:
688
+ print("No session found (DB may not be at default path).", file=_sys.stderr)
689
+ except Exception as exc:
690
+ print(f"Error: {exc}", file=_sys.stderr)
691
+ raise