@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,317 @@
1
+ #!/usr/bin/env python3
2
+ """Grok Build session normalizer for Token Optimizer.
3
+
4
+ Converts raw session dicts from ``grok_state.py`` into TO's canonical session
5
+ shape — the keys measure.py, the savings engine, and the dashboard consume.
6
+
7
+ Token convention (source-verified from the cloned repo):
8
+
9
+ ``updates.jsonl`` ``turn_completed`` records carry ``usage`` (``PromptUsage``)
10
+ whose ``inputTokens`` is the FULL prompt sum including cache reads (the ACP
11
+ identity, notification.rs). So:
12
+
13
+ total_input_tokens = sum(inputTokens) # already includes cache reads
14
+ total_output_tokens = sum(outputTokens)
15
+ total_cache_read = sum(cachedReadTokens) # subset of input, never re-added
16
+ total_cache_create = sum(cacheCreationTokens)
17
+
18
+ When no ``turn_completed`` usage exists (crash before first turn end), fall
19
+ back to ``signals.json`` ``contextTokensUsed`` as a single input estimate
20
+ (``estimated = True``, ``token_source = "grok_signals_only"``). A session is
21
+ NEVER dropped for lacking tokens.
22
+
23
+ Cost convention: ``costUsdTicks`` is 1e10 ticks per USD (notification.rs), and
24
+ is scrubbed (absent) when ``usageIsIncomplete`` or ``costIsPartial``. Absence of
25
+ cost means unknown, not free — so cost_usd is 0.0 with
26
+ ``cost_source = "grok_no_cost_data"`` unless trustworthy ticks were summed.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import logging
32
+ from datetime import datetime, timezone
33
+ from typing import Any, Optional
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ _UNKNOWN_MODEL = "unknown"
38
+
39
+ # Grok Build's default context window (crates/codegen/xai-grok-shell/src/
40
+ # remote/client.rs: DEFAULT_CONTEXT_WINDOW = 256_000). signals.json's
41
+ # ``contextWindowTokens`` is authoritative when present; this is the fallback.
42
+ _GROK_DEFAULT_CONTEXT_WINDOW = 256_000
43
+
44
+ # USD ticks per dollar (notification.rs: "costUsdTicks is 1e10 ticks per $1").
45
+ _USD_TICKS_PER_USD = 10_000_000_000
46
+
47
+
48
+ def _default_context_window() -> int:
49
+ """Grok Build's fixed 256K context-window fallback (remote/client.rs).
50
+
51
+ signals.json's ``contextWindowTokens`` is authoritative when present; this
52
+ is only the fallback. Grok does not expose a per-model window map to the
53
+ adapter in contract-only mode, so there is no per-model lookup here (the
54
+ copilot/hermes ``context_window_for_model`` names would overclaim one).
55
+ """
56
+ return _GROK_DEFAULT_CONTEXT_WINDOW
57
+
58
+
59
+ from grok_state import _safe_int as _safe_int # noqa: E402,F401 — shared helper
60
+
61
+
62
+ def _safe_topic(value: Any) -> Optional[str]:
63
+ """Topic is user text persisted to session_log — redact or drop."""
64
+ if not value:
65
+ return None
66
+ try:
67
+ from credential_patterns import redact_credentials
68
+ return redact_credentials(str(value))
69
+ except Exception:
70
+ return None
71
+
72
+
73
+ def _parse_ts(value: Any) -> Optional[str]:
74
+ """Normalize a timestamp to an ISO-8601 UTC string.
75
+
76
+ summary.json timestamps are RFC3339 strings (chrono ``DateTime<Utc>``);
77
+ hook/signals timestamps may be epoch seconds. Returns None when absent or
78
+ unparseable.
79
+ """
80
+ if value is None:
81
+ return None
82
+ if isinstance(value, (int, float)):
83
+ try:
84
+ return datetime.fromtimestamp(float(value), tz=timezone.utc).isoformat()
85
+ except (TypeError, ValueError, OSError, OverflowError):
86
+ return None
87
+ if isinstance(value, str):
88
+ text = value.strip()
89
+ if not text:
90
+ return None
91
+ try:
92
+ dt = datetime.fromisoformat(text.replace("Z", "+00:00"))
93
+ if dt.tzinfo is None:
94
+ dt = dt.replace(tzinfo=timezone.utc)
95
+ return dt.astimezone(timezone.utc).isoformat()
96
+ except (ValueError, TypeError):
97
+ return None
98
+ return None
99
+
100
+
101
+ try:
102
+ from hermes_session import compute_quality_score as _compute_quality_score
103
+ except Exception:
104
+ _compute_quality_score = None
105
+
106
+
107
+ def _quality(input_tokens, output_tokens, message_count, model, ctx_window, cache_read):
108
+ """Quality score from Grok's session-level fields (mirrors copilot_session)."""
109
+ if _compute_quality_score is not None:
110
+ try:
111
+ return _compute_quality_score(
112
+ input_tokens=input_tokens,
113
+ output_tokens=output_tokens,
114
+ message_count=message_count,
115
+ model=model,
116
+ context_window=ctx_window,
117
+ cache_read=cache_read,
118
+ )
119
+ except Exception as exc: # pragma: no cover - defensive fallback
120
+ logger.debug("[grok_session] quality scorer unavailable: %s", exc)
121
+ fill = min(1.0, (input_tokens + cache_read) / ctx_window) if ctx_window else 0.0
122
+ score = max(0.0, 100.0 - fill * 50.0)
123
+ band = "healthy" if score >= 70 else ("watch" if score >= 50 else "critical")
124
+ if score >= 90:
125
+ grade = "A"
126
+ elif score >= 75:
127
+ grade = "B"
128
+ elif score >= 60:
129
+ grade = "C"
130
+ else:
131
+ grade = "D"
132
+ return {
133
+ "score": round(score, 1),
134
+ "grade": grade,
135
+ "band": band,
136
+ "fill_ratio": round(fill, 4),
137
+ "context_window_used": ctx_window,
138
+ "signals": {"fill": round(fill, 4)},
139
+ "signal_scores": {"fill": round(fill * 100, 1)},
140
+ "signals_active": ["context_fill"],
141
+ "signals_omitted": [],
142
+ "estimated": True,
143
+ }
144
+
145
+
146
+ def _base_canonical(slug: str, token_source: str) -> dict:
147
+ """Shared canonical skeleton shaped like copilot_session._base_canonical."""
148
+ return {
149
+ "slug": slug,
150
+ "topic": None,
151
+ "first_ts": None,
152
+ "duration_minutes": 0.0,
153
+ "total_input_tokens": 0,
154
+ "total_output_tokens": 0,
155
+ "total_cache_read": 0,
156
+ "total_cache_create": 0,
157
+ "total_cache_create_1h": 0,
158
+ "total_cache_create_5m": 0,
159
+ "model_context_window": _GROK_DEFAULT_CONTEXT_WINDOW,
160
+ "cache_hit_rate": 0.0,
161
+ "cost_usd": 0.0,
162
+ "cost_source": "grok_no_cost_data",
163
+ "credits": None,
164
+ "model": _UNKNOWN_MODEL,
165
+ "model_family": None,
166
+ "model_usage": {},
167
+ "model_usage_breakdown": {},
168
+ "message_count": 0,
169
+ "api_calls": 0,
170
+ "tool_calls": {"total": 0},
171
+ "estimated": False,
172
+ "token_source": token_source,
173
+ "runtime": "grok",
174
+ "version": None,
175
+ "avg_call_gap_seconds": None,
176
+ "max_call_gap_seconds": None,
177
+ "p95_call_gap_seconds": None,
178
+ "rate_limits": None,
179
+ "effort": None,
180
+ "effort_breakdown": {},
181
+ "skills_used": {},
182
+ "subagents_used": {},
183
+ "tool_duration_p90_ms": None,
184
+ "task_duration_ms_max": None,
185
+ "ttft_ms_avg": None,
186
+ "end_reason": "",
187
+ "archived": False,
188
+ "cwd": None,
189
+ "billing_provider": "grok",
190
+ "incomplete": False,
191
+ }
192
+
193
+
194
+ def normalize_session(raw: dict) -> Optional[dict]:
195
+ """Normalize a grok_state.read_session() dict into the canonical shape."""
196
+ if not isinstance(raw, dict):
197
+ return None
198
+ session_id = str(raw.get("session_id") or "")
199
+ if not session_id:
200
+ return None
201
+
202
+ usage = raw.get("usage") if isinstance(raw.get("usage"), dict) else {}
203
+ signals = raw.get("signals") if isinstance(raw.get("signals"), dict) else {}
204
+
205
+ # Token resolution: authoritative turn_completed usage first, then the
206
+ # signals contextTokensUsed estimate, then a zero-token row (never dropped).
207
+ turns = _safe_int(usage.get("turns"))
208
+ total_input = _safe_int(usage.get("input_tokens"))
209
+ total_output = _safe_int(usage.get("output_tokens"))
210
+ total_cache_read = _safe_int(usage.get("cache_read_tokens"))
211
+ total_cache_create = _safe_int(usage.get("cache_create_tokens"))
212
+ usage_incomplete = bool(usage.get("usage_incomplete"))
213
+
214
+ if turns > 0 or total_input > 0 or total_output > 0:
215
+ token_source = "grok_updates_jsonl"
216
+ estimated = usage_incomplete # an incomplete bill under-counts
217
+ else:
218
+ ctx_used = _safe_int(signals.get("contextTokensUsed"))
219
+ total_input = ctx_used
220
+ total_output = 0
221
+ token_source = "grok_signals_only"
222
+ estimated = True
223
+
224
+ # Per-model usage: billable = input + output per model (usage.modelUsage).
225
+ model_usage = {}
226
+ model_usage_breakdown = {}
227
+ raw_model_usage = usage.get("model_usage") if isinstance(usage.get("model_usage"), dict) else {}
228
+ for model, row in raw_model_usage.items():
229
+ if not isinstance(row, dict):
230
+ continue
231
+ inp = _safe_int(row.get("input_tokens"))
232
+ out = _safe_int(row.get("output_tokens"))
233
+ cr = _safe_int(row.get("cache_read_tokens"))
234
+ cc = _safe_int(row.get("cache_create_tokens"))
235
+ key = str(model) if model is not None and str(model) != "" else _UNKNOWN_MODEL
236
+ model_usage[key] = inp + out
237
+ model_usage_breakdown[key] = {
238
+ "fresh_input": max(0, inp - cr),
239
+ "cache_read": cr,
240
+ "cache_create": cc,
241
+ "output": out,
242
+ }
243
+
244
+ # Primary model: signals.primaryModelId, else summary.currentModelId, else
245
+ # the highest-billable model from usage.
246
+ model = signals.get("primaryModelId") or raw.get("model_id") or _UNKNOWN_MODEL
247
+ if model == _UNKNOWN_MODEL and model_usage:
248
+ model = max(model_usage, key=lambda k: model_usage[k])
249
+ model = str(model) if isinstance(model, str) and model else _UNKNOWN_MODEL
250
+
251
+ ctx_window = _safe_int(signals.get("contextWindowTokens")) or _default_context_window()
252
+
253
+ # Cost: trustworthy ticks only (scrub rule in notification.rs).
254
+ ticks = _safe_int(usage.get("cost_usd_ticks"))
255
+ if ticks > 0 and not usage_incomplete:
256
+ cost_usd = ticks / _USD_TICKS_PER_USD
257
+ cost_source = "grok_cost_usd_ticks"
258
+ else:
259
+ cost_usd = 0.0
260
+ cost_source = "grok_no_cost_data"
261
+
262
+ # Duration: updatedAt - createdAt (RFC3339), else sessionDurationSeconds.
263
+ duration_minutes = 0.0
264
+ created = raw.get("created_at")
265
+ updated = raw.get("updated_at")
266
+ if isinstance(created, str) and isinstance(updated, str):
267
+ try:
268
+ c = datetime.fromisoformat(created.replace("Z", "+00:00"))
269
+ u = datetime.fromisoformat(updated.replace("Z", "+00:00"))
270
+ duration_minutes = max(0.0, (u - c).total_seconds() / 60.0)
271
+ except (ValueError, TypeError):
272
+ duration_minutes = 0.0
273
+ if duration_minutes == 0.0:
274
+ duration_minutes = _safe_int(signals.get("sessionDurationSeconds")) / 60.0
275
+
276
+ message_count = _safe_int(raw.get("num_messages")) or _safe_int(raw.get("num_chat_messages"))
277
+ tool_calls_total = _safe_int(signals.get("toolCallCount"))
278
+ compactions = _safe_int(signals.get("compactionCount"))
279
+
280
+ cache_hit_rate = (total_cache_read / total_input) if total_input > 0 else 0.0
281
+ quality = _quality(total_input, total_output, message_count, model, ctx_window, total_cache_read)
282
+
283
+ session = _base_canonical(session_id, token_source)
284
+ session.update(
285
+ {
286
+ "topic": _safe_topic(raw.get("title")),
287
+ "first_ts": _parse_ts(created),
288
+ "last_ts": _parse_ts(updated),
289
+ "duration_minutes": round(duration_minutes, 2),
290
+ "total_input_tokens": total_input,
291
+ "total_output_tokens": total_output,
292
+ "total_cache_read": total_cache_read,
293
+ "total_cache_create": total_cache_create,
294
+ "total_cache_create_1h": total_cache_create,
295
+ "model_context_window": ctx_window,
296
+ "cache_hit_rate": round(cache_hit_rate, 4),
297
+ "cost_usd": round(cost_usd, 6),
298
+ "cost_source": cost_source,
299
+ "model": model,
300
+ "model_usage": model_usage,
301
+ "model_usage_breakdown": model_usage_breakdown,
302
+ "message_count": message_count,
303
+ "api_calls": turns,
304
+ "tool_calls": {"total": tool_calls_total},
305
+ "estimated": estimated,
306
+ "version": raw.get("agent_name"),
307
+ "cwd": raw.get("cwd"),
308
+ "incomplete": usage_incomplete,
309
+ "end_reason": "usage_incomplete" if usage_incomplete else "",
310
+ "compactions": compactions,
311
+ "quality": quality,
312
+ "quality_score": quality.get("score"),
313
+ "quality_grade": quality.get("grade"),
314
+ "quality_band": quality.get("band"),
315
+ }
316
+ )
317
+ return session
@@ -0,0 +1,299 @@
1
+ #!/usr/bin/env python3
2
+ """Read-only reader for Grok Build session data.
3
+
4
+ Grok Build persists every session under ``$GROK_HOME/sessions/<encoded-cwd>/<uuid>/``
5
+ (17-sessions.md). The files this adapter reads, all optional / missing-tolerant:
6
+
7
+ summary.json — ``Summary``: ``info.id``, ``info.cwd``, the session title,
8
+ created/updated timestamps, message counts, current model id
9
+ and agent name. Upstream currently writes it with plain
10
+ serde_json (snake_case field names); older builds used
11
+ camelCase, so both spellings are accepted on read.
12
+ Source: crates/codegen/xai-grok-shell/src/session/persistence.rs.
13
+ signals.json — ``SessionSignals`` (camelCase): ``turnCount``, ``toolCallCount``,
14
+ ``toolsUsed``, ``modelsUsed``, ``primaryModelId``,
15
+ ``contextTokensUsed``, ``contextWindowTokens``,
16
+ ``contextWindowUsage``, ``compactionCount``,
17
+ ``sessionDurationSeconds``.
18
+ Source: crates/codegen/xai-grok-shell/src/session/signals.rs.
19
+ updates.jsonl — newline-delimited ``SessionNotification`` (camelCase) lines;
20
+ each line's ``update`` is a ``SessionUpdate`` tagged by
21
+ ``sessionUpdate`` (snake_case variant name). The
22
+ ``turn_completed`` variant carries ``usage`` (``PromptUsage``:
23
+ flattened camelCase ``inputTokens``/``outputTokens``/
24
+ ``cachedReadTokens``/``cacheCreationTokens``/``reasoningTokens``/
25
+ ``modelCalls``/``costUsdTicks``/``costIsPartial`` plus
26
+ ``modelUsage`` + ``numTurns`` + ``usageIsIncomplete``) — the
27
+ authoritative per-turn token totals.
28
+ Source: crates/codegen/xai-grok-shell/src/extensions/notification.rs
29
+ (``SessionNotification``, ``SessionUpdate``, ``PromptUsage``,
30
+ ``PromptUsageModel``) and src/session/turn_completion.rs.
31
+
32
+ Design constraints (mirroring copilot_state.py / cursor_state.py):
33
+
34
+ - **Pure stdlib only.** No Grok imports.
35
+ - **Strictly read-only.** Never writes any file.
36
+ - **No hardcoded user paths.** The Grok home comes from ``runtime_env.grok_home()``;
37
+ callers may pass an explicit ``home`` override.
38
+ - **Schema-defensive.** Every reader degrades to a safe default and never raises.
39
+ """
40
+
41
+ from __future__ import annotations
42
+
43
+ import json
44
+ import logging
45
+ from pathlib import Path
46
+ from typing import Any, Optional
47
+
48
+ logger = logging.getLogger(__name__)
49
+
50
+ _SESSIONS_DIR = "sessions"
51
+ _SUMMARY_FILE = "summary.json"
52
+ _SIGNALS_FILE = "signals.json"
53
+ _UPDATES_FILE = "updates.jsonl"
54
+
55
+ # Bounded reads: a maliciously-crafted or pathological file must never stall a
56
+ # detached rollup (mirrors cursor_state.py / copilot_state.py caps).
57
+ _MAX_JSON_BYTES = 8 * 1024 * 1024
58
+ _MAX_LINE_BYTES = 2 * 1024 * 1024
59
+ _MAX_EVENTS_PER_FILE = 500_000
60
+
61
+ # updates.jsonl SessionUpdate tag value for the authoritative per-turn usage.
62
+ _TURN_COMPLETED_TAG = "turn_completed"
63
+
64
+
65
+ def _safe_int(value: Any, default: int = 0) -> int:
66
+ try:
67
+ return int(float(value)) if value is not None else default
68
+ except (TypeError, ValueError, OverflowError):
69
+ return default
70
+
71
+
72
+ def _read_json_file(path: Path) -> Optional[dict]:
73
+ """Read a bounded JSON file, returning the dict or None when unreadable."""
74
+ try:
75
+ if path.stat().st_size > _MAX_JSON_BYTES:
76
+ return None
77
+ data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
78
+ return data if isinstance(data, dict) else None
79
+ except (OSError, json.JSONDecodeError, ValueError) as exc:
80
+ logger.debug("[grok_state] cannot read %s: %s", path, exc)
81
+ return None
82
+
83
+
84
+ def find_session_dirs(home: Optional[Path] = None) -> list:
85
+ """Return session directories under ``<home>/sessions/<group>/<uuid>/``.
86
+
87
+ The store is two levels deep: the group dir is the URL-encoded cwd (or a
88
+ slug+hash with a ``.cwd`` file when the encoded name exceeds 255 bytes), and
89
+ each group holds one directory per session UUID. Returns [] when the
90
+ sessions dir does not exist. Never raises.
91
+ """
92
+ if home is None:
93
+ try:
94
+ from runtime_env import grok_home
95
+
96
+ home = grok_home()
97
+ except Exception as exc:
98
+ logger.debug("[grok_state] cannot import runtime_env: %s", exc)
99
+ return []
100
+ sessions_dir = home / _SESSIONS_DIR
101
+ if not sessions_dir.is_dir():
102
+ return []
103
+ try:
104
+ result = []
105
+ for group in sessions_dir.iterdir():
106
+ if not group.is_dir():
107
+ continue
108
+ for session_dir in group.iterdir():
109
+ if session_dir.is_dir():
110
+ result.append(session_dir)
111
+ return sorted(result, key=lambda p: str(p))
112
+ except OSError as exc:
113
+ logger.debug("[grok_state] cannot list %s: %s", sessions_dir, exc)
114
+ return []
115
+
116
+
117
+ def read_summary(session_dir: Path) -> Optional[dict]:
118
+ """Read ``summary.json``. None when absent/unreadable/invalid."""
119
+ return _read_json_file(session_dir / _SUMMARY_FILE)
120
+
121
+
122
+ def read_signals(session_dir: Path) -> Optional[dict]:
123
+ """Read ``signals.json``. None when absent/unreadable/invalid."""
124
+ return _read_json_file(session_dir / _SIGNALS_FILE)
125
+
126
+
127
+ def _stream_updates(updates_path: Path):
128
+ """Yield parsed dicts from updates.jsonl, one per valid line.
129
+
130
+ Skips malformed JSON, oversized lines, lines missing an ``update`` object,
131
+ and lines beyond ``_MAX_EVENTS_PER_FILE``. Never raises.
132
+ """
133
+ try:
134
+ count = 0
135
+ with updates_path.open("rb") as fh:
136
+ for raw_line in fh:
137
+ if count >= _MAX_EVENTS_PER_FILE:
138
+ logger.debug(
139
+ "[grok_state] %s: hit %d-event cap, stopping",
140
+ updates_path,
141
+ _MAX_EVENTS_PER_FILE,
142
+ )
143
+ break
144
+ if len(raw_line) > _MAX_LINE_BYTES:
145
+ continue
146
+ line = raw_line.strip()
147
+ if not line:
148
+ continue
149
+ try:
150
+ obj = json.loads(line)
151
+ except json.JSONDecodeError:
152
+ continue
153
+ if not isinstance(obj, dict):
154
+ continue
155
+ count += 1
156
+ yield obj
157
+ except OSError as exc:
158
+ logger.debug("[grok_state] cannot read %s: %s", updates_path, exc)
159
+
160
+
161
+ def read_usage_totals(session_dir: Path) -> dict:
162
+ """Sum the authoritative per-turn usage across updates.jsonl.
163
+
164
+ Only ``turn_completed`` records contribute. Returns a dict with:
165
+ input_tokens, output_tokens, cache_read_tokens, cache_create_tokens,
166
+ reasoning_tokens, model_calls, turns, cost_usd_ticks (summed only from
167
+ records whose usage is NOT incomplete and NOT cost-partial — the scrub
168
+ rule in notification.rs), usage_incomplete (True when any contributing
169
+ record was incomplete), model_usage ({model: {input, output, cache_read,
170
+ cache_create, model_calls}}).
171
+
172
+ Missing/unreadable updates.jsonl yields a zeroed dict. Never raises.
173
+ """
174
+ out = {
175
+ "input_tokens": 0,
176
+ "output_tokens": 0,
177
+ "cache_read_tokens": 0,
178
+ "cache_create_tokens": 0,
179
+ "reasoning_tokens": 0,
180
+ "model_calls": 0,
181
+ "turns": 0,
182
+ "cost_usd_ticks": 0,
183
+ "usage_incomplete": False,
184
+ "model_usage": {},
185
+ }
186
+ updates_path = session_dir / _UPDATES_FILE
187
+
188
+ for line in _stream_updates(updates_path):
189
+ update = line.get("update")
190
+ if not isinstance(update, dict):
191
+ continue
192
+ if update.get("sessionUpdate") != _TURN_COMPLETED_TAG:
193
+ continue
194
+ usage = update.get("usage")
195
+ if not isinstance(usage, dict):
196
+ continue
197
+
198
+ out["turns"] += 1
199
+ out["input_tokens"] += _safe_int(usage.get("inputTokens"))
200
+ out["output_tokens"] += _safe_int(usage.get("outputTokens"))
201
+ out["cache_read_tokens"] += _safe_int(usage.get("cachedReadTokens"))
202
+ out["cache_create_tokens"] += _safe_int(usage.get("cacheCreationTokens"))
203
+ out["reasoning_tokens"] += _safe_int(usage.get("reasoningTokens"))
204
+ out["model_calls"] += _safe_int(usage.get("modelCalls"))
205
+
206
+ incomplete = bool(usage.get("usageIsIncomplete"))
207
+ partial = bool(usage.get("costIsPartial"))
208
+ if incomplete:
209
+ out["usage_incomplete"] = True
210
+ # Scrub rule (notification.rs): cost is trustworthy only when NOT
211
+ # incomplete and NOT partial. Absence of cost means unknown, not free.
212
+ if not incomplete and not partial:
213
+ out["cost_usd_ticks"] += _safe_int(usage.get("costUsdTicks"))
214
+
215
+ model_usage = usage.get("modelUsage")
216
+ if isinstance(model_usage, dict):
217
+ for model, row in model_usage.items():
218
+ if not isinstance(row, dict):
219
+ continue
220
+ model_name = str(model) if model is not None and str(model) != "" else "unknown"
221
+ slot = out["model_usage"].setdefault(
222
+ model_name,
223
+ {
224
+ "input_tokens": 0,
225
+ "output_tokens": 0,
226
+ "cache_read_tokens": 0,
227
+ "cache_create_tokens": 0,
228
+ "model_calls": 0,
229
+ },
230
+ )
231
+ slot["input_tokens"] += _safe_int(row.get("inputTokens"))
232
+ slot["output_tokens"] += _safe_int(row.get("outputTokens"))
233
+ slot["cache_read_tokens"] += _safe_int(row.get("cacheReadInputTokens"))
234
+ slot["cache_create_tokens"] += _safe_int(row.get("cacheCreationInputTokens"))
235
+ slot["model_calls"] += _safe_int(row.get("modelCalls"))
236
+ return out
237
+
238
+
239
+ def read_session(session_dir: Path) -> dict:
240
+ """Parse one Grok session directory into a raw session dict.
241
+
242
+ Combines summary.json (identity/cwd/title/timestamps), signals.json
243
+ (tool/turn/model/context counters), and updates.jsonl (authoritative
244
+ per-turn token totals). Returns a dict with keys:
245
+ session_id, cwd, title, created_at, updated_at, num_messages,
246
+ num_chat_messages, model_id, agent_name, signals, usage,
247
+ data_source ("grok_session_store").
248
+ """
249
+ session_id = session_dir.name
250
+ summary = read_summary(session_dir) or {}
251
+ signals = read_signals(session_dir) or {}
252
+ usage = read_usage_totals(session_dir)
253
+
254
+ info = summary.get("info") if isinstance(summary.get("info"), dict) else {}
255
+ cwd = info.get("cwd") if isinstance(info.get("cwd"), str) else None
256
+
257
+ def field(camel, snake):
258
+ # Upstream serializes Summary with plain serde_json today (snake_case
259
+ # names) and earlier builds used camelCase; accept either so a rename
260
+ # on their side never silently zeroes the session record.
261
+ value = summary.get(camel)
262
+ return value if value is not None else summary.get(snake)
263
+
264
+ return {
265
+ "session_id": session_id,
266
+ "cwd": cwd,
267
+ "title": field("sessionSummary", "session_summary"),
268
+ "created_at": field("createdAt", "created_at"),
269
+ "updated_at": field("updatedAt", "updated_at"),
270
+ "num_messages": _safe_int(field("numMessages", "num_messages")),
271
+ "num_chat_messages": _safe_int(field("numChatMessages", "num_chat_messages")),
272
+ "model_id": field("currentModelId", "current_model_id"),
273
+ "agent_name": field("agentName", "agent_name"),
274
+ "signals": signals,
275
+ "usage": usage,
276
+ "data_source": "grok_session_store",
277
+ }
278
+
279
+
280
+ def read_all_sessions(home: Optional[Path] = None) -> list:
281
+ """Parse all Grok sessions, deduped by session_id (first wins)."""
282
+ seen: set = set()
283
+ results: list = []
284
+ for sd in find_session_dirs(home=home):
285
+ sid = sd.name
286
+ if sid in seen:
287
+ continue
288
+ seen.add(sid)
289
+ try:
290
+ results.append(read_session(sd))
291
+ except Exception as exc:
292
+ logger.debug("[grok_state] error reading session %s: %s", sid, exc)
293
+ return results
294
+
295
+
296
+ if __name__ == "__main__": # pragma: no cover - debug helper
297
+ import json as _json
298
+
299
+ print(_json.dumps(read_all_sessions(), indent=2, default=str))