@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,699 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer — Grok Build hook bridge.
3
+
4
+ Thin, fast, fail-safe entry point invoked by Grok Build's hooks system
5
+ (``$GROK_HOME/hooks/token-optimizer.json``). One bridge handles every event TO
6
+ wires:
7
+
8
+ grok_hook_bridge.py SessionStart
9
+ grok_hook_bridge.py UserPromptSubmit
10
+ grok_hook_bridge.py PreToolUse
11
+ grok_hook_bridge.py PostToolUse
12
+ grok_hook_bridge.py Stop
13
+
14
+ Contract notes (source: the cloned ``github.com/xai-org/grok-build`` repo,
15
+ ``crates/codegen/xai-grok-pager/docs/user-guide/10-hooks.md`` — the only source
16
+ of truth; this adapter is built against the documented contract without a
17
+ live Grok install, so every assumed shape below cites that file and should be
18
+ re-checked against a live session when one is available):
19
+
20
+ - Payloads arrive on stdin as ONE JSON object with a camelCase envelope:
21
+ ``hookEventName`` (grok's snake_case name, e.g. ``pre_tool_use``),
22
+ ``hook_event_name`` (Claude's PascalCase name, e.g. ``PreToolUse``),
23
+ ``sessionId``, ``cwd``, ``workspaceRoot``, ``timestamp``, ``permissionMode``,
24
+ ``promptId``; tool events add ``toolName``, ``toolInput``, ``toolUseId``,
25
+ ``toolInputTruncated`` (10-hooks.md "Writing Hook Scripts / Input").
26
+ - Bash is grok's ``run_terminal_command`` tool (alias table maps ``Bash`` to
27
+ it); the installer scopes PreToolUse with ``matcher: "Bash"`` so only bash
28
+ commands enter the rewrite hot path.
29
+ - Output is Grok's top-level contract (NOT the Copilot ``hookSpecificOutput``
30
+ envelope from the ``updatedInput`` standpoint — grok accepts both a top-level
31
+ ``decision`` and ``hookSpecificOutput.permissionDecision``/``updatedInput``/
32
+ ``additionalContext``): PreToolUse rewrite → ``{"hookSpecificOutput":
33
+ {"hookEventName": "PreToolUse", "updatedInput": {...}}}`` (omitting
34
+ ``decision`` = allow + apply rewrite); PostToolUse nudge → ``{"hookSpecificOutput":
35
+ {"hookEventName": "PostToolUse", "additionalContext": "..."}}``.
36
+ - Fail-open everywhere: TO never emits ``deny``/``block``; a timed-out or
37
+ crashed hook never blocks a tool call (10-hooks.md "How a Hook Resolves",
38
+ step 4).
39
+
40
+ Security posture mirrors bash_hook.py: the bash rewrite inherits its whitelist
41
+ + dangerous-char exclusions and fails CLOSED (emit nothing) on any uncertainty.
42
+ This bridge never imports Grok internals and never writes outside
43
+ ``<grok_home>/token-optimizer/``.
44
+ """
45
+
46
+ from __future__ import annotations
47
+
48
+ import json
49
+ import logging
50
+ import os
51
+ import re
52
+ import shlex
53
+ import subprocess
54
+ import sys
55
+ import time
56
+ from contextlib import contextmanager
57
+ from pathlib import Path
58
+
59
+ logger = logging.getLogger(__name__)
60
+ _observed_warned = False
61
+
62
+ # Windows console-flash guard. getattr -> 0 on POSIX.
63
+ _NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
64
+
65
+ _SCRIPT_DIR = Path(__file__).resolve().parent
66
+ sys.path.insert(0, str(_SCRIPT_DIR))
67
+
68
+ # The bridge must run even if siblings are missing (partial install): every
69
+ # import is optional and the dependent feature degrades/disabled when absent.
70
+ try:
71
+ from runtime_env import grok_home
72
+ except ImportError: # pragma: no cover - broken install
73
+ grok_home = None # type: ignore[assignment]
74
+
75
+ try:
76
+ from spawn_utils import spawn_detached
77
+ except ImportError: # pragma: no cover - broken install
78
+ logger.warning("[grok] spawn_utils import failed; using degraded fallback")
79
+
80
+ def spawn_detached(argv, **popen_kwargs): # type: ignore[no-redef]
81
+ import subprocess as _sp
82
+
83
+ kwargs = dict(popen_kwargs)
84
+ kwargs["creationflags"] = kwargs.get("creationflags", 0) | _NO_WINDOW
85
+ try:
86
+ return _sp.Popen(argv, **kwargs)
87
+ except OSError:
88
+ return None
89
+
90
+ try:
91
+ import bash_hook as _bash_hook
92
+ except ImportError: # pragma: no cover
93
+ _bash_hook = None # type: ignore[assignment]
94
+
95
+ try:
96
+ from codex_io import atomic_write_json as _atomic_write_json_impl
97
+ except ImportError: # pragma: no cover - broken install
98
+ _atomic_write_json_impl = None # type: ignore[assignment]
99
+
100
+ try:
101
+ from hook_runtime import lease_lock
102
+ except ImportError: # pragma: no cover - broken install
103
+ lease_lock = None # type: ignore[assignment]
104
+
105
+ _MAX_STDIN_BYTES = 4 * 1024 * 1024 # refuse absurd payloads (amplification)
106
+ _STALE_LOCK_SECS = 7 * 24 * 3600 # sessionStart lock sweep threshold
107
+ _NUDGE_TOOL_CALLS = (30, 80) # context-growth nudge thresholds (tool proxy)
108
+
109
+ # Snapshot at import: the installed payload is static for the process lifetime.
110
+ _COMPRESS_PATH = _SCRIPT_DIR / "bash_compress.py"
111
+ _COMPRESS_AVAILABLE = _COMPRESS_PATH.exists()
112
+
113
+ _SESSION_ID_RE = re.compile(r"[^A-Za-z0-9_-]")
114
+
115
+
116
+ def _sanitize_session_id(sid):
117
+ """Strip everything but [A-Za-z0-9_-] so a payload id can never traverse."""
118
+ if not sid:
119
+ return "unknown"
120
+ cleaned = _SESSION_ID_RE.sub("", sid)[:64]
121
+ return cleaned if len(cleaned) >= 6 else "unknown"
122
+
123
+
124
+ # ---------------------------------------------------------------------------
125
+ # Documented-capability gate (static; contract-only mode)
126
+ #
127
+ # Unlike the Copilot bridge, Grok hooks are NOT version-gated against a live
128
+ # ``grok --version`` (there is no Grok host to probe in NO-INSTALL mode). The
129
+ # gate keys EVERY assumed capability to the cloned source's documented contract
130
+ # (10-hooks.md) so each assumption is traceable and can be re-checked against
131
+ # a live session when one is available.
132
+ # ---------------------------------------------------------------------------
133
+
134
+ CAP_UPDATED_INPUT = "updated_input" # 10-hooks.md "Output (Blocking Hooks)"
135
+ CAP_POSTTOOL_CTX = "posttooluse_ctx" # 10-hooks.md "PostToolUse Output"
136
+ CAP_SESSIONSTART_CTX = "sessionstart_ctx" # passive: stdout ignored (10-hooks.md "Passive Hooks")
137
+ CAP_USERPROMPT_CTX = "userprompt_ctx" # allowing stdout discarded (10-hooks.md "UserPromptSubmit Decision Control")
138
+
139
+
140
+ _CAPABILITIES = None
141
+
142
+
143
+ def _documented_caps() -> dict:
144
+ """The documented Grok hook contract (static — no live host in this mode)."""
145
+ return {
146
+ CAP_UPDATED_INPUT: True,
147
+ CAP_POSTTOOL_CTX: True,
148
+ CAP_SESSIONSTART_CTX: False, # SessionStart stdout is ignored
149
+ CAP_USERPROMPT_CTX: False, # allowing UserPromptSubmit stdout is discarded
150
+ }
151
+
152
+
153
+ def load_capabilities():
154
+ """Return the static documented matrix.
155
+
156
+ Unlike the Copilot bridge (which re-probes a live CLI version), Grok's
157
+ capability matrix is static in contract-only mode, so there is no refresh.
158
+ Cached at first call to avoid allocating a fresh dict on every tool event.
159
+ """
160
+ global _CAPABILITIES
161
+ if _CAPABILITIES is None:
162
+ _CAPABILITIES = _documented_caps()
163
+ return _CAPABILITIES
164
+
165
+
166
+ # ---------------------------------------------------------------------------
167
+ # Payload decoding (fail-closed)
168
+ # ---------------------------------------------------------------------------
169
+
170
+
171
+ def _read_stdin_payload():
172
+ """Read and decode the Grok hook payload from stdin. None on any failure."""
173
+ try:
174
+ raw = sys.stdin.read(_MAX_STDIN_BYTES + 1)
175
+ except (OSError, UnicodeDecodeError):
176
+ return None
177
+ if not raw or len(raw) > _MAX_STDIN_BYTES:
178
+ return None
179
+ try:
180
+ payload = json.loads(raw)
181
+ except (json.JSONDecodeError, ValueError):
182
+ return None
183
+ if not isinstance(payload, dict):
184
+ return None
185
+ return payload
186
+
187
+
188
+ def _parse_tool_input(raw):
189
+ """toolInput as a dict, or a JSON-encoded string -> dict; {} otherwise."""
190
+ if isinstance(raw, dict):
191
+ return raw
192
+ if isinstance(raw, str) and raw:
193
+ try:
194
+ parsed = json.loads(raw)
195
+ if isinstance(parsed, dict):
196
+ return parsed
197
+ except (json.JSONDecodeError, ValueError):
198
+ pass
199
+ return {}
200
+
201
+
202
+ def decode_payload(payload):
203
+ """Normalize a Grok hook payload into a flat, safe dict.
204
+
205
+ ``hook_event_name`` (PascalCase) wins over ``hookEventName`` (snake_case)
206
+ for the event label the handlers key on. ``cwd`` is capped at 1024 chars
207
+ because it is rewritten into the tally on every tool call.
208
+ """
209
+ out = {
210
+ "session_id": "",
211
+ "event_name": "",
212
+ "cwd": "",
213
+ "workspace_root": "",
214
+ "tool_name": "",
215
+ "tool_args": {},
216
+ "prompt_id": "",
217
+ "permission_mode": "",
218
+ "timestamp": None,
219
+ }
220
+ if not isinstance(payload, dict):
221
+ return out
222
+
223
+ sid = payload.get("sessionId", payload.get("session_id", ""))
224
+ if isinstance(sid, str):
225
+ out["session_id"] = _sanitize_session_id(sid)
226
+
227
+ event = payload.get("hook_event_name", payload.get("hookEventName", ""))
228
+ if isinstance(event, str):
229
+ out["event_name"] = event.strip()
230
+
231
+ cwd = payload.get("cwd", "")
232
+ if isinstance(cwd, str):
233
+ out["cwd"] = cwd[:1024]
234
+
235
+ root = payload.get("workspaceRoot", "")
236
+ if isinstance(root, str):
237
+ out["workspace_root"] = root[:1024]
238
+
239
+ tool_name = payload.get("toolName", payload.get("tool_name", ""))
240
+ if isinstance(tool_name, str):
241
+ out["tool_name"] = tool_name.strip()
242
+
243
+ out["tool_args"] = _parse_tool_input(
244
+ payload.get("toolInput", payload.get("tool_input", {}))
245
+ )
246
+
247
+ prompt_id = payload.get("promptId", "")
248
+ if isinstance(prompt_id, str):
249
+ out["prompt_id"] = prompt_id[:64]
250
+
251
+ mode = payload.get("permissionMode", "")
252
+ if isinstance(mode, str):
253
+ out["permission_mode"] = mode[:64]
254
+
255
+ out["timestamp"] = payload.get("timestamp")
256
+ return out
257
+
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # Data dir + atomic write + observed-events ledger
261
+ # ---------------------------------------------------------------------------
262
+
263
+
264
+ _TO_DIR_HOME = None
265
+ _TO_DIR_CACHED = None
266
+
267
+
268
+ def _to_dir():
269
+ """Token Optimizer's data dir under the Grok home. None if unavailable.
270
+
271
+ Memoized on the resolved grok_home() path so the hot path (3+ calls per
272
+ tool event via _record_observed, _tally_path, _update_tally) does one
273
+ mkdir, not three.
274
+ """
275
+ global _TO_DIR_HOME, _TO_DIR_CACHED
276
+ if grok_home is None:
277
+ return None
278
+ try:
279
+ home = grok_home()
280
+ if _TO_DIR_CACHED is not None and _TO_DIR_HOME == home:
281
+ return _TO_DIR_CACHED
282
+ d = home / "token-optimizer"
283
+ d.mkdir(parents=True, exist_ok=True)
284
+ _TO_DIR_HOME, _TO_DIR_CACHED = home, d
285
+ return d
286
+ except OSError:
287
+ return None
288
+
289
+
290
+ def _atomic_write_json(path, obj):
291
+ if _atomic_write_json_impl is None:
292
+ return False
293
+ try:
294
+ # replace_symlink=True: even if an attacker plants a symlink at the
295
+ # tally/observed-events path between calls, os.replace swaps the
296
+ # symlink itself, never its target. Matches _copy_no_follow in the
297
+ # installer and the hooks-file write.
298
+ _atomic_write_json_impl(path, obj, replace_symlink=True)
299
+ return True
300
+ except OSError:
301
+ return False
302
+
303
+
304
+ def _record_observed(event, **extra):
305
+ """Append one observed-events line (single-line JSONL). Never raises."""
306
+ to_dir = _to_dir()
307
+ if to_dir is None:
308
+ return
309
+ entry = {"event": event, "ts": time.time()}
310
+ entry.update({k: v for k, v in extra.items() if v is not None})
311
+ try:
312
+ with (to_dir / "observed-events.jsonl").open("a", encoding="utf-8") as fh:
313
+ fh.write(json.dumps(entry, default=str) + "\n")
314
+ except OSError:
315
+ global _observed_warned
316
+ if not _observed_warned:
317
+ _observed_warned = True
318
+ logger.warning("[grok_hook_bridge] observed-events append failed; "
319
+ "further append failures are silent", exc_info=True)
320
+
321
+
322
+ # ---------------------------------------------------------------------------
323
+ # Tally read-modify-write (nudge proxy + crash-recovery liveness)
324
+ # ---------------------------------------------------------------------------
325
+
326
+
327
+ def _tally_path(fields):
328
+ to_dir = _to_dir()
329
+ if to_dir is None:
330
+ return None
331
+ sid = fields.get("session_id") or "unknown"
332
+ return to_dir / f"inflight-{sid}.json"
333
+
334
+
335
+ def _load_tally(path):
336
+ if path is None:
337
+ return None
338
+ try:
339
+ data = json.loads(path.read_text(encoding="utf-8"))
340
+ return data if isinstance(data, dict) else None
341
+ except (OSError, json.JSONDecodeError, ValueError):
342
+ return None
343
+
344
+
345
+ @contextmanager
346
+ def _session_lock(to_dir, sid):
347
+ """Bounded portable lease around a tally read-modify-write. Fail-open."""
348
+ if to_dir is None or sid in (None, "", "unknown"):
349
+ yield False
350
+ return
351
+ lock_dir = to_dir / ".locks"
352
+ try:
353
+ lock_dir.mkdir(parents=True, exist_ok=True)
354
+ except OSError:
355
+ yield True
356
+ return
357
+ if lease_lock is None:
358
+ yield True
359
+ return
360
+ lock_path = lock_dir / f"inflight-{sid}.lock"
361
+ with lease_lock(lock_path, acquire_timeout=0.075) as acquired:
362
+ yield acquired
363
+
364
+
365
+ def _update_tally(fields, *, count_tool=False, bump_nudge=False, terminal=False):
366
+ """Read-modify-write the session tally; returns ``(tally, nudge_emitted)``."""
367
+ to_dir = _to_dir()
368
+ if to_dir is None:
369
+ return None, False
370
+ sid = fields.get("session_id") or "unknown"
371
+ with _session_lock(to_dir, sid) as acquired:
372
+ if not acquired:
373
+ return None, False
374
+ path = _tally_path(fields)
375
+ tally = _load_tally(path)
376
+ now = time.time()
377
+ if tally is None:
378
+ tally = {"session_id": sid, "first_ts": now}
379
+ if terminal:
380
+ tally["final"] = True
381
+ tally["end_reason"] = "stop"
382
+ else:
383
+ if tally.get("final") or tally.get("end_reason") == "stop":
384
+ tally["final"] = False
385
+ tally["end_reason"] = ""
386
+ tally["updated_at"] = now
387
+ tally.setdefault("tool_calls", 0)
388
+ if fields.get("cwd"):
389
+ tally["cwd"] = fields["cwd"]
390
+ if fields.get("workspace_root"):
391
+ tally["workspace_root"] = fields["workspace_root"]
392
+
393
+ if count_tool:
394
+ tally["tool_calls"] = int(tally.get("tool_calls", 0) or 0) + 1
395
+
396
+ nudge_emitted = False
397
+ if bump_nudge:
398
+ new_level = _nudge_level(int(tally.get("tool_calls", 0) or 0))
399
+ if new_level > int(tally.get("nudge_level", 0) or 0):
400
+ tally["nudge_level"] = new_level
401
+ nudge_emitted = True
402
+
403
+ _atomic_write_json(path, tally)
404
+ return tally, nudge_emitted
405
+
406
+
407
+ def _sweep_stale_locks():
408
+ """Remove stale lock/candidate artifacts (7d) on SessionStart. Never fatal."""
409
+ to_dir = _to_dir()
410
+ if to_dir is None:
411
+ return
412
+ lock_dir = to_dir / ".locks"
413
+ if not lock_dir.is_dir():
414
+ return
415
+ now = time.time()
416
+ try:
417
+ for pattern in ("*.lock", ".*.lock.candidate-*"):
418
+ for p in lock_dir.glob(pattern):
419
+ try:
420
+ if now - p.stat().st_mtime > _STALE_LOCK_SECS:
421
+ p.unlink()
422
+ except OSError:
423
+ continue
424
+ except OSError:
425
+ pass
426
+
427
+
428
+ # ---------------------------------------------------------------------------
429
+ # Compression + nudge helpers
430
+ # ---------------------------------------------------------------------------
431
+
432
+
433
+ def _compression_enabled():
434
+ return (
435
+ _bash_hook is not None
436
+ and _COMPRESS_AVAILABLE
437
+ and os.environ.get("TOKEN_OPTIMIZER_BASH_COMPRESS", "").strip() != "0"
438
+ )
439
+
440
+
441
+ def _nudge_level(tool_calls):
442
+ level = 0
443
+ for threshold in _NUDGE_TOOL_CALLS:
444
+ if tool_calls >= threshold:
445
+ level += 1
446
+ return level
447
+
448
+
449
+ _NUDGE_TEXT = (
450
+ "[Token Optimizer] Context is growing large for this session. Prefer "
451
+ "targeted reads over full files, avoid re-reading unchanged files, and "
452
+ "summarize before continuing long explorations."
453
+ )
454
+
455
+
456
+ # ---------------------------------------------------------------------------
457
+ # Spawns (fire-and-forget; detach + CREATE_NO_WINDOW)
458
+ # ---------------------------------------------------------------------------
459
+
460
+
461
+ def _measure_env(interactive=False):
462
+ env = dict(os.environ)
463
+ env["TOKEN_OPTIMIZER_RUNTIME"] = "grok"
464
+ env["PYTHONUTF8"] = "1"
465
+ env["PYTHONIOENCODING"] = "utf-8"
466
+ if interactive:
467
+ env["TOKEN_OPTIMIZER_INTERACTIVE"] = "1"
468
+ return env
469
+
470
+
471
+ # The installer does NOT copy measure.py into the plugin dir (version-drift
472
+ # risk); it writes a one-line "measure-path" locator naming the canonical
473
+ # measure.py. Resolution: a sibling measure.py (dev/test checkout), then the
474
+ # locator. Mirrors hermes/cursor _locate_measure_py.
475
+ _MEASURE_LOCATOR = _SCRIPT_DIR / "measure-path"
476
+
477
+
478
+ def _locate_measure_py():
479
+ """Return the path to measure.py, or None (rollups paused) if not found."""
480
+ sibling = _SCRIPT_DIR / "measure.py"
481
+ if sibling.is_file() and not sibling.is_symlink():
482
+ return sibling
483
+ try:
484
+ if _MEASURE_LOCATOR.is_file() and not _MEASURE_LOCATOR.is_symlink():
485
+ located = Path(_MEASURE_LOCATOR.read_text(encoding="utf-8").strip())
486
+ if (located.is_file() and not located.is_symlink()
487
+ and located.name == "measure.py"):
488
+ return located
489
+ except (OSError, ValueError):
490
+ pass
491
+ return None
492
+
493
+
494
+ def _spawn_measure(command, *, interactive=False):
495
+ """Shared spawn path for rollup and dashboard (probe guard + measure
496
+ lookup + detach). Collapses the two near-duplicate helpers."""
497
+ if os.environ.get("TOKEN_OPTIMIZER_PROBE") == "1":
498
+ return
499
+ measure = _locate_measure_py()
500
+ if measure is None:
501
+ return
502
+ try:
503
+ spawn_detached(
504
+ [sys.executable, str(measure)] + command,
505
+ env=_measure_env(interactive=interactive),
506
+ stdout=subprocess.DEVNULL,
507
+ stderr=subprocess.DEVNULL,
508
+ )
509
+ except (OSError, subprocess.SubprocessError):
510
+ logger.warning("[grok_hook_bridge] detached %s spawn failed",
511
+ command[0], exc_info=True)
512
+
513
+
514
+ def _spawn_rollup():
515
+ _spawn_measure(["grok-rollup", "--quiet"])
516
+
517
+
518
+ def _spawn_dashboard():
519
+ _spawn_measure(["dashboard", "--quiet"], interactive=True)
520
+
521
+
522
+ _STOP_ROLLUP_SECS = 120 # at most one stop rollup per machine per 120s
523
+
524
+
525
+ def _stop_rollup_due():
526
+ """True once per 120s per machine. Mirrors the cursor bridge throttle."""
527
+ to_dir = _to_dir()
528
+ if to_dir is None:
529
+ return False
530
+ state = to_dir / ".stop-rollup-last.json"
531
+ now = time.time()
532
+ if lease_lock is not None:
533
+ lock_dir = to_dir / ".locks"
534
+ try:
535
+ lock_dir.mkdir(parents=True, exist_ok=True)
536
+ except OSError:
537
+ lock_dir = None
538
+ if lock_dir is not None:
539
+ with lease_lock(lock_dir / ".stop-rollup.lock",
540
+ acquire_timeout=0.5, lease_seconds=30.0) as acquired:
541
+ if not acquired:
542
+ return False
543
+ return _stop_rollup_due_locked(state, now)
544
+ return _stop_rollup_due_locked(state, now)
545
+
546
+
547
+ def _stop_rollup_due_locked(state, now):
548
+ last = None
549
+ try:
550
+ if state.exists():
551
+ data = json.loads(state.read_text(encoding="utf-8"))
552
+ if isinstance(data, dict):
553
+ last = float(data.get("last", 0) or 0)
554
+ except (OSError, json.JSONDecodeError, ValueError, TypeError):
555
+ last = None
556
+ if last is not None and now - last < _STOP_ROLLUP_SECS:
557
+ return False
558
+ return _atomic_write_json(state, {"last": now})
559
+
560
+
561
+ # ---------------------------------------------------------------------------
562
+ # Event handlers (all fail-open: never raise into Grok)
563
+ # ---------------------------------------------------------------------------
564
+
565
+
566
+ def _emit(obj):
567
+ print(json.dumps(obj))
568
+
569
+
570
+ def handle_session_start(payload):
571
+ """Sweep stale locks + init the tally. Passive: stdout is IGNORED by grok.
572
+
573
+ grok's SessionStart is a passive event whose stdout is ignored
574
+ (10-hooks.md "Passive Hooks"), so no ``additionalContext`` is emitted — the
575
+ documented contract cannot deliver continuity at this seam.
576
+ """
577
+ fields = decode_payload(payload)
578
+ _record_observed("SessionStart", session_id=fields["session_id"] or None)
579
+ _update_tally(fields)
580
+ _sweep_stale_locks()
581
+
582
+
583
+ def handle_user_prompt_submit(payload):
584
+ """Record the prompt submit. Allowing stdout is DISCARDED by grok.
585
+
586
+ grok discards an allowing UserPromptSubmit hook's stdout (10-hooks.md
587
+ "UserPromptSubmit Decision Control"), so TO emits nothing here — only the
588
+ observed-events ledger is updated.
589
+ """
590
+ fields = decode_payload(payload)
591
+ _record_observed("UserPromptSubmit", session_id=fields["session_id"] or None)
592
+ _update_tally(fields)
593
+
594
+
595
+ def handle_pre_tool_use(payload):
596
+ """Bash output compression via updatedInput, gated and fail-closed."""
597
+ fields = decode_payload(payload)
598
+ if not load_capabilities().get(CAP_UPDATED_INPUT):
599
+ return
600
+ # grok's bash tool is ``run_terminal_command`` (alias ``Bash``); the
601
+ # installer's matcher already scoped this hook to the Bash tool, but the
602
+ # name check is defense-in-depth in case a config without the matcher fires.
603
+ if fields["tool_name"] not in ("run_terminal_command", "Bash"):
604
+ return
605
+ if not _compression_enabled():
606
+ return
607
+ command = fields["tool_args"].get("command")
608
+ if not isinstance(command, str) or not command:
609
+ return
610
+ if _bash_hook._has_dangerous_chars(command):
611
+ return
612
+ if not _bash_hook._is_whitelisted(command):
613
+ return
614
+ # Omitting ``decision`` below approves the call, so the rewrite is limited
615
+ # to commands that cannot write, delete or run other programs.
616
+ if not _bash_hook._is_auto_approvable(command):
617
+ return
618
+ try:
619
+ original_tokens = shlex.split(command)
620
+ except ValueError:
621
+ return
622
+ if not original_tokens:
623
+ return
624
+ rewritten = (
625
+ shlex.quote(sys.executable)
626
+ + " " + shlex.quote(str(_COMPRESS_PATH))
627
+ + " " + " ".join(shlex.quote(t) for t in original_tokens)
628
+ )
629
+ # Echo every original field and replace only ``command`` so any future
630
+ # fields survive the whole-toolInput replacement contract.
631
+ updated = dict(fields["tool_args"])
632
+ updated["command"] = rewritten
633
+ # Omitting ``decision`` = allow + apply the rewrite (10-hooks.md).
634
+ _emit({"hookSpecificOutput": {"hookEventName": "PreToolUse",
635
+ "updatedInput": updated}})
636
+ _record_observed("PreToolUse", tool_name=fields["tool_name"] or None,
637
+ rewrite="attempted")
638
+
639
+
640
+ def handle_post_tool_use(payload):
641
+ """Record the tool + nudge via additionalContext (fail-open)."""
642
+ fields = decode_payload(payload)
643
+ _record_observed("PostToolUse", tool_name=fields["tool_name"] or None)
644
+ tally, nudge_emitted = _update_tally(fields, count_tool=True, bump_nudge=True)
645
+ if tally is None:
646
+ return
647
+ if nudge_emitted and load_capabilities().get(CAP_POSTTOOL_CTX):
648
+ _emit({"hookSpecificOutput": {"hookEventName": "PostToolUse",
649
+ "additionalContext": _NUDGE_TEXT}})
650
+
651
+
652
+ def handle_stop(payload):
653
+ """Mark the tally final + throttled detached rollup and dashboard refresh.
654
+
655
+ Exit 0 + no output = allow the stop (10-hooks.md "Stop Decision Control").
656
+ """
657
+ fields = decode_payload(payload)
658
+ _record_observed("Stop", session_id=fields["session_id"] or None)
659
+ _update_tally(fields, terminal=True)
660
+ if _stop_rollup_due():
661
+ _spawn_rollup()
662
+ _spawn_dashboard()
663
+
664
+
665
+ _HANDLERS = {
666
+ "SessionStart": handle_session_start,
667
+ "UserPromptSubmit": handle_user_prompt_submit,
668
+ "PreToolUse": handle_pre_tool_use,
669
+ "PostToolUse": handle_post_tool_use,
670
+ "Stop": handle_stop,
671
+ }
672
+
673
+
674
+ def main(argv=None):
675
+ try:
676
+ from utf8_io import enforce_utf8_io
677
+ enforce_utf8_io()
678
+ except Exception:
679
+ pass
680
+ args = list(sys.argv[1:] if argv is None else argv)
681
+ if not args or args[0] not in _HANDLERS:
682
+ return 0
683
+ os.environ.setdefault("TOKEN_OPTIMIZER_RUNTIME", "grok")
684
+ payload = _read_stdin_payload()
685
+ if payload is None:
686
+ payload = {}
687
+ try:
688
+ _HANDLERS[args[0]](payload)
689
+ except Exception:
690
+ try:
691
+ logger.exception("[grok_hook_bridge] handler %s failed; failing open", args[0])
692
+ except Exception:
693
+ pass
694
+ return 0
695
+ return 0
696
+
697
+
698
+ if __name__ == "__main__":
699
+ sys.exit(main())