@alexgreensh/token-optimizer 0.0.0-stage → 5.13.51

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 +448 -0
  10. package/hooks/posttooluse_runner.py +1110 -0
  11. package/hooks/python-launcher.sh +816 -0
  12. package/hooks/run.py +788 -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 +149 -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 +3633 -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 +141 -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 +93 -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 +379 -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 +1011 -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 +288 -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 +426 -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 +400 -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 +716 -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 +59531 -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 +1923 -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,843 @@
1
+ #!/usr/bin/env python3
2
+ """Token Optimizer — Cursor hook bridge.
3
+
4
+ Thin, fast, fail-safe entry point invoked by Cursor's hooks.json (merged into
5
+ ``~/.cursor/hooks.json``). One bridge handles every Cursor event TO wires:
6
+
7
+ cursor_hook_bridge.py sessionStart
8
+ cursor_hook_bridge.py preToolUse
9
+ cursor_hook_bridge.py postToolUse
10
+ cursor_hook_bridge.py preCompact
11
+ cursor_hook_bridge.py stop
12
+ cursor_hook_bridge.py sessionEnd
13
+
14
+ Contract notes (verified against cursor.com/docs/hooks and the installed
15
+ Cursor CLI bundle as of 2026-08-31):
16
+
17
+ - Payloads arrive on stdin as ONE snake_case JSON object. Common fields:
18
+ ``conversation_id``, ``generation_id``, ``model``, ``model_id``,
19
+ ``hook_event_name``, ``cursor_version``, ``workspace_roots``,
20
+ ``transcript_path``. ``tool_input`` may be an object or a JSON-encoded
21
+ string (either tolerated); anything undecodable is a silent no-op.
22
+ - stdin → stdout JSON, exit 0 to accept. Exit 2 would deny (never emitted:
23
+ TO never blocks). Non-0 non-2 fails open in Cursor, but we always exit 0.
24
+ - No capability matrix. Cursor hooks are observed, not version-gated: every
25
+ handler appends one line to ``observed-events.jsonl`` so ``cursor-doctor``
26
+ can say exactly which events have fired on this install (KTD7/R13).
27
+ - Output is Cursor's top-level contract (NOT the Copilot
28
+ ``hookSpecificOutput`` envelope): ``preToolUse`` → ``{"permission":
29
+ "allow", "updated_input": {...}}``; ``sessionStart`` / ``postToolUse`` →
30
+ ``{"additional_context": "..."}``; the rest emit nothing.
31
+
32
+ Security posture mirrors bash_hook.py: the ``Shell`` rewrite inherits its
33
+ whitelist + dangerous-char exclusions and fails CLOSED (emit nothing) on any
34
+ uncertainty. This bridge never imports Cursor internals and never writes
35
+ outside ``<cursor_home>/token-optimizer/``.
36
+ """
37
+
38
+ from __future__ import annotations
39
+
40
+ import hashlib
41
+ import json
42
+ import logging
43
+ import os
44
+ import re
45
+ import shlex
46
+ import subprocess
47
+ import sys
48
+ import time
49
+ from contextlib import contextmanager
50
+ from pathlib import Path
51
+
52
+ logger = logging.getLogger(__name__)
53
+ _observed_warned = False
54
+
55
+ # Windows console-flash guard. Cursor's hook runners launch hooks
56
+ # directly, so any child we spawn would otherwise allocate a console window on
57
+ # Windows. getattr -> 0 on POSIX (creationflags=0 is an accepted no-op).
58
+ _NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
59
+
60
+ _SCRIPT_DIR = Path(__file__).resolve().parent
61
+ sys.path.insert(0, str(_SCRIPT_DIR))
62
+
63
+ # The bridge must run even if siblings are missing (partial install): each
64
+ # import below is optional, with the dependent feature degraded/disabled.
65
+ try:
66
+ from runtime_env import cursor_home
67
+ except ImportError: # pragma: no cover - broken install
68
+ cursor_home = None # type: ignore[assignment]
69
+
70
+ try:
71
+ from spawn_utils import spawn_detached
72
+ except ImportError: # pragma: no cover - broken install
73
+ logger.warning("[cursor] spawn_utils import failed; using degraded fallback")
74
+
75
+ def spawn_detached(argv, **popen_kwargs): # type: ignore[no-redef]
76
+ # Degraded broken-install path: does NOT detach (see
77
+ # spawn_utils.spawn_detached for the real OS-flag logic + breakaway
78
+ # retry). It DOES OR-in CREATE_NO_WINDOW so a broken install
79
+ # degrades to "child dies with the parent" rather than "console window
80
+ # flashes on every stop/sessionEnd hook".
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
+ _RESTORE_MAX_BYTES = 16_384 # restore-context files above this are ignored
107
+ _ACTIVE_WORKSPACE_SECS = 600 # skip restore when a sibling tally is live
108
+ _STOP_ROLLUP_SECS = 120 # R12: at most one stop rollup per machine per 120s
109
+ _STALE_LOCK_SECS = 7 * 24 * 3600 # sessionStart lock sweep threshold
110
+ _NUDGE_TOOL_CALLS = (30, 80) # context-growth nudge thresholds (turn proxy)
111
+
112
+ # Snapshot at import: the installed payload is static for the process lifetime.
113
+ _COMPRESS_PATH = _SCRIPT_DIR / "bash_compress.py"
114
+ _COMPRESS_AVAILABLE = _COMPRESS_PATH.exists()
115
+
116
+ _SESSION_ID_RE = re.compile(r"[^A-Za-z0-9_-]")
117
+
118
+
119
+ def _sanitize_session_id(sid):
120
+ """Strip everything but [A-Za-z0-9_-] so a payload id can never traverse.
121
+
122
+ Mirrors measure.sanitize_session_id / copilot_hook_bridge: a conversation_id
123
+ like "../../../etc/passwd" would otherwise let _atomic_write_json / the lock
124
+ path escape the data dir.
125
+ """
126
+ if not sid:
127
+ return "unknown"
128
+ cleaned = _SESSION_ID_RE.sub("", sid)[:64]
129
+ return cleaned if len(cleaned) >= 6 else "unknown"
130
+
131
+
132
+ def _read_stdin_payload():
133
+ """Read and decode the Cursor hook payload from stdin. None on any failure."""
134
+ try:
135
+ raw = sys.stdin.read(_MAX_STDIN_BYTES + 1)
136
+ except (OSError, UnicodeDecodeError):
137
+ return None
138
+ if not raw or len(raw) > _MAX_STDIN_BYTES:
139
+ return None
140
+ try:
141
+ payload = json.loads(raw)
142
+ except (json.JSONDecodeError, ValueError):
143
+ return None
144
+ if not isinstance(payload, dict):
145
+ return None
146
+ return payload
147
+
148
+
149
+ def _parse_tool_input(raw):
150
+ """tool_input as a dict, or as a JSON-encoded string -> dict; {} otherwise."""
151
+ if isinstance(raw, dict):
152
+ return raw
153
+ if isinstance(raw, str) and raw:
154
+ try:
155
+ parsed = json.loads(raw)
156
+ if isinstance(parsed, dict):
157
+ return parsed
158
+ except (json.JSONDecodeError, ValueError):
159
+ pass
160
+ return {}
161
+
162
+
163
+ def decode_payload(payload):
164
+ """Normalize a Cursor hook payload into a flat, safe dict.
165
+
166
+ ``conversation_id`` wins over ``session_id`` (sessionStart carries only
167
+ session_id; the tool events carry conversation_id). ``workspace_roots`` is
168
+ the list Cursor exports; ``cwd`` is capped at 1024 chars because it is
169
+ rewritten into the tally on every tool call and into restore-context.
170
+ Missing fields default to empty values so callers never KeyError.
171
+ """
172
+ out = {
173
+ "tool_name": "",
174
+ "tool_args": {},
175
+ "conversation_id": "",
176
+ "hook_event_name": "",
177
+ "cwd": "",
178
+ "cursor_version": "",
179
+ "workspace_roots": [],
180
+ "transcript_path": None,
181
+ "model": None,
182
+ "timestamp": None,
183
+ # preCompact numbers (0/0.0 when absent or the payload is not a dict)
184
+ "context_tokens": 0,
185
+ "context_window_size": 0,
186
+ "context_usage_percent": 0.0,
187
+ "trigger": "",
188
+ }
189
+ if not isinstance(payload, dict):
190
+ return out
191
+
192
+ tool_name = payload.get("tool_name", payload.get("toolName", ""))
193
+ if isinstance(tool_name, str):
194
+ out["tool_name"] = tool_name.strip()
195
+ out["tool_args"] = _parse_tool_input(
196
+ payload.get("tool_input", payload.get("toolInput", {}))
197
+ )
198
+
199
+ sid = payload.get("conversation_id", payload.get("session_id", ""))
200
+ if isinstance(sid, str):
201
+ out["conversation_id"] = _sanitize_session_id(sid)
202
+
203
+ event = payload.get("hook_event_name", "")
204
+ if isinstance(event, str):
205
+ out["hook_event_name"] = event.strip()
206
+
207
+ cwd = payload.get("cwd", "")
208
+ if isinstance(cwd, str):
209
+ out["cwd"] = cwd[:1024]
210
+
211
+ version = payload.get("cursor_version", "")
212
+ if isinstance(version, str):
213
+ out["cursor_version"] = version[:64]
214
+
215
+ roots = payload.get("workspace_roots")
216
+ if isinstance(roots, list):
217
+ out["workspace_roots"] = [
218
+ str(r)[:1024] for r in roots if isinstance(r, str)
219
+ ][:8]
220
+
221
+ tp = payload.get("transcript_path")
222
+ if isinstance(tp, str):
223
+ out["transcript_path"] = tp[:1024]
224
+
225
+ model = payload.get("model")
226
+ if isinstance(model, str):
227
+ out["model"] = model[:128]
228
+
229
+ out["timestamp"] = payload.get("timestamp")
230
+
231
+ for key in ("context_tokens", "context_window_size"):
232
+ try:
233
+ out[key] = int(payload.get(key) or 0)
234
+ except (TypeError, ValueError):
235
+ out[key] = 0
236
+ try:
237
+ out["context_usage_percent"] = float(payload.get("context_usage_percent") or 0.0)
238
+ except (TypeError, ValueError):
239
+ out["context_usage_percent"] = 0.0
240
+ trigger = payload.get("trigger")
241
+ if isinstance(trigger, str):
242
+ out["trigger"] = trigger
243
+ return out
244
+
245
+
246
+ # ---------------------------------------------------------------------------
247
+ # Data dir + atomic write
248
+ # ---------------------------------------------------------------------------
249
+
250
+
251
+ def _to_dir():
252
+ """Token Optimizer's data dir under the Cursor home. None if unavailable."""
253
+ if cursor_home is None:
254
+ return None
255
+ try:
256
+ d = cursor_home() / "token-optimizer"
257
+ d.mkdir(parents=True, exist_ok=True)
258
+ return d
259
+ except OSError:
260
+ return None
261
+
262
+
263
+ def _sessions_dir():
264
+ """<cursor_home>/token-optimizer/sessions/ — the durable tally store."""
265
+ to_dir = _to_dir()
266
+ if to_dir is None:
267
+ return None
268
+ try:
269
+ d = to_dir / "sessions"
270
+ d.mkdir(parents=True, exist_ok=True)
271
+ return d
272
+ except OSError:
273
+ return None
274
+
275
+
276
+ def _atomic_write_json(path, obj):
277
+ """Atomic JSON write via codex_io; concurrent writers never corrupt."""
278
+ if _atomic_write_json_impl is None:
279
+ return False
280
+ try:
281
+ _atomic_write_json_impl(path, obj)
282
+ return True
283
+ except OSError:
284
+ return False
285
+
286
+
287
+ def _record_observed(event, **extra):
288
+ """Append one observed-events line (KTD7/R13). Single-line JSONL append.
289
+
290
+ Each event writes one line; the doctor tolerates a torn final line and sums
291
+ the rest. cursor_version comes from the hook env first (Cursor exports it),
292
+ then the payload. Never raises — the ledger is observational, not gating.
293
+ """
294
+ to_dir = _to_dir()
295
+ if to_dir is None:
296
+ return
297
+ entry = {
298
+ "event": event,
299
+ "cursor_version": str(os.environ.get("CURSOR_VERSION") or "").strip()[:64],
300
+ "ts": time.time(),
301
+ }
302
+ entry.update({k: v for k, v in extra.items() if v is not None})
303
+ try:
304
+ with (to_dir / "observed-events.jsonl").open("a", encoding="utf-8") as fh:
305
+ fh.write(json.dumps(entry, default=str) + "\n")
306
+ except OSError:
307
+ # Log once per process: on a persistently unwritable data dir this fires
308
+ # per hook event, and a full traceback per tool call is log-spam.
309
+ global _observed_warned
310
+ if not _observed_warned:
311
+ _observed_warned = True
312
+ logger.warning("[cursor_hook_bridge] observed-events append failed; "
313
+ "further append failures are silent", exc_info=True)
314
+
315
+
316
+ # ---------------------------------------------------------------------------
317
+ # Tally read-modify-write (durable session record)
318
+ # ---------------------------------------------------------------------------
319
+
320
+
321
+ def _tally_path(fields):
322
+ sdir = _sessions_dir()
323
+ if sdir is None:
324
+ return None
325
+ sid = fields.get("conversation_id") or "unknown"
326
+ return sdir / f"{sid}.json"
327
+
328
+
329
+ def _load_tally(path):
330
+ if path is None or not path.exists():
331
+ return None
332
+ try:
333
+ data = json.loads(path.read_text(encoding="utf-8"))
334
+ return data if isinstance(data, dict) else None
335
+ except (OSError, json.JSONDecodeError, ValueError):
336
+ return None
337
+
338
+
339
+ @contextmanager
340
+ def _session_lock(to_dir, sid):
341
+ """Bounded portable lease around a tally read-modify-write.
342
+
343
+ Fail-open on contention: a contender skips after 75ms rather than blocking
344
+ a Cursor hot path. The tally is a soft counter, so a skipped update is
345
+ tolerable. A missing ``hook_runtime`` (broken install) proceeds unlocked.
346
+ """
347
+ if to_dir is None or sid in (None, "", "unknown"):
348
+ yield False
349
+ return
350
+ lock_dir = to_dir / ".locks"
351
+ try:
352
+ lock_dir.mkdir(parents=True, exist_ok=True)
353
+ except OSError:
354
+ yield True # fail open: tally update proceeds, just unlocked
355
+ return
356
+ if lease_lock is None:
357
+ yield True
358
+ return
359
+ lock_path = lock_dir / f"{sid}.lock"
360
+ with lease_lock(lock_path, acquire_timeout=0.075) as acquired:
361
+ yield acquired
362
+
363
+
364
+ def _update_tally(fields, *, terminal=False, end_reason=None,
365
+ increment_turns=False, count_tool=False, compaction=None,
366
+ bump_nudge=False):
367
+ """Read-modify-write the session tally; returns ``(tally, nudge_emitted)``.
368
+
369
+ Non-terminal activity reopens an idle/sessionEnd-finalised tally (final set
370
+ back to False) so a long-lived IDE composer resumed after lunch is never
371
+ frozen at the old ``idle`` verdict. ``terminal=True`` is sessionEnd only.
372
+ """
373
+ to_dir = _to_dir()
374
+ path = _tally_path(fields) if to_dir is not None else None
375
+ if path is None:
376
+ return None, False
377
+ sid = fields.get("conversation_id") or "unknown"
378
+ with _session_lock(to_dir, sid) as acquired:
379
+ if not acquired:
380
+ return None, False
381
+ tally = _load_tally(path)
382
+ now = time.time()
383
+ if tally is None:
384
+ tally = {"conversation_id": sid, "first_ts": now}
385
+
386
+ if terminal:
387
+ tally["final"] = True
388
+ tally["end_reason"] = end_reason or "sessionEnd"
389
+ else:
390
+ if tally.get("final") or tally.get("end_reason") in ("idle", "sessionEnd"):
391
+ tally["final"] = False
392
+ tally["end_reason"] = ""
393
+
394
+ tally["updated_at"] = now
395
+ tally.setdefault("turns", 0)
396
+ tally.setdefault("tool_calls", 0)
397
+ tally.setdefault("models", {})
398
+ tally.setdefault("tool_names", {})
399
+ tally.setdefault("compactions", [])
400
+
401
+ if fields.get("cwd"):
402
+ tally["cwd"] = fields["cwd"]
403
+ if fields.get("workspace_roots"):
404
+ tally["workspace_roots"] = fields["workspace_roots"]
405
+ if fields.get("transcript_path") is not None:
406
+ tally["transcript_path"] = fields["transcript_path"]
407
+ if fields.get("cursor_version"):
408
+ tally["cursor_version"] = fields["cursor_version"]
409
+
410
+ model = fields.get("model")
411
+ if isinstance(model, str) and model:
412
+ models = tally.setdefault("models", {})
413
+ models[model] = int(models.get(model, 0) or 0) + 1
414
+
415
+ if count_tool:
416
+ tally["tool_calls"] = int(tally.get("tool_calls", 0) or 0) + 1
417
+ name = fields.get("tool_name") or "tool"
418
+ names = tally.setdefault("tool_names", {})
419
+ names[name] = int(names.get(name, 0) or 0) + 1
420
+
421
+ if increment_turns:
422
+ tally["turns"] = int(tally.get("turns", 0) or 0) + 1
423
+
424
+ if compaction is not None:
425
+ comps = tally.setdefault("compactions", [])
426
+ comps.append(compaction)
427
+ tally["compactions"] = comps[-200:]
428
+
429
+ # Context-growth nudge (R10), folded into THIS locked RMW: computing it
430
+ # in the caller needed a second lock (and a gap a concurrent stop/
431
+ # preCompact could exploit to clobber either the tool_calls increment
432
+ # or the nudge_level). preCompact gives real numbers; when it never
433
+ # fired the tool-call count is the honest available proxy.
434
+ nudge_emitted = False
435
+ if bump_nudge:
436
+ new_level = _nudge_level(int(tally.get("tool_calls", 0) or 0))
437
+ if new_level > int(tally.get("nudge_level", 0) or 0):
438
+ tally["nudge_level"] = new_level
439
+ nudge_emitted = True
440
+
441
+ # The emit decision travels as the tuple's second element, never as a
442
+ # key in the tally: no caller can accidentally persist it.
443
+ _atomic_write_json(path, tally)
444
+ return tally, nudge_emitted
445
+
446
+
447
+ # ---------------------------------------------------------------------------
448
+ # Restore context (per workspace)
449
+ # ---------------------------------------------------------------------------
450
+
451
+
452
+ def _workspace_root(fields):
453
+ roots = fields.get("workspace_roots") or []
454
+ if roots and isinstance(roots[0], str) and roots[0]:
455
+ return roots[0]
456
+ return fields.get("cwd") or None
457
+
458
+
459
+ def _restore_for_workspace(fields):
460
+ """Return the restore-context for THIS workspace, or None.
461
+
462
+ Cursor IDE runs many concurrent chats across repos, so a single global
463
+ restore file would seed every new chat with whichever conversation rolled
464
+ up last. Files are keyed by ``sha1(workspace_root)`` and injected only for
465
+ the matching root. Injection is skipped while a non-final sibling tally in
466
+ that workspace has activity in the last 10 minutes.
467
+ """
468
+ root = _workspace_root(fields)
469
+ to_dir = _to_dir()
470
+ if to_dir is None or not root:
471
+ return None
472
+
473
+ sdir = _sessions_dir()
474
+ now = time.time()
475
+ own_id = fields.get("conversation_id") or ""
476
+ if sdir is not None:
477
+ try:
478
+ for p in sdir.glob("*.json"):
479
+ t = _load_tally(p)
480
+ if not t or t.get("final"):
481
+ continue
482
+ # Exclude the session being started: its own freshly-written
483
+ # tally is active by definition and must not suppress restore.
484
+ if own_id and str(t.get("conversation_id") or "") == own_id:
485
+ continue
486
+ troot = None
487
+ wroots = t.get("workspace_roots")
488
+ if isinstance(wroots, list) and wroots and isinstance(wroots[0], str):
489
+ troot = wroots[0]
490
+ else:
491
+ troot = t.get("cwd")
492
+ if str(troot) == str(root):
493
+ try:
494
+ if now - float(t.get("updated_at") or 0) < _ACTIVE_WORKSPACE_SECS:
495
+ return None
496
+ except (TypeError, ValueError):
497
+ pass
498
+ except OSError:
499
+ pass
500
+
501
+ digest = hashlib.sha1(root.encode("utf-8", "replace")).hexdigest()
502
+ path = to_dir / "restore-context" / f"{digest}.md"
503
+ try:
504
+ if path.exists() and path.stat().st_size <= _RESTORE_MAX_BYTES:
505
+ text = path.read_text(encoding="utf-8").strip()
506
+ return text or None
507
+ except OSError:
508
+ return None
509
+ return None
510
+
511
+
512
+ # ---------------------------------------------------------------------------
513
+ # Compression + nudge helpers
514
+ # ---------------------------------------------------------------------------
515
+
516
+
517
+ def _compression_enabled():
518
+ return (
519
+ _bash_hook is not None
520
+ and _COMPRESS_AVAILABLE
521
+ and os.environ.get("TOKEN_OPTIMIZER_BASH_COMPRESS", "").strip() != "0"
522
+ )
523
+
524
+
525
+ def _nudge_level(tool_calls):
526
+ level = 0
527
+ for threshold in _NUDGE_TOOL_CALLS:
528
+ if tool_calls >= threshold:
529
+ level += 1
530
+ return level
531
+
532
+
533
+ _NUDGE_TEXT = (
534
+ "[Token Optimizer] Context is growing large for this session. Prefer "
535
+ "targeted reads over full files, avoid re-reading unchanged files, and "
536
+ "summarize before continuing long explorations."
537
+ )
538
+
539
+
540
+ # ---------------------------------------------------------------------------
541
+ # Spawns (fire-and-forget; detach + CREATE_NO_WINDOW)
542
+ # ---------------------------------------------------------------------------
543
+
544
+
545
+ def _measure_env(interactive=False):
546
+ env = dict(os.environ)
547
+ env["TOKEN_OPTIMIZER_RUNTIME"] = "cursor"
548
+ env["PYTHONUTF8"] = "1"
549
+ env["PYTHONIOENCODING"] = "utf-8"
550
+ if interactive:
551
+ env["TOKEN_OPTIMIZER_INTERACTIVE"] = "1"
552
+ return env
553
+
554
+
555
+ # The installer does NOT copy measure.py into the plugin dir (version-drift
556
+ # risk); it writes a one-line "measure-path" locator next to this bridge naming
557
+ # the canonical measure.py in the checkout. Resolution order: a sibling
558
+ # measure.py (dev/test checkout), then the locator. Mirrors
559
+ # hermes_hook_bridge._locate_measure_py.
560
+ _MEASURE_LOCATOR = _SCRIPT_DIR / "measure-path"
561
+
562
+
563
+ def _locate_measure_py():
564
+ """Return the path to measure.py, or None if not found (rollups paused).
565
+
566
+ The locator is installer-written, but the plugin dir is user-writable: a
567
+ crafted locator pointing anywhere would have this bridge spawn its target
568
+ as code. Only a regular, non-symlinked file named measure.py is accepted.
569
+ """
570
+ sibling = _SCRIPT_DIR / "measure.py"
571
+ if sibling.is_file() and not sibling.is_symlink():
572
+ return sibling
573
+ try:
574
+ if _MEASURE_LOCATOR.is_file() and not _MEASURE_LOCATOR.is_symlink():
575
+ located = Path(_MEASURE_LOCATOR.read_text(encoding="utf-8").strip())
576
+ if (located.is_file() and not located.is_symlink()
577
+ and located.name == "measure.py"):
578
+ return located
579
+ except (OSError, ValueError):
580
+ pass
581
+ return None
582
+
583
+
584
+ def _spawn_rollup():
585
+ # cursor-doctor --probe replays the installed command to prove it fires;
586
+ # it must not trigger a real detached rollup/dashboard as a side effect.
587
+ if os.environ.get("TOKEN_OPTIMIZER_PROBE") == "1":
588
+ return
589
+ measure = _locate_measure_py()
590
+ if measure is None:
591
+ return
592
+ try:
593
+ spawn_detached(
594
+ [sys.executable, str(measure), "cursor-rollup", "--quiet"],
595
+ env=_measure_env(),
596
+ stdout=subprocess.DEVNULL,
597
+ stderr=subprocess.DEVNULL,
598
+ )
599
+ except (OSError, subprocess.SubprocessError):
600
+ logger.warning("[cursor_hook_bridge] detached rollup spawn failed", exc_info=True)
601
+
602
+
603
+ def _spawn_dashboard():
604
+ # Same probe guard as _spawn_rollup(): replay must not spawn detached work.
605
+ if os.environ.get("TOKEN_OPTIMIZER_PROBE") == "1":
606
+ return
607
+ measure = _locate_measure_py()
608
+ if measure is None:
609
+ return
610
+ try:
611
+ spawn_detached(
612
+ [sys.executable, str(measure), "dashboard", "--quiet"],
613
+ env=_measure_env(interactive=True),
614
+ stdout=subprocess.DEVNULL,
615
+ stderr=subprocess.DEVNULL,
616
+ )
617
+ except (OSError, subprocess.SubprocessError):
618
+ logger.warning("[cursor_hook_bridge] detached dashboard spawn failed", exc_info=True)
619
+
620
+
621
+ def _stop_rollup_due():
622
+ """True once per 120s per machine (R12). Best-effort: reads then writes.
623
+
624
+ The read-check-write runs under a lease lock: two concurrent stop hooks
625
+ (multi-window Cursor) would otherwise both read a stale ``last`` and both
626
+ spawn rollup+dashboard. On lock contention we skip the spawn (the winner is
627
+ rolling up); without hook_runtime we degrade to the unlocked path.
628
+ """
629
+ to_dir = _to_dir()
630
+ if to_dir is None:
631
+ return False
632
+ state = to_dir / ".stop-rollup-last.json"
633
+ now = time.time()
634
+ if lease_lock is not None:
635
+ lock_dir = to_dir / ".locks"
636
+ try:
637
+ lock_dir.mkdir(parents=True, exist_ok=True)
638
+ except OSError:
639
+ lock_dir = None
640
+ if lock_dir is not None:
641
+ with lease_lock(lock_dir / ".stop-rollup.lock",
642
+ acquire_timeout=0.5, lease_seconds=30.0) as acquired:
643
+ if not acquired:
644
+ return False
645
+ return _stop_rollup_due_locked(state, now)
646
+ return _stop_rollup_due_locked(state, now)
647
+
648
+
649
+ def _stop_rollup_due_locked(state, now):
650
+ last = None
651
+ try:
652
+ if state.exists():
653
+ data = json.loads(state.read_text(encoding="utf-8"))
654
+ if isinstance(data, dict):
655
+ last = float(data.get("last", 0) or 0)
656
+ except (OSError, json.JSONDecodeError, ValueError, TypeError):
657
+ last = None
658
+ if last is not None and now - last < _STOP_ROLLUP_SECS:
659
+ return False
660
+ # Fail closed: if the throttle-state write fails (disk full, read-only data
661
+ # dir), do NOT spawn — otherwise every stop would spawn a rollup+dashboard
662
+ # storm precisely under the degraded conditions the throttle is meant to
663
+ # contain. _atomic_write_json returns True only on a successful write.
664
+ return _atomic_write_json(state, {"last": now})
665
+
666
+
667
+ def _sweep_stale_locks():
668
+ """Remove stale lock/candidate artifacts (7d) on sessionStart. Never fatal."""
669
+ to_dir = _to_dir()
670
+ if to_dir is None:
671
+ return
672
+ lock_dir = to_dir / ".locks"
673
+ if not lock_dir.is_dir():
674
+ return
675
+ now = time.time()
676
+ try:
677
+ for pattern in ("*.lock", ".*.lock.candidate-*"):
678
+ for p in lock_dir.glob(pattern):
679
+ try:
680
+ if now - p.stat().st_mtime > _STALE_LOCK_SECS:
681
+ p.unlink()
682
+ except OSError:
683
+ continue
684
+ except OSError:
685
+ pass
686
+
687
+
688
+ # ---------------------------------------------------------------------------
689
+ # Event handlers (all fail-open: never raise into Cursor)
690
+ # ---------------------------------------------------------------------------
691
+
692
+
693
+ def _emit(obj):
694
+ print(json.dumps(obj))
695
+
696
+
697
+ def handle_session_start(payload):
698
+ """Sweep stale locks, re/init the tally, inject per-workspace continuity."""
699
+ fields = decode_payload(payload)
700
+ _record_observed("sessionStart",
701
+ conversation_id=fields["conversation_id"] or None)
702
+ _update_tally(fields)
703
+ _sweep_stale_locks()
704
+
705
+ restore = _restore_for_workspace(fields)
706
+ if restore:
707
+ _emit({"additional_context": restore})
708
+
709
+
710
+ def handle_pre_tool_use(payload):
711
+ """Shell bash-compression via updated_input, gated and fail-closed."""
712
+ fields = decode_payload(payload)
713
+ rewrite = None
714
+ if fields["tool_name"] == "Shell" and _compression_enabled():
715
+ command = fields["tool_args"].get("command")
716
+ if isinstance(command, str) and command:
717
+ # The rewrite is emitted with permission "allow", so it is limited
718
+ # to commands that cannot write, delete or run other programs.
719
+ if _bash_hook._is_auto_approvable(command):
720
+ try:
721
+ original_tokens = shlex.split(command)
722
+ except ValueError:
723
+ original_tokens = None
724
+ if original_tokens:
725
+ rewritten = (
726
+ shlex.quote(sys.executable)
727
+ + " " + shlex.quote(str(_COMPRESS_PATH))
728
+ + " " + " ".join(shlex.quote(t) for t in original_tokens)
729
+ )
730
+ # Echo every original field and replace only `command` so
731
+ # working_directory and any future fields survive the
732
+ # whole-tool_input replacement contract.
733
+ updated = dict(fields["tool_args"])
734
+ updated["command"] = rewritten
735
+ _emit({"permission": "allow", "updated_input": updated})
736
+ rewrite = "attempted"
737
+ _record_observed("preToolUse",
738
+ tool_name=fields["tool_name"] or None,
739
+ rewrite=rewrite)
740
+
741
+
742
+ def handle_post_tool_use(payload):
743
+ """Update the tally and, for Shell, record whether the rewrite was honoured.
744
+
745
+ Cursor's postToolUse tool_input carries the command as actually executed:
746
+ ``command`` containing ``bash_compress.py`` proves the rewrite was honoured;
747
+ a whitelisted command that arrived bare proves it was ignored.
748
+ """
749
+ fields = decode_payload(payload)
750
+ rewrite = None
751
+ if fields["tool_name"] == "Shell" and _compression_enabled():
752
+ command = fields["tool_args"].get("command")
753
+ if isinstance(command, str) and command:
754
+ if not _bash_hook._has_dangerous_chars(command) and _bash_hook._is_whitelisted(command):
755
+ rewrite = "honoured" if "bash_compress.py" in command else "ignored"
756
+ _record_observed("postToolUse",
757
+ tool_name=fields["tool_name"] or None,
758
+ rewrite=rewrite)
759
+
760
+ tally, nudge_emitted = _update_tally(fields, count_tool=True, bump_nudge=True)
761
+ if tally is None:
762
+ return
763
+ if nudge_emitted:
764
+ _emit({"additional_context": _NUDGE_TEXT})
765
+
766
+
767
+ def handle_pre_compact(payload):
768
+ """Record Cursor's real context numbers and compaction trigger."""
769
+ fields = decode_payload(payload)
770
+ _record_observed("preCompact", conversation_id=fields["conversation_id"] or None)
771
+ _update_tally(
772
+ fields,
773
+ compaction={
774
+ "trigger": fields["trigger"][:64],
775
+ "context_tokens": fields["context_tokens"],
776
+ "context_window_size": fields["context_window_size"],
777
+ "context_usage_percent": fields["context_usage_percent"],
778
+ "ts": time.time(),
779
+ },
780
+ )
781
+
782
+
783
+ def handle_stop(payload):
784
+ """Per-turn tally + throttled detached rollup and dashboard refresh."""
785
+ fields = decode_payload(payload)
786
+ _record_observed("stop", conversation_id=fields["conversation_id"] or None)
787
+ _update_tally(fields, increment_turns=True)
788
+ if _stop_rollup_due():
789
+ _spawn_rollup()
790
+ _spawn_dashboard()
791
+
792
+
793
+ def handle_session_end(payload):
794
+ """Mark the tally final and spawn an unthrottled rollup + dashboard."""
795
+ fields = decode_payload(payload)
796
+ reason = payload.get("reason") if isinstance(payload, dict) else None
797
+ _record_observed("sessionEnd", conversation_id=fields["conversation_id"] or None)
798
+ _update_tally(fields, terminal=True,
799
+ end_reason=str(reason)[:64] if reason else "sessionEnd")
800
+ _spawn_rollup()
801
+ _spawn_dashboard()
802
+
803
+
804
+ _HANDLERS = {
805
+ "sessionStart": handle_session_start,
806
+ "preToolUse": handle_pre_tool_use,
807
+ "postToolUse": handle_post_tool_use,
808
+ "preCompact": handle_pre_compact,
809
+ "stop": handle_stop,
810
+ "sessionEnd": handle_session_end,
811
+ }
812
+
813
+
814
+ def main(argv=None):
815
+ try:
816
+ from utf8_io import enforce_utf8_io
817
+ enforce_utf8_io()
818
+ except Exception:
819
+ pass
820
+ args = list(sys.argv[1:] if argv is None else argv)
821
+ if not args or args[0] not in _HANDLERS:
822
+ return 0
823
+ os.environ.setdefault("TOKEN_OPTIMIZER_RUNTIME", "cursor")
824
+ payload = _read_stdin_payload()
825
+ if payload is None:
826
+ payload = {}
827
+ try:
828
+ _HANDLERS[args[0]](payload)
829
+ except Exception:
830
+ # A hook must never break the user's Cursor session: still exit 0, but
831
+ # never silently. The log itself is guarded — a closed/full stderr
832
+ # (Cursor may not drain hook pipes) must not turn fail-open into
833
+ # fail-hung inside the handler that guarantees exit 0.
834
+ try:
835
+ logger.exception("[cursor_hook_bridge] handler %s failed; failing open", args[0])
836
+ except Exception:
837
+ pass
838
+ return 0
839
+ return 0
840
+
841
+
842
+ if __name__ == "__main__":
843
+ sys.exit(main())