@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,448 @@
1
+ #!/usr/bin/env python3
2
+ """Read-only reader for Hermes agent's runtime SQLite state.
3
+
4
+ NousResearch/hermes-agent stores per-session token + cost data in a clean
5
+ SQLite schema at ``~/.hermes/state.db``. This module reads that database to
6
+ power cost pass-through, quality scoring, and dashboard rollup in Token
7
+ Optimizer's Hermes adapter.
8
+
9
+ Design constraints (mirroring codex_state.py):
10
+
11
+ - **Pure stdlib only.** No import of Hermes modules (``agent.*``, etc.).
12
+ Hermes's own ``hermes_state.py`` transitively imports ``agent.memory_manager``
13
+ and other heavy dependencies; coupling TO to those would break standalone CLI
14
+ and fixture tests and couple us to Hermes internals. We open the DB
15
+ read-only with plain ``sqlite3``.
16
+ - **Strictly read-only.** Opens with ``file:...?mode=ro`` URI + sets
17
+ ``PRAGMA query_only = ON`` as defence-in-depth. Sets a short busy-timeout
18
+ so a locked DB degrades gracefully instead of hanging.
19
+ - **Tolerates schema drift.** Missing columns fall back to safe defaults; a
20
+ missing table returns an empty/zero result; a missing DB file returns an
21
+ empty result (no exception). Every public function degrades rather than
22
+ raises so hook callbacks that call us never crash the host agent.
23
+ - **Minimal open window.** Each function opens, queries, closes. No
24
+ long-lived connections that would defer WAL checkpoints inside Hermes.
25
+
26
+ Path resolution: ``~/.hermes/state.db`` by default; override via
27
+ ``HERMES_HOME`` env var (mirrors how Hermes itself uses
28
+ ``hermes_constants.get_hermes_home()``). Unsafe/relative values are rejected
29
+ with a warning, matching the ``codex_home()`` / ``_safe_home_from_env``
30
+ pattern in ``runtime_env.py``.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import logging
36
+ import os
37
+ import sqlite3
38
+ import time
39
+ from contextlib import contextmanager
40
+ from pathlib import Path
41
+ from typing import Any, Iterator
42
+
43
+ logger = logging.getLogger(__name__)
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Constants
47
+ # ---------------------------------------------------------------------------
48
+
49
+ _HERMES_HOME_ENV = "HERMES_HOME"
50
+ _DEFAULT_HERMES_DIR = ".hermes"
51
+ _DB_NAME = "state.db"
52
+ _BUSY_TIMEOUT_SECONDS = 0.25
53
+ _MAX_ROWS = 2000
54
+
55
+ # Columns we select from sessions. Ordered to match ``_SESSION_DEFAULTS``.
56
+ _SESSION_COLUMNS = (
57
+ "id",
58
+ "model",
59
+ "started_at",
60
+ "ended_at",
61
+ "end_reason",
62
+ "message_count",
63
+ "tool_call_count",
64
+ "api_call_count",
65
+ "input_tokens",
66
+ "output_tokens",
67
+ "cache_read_tokens",
68
+ "cache_write_tokens",
69
+ "reasoning_tokens",
70
+ "estimated_cost_usd",
71
+ "actual_cost_usd",
72
+ "cost_status",
73
+ "cost_source",
74
+ "archived",
75
+ "title",
76
+ "cwd",
77
+ "billing_provider",
78
+ "billing_mode",
79
+ "compression_failure_cooldown_until",
80
+ "compression_failure_error",
81
+ "compression_fallback_streak",
82
+ "compression_ineffective_count",
83
+ "compression_recovery_deadline",
84
+ )
85
+
86
+ _SESSION_DEFAULTS: dict[str, Any] = {
87
+ "id": "",
88
+ "model": "unknown",
89
+ "started_at": None,
90
+ "ended_at": None,
91
+ "end_reason": None,
92
+ "message_count": 0,
93
+ "tool_call_count": 0,
94
+ "api_call_count": 0,
95
+ "input_tokens": 0,
96
+ "output_tokens": 0,
97
+ "cache_read_tokens": 0,
98
+ "cache_write_tokens": 0,
99
+ "reasoning_tokens": 0,
100
+ "estimated_cost_usd": None,
101
+ "actual_cost_usd": None,
102
+ "cost_status": "unknown",
103
+ "cost_source": None,
104
+ "archived": 0,
105
+ "title": "",
106
+ "cwd": None,
107
+ "billing_provider": None,
108
+ "billing_mode": None,
109
+ "compression_failure_cooldown_until": None,
110
+ "compression_failure_error": None,
111
+ "compression_fallback_streak": 0,
112
+ "compression_ineffective_count": 0,
113
+ "compression_recovery_deadline": None,
114
+ }
115
+
116
+ # Whitelist of tables this module ever inspects.
117
+ _ALLOWED_TABLES = frozenset({"sessions", "messages", "schema_version", "state_meta"})
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Path resolution
122
+ # ---------------------------------------------------------------------------
123
+
124
+ def _home_root() -> Path:
125
+ return Path.home().resolve(strict=False)
126
+
127
+
128
+ def _is_safe_home_dir(path: Path) -> bool:
129
+ """True when path is a non-symlink directory under the user's home."""
130
+ try:
131
+ if not path.is_absolute():
132
+ return False
133
+ resolved = path.resolve(strict=False)
134
+ home = _home_root()
135
+ if resolved == home or not resolved.is_relative_to(home):
136
+ return False
137
+ if path.exists():
138
+ return path.is_dir() and not path.is_symlink()
139
+ return False
140
+ except (OSError, ValueError):
141
+ return False
142
+
143
+
144
+ # Default-off explicit override: on containerized deploys (Docker/Umbrel)
145
+ # the runtime home may be a PARENT of $HOME (e.g. HERMES_HOME=/opt/data with
146
+ # HOME=/opt/data/home). This drops ONLY the under-$HOME containment policy;
147
+ # every other safety check (absolute, resolve, exists, is_dir, not symlink)
148
+ # is still enforced by _is_safe_home_dir_relaxed below. Mirrors runtime_env.py
149
+ # so the read-only state.db reader agrees with the installer.
150
+ _UNSAFE_RUNTIME_HOME_OVERRIDE_ENV = "TOKEN_OPTIMIZER_ALLOW_UNSAFE_RUNTIME_HOME"
151
+
152
+
153
+ def _truthy_env(env_var: str) -> bool:
154
+ """Parse a truthy env var (1/true/yes/on, case-insensitive). Mirrors the
155
+ parser style in measure.py/runtime_env.py without importing either (keeps
156
+ hermes_state dependency-light)."""
157
+ val = os.environ.get(env_var)
158
+ return isinstance(val, str) and val.strip().lower() in ("1", "true", "yes", "on")
159
+
160
+
161
+ def _is_safe_home_dir_relaxed(path: Path) -> bool:
162
+ """Like _is_safe_home_dir but DROPS the under-$HOME containment check.
163
+
164
+ Keeps every other guard: absolute path, resolve(strict=False), must exist,
165
+ must be a real dir, must NOT be a symlink. Used only when the explicit
166
+ TOKEN_OPTIMIZER_ALLOW_UNSAFE_RUNTIME_HOME override is truthy, for
167
+ containerized deploys where the runtime home is a parent of $HOME.
168
+ """
169
+ try:
170
+ if not path.is_absolute():
171
+ return False
172
+ path.resolve(strict=False)
173
+ if path.exists():
174
+ return path.is_dir() and not path.is_symlink()
175
+ return False
176
+ except (OSError, ValueError):
177
+ return False
178
+
179
+
180
+ def hermes_home() -> Path:
181
+ """Return the Hermes data directory, safely honoring HERMES_HOME when valid."""
182
+ raw = os.environ.get(_HERMES_HOME_ENV, "").strip()
183
+ if raw:
184
+ candidate = Path(raw).expanduser()
185
+ if _is_safe_home_dir(candidate):
186
+ return candidate.resolve(strict=False)
187
+ # Override: on containerized deploys (Docker/Umbrel) the runtime
188
+ # home may be a PARENT of $HOME. When the explicit override env var is
189
+ # truthy, re-validate with the under-$HOME requirement DROPPED but all
190
+ # other checks kept (absolute, resolve, exists, is_dir, not symlink).
191
+ if _truthy_env(_UNSAFE_RUNTIME_HOME_OVERRIDE_ENV) and _is_safe_home_dir_relaxed(candidate):
192
+ return candidate.resolve(strict=False)
193
+ logger.warning(
194
+ "[Token Optimizer] HERMES_HOME=%r rejected (not a safe directory). Using default.",
195
+ raw,
196
+ )
197
+ return Path.home() / _DEFAULT_HERMES_DIR
198
+
199
+
200
+ def state_db_path() -> Path:
201
+ """Return the canonical path to Hermes's state.db."""
202
+ return hermes_home() / _DB_NAME
203
+
204
+
205
+ # ---------------------------------------------------------------------------
206
+ # Internal connection helpers
207
+ # ---------------------------------------------------------------------------
208
+
209
+ @contextmanager
210
+ def _ro_connect(path: Path, *, immutable: bool = True) -> Iterator[sqlite3.Connection]:
211
+ """Open ``path`` read-only with a short busy-timeout; always close.
212
+
213
+ Never writes, never checkpoints, never attaches. Uses PRAGMA query_only
214
+ as defence-in-depth so even future code changes cannot write via this
215
+ connection.
216
+
217
+ ``immutable=True`` (the default) reads the checkpointed main file only.
218
+ Pass ``immutable=False`` for a WAL-visible view: plain ``mode=ro`` reads
219
+ committed -wal pages, which is what a probe of the *live* session needs —
220
+ with immutable=1 the read silently misses writes that have not checkpointed
221
+ yet. The trade-off is that non-immutable opens may consult/create the
222
+ -shm/-wal side files, so it is opt-in per call site.
223
+ """
224
+ # Q3: immutable=1 prevents SQLite from creating WAL/SHM side-effect files
225
+ # when opening a read-only view of a DB owned by another process (Hermes).
226
+ # H-2: build the file: URI via Path.as_uri() rather than string
227
+ # interpolation. With uri=True, characters like ?, #, % and spaces in the
228
+ # path are URI syntax, so a path containing '?' would start the query
229
+ # string early and could drop or override mode=ro (opening read-write).
230
+ # N-4 (M-3 parity): resolve() first so a relative path doesn't raise an
231
+ # uncaught ValueError past callers that only catch (sqlite3.Error, OSError).
232
+ db_uri = Path(path).resolve().as_uri()
233
+ uri = f"{db_uri}?mode=ro" + ("&immutable=1" if immutable else "")
234
+ conn = sqlite3.connect(
235
+ uri,
236
+ uri=True,
237
+ timeout=_BUSY_TIMEOUT_SECONDS,
238
+ )
239
+ try:
240
+ conn.execute("PRAGMA query_only = ON")
241
+ conn.row_factory = sqlite3.Row
242
+ yield conn
243
+ finally:
244
+ conn.close()
245
+
246
+
247
+ def _table_columns(conn: sqlite3.Connection, table: str) -> set[str]:
248
+ """Return column names of ``table``, or empty set when it does not exist.
249
+
250
+ Guards every read against a missing table or renamed column on a future
251
+ Hermes schema version. ``PRAGMA table_info`` returns no rows for an
252
+ unknown table, so this doubles as an existence check.
253
+ """
254
+ if table not in _ALLOWED_TABLES:
255
+ return set()
256
+ try:
257
+ rows = conn.execute(f"PRAGMA table_info({table})").fetchall()
258
+ except sqlite3.Error:
259
+ return set()
260
+ return {str(row[1]) for row in rows}
261
+
262
+
263
+ def _safe_int(value: Any, default: int = 0) -> int:
264
+ try:
265
+ return int(float(value)) if value is not None else default
266
+ except (TypeError, ValueError, OverflowError):
267
+ return default
268
+
269
+
270
+ def _safe_float(value: Any) -> float | None:
271
+ if value is None:
272
+ return None
273
+ try:
274
+ return float(value)
275
+ except (TypeError, ValueError):
276
+ return None
277
+
278
+
279
+ def _row_to_dict(row: sqlite3.Row, available_cols: set[str]) -> dict[str, Any]:
280
+ """Convert a sqlite3.Row to a plain dict, falling back to defaults for missing columns."""
281
+ result: dict[str, Any] = dict(_SESSION_DEFAULTS)
282
+ for col in _SESSION_COLUMNS:
283
+ if col in available_cols:
284
+ try:
285
+ val = row[col]
286
+ except (IndexError, KeyError):
287
+ val = _SESSION_DEFAULTS.get(col)
288
+ result[col] = val if val is not None else _SESSION_DEFAULTS.get(col)
289
+ return result
290
+
291
+
292
+ # ---------------------------------------------------------------------------
293
+ # Public API
294
+ # ---------------------------------------------------------------------------
295
+
296
+ def get_session(session_id: str, *, live: bool = False) -> dict[str, Any] | None:
297
+ """Return a single session row as a dict, or None when not found.
298
+
299
+ Absent DB or locked DB returns None gracefully. Missing columns in the
300
+ sessions table fall back to the corresponding entry in ``_SESSION_DEFAULTS``.
301
+
302
+ ``live=True`` opens the DB WAL-visible (plain ``mode=ro``) so a probe
303
+ running alongside a live Hermes session sees writes that are committed but
304
+ not yet checkpointed. The default keeps the immutable snapshot view used
305
+ for collecting already-ended sessions.
306
+ """
307
+ if not session_id:
308
+ return None
309
+ db = state_db_path()
310
+ if not db.exists():
311
+ return None
312
+ try:
313
+ with _ro_connect(db, immutable=not live) as conn:
314
+ available = _table_columns(conn, "sessions")
315
+ if not available:
316
+ return None
317
+ # Build SELECT only for columns that exist in the schema.
318
+ select_cols = [c for c in _SESSION_COLUMNS if c in available]
319
+ if not select_cols:
320
+ return None
321
+ sql = f"SELECT {', '.join(select_cols)} FROM sessions WHERE id = ? LIMIT 1"
322
+ row = conn.execute(sql, (session_id,)).fetchone()
323
+ if row is None:
324
+ return None
325
+ return _row_to_dict(row, set(select_cols))
326
+ except (sqlite3.Error, OSError) as exc:
327
+ logger.debug("[hermes_state] get_session(%r) error: %s", session_id, exc)
328
+ return None
329
+
330
+
331
+ def recent_sessions(days: int = 30, max_rows: int = _MAX_ROWS) -> list[dict[str, Any]]:
332
+ """Return sessions started within the last ``days`` days, newest first.
333
+
334
+ Returns an empty list when the DB is absent, locked, or has no sessions
335
+ table. Missing columns fall back to defaults.
336
+ """
337
+ db = state_db_path()
338
+ if not db.exists():
339
+ return []
340
+ cutoff = time.time() - (max(1, days) * 86400)
341
+ try:
342
+ with _ro_connect(db) as conn:
343
+ available = _table_columns(conn, "sessions")
344
+ if not available:
345
+ return []
346
+ select_cols = [c for c in _SESSION_COLUMNS if c in available]
347
+ if not select_cols:
348
+ return []
349
+ # Use started_at filter only when the column exists.
350
+ if "started_at" in available:
351
+ sql = (
352
+ f"SELECT {', '.join(select_cols)} FROM sessions "
353
+ f"WHERE started_at >= ? "
354
+ f"ORDER BY started_at DESC LIMIT ?"
355
+ )
356
+ rows = conn.execute(sql, (cutoff, max_rows)).fetchall()
357
+ else:
358
+ sql = f"SELECT {', '.join(select_cols)} FROM sessions LIMIT ?"
359
+ rows = conn.execute(sql, (max_rows,)).fetchall()
360
+ return [_row_to_dict(r, set(select_cols)) for r in rows]
361
+ except (sqlite3.Error, OSError) as exc:
362
+ logger.debug("[hermes_state] recent_sessions() error: %s", exc)
363
+ return []
364
+
365
+
366
+ def session_token_totals(session_id: str) -> dict[str, Any]:
367
+ """Return token/cost columns for a session as a flat dict.
368
+
369
+ Always returns a dict (never raises). Zero/None defaults when the DB is
370
+ absent, the session does not exist, or columns are missing.
371
+
372
+ Returned keys:
373
+ input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
374
+ reasoning_tokens, message_count, tool_call_count, api_call_count,
375
+ model, estimated_cost_usd, cost_status, started_at, ended_at,
376
+ end_reason.
377
+ """
378
+ empty: dict[str, Any] = {
379
+ "input_tokens": 0,
380
+ "output_tokens": 0,
381
+ "cache_read_tokens": 0,
382
+ "cache_write_tokens": 0,
383
+ "reasoning_tokens": 0,
384
+ "message_count": 0,
385
+ "tool_call_count": 0,
386
+ "api_call_count": 0,
387
+ "model": "unknown",
388
+ "estimated_cost_usd": None,
389
+ "cost_status": "unknown",
390
+ "started_at": None,
391
+ "ended_at": None,
392
+ "end_reason": None,
393
+ }
394
+ row = get_session(session_id)
395
+ if row is None:
396
+ return empty
397
+ return {
398
+ "input_tokens": _safe_int(row.get("input_tokens")),
399
+ "output_tokens": _safe_int(row.get("output_tokens")),
400
+ "cache_read_tokens": _safe_int(row.get("cache_read_tokens")),
401
+ "cache_write_tokens": _safe_int(row.get("cache_write_tokens")),
402
+ "reasoning_tokens": _safe_int(row.get("reasoning_tokens")),
403
+ "message_count": _safe_int(row.get("message_count")),
404
+ "tool_call_count": _safe_int(row.get("tool_call_count")),
405
+ "api_call_count": _safe_int(row.get("api_call_count")),
406
+ "model": str(row.get("model") or "unknown"),
407
+ "estimated_cost_usd": _safe_float(row.get("estimated_cost_usd")),
408
+ "cost_status": str(row.get("cost_status") or "unknown"),
409
+ "started_at": row.get("started_at"),
410
+ "ended_at": row.get("ended_at"),
411
+ "end_reason": row.get("end_reason"),
412
+ }
413
+
414
+
415
+ def db_status() -> dict[str, Any]:
416
+ """Lightweight presence/readability report for the doctor."""
417
+ db = state_db_path()
418
+ readable = False
419
+ row_count = 0
420
+ schema_version = None
421
+ if db.exists():
422
+ try:
423
+ with _ro_connect(db) as conn:
424
+ available = _table_columns(conn, "sessions")
425
+ if available:
426
+ result = conn.execute("SELECT COUNT(*) FROM sessions").fetchone()
427
+ row_count = int(result[0]) if result else 0
428
+ readable = True
429
+ sv_cols = _table_columns(conn, "schema_version")
430
+ if sv_cols:
431
+ svrow = conn.execute("SELECT version FROM schema_version LIMIT 1").fetchone()
432
+ if svrow:
433
+ schema_version = int(svrow[0])
434
+ except (sqlite3.Error, OSError):
435
+ pass
436
+ return {
437
+ "db_path": str(db),
438
+ "db_exists": db.exists(),
439
+ "readable": readable,
440
+ "session_count": row_count,
441
+ "schema_version": schema_version,
442
+ }
443
+
444
+
445
+ if __name__ == "__main__":
446
+ import json
447
+
448
+ print(json.dumps(db_status(), indent=2))
@@ -0,0 +1,120 @@
1
+ """Shared I/O utilities for Token Optimizer hook scripts.
2
+
3
+ Single source of truth for reading JSON hook input from stdin.
4
+ Each hook script runs as a separate subprocess; this module
5
+ provides a consistent, bounded stdin reader across all of them.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import sys
12
+ import threading
13
+
14
+ _STDIN_TIMEOUT = 0.5
15
+
16
+
17
+ def _read_stdin_windows(timeout: float = _STDIN_TIMEOUT, max_bytes: int = 1_048_576) -> str:
18
+ result = [""]
19
+
20
+ def _reader() -> None:
21
+ try:
22
+ result[0] = sys.stdin.buffer.read(max_bytes).decode("utf-8", errors="replace")
23
+ except Exception:
24
+ pass
25
+
26
+ t = threading.Thread(target=_reader, daemon=True)
27
+ t.start()
28
+ t.join(timeout)
29
+ return result[0]
30
+
31
+
32
+ def read_stdin_hook_input(max_bytes: int = 1_048_576) -> dict:
33
+ """Read JSON hook input from stdin non-blocking.
34
+
35
+ Returns parsed dict or empty dict on failure.
36
+ Bounds read size to max_bytes (default 1MB for PostToolUse payloads
37
+ that include tool_response). PreToolUse callers can pass a lower cap.
38
+ Works on Unix and Windows.
39
+
40
+ C9: if the parsed JSON is valid but NOT a dict (e.g. a list, string, or
41
+ number), prints a loud warning to stderr and returns {}. Callers do
42
+ hook_input.get(...) which would AttributeError on a non-dict; the empty
43
+ dict lets the existing `if not hook_input:` guards catch it.
44
+ """
45
+ try:
46
+ if sys.platform == "win32":
47
+ data = _read_stdin_windows(max_bytes=max_bytes)
48
+ else:
49
+ import os
50
+ import select
51
+ import time
52
+ # H-7: set the deadline BEFORE the first select. The old code set
53
+ # it after, so if the first select() consumed most of the 0.5s
54
+ # timeout, the read loop got a FULL additional 0.5s — measured
55
+ # 1098ms peak (2.2x the stated 0.5s). One deadline, used for all
56
+ # select() calls, so the total budget is _STDIN_TIMEOUT end to end.
57
+ deadline = time.monotonic() + _STDIN_TIMEOUT
58
+ remaining = deadline - time.monotonic()
59
+ if remaining <= 0 or not select.select([sys.stdin], [], [], remaining)[0]:
60
+ return {}
61
+ try:
62
+ fd = sys.stdin.fileno()
63
+ except (OSError, ValueError, AttributeError):
64
+ fd = None
65
+ if fd is not None:
66
+ # select() only guarantees one byte is ready; a blocking
67
+ # read(max_bytes) would then hang until max_bytes or EOF, so a
68
+ # host that writes a partial payload and holds the pipe open
69
+ # defeats the timeout. Read what is actually available in a loop
70
+ # bounded by the same deadline, assembling chunked payloads
71
+ # without ever blocking past _STDIN_TIMEOUT.
72
+ chunks = []
73
+ total = 0
74
+ while total < max_bytes:
75
+ remaining = deadline - time.monotonic()
76
+ if remaining <= 0:
77
+ break
78
+ if not select.select([sys.stdin], [], [], remaining)[0]:
79
+ break # timed out with no further data
80
+ chunk = os.read(fd, max_bytes - total)
81
+ if not chunk:
82
+ break # EOF: host closed stdin, payload complete
83
+ chunks.append(chunk)
84
+ total += len(chunk)
85
+ raw = b"".join(chunks)
86
+ else:
87
+ # Non-fd stdin (e.g. a test double): no pipe to hang on.
88
+ raw = sys.stdin.buffer.read(max_bytes)
89
+ # Decode from raw bytes as UTF-8 so a non-UTF-8 host locale can't
90
+ # corrupt or crash on non-ASCII hook payloads (e.g. Hebrew cwd /
91
+ # tool args). Mirrors the Windows path above.
92
+ data = raw.decode("utf-8", errors="replace")
93
+ if not data:
94
+ return {}
95
+ parsed = json.loads(data)
96
+ if not isinstance(parsed, dict):
97
+ # Loud fail + return. A non-dict payload (list, string, number)
98
+ # is a protocol violation; callers would AttributeError on .get().
99
+ print(
100
+ f"[hook_io] stdin JSON is {type(parsed).__name__}, not a dict; "
101
+ f"treating as empty (hook will no-op)",
102
+ file=sys.stderr,
103
+ )
104
+ return {}
105
+ from runtime_env import detect_runtime
106
+ if detect_runtime() == 'codex':
107
+ import codex_session
108
+ sid = codex_session._safe_session_id(parsed.get('session_id'))
109
+ if sid:
110
+ resolved = codex_session.resolve_session(parsed.get('transcript_path'), sid)
111
+ # Only overwrite on success: resolve_session returns None when
112
+ # the transcript exists but names a different session. Clobbering
113
+ # a valid caller-provided path with None would silently lose the
114
+ # transcript for every hook whose session_id is stale/mismatched.
115
+ if resolved:
116
+ parsed['transcript_path'] = str(resolved)
117
+ return parsed
118
+ except (OSError, json.JSONDecodeError, ValueError):
119
+ pass
120
+ return {}