@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,397 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer — Grok Build installer.
|
|
3
|
+
|
|
4
|
+
Wires Token Optimizer into Grok Build's hooks system:
|
|
5
|
+
|
|
6
|
+
1. Copies the adapter modules into ``<grok_home>/token-optimizer/plugin/``
|
|
7
|
+
so the hook bridge runs from a stable path that survives repo moves.
|
|
8
|
+
2. Writes OUR OWN hooks file ``$GROK_HOME/hooks/token-optimizer.json``
|
|
9
|
+
(Grok scans ``~/.grok/hooks/*.json`` as a DIRECTORY of files — unlike
|
|
10
|
+
Cursor's single shared hooks.json — so TO owns its file outright and never
|
|
11
|
+
merges with, or clobbers, another tool'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.
|
|
14
|
+
|
|
15
|
+
The hooks JSON format is Grok's documented shape (10-hooks.md "The Hook JSON
|
|
16
|
+
Format"): ``{"hooks": {<Event>: [{matcher?, hooks: [{type, command, timeout}]}]}}``.
|
|
17
|
+
|
|
18
|
+
Idempotent: re-running refreshes the payload and rewrites OUR file only.
|
|
19
|
+
Uninstall removes only OUR hooks file and the payload dir; session data stays.
|
|
20
|
+
|
|
21
|
+
Usage:
|
|
22
|
+
python3 grok_install.py install [--dry-run]
|
|
23
|
+
python3 grok_install.py uninstall [--dry-run]
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import argparse
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import shlex
|
|
32
|
+
import shutil
|
|
33
|
+
import sys
|
|
34
|
+
from contextlib import contextmanager
|
|
35
|
+
from pathlib import Path
|
|
36
|
+
|
|
37
|
+
_SCRIPT_DIR = Path(__file__).resolve().parent
|
|
38
|
+
sys.path.insert(0, str(_SCRIPT_DIR))
|
|
39
|
+
|
|
40
|
+
from py_trust import py_path_is_trusted, py_trust_reason # noqa: E402
|
|
41
|
+
from runtime_env import grok_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
|
|
42
|
+
|
|
43
|
+
# Observe hooks default to 5s; PostToolUse/Stop default to 600s in grok. TO's
|
|
44
|
+
# handlers are fast, so pin short explicit timeouts (10-hooks.md "Key Fields").
|
|
45
|
+
SESSION_TIMEOUT_SEC = 5
|
|
46
|
+
PRETOOL_TIMEOUT_SEC = 5
|
|
47
|
+
POSTTOOL_TIMEOUT_SEC = 10
|
|
48
|
+
STOP_TIMEOUT_SEC = 10
|
|
49
|
+
|
|
50
|
+
# Modules the bridge needs at runtime, copied next to it so the installed
|
|
51
|
+
# hook never depends on the repo checkout location.
|
|
52
|
+
_PAYLOAD_MODULES = (
|
|
53
|
+
"grok_hook_bridge.py",
|
|
54
|
+
"grok_state.py",
|
|
55
|
+
"grok_session.py",
|
|
56
|
+
"bash_hook.py",
|
|
57
|
+
"bash_compress.py",
|
|
58
|
+
# Dependency-free whitelist gate shared by bash_hook + bash_compress.
|
|
59
|
+
# Without it, `import bash_hook` fails in the installed path, the bridge
|
|
60
|
+
# sets _bash_hook = None, and the entire PreToolUse bash compression
|
|
61
|
+
# feature silently no-ops.
|
|
62
|
+
"bash_whitelist.py",
|
|
63
|
+
"hook_io.py",
|
|
64
|
+
"plugin_env.py",
|
|
65
|
+
"runtime_env.py",
|
|
66
|
+
# codex_io supplies atomic_write_json — without it the bridge's tally and
|
|
67
|
+
# observed-events writes silently no-op.
|
|
68
|
+
"codex_io.py",
|
|
69
|
+
# hermes_session supplies compute_quality_score — without it grok_session
|
|
70
|
+
# silently falls back to a single-signal quality estimate.
|
|
71
|
+
"hermes_session.py",
|
|
72
|
+
# spawn_utils supplies spawn_detached — without it the bridge's degraded
|
|
73
|
+
# fallback does NOT detach, so rollup/dashboard spawns die with the hook.
|
|
74
|
+
"spawn_utils.py",
|
|
75
|
+
# hook_runtime supplies lease_lock (tally RMW + stop throttle).
|
|
76
|
+
"hook_runtime.py",
|
|
77
|
+
"utf8_io.py",
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
# One-line locator written next to the bridge, naming the canonical measure.py
|
|
81
|
+
# in the checkout (measure.py is never copied into the plugin dir — version-
|
|
82
|
+
# drift risk). Mirrors hermes/cursor _MEASURE_LOCATOR_NAME.
|
|
83
|
+
_MEASURE_LOCATOR_NAME = "measure-path"
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _plugin_dir(root: Path) -> Path:
|
|
87
|
+
return root / "token-optimizer" / "plugin"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _hooks_file(root: Path) -> Path:
|
|
91
|
+
return root / "hooks" / "token-optimizer.json"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _resolve_safe_python() -> str:
|
|
95
|
+
"""An ABSOLUTE, trusted python for the persisted Grok hook command.
|
|
96
|
+
|
|
97
|
+
Never emit a bare "python3": that string is resolved via $PATH every time
|
|
98
|
+
the hook fires, so a hijacked PATH entry runs attacker code. Resolution:
|
|
99
|
+
1. TOKEN_OPTIMIZER_PYTHON, if it names a trusted file;
|
|
100
|
+
2. sys.executable (absolute, baked in ONCE) — through the same gate;
|
|
101
|
+
3. a $PATH search, accepting only a candidate that passes the gate.
|
|
102
|
+
Raises RuntimeError rather than persist an unsafe command.
|
|
103
|
+
"""
|
|
104
|
+
override = os.environ.get("TOKEN_OPTIMIZER_PYTHON", "").strip()
|
|
105
|
+
candidates = []
|
|
106
|
+
if override:
|
|
107
|
+
candidates.append(("TOKEN_OPTIMIZER_PYTHON", override))
|
|
108
|
+
if sys.executable:
|
|
109
|
+
candidates.append(("sys.executable", sys.executable))
|
|
110
|
+
for name in ("python3", "python"):
|
|
111
|
+
cand = shutil.which(name)
|
|
112
|
+
if cand:
|
|
113
|
+
candidates.append((name, cand))
|
|
114
|
+
for _label, cand in candidates:
|
|
115
|
+
if py_path_is_trusted(cand):
|
|
116
|
+
# Persist the RESOLVED realpath, not abspath: the gate validated
|
|
117
|
+
# realpath(cand) (the symlink target + its parent dir), so persisting
|
|
118
|
+
# the original symlink path would leave a swap window between install
|
|
119
|
+
# and hook fire (an attacker with write access to the symlink's parent
|
|
120
|
+
# dir could redirect the symlink to a malicious interpreter).
|
|
121
|
+
return os.path.realpath(cand)
|
|
122
|
+
reasons = [f"{label}={cand}: {py_trust_reason(cand)}"
|
|
123
|
+
for label, cand in candidates]
|
|
124
|
+
raise RuntimeError(
|
|
125
|
+
"no trusted python interpreter found for the Grok hook; "
|
|
126
|
+
"set TOKEN_OPTIMIZER_PYTHON to an absolute python3 path and re-run install. "
|
|
127
|
+
"Candidates: " + "; ".join(reasons)
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _hook_entries(bridge_path: Path) -> dict:
|
|
132
|
+
"""The hook entries TO writes to $GROK_HOME/hooks/token-optimizer.json.
|
|
133
|
+
|
|
134
|
+
Format is Grok's documented 10-hooks.md shape. ``command`` is assumed to run
|
|
135
|
+
through a POSIX shell, so the two paths are shlex-quoted and the runtime is
|
|
136
|
+
pinned so the bridge never process-scans on the hot path.
|
|
137
|
+
"""
|
|
138
|
+
py_q = shlex.quote(_resolve_safe_python())
|
|
139
|
+
bridge_q = shlex.quote(str(bridge_path))
|
|
140
|
+
|
|
141
|
+
def handler(event: str, timeout: int) -> dict:
|
|
142
|
+
return {
|
|
143
|
+
"type": "command",
|
|
144
|
+
"command": f"TOKEN_OPTIMIZER_RUNTIME=grok {py_q} {bridge_q} {event}",
|
|
145
|
+
"timeout": timeout,
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
def entry(event: str, timeout: int, matcher: str | None = None) -> dict:
|
|
149
|
+
e = {"hooks": [handler(event, timeout)]}
|
|
150
|
+
if matcher is not None:
|
|
151
|
+
e["matcher"] = matcher
|
|
152
|
+
return e
|
|
153
|
+
|
|
154
|
+
return {
|
|
155
|
+
"SessionStart": [entry("SessionStart", SESSION_TIMEOUT_SEC)],
|
|
156
|
+
"UserPromptSubmit": [entry("UserPromptSubmit", SESSION_TIMEOUT_SEC)],
|
|
157
|
+
# Only the bash tool is rewritten; matcher "Bash" maps to grok's own
|
|
158
|
+
# ``run_terminal_command`` (10-hooks.md "Tool Name Aliases") and keeps
|
|
159
|
+
# every other tool out of the rewrite hot path.
|
|
160
|
+
"PreToolUse": [entry("PreToolUse", PRETOOL_TIMEOUT_SEC, matcher="Bash")],
|
|
161
|
+
"PostToolUse": [entry("PostToolUse", POSTTOOL_TIMEOUT_SEC)],
|
|
162
|
+
"Stop": [entry("Stop", STOP_TIMEOUT_SEC)],
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _hooks_payload(bridge_path: Path) -> dict:
|
|
167
|
+
return {"hooks": _hook_entries(bridge_path)}
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _read_hooks_file(path: Path) -> dict:
|
|
171
|
+
"""Read OUR hooks file. Missing -> {}. Symlink/unreadable/invalid -> raise.
|
|
172
|
+
|
|
173
|
+
TO owns this file outright, but it lives in a user-writable dir: writing
|
|
174
|
+
through a symlink (or silently overwriting an invalid root) would redirect
|
|
175
|
+
the installer's output. Refuse rather than write through an attacker-chosen
|
|
176
|
+
target.
|
|
177
|
+
"""
|
|
178
|
+
if path.is_symlink():
|
|
179
|
+
raise RuntimeError(
|
|
180
|
+
f"{path} is a symlink; refusing to write through it. "
|
|
181
|
+
"Remove the symlink and re-run."
|
|
182
|
+
)
|
|
183
|
+
if not path.exists():
|
|
184
|
+
return {}
|
|
185
|
+
try:
|
|
186
|
+
raw = path.read_text(encoding="utf-8")
|
|
187
|
+
except OSError as exc:
|
|
188
|
+
raise RuntimeError(f"cannot read {path}: {exc}") from exc
|
|
189
|
+
try:
|
|
190
|
+
data = json.loads(raw)
|
|
191
|
+
except (json.JSONDecodeError, ValueError) as exc:
|
|
192
|
+
raise RuntimeError(f"{path} is not valid JSON: {exc}") from exc
|
|
193
|
+
if not isinstance(data, dict):
|
|
194
|
+
raise RuntimeError(f"{path} has a non-object root; refusing to overwrite it.")
|
|
195
|
+
return data
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def _write_hooks_file(path: Path, data: dict) -> None:
|
|
199
|
+
"""Atomically write OUR hooks file, never following a symlink at dest.
|
|
200
|
+
|
|
201
|
+
codex_io.atomic_write_json (in this checkout) resolves a symlink before
|
|
202
|
+
writing; that would follow an attacker-planted symlink in the user-writable
|
|
203
|
+
hooks dir. tempfile + os.replace swaps the symlink itself instead, matching
|
|
204
|
+
_copy_no_follow.
|
|
205
|
+
"""
|
|
206
|
+
import tempfile
|
|
207
|
+
|
|
208
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
209
|
+
fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=str(path.parent))
|
|
210
|
+
try:
|
|
211
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
212
|
+
json.dump(data, fh, indent=2)
|
|
213
|
+
fh.write("\n")
|
|
214
|
+
os.chmod(tmp_name, 0o644)
|
|
215
|
+
os.replace(tmp_name, path) # swaps a symlink, never follows it
|
|
216
|
+
except BaseException:
|
|
217
|
+
try:
|
|
218
|
+
os.unlink(tmp_name)
|
|
219
|
+
except OSError:
|
|
220
|
+
pass
|
|
221
|
+
raise
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
@contextmanager
|
|
225
|
+
def _hooks_lock(hooks_path: Path):
|
|
226
|
+
"""Exclusive lease around the hooks-file read-modify-write.
|
|
227
|
+
|
|
228
|
+
Two concurrent installs (or install racing uninstall) would otherwise race.
|
|
229
|
+
Uses hook_runtime.lease_lock (the same portable lock the bridges use).
|
|
230
|
+
"""
|
|
231
|
+
from hook_runtime import lease_lock
|
|
232
|
+
|
|
233
|
+
lock_path = hooks_path.parent / f".{hooks_path.name}.to-install.lock"
|
|
234
|
+
# cohort_throttle=False: install and uninstall are distinct mutations
|
|
235
|
+
# (write the payload vs remove it) and a trailing distinct-PID writer must
|
|
236
|
+
# be able to immediately reclaim a released lease rather than be suppressed
|
|
237
|
+
# for the full lease window — otherwise a user who installs then quickly
|
|
238
|
+
# uninstalls is told "another install is in progress" for 120s.
|
|
239
|
+
with lease_lock(lock_path, acquire_timeout=5.0, lease_seconds=120.0,
|
|
240
|
+
cohort_throttle=False) as acquired:
|
|
241
|
+
if not acquired:
|
|
242
|
+
raise RuntimeError(
|
|
243
|
+
"another Grok install/uninstall is in progress "
|
|
244
|
+
f"(could not acquire {lock_path}); re-run in a moment"
|
|
245
|
+
)
|
|
246
|
+
yield
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def _copy_no_follow(src: Path, dest: Path) -> None:
|
|
250
|
+
"""Copy src to dest without ever writing through a symlink at dest.
|
|
251
|
+
|
|
252
|
+
A pre-write is_symlink() check is TOCTOU-racy; tempfile + os.replace swaps
|
|
253
|
+
whatever is at dest (a symlink included) instead of following it.
|
|
254
|
+
"""
|
|
255
|
+
import tempfile
|
|
256
|
+
|
|
257
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
258
|
+
fd, tmp_name = tempfile.mkstemp(prefix=f".{dest.name}.", dir=str(dest.parent))
|
|
259
|
+
try:
|
|
260
|
+
with os.fdopen(fd, "wb") as out, open(src, "rb") as inp:
|
|
261
|
+
shutil.copyfileobj(inp, out)
|
|
262
|
+
os.chmod(tmp_name, 0o644)
|
|
263
|
+
os.replace(tmp_name, dest)
|
|
264
|
+
except BaseException:
|
|
265
|
+
try:
|
|
266
|
+
os.unlink(tmp_name)
|
|
267
|
+
except OSError:
|
|
268
|
+
pass
|
|
269
|
+
raise
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def install(*, dry_run: bool = False, home: Path | None = None) -> dict:
|
|
273
|
+
"""Install the adapter. Returns a summary dict of actions taken."""
|
|
274
|
+
if os.name == "nt":
|
|
275
|
+
raise RuntimeError(
|
|
276
|
+
"Grok install on native Windows is not supported yet: the persisted "
|
|
277
|
+
"hook command is POSIX-shell quoted and cmd.exe would not parse it. "
|
|
278
|
+
"Install from a POSIX shell or WSL."
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
root = home if home is not None else grok_home()
|
|
282
|
+
actions = {"copied": [], "hook_file": None, "skipped": [], "dry_run": dry_run}
|
|
283
|
+
plugin_dir = _plugin_dir(root)
|
|
284
|
+
|
|
285
|
+
for name in _PAYLOAD_MODULES:
|
|
286
|
+
src = _SCRIPT_DIR / name
|
|
287
|
+
if not src.exists():
|
|
288
|
+
actions["skipped"].append(name)
|
|
289
|
+
continue
|
|
290
|
+
dest = plugin_dir / name
|
|
291
|
+
if not dry_run:
|
|
292
|
+
try:
|
|
293
|
+
_copy_no_follow(src, dest)
|
|
294
|
+
except OSError as exc:
|
|
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.
|
|
306
|
+
measure_py = _SCRIPT_DIR / "measure.py"
|
|
307
|
+
if measure_py.is_file():
|
|
308
|
+
locator = plugin_dir / _MEASURE_LOCATOR_NAME
|
|
309
|
+
if not dry_run:
|
|
310
|
+
try:
|
|
311
|
+
tmp = locator.with_name(f".{locator.name}.tmp")
|
|
312
|
+
tmp.write_text(f"{measure_py}\n", encoding="utf-8")
|
|
313
|
+
os.replace(tmp, locator) # swaps a symlink, never follows it
|
|
314
|
+
except OSError as exc:
|
|
315
|
+
raise RuntimeError(f"failed writing measure-path locator: {exc}") from exc
|
|
316
|
+
actions["measure_locator"] = str(measure_py)
|
|
317
|
+
|
|
318
|
+
bridge_path = plugin_dir / "grok_hook_bridge.py"
|
|
319
|
+
hooks_path = _hooks_file(root)
|
|
320
|
+
with _hooks_lock(hooks_path):
|
|
321
|
+
# TO owns this file; replace its contents outright with the current
|
|
322
|
+
# payload definition. No foreign entries exist to preserve (unlike
|
|
323
|
+
# Cursor's shared hooks.json).
|
|
324
|
+
_read_hooks_file(hooks_path) # only to trip the symlink/invalid guard
|
|
325
|
+
payload = _hooks_payload(bridge_path)
|
|
326
|
+
if not dry_run:
|
|
327
|
+
try:
|
|
328
|
+
_write_hooks_file(hooks_path, payload)
|
|
329
|
+
except OSError as exc:
|
|
330
|
+
raise RuntimeError(f"failed writing {hooks_path}: {exc}") from exc
|
|
331
|
+
actions["hook_file"] = str(hooks_path)
|
|
332
|
+
return actions
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def uninstall(*, dry_run: bool = False, home: Path | None = None) -> dict:
|
|
336
|
+
"""Remove OUR hooks file and the payload dir. Session data stays."""
|
|
337
|
+
root = home if home is not None else grok_home()
|
|
338
|
+
actions = {"removed": [], "dry_run": dry_run}
|
|
339
|
+
|
|
340
|
+
hooks_path = _hooks_file(root)
|
|
341
|
+
with _hooks_lock(hooks_path):
|
|
342
|
+
if hooks_path.exists() or hooks_path.is_symlink():
|
|
343
|
+
if not dry_run:
|
|
344
|
+
try:
|
|
345
|
+
# Unlink a symlink (never its target) or a regular file.
|
|
346
|
+
hooks_path.unlink()
|
|
347
|
+
except OSError as exc:
|
|
348
|
+
raise RuntimeError(f"failed removing {hooks_path}: {exc}") from exc
|
|
349
|
+
actions["removed"].append(str(hooks_path))
|
|
350
|
+
|
|
351
|
+
plugin_dir = _plugin_dir(root)
|
|
352
|
+
if plugin_dir.exists():
|
|
353
|
+
if not dry_run:
|
|
354
|
+
try:
|
|
355
|
+
shutil.rmtree(plugin_dir)
|
|
356
|
+
except OSError as exc:
|
|
357
|
+
raise RuntimeError(f"failed removing {plugin_dir}: {exc}") from exc
|
|
358
|
+
actions["removed"].append(str(plugin_dir))
|
|
359
|
+
|
|
360
|
+
return actions
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
364
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
365
|
+
parser.add_argument("action", choices=("install", "uninstall"))
|
|
366
|
+
parser.add_argument("--dry-run", action="store_true")
|
|
367
|
+
# --home overrides the resolved Grok home (install.sh forwards the
|
|
368
|
+
# WSL-aware resolved path so the install and its banner agree, mirroring
|
|
369
|
+
# copilot_install --home).
|
|
370
|
+
parser.add_argument("--home", type=Path, default=None)
|
|
371
|
+
return parser
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def main(argv=None) -> int:
|
|
375
|
+
args = build_parser().parse_args(argv)
|
|
376
|
+
try:
|
|
377
|
+
if args.action == "install":
|
|
378
|
+
result = install(dry_run=args.dry_run, home=args.home)
|
|
379
|
+
verb = "Would install" if args.dry_run else "Installed"
|
|
380
|
+
print(f"{verb} Token Optimizer for Grok Build.")
|
|
381
|
+
print(f" Hooks written to: {result['hook_file']}")
|
|
382
|
+
print(f" Modules: {len(result['copied'])} copied"
|
|
383
|
+
+ (f", {len(result['skipped'])} missing: {result['skipped']}" if result["skipped"] else ""))
|
|
384
|
+
print(_hint(" Run `python3 measure.py grok-doctor` to verify readiness."))
|
|
385
|
+
else:
|
|
386
|
+
result = uninstall(dry_run=args.dry_run, home=args.home)
|
|
387
|
+
verb = "Would remove" if args.dry_run else "Removed"
|
|
388
|
+
for item in result["removed"] or ["(nothing installed)"]:
|
|
389
|
+
print(f"{verb}: {item}")
|
|
390
|
+
return 0
|
|
391
|
+
except RuntimeError as exc:
|
|
392
|
+
print(f"[Token Optimizer] {exc}", file=sys.stderr)
|
|
393
|
+
return 1
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
if __name__ == "__main__":
|
|
397
|
+
sys.exit(main())
|