@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.
- package/.claude-plugin/marketplace.json +76 -0
- package/.claude-plugin/plugin.json +21 -0
- package/LICENSE +130 -0
- package/LICENSE-SMALL-BUSINESS.md +62 -0
- package/PRIVACY.md +200 -0
- package/README.md +13 -2
- package/hooks/codex-hooks.json +4 -0
- package/hooks/hooks.json +182 -0
- package/hooks/module_runner.py +149 -0
- package/hooks/posttooluse_runner.py +1110 -0
- package/hooks/python-launcher.sh +816 -0
- package/hooks/run.py +776 -0
- package/hooks/sessionstart_runner.py +629 -0
- package/hooks/stop_runner.py +408 -0
- package/hooks/userpromptsubmit_runner.py +722 -0
- package/hooks/windows-launcher.py +163 -0
- package/install-cloud.sh +23 -0
- package/package.json +29 -4
- package/skills/fleet-auditor/SKILL.md +150 -0
- package/skills/fleet-auditor/references/fleet-systems.md +167 -0
- package/skills/fleet-auditor/references/report-template.md +50 -0
- package/skills/fleet-auditor/references/waste-patterns.md +126 -0
- package/skills/fleet-auditor/scripts/fleet.py +3612 -0
- package/skills/fleet-auditor/scripts/shared.py +277 -0
- package/skills/resume-checkpoint/SKILL.md +52 -0
- package/skills/resume-checkpoint/scripts/pull_checkpoint.py +188 -0
- package/skills/token-coach/SKILL.md +129 -0
- package/skills/token-coach/assets/coach-dashboard-tab.html +45 -0
- package/skills/token-coach/examples/coaching-session-agentic.md +62 -0
- package/skills/token-coach/examples/coaching-session-heavy-setup.md +46 -0
- package/skills/token-coach/examples/coaching-session-new-project.md +38 -0
- package/skills/token-coach/references/agentic-systems.md +147 -0
- package/skills/token-coach/references/coach-patterns.md +120 -0
- package/skills/token-coach/references/coaching-scripts.md +146 -0
- package/skills/token-coach/references/deterministic-stages.md +102 -0
- package/skills/token-coach/references/keepwarm-consent.md +48 -0
- package/skills/token-coach/references/quick-reference.md +155 -0
- package/skills/token-dashboard/SKILL.md +72 -0
- package/skills/token-optimizer/SKILL.md +150 -0
- package/skills/token-optimizer/assets/dashboard.html +7251 -0
- package/skills/token-optimizer/examples/claude-md-optimized.md +40 -0
- package/skills/token-optimizer/examples/hooks-starter.json +179 -0
- package/skills/token-optimizer/examples/permissions-deny-template.json +24 -0
- package/skills/token-optimizer/pricing/prices.json +695 -0
- package/skills/token-optimizer/references/agent-prompts.md +687 -0
- package/skills/token-optimizer/references/cli-reference.md +92 -0
- package/skills/token-optimizer/references/codex-workflow.md +188 -0
- package/skills/token-optimizer/references/cursor-workflow.md +74 -0
- package/skills/token-optimizer/references/error-recovery.md +37 -0
- package/skills/token-optimizer/references/implementation-playbook.md +416 -0
- package/skills/token-optimizer/references/keepwarm-consent.md +48 -0
- package/skills/token-optimizer/references/opencode-workflow.md +72 -0
- package/skills/token-optimizer/references/optimization-checklist.md +714 -0
- package/skills/token-optimizer/references/phase0-setup.md +142 -0
- package/skills/token-optimizer/references/presentation-workflow.md +72 -0
- package/skills/token-optimizer/references/session-continuity.md +19 -0
- package/skills/token-optimizer/references/token-flow-architecture.md +629 -0
- package/skills/token-optimizer/scripts/activity_tracker.py +143 -0
- package/skills/token-optimizer/scripts/antigravity_doctor.py +548 -0
- package/skills/token-optimizer/scripts/antigravity_hook_bridge.py +511 -0
- package/skills/token-optimizer/scripts/antigravity_install.py +376 -0
- package/skills/token-optimizer/scripts/antigravity_proto.py +413 -0
- package/skills/token-optimizer/scripts/antigravity_session.py +346 -0
- package/skills/token-optimizer/scripts/antigravity_state.py +486 -0
- package/skills/token-optimizer/scripts/archive_result.py +1725 -0
- package/skills/token-optimizer/scripts/bash_compress.py +2490 -0
- package/skills/token-optimizer/scripts/bash_compress_hook.py +766 -0
- package/skills/token-optimizer/scripts/bash_hook.py +61 -0
- package/skills/token-optimizer/scripts/bash_whitelist.py +243 -0
- package/skills/token-optimizer/scripts/benchmark.py +1765 -0
- package/skills/token-optimizer/scripts/build_output_compress.py +776 -0
- package/skills/token-optimizer/scripts/cloud_kit.py +991 -0
- package/skills/token-optimizer/scripts/codex_command_compress.py +434 -0
- package/skills/token-optimizer/scripts/codex_compact_prompt.py +273 -0
- package/skills/token-optimizer/scripts/codex_doctor.py +454 -0
- package/skills/token-optimizer/scripts/codex_hook_bridge.py +311 -0
- package/skills/token-optimizer/scripts/codex_install.py +810 -0
- package/skills/token-optimizer/scripts/codex_io.py +119 -0
- package/skills/token-optimizer/scripts/codex_log_index.py +219 -0
- package/skills/token-optimizer/scripts/codex_models.py +34 -0
- package/skills/token-optimizer/scripts/codex_session.py +1186 -0
- package/skills/token-optimizer/scripts/codex_state.py +707 -0
- package/skills/token-optimizer/scripts/codex_statusline.py +303 -0
- package/skills/token-optimizer/scripts/command_filters.py +386 -0
- package/skills/token-optimizer/scripts/compression_backfill.py +600 -0
- package/skills/token-optimizer/scripts/compression_log.py +230 -0
- package/skills/token-optimizer/scripts/context_intel.py +331 -0
- package/skills/token-optimizer/scripts/context_pressure.py +115 -0
- package/skills/token-optimizer/scripts/copilot_doctor.py +406 -0
- package/skills/token-optimizer/scripts/copilot_hook_bridge.py +709 -0
- package/skills/token-optimizer/scripts/copilot_install.py +277 -0
- package/skills/token-optimizer/scripts/copilot_session.py +496 -0
- package/skills/token-optimizer/scripts/copilot_state.py +569 -0
- package/skills/token-optimizer/scripts/copilot_vscode.py +832 -0
- package/skills/token-optimizer/scripts/cowork_doctor.py +270 -0
- package/skills/token-optimizer/scripts/cowork_install.py +380 -0
- package/skills/token-optimizer/scripts/credential_patterns.py +1514 -0
- package/skills/token-optimizer/scripts/cursor_doctor.py +602 -0
- package/skills/token-optimizer/scripts/cursor_hook_bridge.py +843 -0
- package/skills/token-optimizer/scripts/cursor_install.py +423 -0
- package/skills/token-optimizer/scripts/cursor_session.py +303 -0
- package/skills/token-optimizer/scripts/cursor_state.py +348 -0
- package/skills/token-optimizer/scripts/delta_diff.py +110 -0
- package/skills/token-optimizer/scripts/detectors/__init__.py +2 -0
- package/skills/token-optimizer/scripts/detectors/bad_decomposition.py +78 -0
- package/skills/token-optimizer/scripts/detectors/cache_instability.py +504 -0
- package/skills/token-optimizer/scripts/detectors/looping.py +88 -0
- package/skills/token-optimizer/scripts/detectors/output_waste.py +143 -0
- package/skills/token-optimizer/scripts/detectors/overpowered.py +116 -0
- package/skills/token-optimizer/scripts/detectors/pdf_ingestion.py +52 -0
- package/skills/token-optimizer/scripts/detectors/registry.py +65 -0
- package/skills/token-optimizer/scripts/detectors/respond_to_bash.py +76 -0
- package/skills/token-optimizer/scripts/detectors/retry_churn.py +83 -0
- package/skills/token-optimizer/scripts/detectors/tool_cascade.py +62 -0
- package/skills/token-optimizer/scripts/detectors/wasteful_thinking.py +75 -0
- package/skills/token-optimizer/scripts/detectors/weak_model.py +55 -0
- package/skills/token-optimizer/scripts/detectors/websearch_routing.py +72 -0
- package/skills/token-optimizer/scripts/deterministic_candidates.py +1458 -0
- package/skills/token-optimizer/scripts/devin_compress.py +790 -0
- package/skills/token-optimizer/scripts/devin_doctor.py +403 -0
- package/skills/token-optimizer/scripts/devin_hooks.py +453 -0
- package/skills/token-optimizer/scripts/devin_install.py +1086 -0
- package/skills/token-optimizer/scripts/devin_source.py +119 -0
- package/skills/token-optimizer/scripts/devin_state.py +330 -0
- package/skills/token-optimizer/scripts/devin_verify.py +67 -0
- package/skills/token-optimizer/scripts/grok_doctor.py +560 -0
- package/skills/token-optimizer/scripts/grok_hook_bridge.py +699 -0
- package/skills/token-optimizer/scripts/grok_install.py +397 -0
- package/skills/token-optimizer/scripts/grok_session.py +317 -0
- package/skills/token-optimizer/scripts/grok_state.py +299 -0
- package/skills/token-optimizer/scripts/hermes_doctor.py +479 -0
- package/skills/token-optimizer/scripts/hermes_hook_bridge.py +285 -0
- package/skills/token-optimizer/scripts/hermes_install.py +668 -0
- package/skills/token-optimizer/scripts/hermes_session.py +691 -0
- package/skills/token-optimizer/scripts/hermes_state.py +448 -0
- package/skills/token-optimizer/scripts/hook_io.py +120 -0
- package/skills/token-optimizer/scripts/hook_runtime.py +713 -0
- package/skills/token-optimizer/scripts/injection.py +156 -0
- package/skills/token-optimizer/scripts/install_reconcile.py +952 -0
- package/skills/token-optimizer/scripts/measure.py +58739 -0
- package/skills/token-optimizer/scripts/outline.py +53 -0
- package/skills/token-optimizer/scripts/pipeline_analyzer.py +723 -0
- package/skills/token-optimizer/scripts/plugin_env.py +562 -0
- package/skills/token-optimizer/scripts/py_trust.py +80 -0
- package/skills/token-optimizer/scripts/quality_cache_gate.py +320 -0
- package/skills/token-optimizer/scripts/read_cache.py +2489 -0
- package/skills/token-optimizer/scripts/recovery_output.py +110 -0
- package/skills/token-optimizer/scripts/refetch_fingerprint.py +236 -0
- package/skills/token-optimizer/scripts/refetch_guard.py +244 -0
- package/skills/token-optimizer/scripts/routing_advisor.py +389 -0
- package/skills/token-optimizer/scripts/runtime_env.py +1893 -0
- package/skills/token-optimizer/scripts/session_store.py +979 -0
- package/skills/token-optimizer/scripts/spawn_utils.py +122 -0
- package/skills/token-optimizer/scripts/statusline.js +660 -0
- package/skills/token-optimizer/scripts/structure_map.py +2880 -0
- package/skills/token-optimizer/scripts/structure_map_ts.py +676 -0
- package/skills/token-optimizer/scripts/structure_replay.py +1556 -0
- package/skills/token-optimizer/scripts/thrash_guard.py +604 -0
- package/skills/token-optimizer/scripts/token_estimate.py +80 -0
- package/skills/token-optimizer/scripts/tool_search_diagnostic.py +61 -0
- package/skills/token-optimizer/scripts/utf8_io.py +219 -0
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer — Cursor installer.
|
|
3
|
+
|
|
4
|
+
Wires Token Optimizer into Cursor's shared user hooks file:
|
|
5
|
+
|
|
6
|
+
1. Copies the adapter modules into ``<cursor_home>/token-optimizer/plugin/``
|
|
7
|
+
so the hook bridge runs from a stable path that survives repo moves.
|
|
8
|
+
2. READ-MERGE-WRITES ``~/.cursor/hooks.json``: existing entries owned by other
|
|
9
|
+
tools are preserved verbatim; only entries whose ``command`` points at our
|
|
10
|
+
bridge path are replaced. Cursor has one shared hooks.json (no per-plugin
|
|
11
|
+
file like Copilot), so clobbering it would destroy other people's hooks.
|
|
12
|
+
3. Refuses on native Windows (``os.name == "nt"``): the persisted ``command``
|
|
13
|
+
string is POSIX-shell quoted and cmd.exe would not parse it. Windows work is
|
|
14
|
+
deferred rather than silently writing a no-op hook.
|
|
15
|
+
|
|
16
|
+
Idempotent: re-running refreshes the payload and replaces only OUR entries.
|
|
17
|
+
Uninstall removes only OUR entries and the payload dir; session data stays.
|
|
18
|
+
|
|
19
|
+
Usage:
|
|
20
|
+
python3 cursor_install.py install [--dry-run]
|
|
21
|
+
python3 cursor_install.py uninstall [--dry-run]
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import argparse
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import shlex
|
|
30
|
+
import shutil
|
|
31
|
+
import stat as _stat
|
|
32
|
+
import sys
|
|
33
|
+
from contextlib import contextmanager
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
_SCRIPT_DIR = Path(__file__).resolve().parent
|
|
37
|
+
sys.path.insert(0, str(_SCRIPT_DIR))
|
|
38
|
+
|
|
39
|
+
from py_trust import py_path_is_trusted, py_trust_reason # noqa: E402
|
|
40
|
+
from runtime_env import cursor_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
|
|
41
|
+
|
|
42
|
+
HOOK_TIMEOUT_SEC = 10
|
|
43
|
+
|
|
44
|
+
# Modules the bridge needs at runtime, copied next to it so the installed
|
|
45
|
+
# hook never depends on the repo checkout location.
|
|
46
|
+
_PAYLOAD_MODULES = (
|
|
47
|
+
"cursor_hook_bridge.py",
|
|
48
|
+
"cursor_state.py",
|
|
49
|
+
"cursor_session.py",
|
|
50
|
+
"bash_hook.py",
|
|
51
|
+
"bash_compress.py",
|
|
52
|
+
# Dependency-free whitelist gate shared by bash_hook + bash_compress.
|
|
53
|
+
"bash_whitelist.py",
|
|
54
|
+
"hook_io.py",
|
|
55
|
+
"plugin_env.py",
|
|
56
|
+
"runtime_env.py",
|
|
57
|
+
# codex_io supplies atomic_write_json — without it the bridge's tally and
|
|
58
|
+
# observed-events writes silently no-op (crash recovery would be dead).
|
|
59
|
+
"codex_io.py",
|
|
60
|
+
# hermes_session supplies compute_quality_score — without it cursor_session
|
|
61
|
+
# silently falls back to a single-signal quality estimate.
|
|
62
|
+
"hermes_session.py",
|
|
63
|
+
# spawn_utils supplies spawn_detached — without it the bridge's degraded
|
|
64
|
+
# fallback does NOT detach, so rollup/dashboard spawns die with the hook.
|
|
65
|
+
"spawn_utils.py",
|
|
66
|
+
# hook_runtime supplies lease_lock (tally RMW + stop throttle) and
|
|
67
|
+
# utf8_io is enforced at startup; both degrade silently when absent.
|
|
68
|
+
"hook_runtime.py",
|
|
69
|
+
"utf8_io.py",
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
# One-line locator written next to the bridge, naming the canonical measure.py
|
|
73
|
+
# in the checkout. The bridge's detached rollup/dashboard spawns resolve
|
|
74
|
+
# measure.py through this locator because measure.py itself is NOT copied into
|
|
75
|
+
# the plugin dir (version-drift risk — nothing refreshes a plugin-dir copy on
|
|
76
|
+
# update; the checkout's measure.py stays the single source). Mirrors
|
|
77
|
+
# hermes_install._MEASURE_LOCATOR_NAME.
|
|
78
|
+
_MEASURE_LOCATOR_NAME = "measure-path"
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _plugin_dir(root: Path) -> Path:
|
|
82
|
+
return root / "token-optimizer" / "plugin"
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _host_hooks_path(root: Path) -> Path:
|
|
86
|
+
return root / "hooks.json"
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _py_trust_reason(p: str) -> str | None:
|
|
90
|
+
"""None when trusted, else a short human-readable rejection reason."""
|
|
91
|
+
return py_trust_reason(p)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _py_path_is_trusted(p: str) -> bool:
|
|
95
|
+
"""Trusted iff the interpreter's bytes are admin-owned (euid or root) and
|
|
96
|
+
not group/other-writable, and its dir is not world-writable and not
|
|
97
|
+
group-writable by a third party. Pure stat, never runs the target. On
|
|
98
|
+
Windows, stat ownership is unreliable under Git-Bash, so require only that
|
|
99
|
+
the path is a real file."""
|
|
100
|
+
return py_path_is_trusted(p)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _resolve_safe_python() -> str:
|
|
104
|
+
"""An ABSOLUTE, trusted python for the persisted Cursor hook command.
|
|
105
|
+
|
|
106
|
+
Never emit a bare "python3": that string is resolved via $PATH every time the
|
|
107
|
+
hook fires, so a hijacked PATH entry runs attacker code. Resolution order:
|
|
108
|
+
1. TOKEN_OPTIMIZER_PYTHON, if it names a trusted file;
|
|
109
|
+
2. sys.executable (absolute path baked in ONCE) -- but only through the
|
|
110
|
+
same trust gate: a writable venv interpreter must never be persisted;
|
|
111
|
+
3. a $PATH search, accepting only a candidate that passes the gate.
|
|
112
|
+
Raises RuntimeError rather than persist an unsafe command.
|
|
113
|
+
"""
|
|
114
|
+
override = os.environ.get("TOKEN_OPTIMIZER_PYTHON", "").strip()
|
|
115
|
+
candidates = []
|
|
116
|
+
if override:
|
|
117
|
+
candidates.append(("TOKEN_OPTIMIZER_PYTHON", override))
|
|
118
|
+
if sys.executable:
|
|
119
|
+
candidates.append(("sys.executable", sys.executable))
|
|
120
|
+
for name in ("python3", "python"):
|
|
121
|
+
cand = shutil.which(name)
|
|
122
|
+
if cand:
|
|
123
|
+
candidates.append((name, cand))
|
|
124
|
+
for _label, cand in candidates:
|
|
125
|
+
if _py_path_is_trusted(cand):
|
|
126
|
+
# Persist the RESOLVED realpath, not abspath: the gate validated
|
|
127
|
+
# realpath(cand) (the symlink target + its parent dir), so persisting
|
|
128
|
+
# the original symlink path would leave a swap window between install
|
|
129
|
+
# and hook fire (an attacker with write access to the symlink's parent
|
|
130
|
+
# dir could redirect the symlink to a malicious interpreter).
|
|
131
|
+
return os.path.realpath(cand)
|
|
132
|
+
reasons = [f"{label}={cand}: {_py_trust_reason(cand)}"
|
|
133
|
+
for label, cand in candidates]
|
|
134
|
+
raise RuntimeError(
|
|
135
|
+
"no trusted python interpreter found for the Cursor hook; "
|
|
136
|
+
"set TOKEN_OPTIMIZER_PYTHON to an absolute python3 path and re-run install. "
|
|
137
|
+
"Candidates: " + "; ".join(reasons)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _hook_entries(bridge_path: Path) -> dict:
|
|
142
|
+
"""The hook entries TO appends to ~/.cursor/hooks.json.
|
|
143
|
+
|
|
144
|
+
Cursor's per-hook schema is ``{command, type, matcher?, timeout,
|
|
145
|
+
failClosed?, loop_limit?}`` (verified 2026-09-01). ``command`` is assumed to
|
|
146
|
+
run through a POSIX shell, so the two paths are shlex-quoted and the runtime
|
|
147
|
+
is pinned so the bridge never process-scans on the hot path.
|
|
148
|
+
"""
|
|
149
|
+
py_q = shlex.quote(_resolve_safe_python())
|
|
150
|
+
bridge_q = shlex.quote(str(bridge_path))
|
|
151
|
+
|
|
152
|
+
def entry(event: str, *, matcher: str | None = None) -> dict:
|
|
153
|
+
e = {
|
|
154
|
+
"command": f"TOKEN_OPTIMIZER_RUNTIME=cursor {py_q} {bridge_q} {event}",
|
|
155
|
+
"type": "command",
|
|
156
|
+
"timeout": HOOK_TIMEOUT_SEC,
|
|
157
|
+
}
|
|
158
|
+
if matcher is not None:
|
|
159
|
+
e["matcher"] = matcher
|
|
160
|
+
return e
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
"sessionStart": [entry("sessionStart")],
|
|
164
|
+
# Only the Shell tool is rewritten; matcher keeps every other tool out
|
|
165
|
+
# of the bridge's hot path (Cursor matchers are JS regex over tool name).
|
|
166
|
+
"preToolUse": [entry("preToolUse", matcher="Shell")],
|
|
167
|
+
"postToolUse": [entry("postToolUse")],
|
|
168
|
+
"preCompact": [entry("preCompact")],
|
|
169
|
+
"stop": [entry("stop")],
|
|
170
|
+
"sessionEnd": [entry("sessionEnd")],
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _is_ours(entry, bridge_path: Path) -> bool:
|
|
175
|
+
if not isinstance(entry, dict):
|
|
176
|
+
return False
|
|
177
|
+
cmd = entry.get("command")
|
|
178
|
+
return isinstance(cmd, str) and str(bridge_path) in cmd
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _read_hooks(path: Path) -> dict:
|
|
182
|
+
"""Read hooks.json. Missing -> {} (fresh install). A symlink, an unreadable,
|
|
183
|
+
invalid, or non-object root -> RuntimeError: Cursor has ONE shared
|
|
184
|
+
hooks.json, so silently treating a corrupt file as empty would clobber
|
|
185
|
+
other tools' (and Cursor's own) entries on the next write, and writing
|
|
186
|
+
through a symlink would redirect the installer's output to an
|
|
187
|
+
attacker-chosen target."""
|
|
188
|
+
if path.is_symlink():
|
|
189
|
+
raise RuntimeError(
|
|
190
|
+
f"{path} is a symlink; refusing to read-merge-write through it. "
|
|
191
|
+
"Remove the symlink (or point it at the real hooks.json) and re-run."
|
|
192
|
+
)
|
|
193
|
+
if not path.exists():
|
|
194
|
+
return {}
|
|
195
|
+
try:
|
|
196
|
+
raw = path.read_text(encoding="utf-8")
|
|
197
|
+
except OSError as exc:
|
|
198
|
+
raise RuntimeError(f"cannot read {path}: {exc}") from exc
|
|
199
|
+
try:
|
|
200
|
+
data = json.loads(raw)
|
|
201
|
+
except (json.JSONDecodeError, ValueError) as exc:
|
|
202
|
+
raise RuntimeError(f"{path} is not valid JSON: {exc}") from exc
|
|
203
|
+
if not isinstance(data, dict):
|
|
204
|
+
raise RuntimeError(
|
|
205
|
+
f"{path} has a non-object root; refusing to overwrite it."
|
|
206
|
+
)
|
|
207
|
+
return data
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _write_hooks(path: Path, data: dict) -> None:
|
|
211
|
+
try:
|
|
212
|
+
from codex_io import atomic_write_json
|
|
213
|
+
|
|
214
|
+
# replace_symlink: even if a symlink appears between _read_hooks and
|
|
215
|
+
# here, os.replace swaps the symlink itself, never its target.
|
|
216
|
+
atomic_write_json(path, data, replace_symlink=True)
|
|
217
|
+
except ImportError: # pragma: no cover - broken checkout
|
|
218
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
219
|
+
path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
@contextmanager
|
|
223
|
+
def _hooks_lock(hooks_path: Path):
|
|
224
|
+
"""Exclusive lease around the hooks.json read-merge-write.
|
|
225
|
+
|
|
226
|
+
Two concurrent installs (or install racing uninstall) would otherwise both
|
|
227
|
+
read stale content and the second write would silently drop the first's
|
|
228
|
+
entries. Uses hook_runtime.lease_lock (the same portable lock the bridges
|
|
229
|
+
use); a failed acquire aborts loudly instead of racing.
|
|
230
|
+
"""
|
|
231
|
+
from hook_runtime import lease_lock
|
|
232
|
+
|
|
233
|
+
lock_path = hooks_path.parent / f".{hooks_path.name}.to-install.lock"
|
|
234
|
+
# 120s lease: the critical section copies the payload and rewrites
|
|
235
|
+
# hooks.json; a 30s lease could lapse mid-RMW on a slow disk and let a
|
|
236
|
+
# concurrent installer reclaim it, reintroducing the clobber.
|
|
237
|
+
with lease_lock(lock_path, acquire_timeout=5.0, lease_seconds=120.0) as acquired:
|
|
238
|
+
if not acquired:
|
|
239
|
+
raise RuntimeError(
|
|
240
|
+
"another Cursor install/uninstall is in progress "
|
|
241
|
+
f"(could not acquire {lock_path}); re-run in a moment"
|
|
242
|
+
)
|
|
243
|
+
yield
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _copy_no_follow(src: Path, dest: Path) -> None:
|
|
247
|
+
"""Copy src to dest without ever writing through a symlink at dest.
|
|
248
|
+
|
|
249
|
+
A pre-write is_symlink() check is TOCTOU-racy; tempfile + os.replace swaps
|
|
250
|
+
whatever is at dest (a symlink included) instead of following it.
|
|
251
|
+
"""
|
|
252
|
+
import tempfile
|
|
253
|
+
|
|
254
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
255
|
+
fd, tmp_name = tempfile.mkstemp(prefix=f".{dest.name}.", dir=str(dest.parent))
|
|
256
|
+
try:
|
|
257
|
+
with os.fdopen(fd, "wb") as out, open(src, "rb") as inp:
|
|
258
|
+
shutil.copyfileobj(inp, out)
|
|
259
|
+
os.chmod(tmp_name, 0o644)
|
|
260
|
+
os.replace(tmp_name, dest)
|
|
261
|
+
except BaseException:
|
|
262
|
+
try:
|
|
263
|
+
os.unlink(tmp_name)
|
|
264
|
+
except OSError:
|
|
265
|
+
pass
|
|
266
|
+
raise
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def install(*, dry_run: bool = False, home: Path = None) -> dict:
|
|
270
|
+
"""Install the adapter. Returns a summary dict of actions taken."""
|
|
271
|
+
# Windows refusal (deferred quoting: cmd.exe would not parse shlex.quote).
|
|
272
|
+
if os.name == "nt":
|
|
273
|
+
raise RuntimeError(
|
|
274
|
+
"Cursor install on native Windows is not supported yet: the persisted "
|
|
275
|
+
"hook command is POSIX-shell quoted and cmd.exe would not parse it. "
|
|
276
|
+
"Install from a POSIX shell or WSL."
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
root = home if home is not None else cursor_home()
|
|
280
|
+
actions = {"copied": [], "hook_file": None, "skipped": [], "dry_run": dry_run}
|
|
281
|
+
plugin_dir = _plugin_dir(root)
|
|
282
|
+
|
|
283
|
+
for name in _PAYLOAD_MODULES:
|
|
284
|
+
src = _SCRIPT_DIR / name
|
|
285
|
+
if not src.exists():
|
|
286
|
+
actions["skipped"].append(name)
|
|
287
|
+
continue
|
|
288
|
+
dest = plugin_dir / name
|
|
289
|
+
if not dry_run:
|
|
290
|
+
try:
|
|
291
|
+
_copy_no_follow(src, dest)
|
|
292
|
+
except OSError as exc:
|
|
293
|
+
# A partial payload would silently break the bridge; abort BEFORE
|
|
294
|
+
# touching hooks.json.
|
|
295
|
+
raise RuntimeError(f"failed copying {name}: {exc}") from exc
|
|
296
|
+
actions["copied"].append(name)
|
|
297
|
+
|
|
298
|
+
if actions["skipped"]:
|
|
299
|
+
raise RuntimeError(
|
|
300
|
+
"missing payload modules in this checkout: "
|
|
301
|
+
f"{actions['skipped']} — refusing to wire hooks against an incomplete bridge."
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
# Write the measure.py locator so the bridge's detached rollup/dashboard
|
|
305
|
+
# spawns resolve the canonical measure.py (measure.py is never copied into
|
|
306
|
+
# the plugin dir — version-drift risk). Only written when measure.py exists
|
|
307
|
+
# next to the installer; the bridge degrades to "rollups paused" otherwise.
|
|
308
|
+
measure_py = _SCRIPT_DIR / "measure.py"
|
|
309
|
+
if measure_py.is_file():
|
|
310
|
+
locator = plugin_dir / _MEASURE_LOCATOR_NAME
|
|
311
|
+
if not dry_run:
|
|
312
|
+
try:
|
|
313
|
+
tmp = locator.with_name(f".{locator.name}.tmp")
|
|
314
|
+
tmp.write_text(f"{measure_py}\n", encoding="utf-8")
|
|
315
|
+
os.replace(tmp, locator) # swaps a symlink, never follows it
|
|
316
|
+
except OSError as exc:
|
|
317
|
+
raise RuntimeError(f"failed writing measure-path locator: {exc}") from exc
|
|
318
|
+
actions["measure_locator"] = str(measure_py)
|
|
319
|
+
|
|
320
|
+
bridge_path = plugin_dir / "cursor_hook_bridge.py"
|
|
321
|
+
hooks_path = _host_hooks_path(root)
|
|
322
|
+
with _hooks_lock(hooks_path):
|
|
323
|
+
existing = _read_hooks(hooks_path)
|
|
324
|
+
hooks = existing.get("hooks")
|
|
325
|
+
if not isinstance(hooks, dict):
|
|
326
|
+
hooks = {}
|
|
327
|
+
for event, new_entries in _hook_entries(bridge_path).items():
|
|
328
|
+
old = hooks.get(event, [])
|
|
329
|
+
if not isinstance(old, list):
|
|
330
|
+
old = []
|
|
331
|
+
hooks[event] = [e for e in old if not _is_ours(e, bridge_path)] + new_entries
|
|
332
|
+
existing["hooks"] = hooks
|
|
333
|
+
existing.setdefault("version", 1)
|
|
334
|
+
|
|
335
|
+
if not dry_run:
|
|
336
|
+
try:
|
|
337
|
+
_write_hooks(hooks_path, existing)
|
|
338
|
+
except OSError as exc:
|
|
339
|
+
raise RuntimeError(f"failed writing {hooks_path}: {exc}") from exc
|
|
340
|
+
actions["hook_file"] = str(hooks_path)
|
|
341
|
+
return actions
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def uninstall(*, dry_run: bool = False, home: Path = None) -> dict:
|
|
345
|
+
"""Remove only entries install() added, plus the payload dir.
|
|
346
|
+
|
|
347
|
+
Session data (``<cursor_home>/token-optimizer/sessions``,
|
|
348
|
+
``restore-context``, ``observed-events.jsonl``) and trends are left in place
|
|
349
|
+
for the user to purge manually, matching the Copilot uninstall contract.
|
|
350
|
+
"""
|
|
351
|
+
root = home if home is not None else cursor_home()
|
|
352
|
+
actions = {"removed": [], "dry_run": dry_run}
|
|
353
|
+
|
|
354
|
+
bridge_path = _plugin_dir(root) / "cursor_hook_bridge.py"
|
|
355
|
+
hooks_path = _host_hooks_path(root)
|
|
356
|
+
with _hooks_lock(hooks_path):
|
|
357
|
+
existing = _read_hooks(hooks_path)
|
|
358
|
+
hooks = existing.get("hooks")
|
|
359
|
+
if isinstance(hooks, dict):
|
|
360
|
+
changed = False
|
|
361
|
+
pruned = {}
|
|
362
|
+
for event, entries in hooks.items():
|
|
363
|
+
if not isinstance(entries, list):
|
|
364
|
+
pruned[event] = entries
|
|
365
|
+
continue
|
|
366
|
+
kept = [e for e in entries if not _is_ours(e, bridge_path)]
|
|
367
|
+
if len(kept) != len(entries):
|
|
368
|
+
changed = True
|
|
369
|
+
pruned[event] = kept
|
|
370
|
+
if changed:
|
|
371
|
+
existing["hooks"] = pruned
|
|
372
|
+
if not dry_run:
|
|
373
|
+
try:
|
|
374
|
+
_write_hooks(hooks_path, existing)
|
|
375
|
+
except OSError as exc:
|
|
376
|
+
raise RuntimeError(f"failed writing {hooks_path}: {exc}") from exc
|
|
377
|
+
actions["removed"].append(f"{hooks_path} (Cursor entries)")
|
|
378
|
+
|
|
379
|
+
plugin_dir = _plugin_dir(root)
|
|
380
|
+
if plugin_dir.exists():
|
|
381
|
+
if not dry_run:
|
|
382
|
+
try:
|
|
383
|
+
shutil.rmtree(plugin_dir)
|
|
384
|
+
except OSError as exc:
|
|
385
|
+
# main() only surfaces RuntimeError; a raw OSError would escape
|
|
386
|
+
# as a traceback and leave a half-uninstalled state unexplained.
|
|
387
|
+
raise RuntimeError(f"failed removing {plugin_dir}: {exc}") from exc
|
|
388
|
+
actions["removed"].append(str(plugin_dir))
|
|
389
|
+
|
|
390
|
+
return actions
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
394
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
395
|
+
parser.add_argument("action", choices=("install", "uninstall"))
|
|
396
|
+
parser.add_argument("--dry-run", action="store_true")
|
|
397
|
+
return parser
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def main(argv=None) -> int:
|
|
401
|
+
args = build_parser().parse_args(argv)
|
|
402
|
+
try:
|
|
403
|
+
if args.action == "install":
|
|
404
|
+
result = install(dry_run=args.dry_run)
|
|
405
|
+
verb = "Would install" if args.dry_run else "Installed"
|
|
406
|
+
print(f"{verb} Token Optimizer for Cursor.")
|
|
407
|
+
print(f" Hooks merged into: {result['hook_file']}")
|
|
408
|
+
print(f" Modules: {len(result['copied'])} copied"
|
|
409
|
+
+ (f", {len(result['skipped'])} missing: {result['skipped']}" if result["skipped"] else ""))
|
|
410
|
+
print(_hint(" Run `python3 measure.py cursor-doctor` to verify readiness."))
|
|
411
|
+
else:
|
|
412
|
+
result = uninstall(dry_run=args.dry_run)
|
|
413
|
+
verb = "Would remove" if args.dry_run else "Removed"
|
|
414
|
+
for item in result["removed"] or ["(nothing installed)"]:
|
|
415
|
+
print(f"{verb}: {item}")
|
|
416
|
+
return 0
|
|
417
|
+
except RuntimeError as exc:
|
|
418
|
+
print(f"[Token Optimizer] {exc}", file=sys.stderr)
|
|
419
|
+
return 1
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
if __name__ == "__main__":
|
|
423
|
+
sys.exit(main())
|