@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,376 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer — Google Antigravity adapter installer.
|
|
3
|
+
|
|
4
|
+
Wires Token Optimizer into an Antigravity (CLI ``agy``, Antigravity 2.0 app,
|
|
5
|
+
or IDE) setup as a USER-LEVEL PLUGIN directory:
|
|
6
|
+
|
|
7
|
+
1. Copies the adapter payload modules into
|
|
8
|
+
``<home>/config/plugins/token-optimizer/`` so the hook bridge runs from a
|
|
9
|
+
stable path that survives repo moves.
|
|
10
|
+
2. Writes ``hooks.json`` and ``plugin.json`` inside that plugin directory —
|
|
11
|
+
never touching the user-owned ``<home>/config/hooks.json``, ``config.json``,
|
|
12
|
+
or any ``settings.json``.
|
|
13
|
+
3. Records consent in ``<home>/token-optimizer/config.json`` (R20).
|
|
14
|
+
|
|
15
|
+
Idempotent: re-running refreshes the payload and rewrites OUR files only.
|
|
16
|
+
Uninstall removes only the plugin directory; conversation data and trends stay.
|
|
17
|
+
|
|
18
|
+
Usage:
|
|
19
|
+
python3 antigravity_install.py install [--dry-run]
|
|
20
|
+
python3 antigravity_install.py uninstall [--dry-run]
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import argparse
|
|
26
|
+
import json
|
|
27
|
+
import os
|
|
28
|
+
import stat as _stat
|
|
29
|
+
import shlex
|
|
30
|
+
import shutil
|
|
31
|
+
import sys
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
_SCRIPT_DIR = Path(__file__).resolve().parent
|
|
35
|
+
sys.path.insert(0, str(_SCRIPT_DIR))
|
|
36
|
+
|
|
37
|
+
from py_trust import py_path_is_trusted, py_trust_reason # noqa: E402
|
|
38
|
+
from runtime_env import antigravity_home, measure_cli as _measure_cli, with_measure_cli as _hint # noqa: E402
|
|
39
|
+
|
|
40
|
+
HOOK_NAME = "token-optimizer"
|
|
41
|
+
PRE_TIMEOUT_SEC = 10
|
|
42
|
+
STOP_TIMEOUT_SEC = 15
|
|
43
|
+
|
|
44
|
+
# Consent flag recorded in <home>/token-optimizer/config.json. The bridge and
|
|
45
|
+
# the rollup are no-ops until it is true (R20).
|
|
46
|
+
CONSENT_KEY = "antigravity_consent"
|
|
47
|
+
|
|
48
|
+
# Modules the bridge needs at runtime, copied next to it so the installed hook
|
|
49
|
+
# never depends on the repo checkout location. antigravity_session is NOT here:
|
|
50
|
+
# it is only imported by measure.py's collector, which runs from the checkout
|
|
51
|
+
# via the measure-path locator, never from the plugin directory.
|
|
52
|
+
_PAYLOAD_MODULES = (
|
|
53
|
+
"antigravity_hook_bridge.py",
|
|
54
|
+
"antigravity_proto.py",
|
|
55
|
+
"antigravity_state.py",
|
|
56
|
+
"runtime_env.py",
|
|
57
|
+
"plugin_env.py",
|
|
58
|
+
"bash_hook.py",
|
|
59
|
+
"bash_compress.py",
|
|
60
|
+
# Dependency-free whitelist gate shared by bash_hook + bash_compress.
|
|
61
|
+
"bash_whitelist.py",
|
|
62
|
+
"command_filters.py",
|
|
63
|
+
"spawn_utils.py",
|
|
64
|
+
"utf8_io.py",
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _py_trust_reason(p: str) -> str | None:
|
|
69
|
+
"""None when trusted, else a short human-readable rejection reason."""
|
|
70
|
+
return py_trust_reason(p)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _py_path_is_trusted(p: str) -> bool:
|
|
74
|
+
"""Trusted iff the interpreter's bytes are admin-owned (euid or root) and
|
|
75
|
+
not group/other-writable, and its dir is not world-writable and not
|
|
76
|
+
group-writable by a third party. Pure stat, never runs the target. On
|
|
77
|
+
Windows, stat ownership is unreliable under Git-Bash, so require only that
|
|
78
|
+
the path is a real file."""
|
|
79
|
+
return py_path_is_trusted(p)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _resolve_safe_python() -> str:
|
|
83
|
+
"""An ABSOLUTE, trusted python for the persisted Antigravity hook command.
|
|
84
|
+
|
|
85
|
+
Never emit a bare "python3": that string is resolved via $PATH every time
|
|
86
|
+
the hook fires, so a hijacked PATH entry runs attacker code. Resolution
|
|
87
|
+
order:
|
|
88
|
+
1. TOKEN_OPTIMIZER_PYTHON, if it names a trusted file;
|
|
89
|
+
2. sys.executable (absolute path baked in ONCE) -- but only through the
|
|
90
|
+
same trust gate: a writable venv interpreter must never be persisted;
|
|
91
|
+
3. a $PATH search, accepting only a candidate that passes the gate.
|
|
92
|
+
The RESOLVED realpath is persisted, not abspath: the gate validated
|
|
93
|
+
realpath(cand) (the symlink target + its parent dir), so persisting the
|
|
94
|
+
original symlink path would leave a swap window between install and hook
|
|
95
|
+
fire. Raises RuntimeError rather than persist an unsafe command.
|
|
96
|
+
"""
|
|
97
|
+
override = os.environ.get("TOKEN_OPTIMIZER_PYTHON", "").strip()
|
|
98
|
+
candidates = []
|
|
99
|
+
if override:
|
|
100
|
+
candidates.append(("TOKEN_OPTIMIZER_PYTHON", override))
|
|
101
|
+
if sys.executable:
|
|
102
|
+
candidates.append(("sys.executable", sys.executable))
|
|
103
|
+
for name in ("python3", "python"):
|
|
104
|
+
cand = shutil.which(name)
|
|
105
|
+
if cand:
|
|
106
|
+
candidates.append((name, cand))
|
|
107
|
+
for _label, cand in candidates:
|
|
108
|
+
if _py_path_is_trusted(cand):
|
|
109
|
+
return os.path.realpath(cand)
|
|
110
|
+
reasons = [f"{label}={cand}: {_py_trust_reason(cand)}"
|
|
111
|
+
for label, cand in candidates]
|
|
112
|
+
raise RuntimeError(
|
|
113
|
+
"no trusted python interpreter found for the Antigravity hook; "
|
|
114
|
+
"set TOKEN_OPTIMIZER_PYTHON to an absolute python3 path and re-run install. "
|
|
115
|
+
"Candidates: " + "; ".join(reasons)
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def plugin_dir(home: Path) -> Path:
|
|
120
|
+
return home / "config" / "plugins" / HOOK_NAME
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def data_dir(home: Path) -> Path:
|
|
124
|
+
return home / "token-optimizer"
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _hooks_config(bridge_path: Path) -> dict:
|
|
128
|
+
"""hooks.json per the Antigravity hooks contract (builtin agy-customizations
|
|
129
|
+
docs): a JSON object keyed by hook NAME; PreToolUse uses a matcher group,
|
|
130
|
+
PreInvocation/Stop are flat handler lists."""
|
|
131
|
+
py = _resolve_safe_python()
|
|
132
|
+
py_q = shlex.quote(py)
|
|
133
|
+
bridge_q = shlex.quote(str(bridge_path))
|
|
134
|
+
|
|
135
|
+
def cmd(event: str, timeout: int) -> dict:
|
|
136
|
+
return {
|
|
137
|
+
"type": "command",
|
|
138
|
+
# -E -s: ignore PYTHONPATH + user site so an inherited env cannot
|
|
139
|
+
# hijack payload imports (R16). TOKEN_OPTIMIZER_RUNTIME is pinned so
|
|
140
|
+
# the bridge never process-scans on the hot path.
|
|
141
|
+
"command": f"TOKEN_OPTIMIZER_RUNTIME=antigravity {py_q} -E -s {bridge_q} {event}",
|
|
142
|
+
"timeout": timeout,
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
pre_tool = cmd("pre-tool-use", PRE_TIMEOUT_SEC)
|
|
146
|
+
return {
|
|
147
|
+
HOOK_NAME: {
|
|
148
|
+
"PreToolUse": [
|
|
149
|
+
# Only the run_command tool is rewritten; the matcher keeps every
|
|
150
|
+
# other tool call out of the bridge's hot path entirely.
|
|
151
|
+
{"matcher": "run_command", "hooks": [pre_tool]},
|
|
152
|
+
],
|
|
153
|
+
"PreInvocation": [cmd("pre-invocation", PRE_TIMEOUT_SEC)],
|
|
154
|
+
"Stop": [cmd("stop", STOP_TIMEOUT_SEC)],
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _ensure_config_dir_permissions(path: Path) -> None:
|
|
160
|
+
"""Create a directory 0o700 (private data dir). Never follows symlinks."""
|
|
161
|
+
try:
|
|
162
|
+
path.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
163
|
+
os.chmod(path, 0o700)
|
|
164
|
+
except OSError as exc:
|
|
165
|
+
raise RuntimeError(f"failed to create {path}: {exc}") from exc
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _write_consent(home: Path) -> None:
|
|
169
|
+
"""Record the consent flag in <home>/token-optimizer/config.json (R20)."""
|
|
170
|
+
dd = data_dir(home)
|
|
171
|
+
_ensure_config_dir_permissions(dd)
|
|
172
|
+
config_path = dd / "config.json"
|
|
173
|
+
cfg: dict = {}
|
|
174
|
+
try:
|
|
175
|
+
if config_path.is_file():
|
|
176
|
+
cfg = json.loads(config_path.read_text(encoding="utf-8"))
|
|
177
|
+
if not isinstance(cfg, dict):
|
|
178
|
+
cfg = {}
|
|
179
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
180
|
+
cfg = {}
|
|
181
|
+
cfg[CONSENT_KEY] = True
|
|
182
|
+
try:
|
|
183
|
+
config_path.write_text(json.dumps(cfg, indent=2) + "\n", encoding="utf-8")
|
|
184
|
+
except OSError as exc:
|
|
185
|
+
raise RuntimeError(
|
|
186
|
+
f"failed to write consent record {config_path}: {exc}"
|
|
187
|
+
) from exc
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def install(*, dry_run: bool = False, home: Path | None = None) -> dict:
|
|
191
|
+
"""Install the adapter. Returns a summary dict of actions taken."""
|
|
192
|
+
# Windows refusal (deferred quoting: cmd.exe would not parse shlex.quote,
|
|
193
|
+
# and the env-prefix form of the persisted hook command is POSIX-only).
|
|
194
|
+
# Refuse loudly rather than register hooks that can never fire.
|
|
195
|
+
if os.name == "nt":
|
|
196
|
+
raise RuntimeError(
|
|
197
|
+
"Antigravity install on native Windows is not supported yet: the "
|
|
198
|
+
"persisted hook command is POSIX-shell quoted and cmd.exe would "
|
|
199
|
+
"not parse it. Install from a POSIX shell or WSL."
|
|
200
|
+
)
|
|
201
|
+
|
|
202
|
+
root = home if home is not None else antigravity_home()
|
|
203
|
+
actions = {
|
|
204
|
+
"copied": [],
|
|
205
|
+
"plugin_dir": None,
|
|
206
|
+
"consent": None,
|
|
207
|
+
"skipped": [],
|
|
208
|
+
"dry_run": dry_run,
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
pdir = plugin_dir(root)
|
|
212
|
+
# One lstat, not exists()+is_dir(): a concurrent installer can move the
|
|
213
|
+
# directory aside between two stat calls, and the second one would then
|
|
214
|
+
# report "not a directory" for a path that simply vanished.
|
|
215
|
+
try:
|
|
216
|
+
_pdir_st = os.lstat(pdir)
|
|
217
|
+
except FileNotFoundError:
|
|
218
|
+
_pdir_st = None
|
|
219
|
+
if _pdir_st is not None and (
|
|
220
|
+
_stat.S_ISLNK(_pdir_st.st_mode) or not _stat.S_ISDIR(_pdir_st.st_mode)
|
|
221
|
+
):
|
|
222
|
+
raise RuntimeError(
|
|
223
|
+
f"{pdir} exists but is not a directory — refusing to install. "
|
|
224
|
+
"Move it aside and re-run."
|
|
225
|
+
)
|
|
226
|
+
if _pdir_st is not None:
|
|
227
|
+
try:
|
|
228
|
+
resolved = pdir.resolve(strict=False)
|
|
229
|
+
if not resolved.is_relative_to(root.resolve(strict=False)):
|
|
230
|
+
raise RuntimeError(
|
|
231
|
+
f"{pdir} resolves outside the Antigravity home — refusing to install."
|
|
232
|
+
)
|
|
233
|
+
except (OSError, ValueError):
|
|
234
|
+
raise RuntimeError(f"{pdir} is unsafe — refusing to install.")
|
|
235
|
+
|
|
236
|
+
# Resolve/validate the payload before writing anything.
|
|
237
|
+
for name in _PAYLOAD_MODULES:
|
|
238
|
+
src = _SCRIPT_DIR / name
|
|
239
|
+
if not src.is_file():
|
|
240
|
+
actions["skipped"].append(name)
|
|
241
|
+
if actions["skipped"]:
|
|
242
|
+
raise RuntimeError(
|
|
243
|
+
"missing payload modules in this checkout: "
|
|
244
|
+
f"{actions['skipped']} — refusing to wire hooks against an incomplete bridge."
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
if not dry_run:
|
|
248
|
+
# Build the payload in a staging dir and swap it in atomically. Two
|
|
249
|
+
# concurrent installs (or an install racing a reader) must never see a
|
|
250
|
+
# half-copied plugin dir: hooks.json and plugin.json would register
|
|
251
|
+
# against a partial payload and the bridge would fail on every fire.
|
|
252
|
+
import tempfile
|
|
253
|
+
_ensure_config_dir_permissions(pdir.parent)
|
|
254
|
+
staging = Path(tempfile.mkdtemp(prefix=f".{pdir.name}.stage.", dir=str(pdir.parent)))
|
|
255
|
+
trash_dirs: list[Path] = []
|
|
256
|
+
staging_moved = False
|
|
257
|
+
try:
|
|
258
|
+
try:
|
|
259
|
+
for name in _PAYLOAD_MODULES:
|
|
260
|
+
src = _SCRIPT_DIR / name
|
|
261
|
+
shutil.copy2(src, staging / name)
|
|
262
|
+
actions["copied"].append(name)
|
|
263
|
+
|
|
264
|
+
# measure-path locator: name the checkout's measure.py (KTD5).
|
|
265
|
+
(staging / "measure-path").write_text(
|
|
266
|
+
str(_SCRIPT_DIR / "measure.py") + "\n", encoding="utf-8"
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
# Write hooks.json, then plugin.json LAST so a partial payload
|
|
270
|
+
# never registers hooks (R1/U5).
|
|
271
|
+
(staging / "hooks.json").write_text(
|
|
272
|
+
json.dumps(_hooks_config(staging / "antigravity_hook_bridge.py"), indent=2)
|
|
273
|
+
+ "\n",
|
|
274
|
+
encoding="utf-8",
|
|
275
|
+
)
|
|
276
|
+
(staging / "plugin.json").write_text(
|
|
277
|
+
json.dumps({"name": HOOK_NAME}, indent=2) + "\n", encoding="utf-8"
|
|
278
|
+
)
|
|
279
|
+
os.chmod(staging, 0o700)
|
|
280
|
+
except OSError as exc:
|
|
281
|
+
raise RuntimeError(f"failed staging plugin payload: {exc}") from exc
|
|
282
|
+
|
|
283
|
+
# Swap: move any existing dir aside, move staging in. Concurrent
|
|
284
|
+
# installers interleave the two renames, so a losing os.replace
|
|
285
|
+
# (target re-populated between exists-check and rename) retries
|
|
286
|
+
# until it wins or the budget is spent.
|
|
287
|
+
last_swap_error: OSError | None = None
|
|
288
|
+
for _attempt in range(10):
|
|
289
|
+
if pdir.exists():
|
|
290
|
+
trash = pdir.parent / f".{pdir.name}.old.{os.getpid()}.{_attempt}"
|
|
291
|
+
try:
|
|
292
|
+
os.replace(pdir, trash)
|
|
293
|
+
except FileNotFoundError:
|
|
294
|
+
pass # another installer moved it aside first
|
|
295
|
+
except OSError as exc:
|
|
296
|
+
raise RuntimeError(f"failed activating plugin dir: {exc}") from exc
|
|
297
|
+
trash_dirs.append(trash)
|
|
298
|
+
try:
|
|
299
|
+
os.replace(staging, pdir)
|
|
300
|
+
staging_moved = True
|
|
301
|
+
break
|
|
302
|
+
except OSError as exc:
|
|
303
|
+
last_swap_error = exc
|
|
304
|
+
if not staging_moved:
|
|
305
|
+
raise RuntimeError(f"failed activating plugin dir: {last_swap_error}")
|
|
306
|
+
finally:
|
|
307
|
+
for trash in trash_dirs:
|
|
308
|
+
if trash.exists():
|
|
309
|
+
shutil.rmtree(trash, ignore_errors=True)
|
|
310
|
+
if not staging_moved:
|
|
311
|
+
shutil.rmtree(staging, ignore_errors=True)
|
|
312
|
+
|
|
313
|
+
_write_consent(root)
|
|
314
|
+
actions["consent"] = str(data_dir(root) / "config.json")
|
|
315
|
+
|
|
316
|
+
actions["plugin_dir"] = str(pdir)
|
|
317
|
+
return actions
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def uninstall(*, dry_run: bool = False, home: Path | None = None) -> dict:
|
|
321
|
+
"""Remove ONLY what install() created (the plugin directory). Session data
|
|
322
|
+
and trends stay in place (R3)."""
|
|
323
|
+
root = home if home is not None else antigravity_home()
|
|
324
|
+
pdir = plugin_dir(root)
|
|
325
|
+
actions = {"removed": [], "dry_run": dry_run}
|
|
326
|
+
if pdir.exists() or pdir.is_symlink():
|
|
327
|
+
if not dry_run:
|
|
328
|
+
# rmtree on the symlink itself raises; rmdir is used for symlinks.
|
|
329
|
+
try:
|
|
330
|
+
if pdir.is_symlink() or pdir.is_file():
|
|
331
|
+
pdir.unlink()
|
|
332
|
+
else:
|
|
333
|
+
shutil.rmtree(pdir)
|
|
334
|
+
except OSError as exc:
|
|
335
|
+
raise RuntimeError(f"failed removing {pdir}: {exc}") from exc
|
|
336
|
+
actions["removed"].append(str(pdir))
|
|
337
|
+
return actions
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
341
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
342
|
+
parser.add_argument("action", choices=("install", "uninstall"))
|
|
343
|
+
parser.add_argument("--dry-run", action="store_true")
|
|
344
|
+
return parser
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def main(argv=None) -> int:
|
|
348
|
+
args = build_parser().parse_args(argv)
|
|
349
|
+
try:
|
|
350
|
+
if args.action == "install":
|
|
351
|
+
result = install(dry_run=args.dry_run)
|
|
352
|
+
verb = "Would install" if args.dry_run else "Installed"
|
|
353
|
+
print(f"{verb} Token Optimizer for Google Antigravity.")
|
|
354
|
+
print(f" Plugin directory: {result['plugin_dir']}")
|
|
355
|
+
if not args.dry_run:
|
|
356
|
+
print(f" Modules: {len(result['copied'])} copied")
|
|
357
|
+
print(f" Consent: {result['consent']}")
|
|
358
|
+
print(_hint(" Run `python3 measure.py antigravity-doctor` to verify readiness."))
|
|
359
|
+
else:
|
|
360
|
+
result = uninstall(dry_run=args.dry_run)
|
|
361
|
+
verb = "Would remove" if args.dry_run else "Removed"
|
|
362
|
+
for item in result["removed"] or ["(nothing installed)"]:
|
|
363
|
+
print(f"{verb}: {item}")
|
|
364
|
+
if not args.dry_run and result["removed"]:
|
|
365
|
+
print(
|
|
366
|
+
" Note: <home>/config/config.json may keep a stale `plugins` "
|
|
367
|
+
"entry, which Antigravity ignores once the plugin dir is gone."
|
|
368
|
+
)
|
|
369
|
+
return 0
|
|
370
|
+
except RuntimeError as exc:
|
|
371
|
+
print(f"[Token Optimizer] {exc}", file=sys.stderr)
|
|
372
|
+
return 1
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
if __name__ == "__main__":
|
|
376
|
+
sys.exit(main())
|