@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,303 @@
1
+ #!/usr/bin/env python3
2
+ """Cursor session normalizer for Token Optimizer.
3
+
4
+ Converts a Cursor hook tally (plus resolved token sources from
5
+ ``cursor_state.py``) into TO's canonical session shape — the keys measure.py,
6
+ the savings engine, and the dashboard consume.
7
+
8
+ Token convention (R16, load-bearing): token counts come from, in order:
9
+
10
+ 1. ``state.vscdb`` bubble ``tokenCount`` when non-zero (``estimated = False``,
11
+ ``token_source = "cursor_state_vscdb"``);
12
+ 2. else a chars-over-four estimate from the transcript
13
+ (``estimated = True``, ``token_source = "cursor_transcript_estimate"``);
14
+ 3. else zero tokens, still a valid row (``estimated = True``,
15
+ ``token_source = "cursor_tally_only"``).
16
+
17
+ A tallied session is NEVER dropped for lacking tokens; the hook tally is the
18
+ primary record (tool calls, turns, compaction context numbers), and the token
19
+ sources only improve it best-effort.
20
+
21
+ Cost convention (R18): Cursor stores no local cost data, so cost_usd is always
22
+ 0.0 with ``cost_source = "cursor_no_cost_data"`` and the token-priced
23
+ before/after transformation is not rendered under the cursor runtime.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import logging
29
+ from datetime import datetime, timezone
30
+ from typing import Any, Optional
31
+
32
+ logger = logging.getLogger(__name__)
33
+
34
+ _UNKNOWN_MODEL = "unknown"
35
+
36
+ # Cursor serves a mixed model fleet; there is no single documented context
37
+ # window. 128K is the honest conservative default (mirrors copilot_session).
38
+ _CURSOR_DEFAULT_CONTEXT_WINDOW = 128_000
39
+ _CONTEXT_WINDOW_PREFIXES = (
40
+ ("gpt-5", 128_000),
41
+ ("gpt-4.1", 128_000),
42
+ ("gpt-4o", 128_000),
43
+ ("claude", 200_000),
44
+ ("gemini", 128_000),
45
+ ("o3", 200_000),
46
+ ("o4", 200_000),
47
+ )
48
+
49
+
50
+ def surface_from_version(version: Any) -> str:
51
+ """Heuristic: date-shaped cursor_version means CLI, semver means IDE.
52
+
53
+ The CLI bundle versions look like ``2026.08.31-4057e58`` (leading year);
54
+ IDE versions are semver like ``3.18.9``. Returns "cli", "ide", or "unknown".
55
+ """
56
+ if not isinstance(version, str) or not version:
57
+ return "unknown"
58
+ text = version.strip()
59
+ # Date-shaped: YYYY.MM.DD or YYYY.M.D anywhere in the leading token.
60
+ import re
61
+
62
+ if re.match(r"^\d{4}[.-]\d{1,2}[.-]\d{1,2}", text):
63
+ return "cli"
64
+ if re.match(r"^\d+\.\d+\.\d+", text):
65
+ return "ide"
66
+ return "unknown"
67
+
68
+
69
+ def context_window_for_model(model: str) -> int:
70
+ name = (model or "").strip().lower()
71
+ for prefix, window in _CONTEXT_WINDOW_PREFIXES:
72
+ if name.startswith(prefix):
73
+ return window
74
+ return _CURSOR_DEFAULT_CONTEXT_WINDOW
75
+
76
+
77
+ def _safe_int(value: Any, default: int = 0) -> int:
78
+ try:
79
+ # H-1/N-1b: parse through float() first so float-shaped strings from
80
+ # JSON (e.g. "1234.0") don't raise ValueError and silently zero token
81
+ # counts, and so float('inf') raises OverflowError (caught below)
82
+ # instead of escaping.
83
+ return int(float(value)) if value is not None else default
84
+ except (TypeError, ValueError, OverflowError):
85
+ return default
86
+
87
+
88
+ def _parse_ts(value: Any) -> Optional[str]:
89
+ """Epoch seconds -> ISO-8601 UTC string (None when absent/invalid)."""
90
+ if value is None:
91
+ return None
92
+ try:
93
+ return datetime.fromtimestamp(float(value), tz=timezone.utc).isoformat()
94
+ except (TypeError, ValueError, OSError, OverflowError):
95
+ return None
96
+
97
+
98
+ def _quality(input_tokens, output_tokens, message_count, model, ctx_window):
99
+ """Quality score from Cursor's session-level fields (mirrors copilot_session)."""
100
+ try:
101
+ from hermes_session import compute_quality_score
102
+
103
+ return compute_quality_score(
104
+ input_tokens=input_tokens,
105
+ output_tokens=output_tokens,
106
+ message_count=message_count,
107
+ model=model,
108
+ context_window=ctx_window,
109
+ cache_read=0,
110
+ )
111
+ except Exception as exc: # pragma: no cover - defensive fallback
112
+ logger.debug("[cursor_session] quality scorer unavailable: %s", exc)
113
+ fill = min(1.0, input_tokens / ctx_window) if ctx_window else 0.0
114
+ score = max(0.0, 100.0 - fill * 50.0)
115
+ band = "healthy" if score >= 70 else ("watch" if score >= 50 else "critical")
116
+ grade = "A" if score >= 90 else ("B" if score >= 75 else ("C" if score >= 60 else "D"))
117
+ return {
118
+ "score": round(score, 1),
119
+ "grade": grade,
120
+ "band": band,
121
+ "fill_ratio": round(fill, 4),
122
+ "context_window_used": ctx_window,
123
+ }
124
+
125
+
126
+ def _base_canonical(slug: str, token_source: str) -> dict:
127
+ """Shared canonical skeleton shaped like copilot_session._base_canonical."""
128
+ return {
129
+ "slug": slug,
130
+ "topic": None,
131
+ "first_ts": None,
132
+ "duration_minutes": 0.0,
133
+ "total_input_tokens": 0,
134
+ "total_output_tokens": 0,
135
+ "total_cache_read": 0,
136
+ "total_cache_create": 0,
137
+ "total_cache_create_1h": 0,
138
+ "total_cache_create_5m": 0,
139
+ "model_context_window": _CURSOR_DEFAULT_CONTEXT_WINDOW,
140
+ "cache_hit_rate": 0.0,
141
+ "cost_usd": 0.0,
142
+ "cost_source": "cursor_no_cost_data",
143
+ "credits": None,
144
+ "model": _UNKNOWN_MODEL,
145
+ "model_family": None,
146
+ "model_usage": {},
147
+ "model_usage_breakdown": {},
148
+ "message_count": 0,
149
+ "api_calls": 0,
150
+ "tool_calls": {"total": 0},
151
+ "estimated": False,
152
+ "token_source": token_source,
153
+ "runtime": "cursor",
154
+ "version": None,
155
+ "avg_call_gap_seconds": None,
156
+ "max_call_gap_seconds": None,
157
+ "p95_call_gap_seconds": None,
158
+ "rate_limits": None,
159
+ "effort": None,
160
+ "effort_breakdown": {},
161
+ "skills_used": {},
162
+ "subagents_used": {},
163
+ "tool_duration_p90_ms": None,
164
+ "task_duration_ms_max": None,
165
+ "ttft_ms_avg": None,
166
+ "end_reason": "",
167
+ "archived": False,
168
+ "cwd": None,
169
+ "billing_provider": "cursor",
170
+ "incomplete": False,
171
+ "compactions": 0,
172
+ "surface": "unknown",
173
+ }
174
+
175
+
176
+ def resolve_token_source(bubble_tokens, transcript_tokens):
177
+ """R16 ordered token resolution.
178
+
179
+ Returns ``(input_tokens, output_tokens, token_source, estimated)``.
180
+ Bubble tokens win only when at least one of input/output is non-zero;
181
+ otherwise the transcript estimate; otherwise a zero-token tally-only row.
182
+ """
183
+ if isinstance(bubble_tokens, dict) and (
184
+ _safe_int(bubble_tokens.get("input_tokens")) > 0
185
+ or _safe_int(bubble_tokens.get("output_tokens")) > 0
186
+ ):
187
+ return (
188
+ _safe_int(bubble_tokens.get("input_tokens")),
189
+ _safe_int(bubble_tokens.get("output_tokens")),
190
+ "cursor_state_vscdb",
191
+ False,
192
+ )
193
+ if transcript_tokens is not None:
194
+ try:
195
+ tt = max(0, int(transcript_tokens))
196
+ except (TypeError, ValueError):
197
+ tt = 0
198
+ return (tt, 0, "cursor_transcript_estimate", True)
199
+ return (0, 0, "cursor_tally_only", True)
200
+
201
+
202
+ def normalize_session(raw: dict) -> Optional[dict]:
203
+ """Normalize a Cursor tally (+ resolved token sources) into a canonical dict.
204
+
205
+ ``raw`` is the tally dict with (optionally) two injected keys from the
206
+ collector: ``bubble_tokens`` (dict from cursor_state.read_state_vscdb_tokens)
207
+ and ``transcript_tokens`` (int from cursor_state.transcript_estimate).
208
+ """
209
+ if not isinstance(raw, dict):
210
+ return None
211
+ conversation_id = str(raw.get("conversation_id") or raw.get("session_id") or "")
212
+ if not conversation_id:
213
+ return None
214
+
215
+ bubble_tokens = raw.get("bubble_tokens")
216
+ transcript_tokens = raw.get("transcript_tokens")
217
+ total_input, total_output, token_source, estimated = resolve_token_source(
218
+ bubble_tokens, transcript_tokens
219
+ )
220
+
221
+ # Primary model: bubble model first, else the tally's most-seen model.
222
+ models = raw.get("models") if isinstance(raw.get("models"), dict) else {}
223
+ model = _UNKNOWN_MODEL
224
+ if isinstance(bubble_tokens, dict) and bubble_tokens.get("model"):
225
+ model = str(bubble_tokens["model"])
226
+ elif models:
227
+ model = str(max(models, key=lambda k: _safe_int(models.get(k))))
228
+ ctx_window = context_window_for_model(model)
229
+
230
+ turns = _safe_int(raw.get("turns"))
231
+ tool_calls_total = _safe_int(raw.get("tool_calls"))
232
+ tool_names = raw.get("tool_names") if isinstance(raw.get("tool_names"), dict) else {}
233
+ message_count = turns
234
+
235
+ model_usage = {}
236
+ for name, count in models.items():
237
+ try:
238
+ model_usage[str(name)] = _safe_int(count)
239
+ except (TypeError, ValueError):
240
+ continue
241
+
242
+ compactions = raw.get("compactions")
243
+ compactions_count = len(compactions) if isinstance(compactions, list) else 0
244
+
245
+ first_ts_raw = raw.get("first_ts")
246
+ updated_at_raw = raw.get("updated_at")
247
+ duration_minutes = 0.0
248
+ if first_ts_raw is not None and updated_at_raw is not None:
249
+ try:
250
+ duration_minutes = max(0.0, (float(updated_at_raw) - float(first_ts_raw)) / 60.0)
251
+ except (TypeError, ValueError):
252
+ duration_minutes = 0.0
253
+
254
+ final = bool(raw.get("final"))
255
+ end_reason = str(raw.get("end_reason") or "")
256
+ # A tally finalized as idle is complete for dashboard purposes; a final
257
+ # tally from sessionEnd is complete; anything else is in-progress.
258
+ incomplete = not final
259
+
260
+ version = raw.get("cursor_version")
261
+ surface = surface_from_version(version)
262
+
263
+ roots = raw.get("workspace_roots")
264
+ roots_list = roots if isinstance(roots, list) else None
265
+ root = None
266
+ if isinstance(raw.get("cwd"), str) and raw["cwd"]:
267
+ root = raw["cwd"]
268
+ elif roots_list and isinstance(roots_list[0], str):
269
+ root = roots_list[0]
270
+
271
+ quality = _quality(total_input, total_output, message_count, model, ctx_window)
272
+
273
+ session = _base_canonical(conversation_id, token_source)
274
+ session.update(
275
+ {
276
+ "first_ts": _parse_ts(first_ts_raw),
277
+ "last_ts": _parse_ts(updated_at_raw),
278
+ "duration_minutes": round(duration_minutes, 2),
279
+ "total_input_tokens": total_input,
280
+ "total_output_tokens": total_output,
281
+ "model_context_window": ctx_window,
282
+ "model": model,
283
+ "model_usage": model_usage,
284
+ "message_count": message_count,
285
+ "api_calls": turns,
286
+ "tool_calls": {"total": tool_calls_total},
287
+ "estimated": estimated,
288
+ "token_source": token_source,
289
+ "version": version,
290
+ "cwd": root,
291
+ "workspace_roots": roots_list,
292
+ "incomplete": incomplete,
293
+ "end_reason": end_reason,
294
+ "compactions": compactions_count,
295
+ "surface": surface,
296
+ "tool_names": tool_names,
297
+ "quality": quality,
298
+ "quality_score": quality.get("score"),
299
+ "quality_grade": quality.get("grade"),
300
+ "quality_band": quality.get("band"),
301
+ }
302
+ )
303
+ return session
@@ -0,0 +1,348 @@
1
+ #!/usr/bin/env python3
2
+ """Read-only reader for Cursor session data (token-optimizer tally + Cursor data planes).
3
+
4
+ Cursor exposes two on-disk data planes, neither of which carries reliable,
5
+ authoritative per-session token totals:
6
+
7
+ - Hook tally — Token Optimizer's own record under
8
+ ``~/.cursor/token-optimizer/sessions/<conversation_id>.json``. This is the
9
+ primary record (tool calls, turns, compaction context numbers from
10
+ ``preCompact``, cursor_version, transcript_path). The hook bridge writes it;
11
+ this module reads it back.
12
+ - ``state.vscdb`` (IDE chats) — a SQLite DB at
13
+ ``<cursor-home>/User/globalStorage/state.vscdb`` whose ``cursorDiskKV`` table
14
+ stores ``bubbleId:<composerId>:<bubbleId>`` rows with a ``tokenCount`` field
15
+ that Cursor staff call best-effort (timing-dependent; often zero). Read-only,
16
+ key-prefix queries only, opened ``mode=ro`` (NOT ``immutable=1`` — a live IDE
17
+ DB must not gain ``-shm`` side effects from an immutable-URI mismatch).
18
+ - Transcripts (CLI chats) — ``~/.cursor/projects/<slug>/agent-transcripts/
19
+ <conversation_id>/*.jsonl``. No usage fields; only a chars-over-four size
20
+ estimate is available.
21
+
22
+ Design constraints (mirroring copilot_state.py / hermes_state.py):
23
+
24
+ - **Pure stdlib only.** sqlite3 is OK; no Cursor imports.
25
+ - **Strictly read-only.** Never writes any file.
26
+ - **No hardcoded user paths.** The Cursor home comes from
27
+ ``runtime_env.cursor_home()``; callers may pass an explicit ``home``
28
+ override.
29
+ - **Schema-defensive.** Tally JSON and the community-reverse-engineered
30
+ state.vscdb schema both drift; every reader degrades to a safe default and
31
+ never raises.
32
+ """
33
+
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import logging
38
+ import os
39
+ import sqlite3
40
+ import sys
41
+ from pathlib import Path
42
+ from typing import Any, Optional
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+ _TO_DIR = "token-optimizer"
47
+ _SESSIONS_SUBDIR = "sessions"
48
+
49
+ # Idle finalisation threshold (R17/KTD11): a conversation whose last activity
50
+ # is older than this and that never saw sessionEnd is finalised as idle.
51
+ _IDLE_SECS = 2 * 3600
52
+
53
+ # Bounded reads: a maliciously-crafted or pathological file must never stall a
54
+ # detached rollup. These caps match the streaming-reader spirit of
55
+ # copilot_state.py without pulling in its event-stream machinery.
56
+ _MAX_TALLY_BYTES = 4 * 1024 * 1024
57
+ _MAX_TRANSCRIPT_BYTES = 8 * 1024 * 1024
58
+ _MAX_BUBBLE_ROWS = 2000
59
+ _MAX_COMPOSERS = 500
60
+
61
+
62
+ def _safe_home() -> Path:
63
+ try:
64
+ return Path.home()
65
+ except (OSError, RuntimeError):
66
+ for key in ("USERPROFILE", "HOME"):
67
+ val = os.environ.get(key, "").strip()
68
+ if val:
69
+ return Path(val)
70
+ return Path(".")
71
+
72
+
73
+ # ---------------------------------------------------------------------------
74
+ # Tally readers
75
+ # ---------------------------------------------------------------------------
76
+
77
+
78
+ def find_tallies(home: Optional[Path] = None) -> list:
79
+ """Return tally JSON files under <home>/token-optimizer/sessions/.
80
+
81
+ Returns [] when the directory does not exist. Never raises.
82
+ """
83
+ if home is None:
84
+ try:
85
+ from runtime_env import cursor_home
86
+
87
+ home = cursor_home()
88
+ except Exception as exc:
89
+ logger.debug("[cursor_state] cannot import runtime_env: %s", exc)
90
+ return []
91
+ sessions_dir = home / _TO_DIR / _SESSIONS_SUBDIR
92
+ if not sessions_dir.is_dir():
93
+ return []
94
+ try:
95
+ return sorted(
96
+ p for p in sessions_dir.iterdir()
97
+ if p.is_file() and p.suffix == ".json"
98
+ )
99
+ except OSError as exc:
100
+ logger.debug("[cursor_state] cannot list %s: %s", sessions_dir, exc)
101
+ return []
102
+
103
+
104
+ def read_tally(path: Path) -> Optional[dict]:
105
+ """Read a tally JSON file, returning the dict or None when unreadable."""
106
+ try:
107
+ if path.stat().st_size > _MAX_TALLY_BYTES:
108
+ return None
109
+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
110
+ return data if isinstance(data, dict) else None
111
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
112
+ logger.debug("[cursor_state] cannot read tally %s: %s", path, exc)
113
+ return None
114
+
115
+
116
+ def idle_finalise(tally: dict, now: Optional[float] = None) -> dict:
117
+ """Mark a never-finalised, stale tally as ``end_reason = "idle"``.
118
+
119
+ Returns a COPY (never mutates the caller's dict). A tally whose latest
120
+ activity is older than two hours and that never saw sessionEnd is
121
+ finalised as idle; anything newer (or already final) is returned unchanged.
122
+ The bridge clears the idle verdict on the next activity for that
123
+ conversation (reopen), so an idle row is always upgradeable.
124
+
125
+ ``now`` defaults to ``time.time()``; tests pass an explicit value.
126
+ """
127
+ import time
128
+
129
+ if not isinstance(tally, dict) or tally.get("final"):
130
+ return tally
131
+ updated = tally.get("updated_at")
132
+ if updated is None:
133
+ return tally
134
+ try:
135
+ now_f = time.time() if now is None else float(now)
136
+ if now_f - float(updated) >= _IDLE_SECS:
137
+ out = dict(tally)
138
+ out["final"] = True
139
+ out["end_reason"] = "idle"
140
+ return out
141
+ except (TypeError, ValueError, OverflowError):
142
+ return tally
143
+ return tally
144
+
145
+
146
+ # ---------------------------------------------------------------------------
147
+ # Transcript estimate (CLI plane)
148
+ # ---------------------------------------------------------------------------
149
+
150
+
151
+ def transcript_estimate(transcript_path: Any, home: Path) -> Optional[int]:
152
+ """Chars-over-four token estimate for a transcript, or None when absent.
153
+
154
+ The transcript must live under ``<home>/projects`` (containment check so a
155
+ crafted transcripts_path in the tally can't make the rollup read arbitrary
156
+ files). Reads are capped; a missing/unreadable file returns None so the
157
+ caller falls through to the tally-only source. Returns the char count // 4
158
+ (possibly 0 for a tiny file) when a transcript IS present.
159
+ """
160
+ if not transcript_path:
161
+ return None
162
+ try:
163
+ path = Path(str(transcript_path))
164
+ root = (home / "projects").resolve(strict=False)
165
+ resolved = path.resolve(strict=False)
166
+ if not resolved.is_relative_to(root):
167
+ return None
168
+ except (OSError, ValueError):
169
+ return None
170
+ if not path.is_file():
171
+ return None
172
+ try:
173
+ with path.open("rb") as fh:
174
+ raw = fh.read(_MAX_TRANSCRIPT_BYTES + 1)
175
+ if len(raw) > _MAX_TRANSCRIPT_BYTES:
176
+ raw = raw[:_MAX_TRANSCRIPT_BYTES]
177
+ except OSError as exc:
178
+ logger.debug("[cursor_state] cannot read transcript %s: %s", path, exc)
179
+ return None
180
+ text = raw.decode("utf-8", errors="replace")
181
+ return len(text) // 4
182
+
183
+
184
+ # ---------------------------------------------------------------------------
185
+ # state.vscdb reader (IDE plane)
186
+ # ---------------------------------------------------------------------------
187
+
188
+
189
+ def state_vscdb_path() -> Path:
190
+ """Default state.vscdb path per OS. May not exist."""
191
+ home = _safe_home()
192
+ if sys.platform == "darwin":
193
+ base = home / "Library" / "Application Support" / "Cursor"
194
+ elif sys.platform.startswith("win"):
195
+ appdata = os.environ.get("APPDATA") or str(home / "AppData" / "Roaming")
196
+ base = Path(appdata) / "Cursor"
197
+ else:
198
+ base = home / ".config" / "Cursor"
199
+ return base / "User" / "globalStorage" / "state.vscdb"
200
+
201
+
202
+ def _ro_connect_vscdb(path: Path):
203
+ """Open state.vscdb read-only. ``mode=ro`` only — not ``immutable=1``."""
204
+ # Build the file: URI via Path.as_uri() rather than string interpolation
205
+ # (same fix as codex_state._ro_connect, H-2/N-1): with uri=True, characters
206
+ # like ?, #, % and spaces in the path are URI syntax, so a path containing
207
+ # '?' would start the query string early and drop mode=ro — silently
208
+ # opening a truncated path read-write. as_uri() percent-encodes those.
209
+ # resolve() first (M-3) so a relative path doesn't raise an uncaught
210
+ # ValueError past callers that only catch (sqlite3.Error, OSError).
211
+ db_uri = Path(path).resolve().as_uri()
212
+ conn = sqlite3.connect(
213
+ f"{db_uri}?mode=ro",
214
+ uri=True,
215
+ timeout=0.25,
216
+ )
217
+ try:
218
+ conn.execute("PRAGMA query_only = ON")
219
+ conn.row_factory = sqlite3.Row
220
+ return conn
221
+ except sqlite3.Error:
222
+ conn.close()
223
+ raise
224
+
225
+
226
+ def read_state_vscdb_tokens(
227
+ composer_ids: Any, db_path: Optional[Path] = None
228
+ ) -> dict:
229
+ """Best-effort per-composer token/model read from state.vscdb.
230
+
231
+ For each composer id, sums ``tokenCount.inputTokens`` / ``outputTokens``
232
+ across ``bubbleId:<id>:`` rows and reads ``composerData:<id>`` for the model
233
+ name and ``createdAt``.
234
+
235
+ Returns ``{composer_id: {"input_tokens", "output_tokens", "model",
236
+ "created_at_ms"}}``. Missing ids are omitted. A locked or missing DB yields
237
+ ``{}`` (never raises) — a detached rollup must not stall on a live IDE DB.
238
+ """
239
+ result: dict = {}
240
+ if db_path is None:
241
+ db_path = state_vscdb_path()
242
+ if not isinstance(db_path, Path):
243
+ db_path = Path(str(db_path))
244
+ if not db_path.is_file():
245
+ return result
246
+ ids = list(composer_ids) if composer_ids else []
247
+ if not ids:
248
+ return result
249
+
250
+ try:
251
+ conn = _ro_connect_vscdb(db_path)
252
+ except (sqlite3.Error, OSError):
253
+ # Locked (OperationalError: database is locked) -> skip this pass.
254
+ return result
255
+
256
+ # Exact ids we are looking for. Matching happens in Python on the id parsed
257
+ # out of the key, so LIKE wildcards in an id (% _) can never widen the match
258
+ # and misattribute another conversation's tokens.
259
+ wanted = {}
260
+ for cid in ids[:_MAX_COMPOSERS]:
261
+ if isinstance(cid, str) and cid:
262
+ wanted[cid] = {"input_tokens": 0, "output_tokens": 0, "model": None,
263
+ "created_at_ms": None, "_bubble_rows": 0}
264
+ if not wanted:
265
+ return result
266
+
267
+ try:
268
+ # ONE scan over the two key prefixes (was 2 queries per composer id:
269
+ # N+1 full-table scans, 4.6s on a 55K-row DB with 500 composers).
270
+ # With an index on cursorDiskKV(key) SQLite serves each LIKE prefix
271
+ # from the index; without one this is a single pass instead of 2N.
272
+ cur = conn.execute(
273
+ "SELECT key, value FROM cursorDiskKV "
274
+ "WHERE key LIKE 'bubbleId:%' OR key LIKE 'composerData:%'"
275
+ )
276
+ for row in cur:
277
+ key = row["key"]
278
+ if key.startswith("bubbleId:"):
279
+ # Key shape is bubbleId:<composerId>:<bubbleId>; Cursor composer
280
+ # ids are UUIDs (no ':'), so partition on the first colon is
281
+ # exact. (The composerData branch needs no split.)
282
+ rest = key[len("bubbleId:"):]
283
+ cid, sep, _suffix = rest.partition(":")
284
+ entry = wanted.get(cid)
285
+ if entry is None or not sep:
286
+ continue
287
+ if entry["_bubble_rows"] >= _MAX_BUBBLE_ROWS:
288
+ continue
289
+ entry["_bubble_rows"] += 1
290
+ try:
291
+ bubble = json.loads(row["value"])
292
+ except (TypeError, ValueError, json.JSONDecodeError):
293
+ continue
294
+ if not isinstance(bubble, dict):
295
+ continue
296
+ # The DB knows about this id even if the bubble carries no
297
+ # tokenCount: report it (zeroed) rather than omit it.
298
+ entry["_found"] = True
299
+ tc = bubble.get("tokenCount")
300
+ if not isinstance(tc, dict):
301
+ continue
302
+ try:
303
+ entry["input_tokens"] += int(tc.get("inputTokens") or 0)
304
+ entry["output_tokens"] += int(tc.get("outputTokens") or 0)
305
+ except (TypeError, ValueError):
306
+ continue
307
+ else: # composerData:<id>
308
+ cid = key[len("composerData:"):]
309
+ entry = wanted.get(cid)
310
+ if entry is None:
311
+ continue
312
+ entry["_found"] = True
313
+ try:
314
+ data = json.loads(row["value"])
315
+ except (TypeError, ValueError, json.JSONDecodeError):
316
+ continue
317
+ if isinstance(data, dict):
318
+ mc = data.get("modelConfig")
319
+ if isinstance(mc, dict):
320
+ entry["model"] = mc.get("modelName") or entry["model"]
321
+ entry["created_at_ms"] = data.get("createdAt")
322
+ except sqlite3.Error:
323
+ # A mid-scan failure must not look like "no data": leave a signal.
324
+ logger.warning("[cursor_state] vscdb scan aborted by sqlite error", exc_info=True)
325
+ finally:
326
+ conn.close()
327
+
328
+ # Only report composers the DB actually knows about; a conversation
329
+ # id with no bubble rows and no composerData is absent, not zero.
330
+ for cid, entry in wanted.items():
331
+ if entry.pop("_found", False):
332
+ entry.pop("_bubble_rows", None)
333
+ result[cid] = entry
334
+ return result
335
+
336
+
337
+ if __name__ == "__main__": # pragma: no cover - debug helper
338
+ import json as _json
339
+
340
+ home = None
341
+ try:
342
+ from runtime_env import cursor_home
343
+
344
+ home = cursor_home()
345
+ except Exception:
346
+ home = _safe_home() / ".cursor"
347
+ tallies = [read_tally(p) for p in find_tallies(home)]
348
+ print(_json.dumps({"tallies": tallies, "db": str(state_vscdb_path())}, indent=2, default=str))