@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,511 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Token Optimizer — Google Antigravity hook bridge.
|
|
3
|
+
|
|
4
|
+
One fast, fail-open entry point for the three wired Antigravity lifecycle
|
|
5
|
+
events, registered via ``~/.gemini/config/plugins/token-optimizer/hooks.json``:
|
|
6
|
+
|
|
7
|
+
pre-invocation -> continuity restore (invocationNum 1) or context nudge
|
|
8
|
+
pre-tool-use -> bash output compression (run_command only)
|
|
9
|
+
stop -> detached rollup + dashboard regeneration
|
|
10
|
+
|
|
11
|
+
Design contract (R15): every handler exits 0 and emits EITHER one JSON object
|
|
12
|
+
or nothing, on any error, malformed stdin, oversize stdin (over 4 MB), or a
|
|
13
|
+
missing dependency. Consent-gated (R20): without the install record in
|
|
14
|
+
``~/.gemini/token-optimizer/config.json`` every handler no-ops to ``{}``.
|
|
15
|
+
|
|
16
|
+
Hot-path imports stay stdlib + the copied payload modules (runtime_env,
|
|
17
|
+
bash_hook, spawn_utils). ``measure.py`` is never imported here — the Stop hook
|
|
18
|
+
locates it through the ``measure-path`` locator written by the installer (KTD5,
|
|
19
|
+
the Hermes installer precedent).
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import shlex
|
|
27
|
+
import subprocess
|
|
28
|
+
import sys
|
|
29
|
+
import tempfile
|
|
30
|
+
import time
|
|
31
|
+
from pathlib import Path
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
from utf8_io import enforce_utf8_io # noqa: PLC0415
|
|
35
|
+
except Exception: # pragma: no cover
|
|
36
|
+
|
|
37
|
+
def enforce_utf8_io() -> None:
|
|
38
|
+
pass
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
_CONVERSATION_ID_RE = None
|
|
42
|
+
try:
|
|
43
|
+
import re as _re
|
|
44
|
+
|
|
45
|
+
_CONVERSATION_ID_RE = _re.compile(r"^[0-9a-f-]{1,64}$")
|
|
46
|
+
except Exception: # pragma: no cover
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
_STDIN_MAX_BYTES = 4 * 1024 * 1024 # 4 MB (R15)
|
|
50
|
+
_RESTORE_MAX_BYTES = 16 * 1024 # 16 KB (R11)
|
|
51
|
+
_FIELD_MAX_CHARS = 200 # R22 per-field cap
|
|
52
|
+
_NUDGE_STATE_TTL_SECONDS = 7 * 86400
|
|
53
|
+
_ROLLUP_LEASE_SECONDS = 30
|
|
54
|
+
|
|
55
|
+
_SURFACES = ("antigravity-cli", "antigravity", "antigravity-ide")
|
|
56
|
+
|
|
57
|
+
_SCRIPT_DIR = Path(__file__).resolve().parent
|
|
58
|
+
_MEASURE_LOCATOR = _SCRIPT_DIR / "measure-path"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _to_dir(home: Path) -> Path:
|
|
62
|
+
return home / "token-optimizer"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _consent_ok(home: Path) -> bool:
|
|
66
|
+
"""True when the installer recorded data consent."""
|
|
67
|
+
config_path = _to_dir(home) / "config.json"
|
|
68
|
+
try:
|
|
69
|
+
if not config_path.is_file():
|
|
70
|
+
return False
|
|
71
|
+
cfg = json.loads(config_path.read_text(encoding="utf-8"))
|
|
72
|
+
return bool(isinstance(cfg, dict) and cfg.get("antigravity_consent"))
|
|
73
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
74
|
+
return False
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _clean_field(value, max_chars: int = _FIELD_MAX_CHARS) -> str:
|
|
78
|
+
"""Printable-only, single-line, length-capped text (R22)."""
|
|
79
|
+
text = str(value or "")
|
|
80
|
+
text = "".join(ch if ch == " " or ch.isprintable() else " " for ch in text)
|
|
81
|
+
return " ".join(text.split())[:max_chars]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _read_payload() -> dict | None:
|
|
85
|
+
"""Read the hook JSON payload from stdin with a 4 MB cap."""
|
|
86
|
+
try:
|
|
87
|
+
data = sys.stdin.buffer.read(_STDIN_MAX_BYTES + 1)
|
|
88
|
+
except (OSError, AttributeError):
|
|
89
|
+
return None
|
|
90
|
+
if not data:
|
|
91
|
+
return {}
|
|
92
|
+
if len(data) > _STDIN_MAX_BYTES:
|
|
93
|
+
return None
|
|
94
|
+
try:
|
|
95
|
+
obj = json.loads(data.decode("utf-8", errors="replace"))
|
|
96
|
+
except (json.JSONDecodeError, ValueError):
|
|
97
|
+
return None
|
|
98
|
+
return obj if isinstance(obj, dict) else None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _emit(obj: dict) -> None:
|
|
102
|
+
"""Write exactly one JSON object to stdout."""
|
|
103
|
+
try:
|
|
104
|
+
sys.stdout.write(json.dumps(obj))
|
|
105
|
+
sys.stdout.flush()
|
|
106
|
+
except (OSError, ValueError):
|
|
107
|
+
pass
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
# ---------------------------------------------------------------------------
|
|
111
|
+
# PreInvocation
|
|
112
|
+
# ---------------------------------------------------------------------------
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _restore_message(home: Path) -> str | None:
|
|
116
|
+
restore_path = _to_dir(home) / "restore-context.md"
|
|
117
|
+
try:
|
|
118
|
+
if (
|
|
119
|
+
not restore_path.is_file()
|
|
120
|
+
or restore_path.stat().st_size > _RESTORE_MAX_BYTES
|
|
121
|
+
):
|
|
122
|
+
return None
|
|
123
|
+
content = restore_path.read_text(encoding="utf-8", errors="replace")
|
|
124
|
+
except OSError:
|
|
125
|
+
return None
|
|
126
|
+
if not content:
|
|
127
|
+
return None
|
|
128
|
+
# Defense-in-depth: re-clean every line (printable, single-line, capped).
|
|
129
|
+
cleaned = "\n".join(_clean_field(line) for line in content.splitlines())
|
|
130
|
+
return cleaned.strip() or None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _surface_dir_for_transcript(home: Path, transcript_path) -> Path | None:
|
|
134
|
+
"""Resolve the surface directory from transcriptPath's parent basename.
|
|
135
|
+
|
|
136
|
+
The Antigravity hook contract names the surface as the immediate parent
|
|
137
|
+
directory of the transcript (e.g. ``.../.gemini/antigravity-cli/transcript.jsonl``).
|
|
138
|
+
Anything else is rejected (no file access), the KTD6 exact-parent match.
|
|
139
|
+
"""
|
|
140
|
+
try:
|
|
141
|
+
parent = Path(str(transcript_path)).parent
|
|
142
|
+
if parent.name not in _SURFACES:
|
|
143
|
+
return None
|
|
144
|
+
surf = home / parent.name
|
|
145
|
+
return surf if (surf.is_dir() and not surf.is_symlink()) else None
|
|
146
|
+
except (OSError, ValueError):
|
|
147
|
+
return None
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _live_fill(surface_dir: Path, conversation_id: str) -> float | None:
|
|
151
|
+
try:
|
|
152
|
+
from antigravity_state import read_live_conversation
|
|
153
|
+
except Exception:
|
|
154
|
+
return None
|
|
155
|
+
db = surface_dir / "conversations" / f"{conversation_id}.db"
|
|
156
|
+
session = read_live_conversation(db)
|
|
157
|
+
if session is None:
|
|
158
|
+
return None
|
|
159
|
+
return session.get("last_fill")
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _current_fill_from_payload(home: Path, payload: dict) -> float | None:
|
|
163
|
+
conversation_id = str(payload.get("conversationId") or "")
|
|
164
|
+
if not _CONVERSATION_ID_RE or not _CONVERSATION_ID_RE.match(conversation_id):
|
|
165
|
+
return None
|
|
166
|
+
surface_dir = _surface_dir_for_transcript(home, payload.get("transcriptPath") or "")
|
|
167
|
+
if surface_dir is None:
|
|
168
|
+
return None
|
|
169
|
+
return _live_fill(surface_dir, conversation_id)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _nudge_state_path(home: Path, conversation_id: str) -> Path:
|
|
173
|
+
return _to_dir(home) / "nudge-state" / f"{conversation_id}.json"
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _nudge_already_sent(home: Path, conversation_id: str, threshold: str) -> bool:
|
|
177
|
+
path = _nudge_state_path(home, conversation_id)
|
|
178
|
+
try:
|
|
179
|
+
if not path.is_file():
|
|
180
|
+
return False
|
|
181
|
+
state = json.loads(path.read_text(encoding="utf-8"))
|
|
182
|
+
return bool(isinstance(state, dict) and state.get(threshold))
|
|
183
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
184
|
+
return False
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _record_nudge(home: Path, conversation_id: str, threshold: str) -> None:
|
|
188
|
+
_sweep_nudge_state(home)
|
|
189
|
+
path = _nudge_state_path(home, conversation_id)
|
|
190
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
191
|
+
# Two hook processes can fire for the same conversation concurrently; an
|
|
192
|
+
# unlocked read-modify-write loses one writer's threshold key and the
|
|
193
|
+
# nudge fires twice. Serialize the whole RMW on a sidecar lock file.
|
|
194
|
+
lock_fd = None
|
|
195
|
+
try:
|
|
196
|
+
lock_fd = os.open(str(path.parent / f".{path.name}.lock"), os.O_CREAT | os.O_RDWR, 0o600)
|
|
197
|
+
import fcntl
|
|
198
|
+
fcntl.flock(lock_fd, fcntl.LOCK_EX)
|
|
199
|
+
except Exception:
|
|
200
|
+
if lock_fd is not None:
|
|
201
|
+
try:
|
|
202
|
+
os.close(lock_fd)
|
|
203
|
+
except OSError:
|
|
204
|
+
pass
|
|
205
|
+
lock_fd = None # no lock available: proceed, best-effort
|
|
206
|
+
try:
|
|
207
|
+
state: dict = {}
|
|
208
|
+
try:
|
|
209
|
+
if path.is_file():
|
|
210
|
+
state = json.loads(path.read_text(encoding="utf-8"))
|
|
211
|
+
if not isinstance(state, dict):
|
|
212
|
+
state = {}
|
|
213
|
+
except (OSError, json.JSONDecodeError, ValueError):
|
|
214
|
+
state = {}
|
|
215
|
+
state[threshold] = True
|
|
216
|
+
fd, tmp = tempfile.mkstemp(prefix=".nudge.", suffix=".tmp", dir=str(path.parent))
|
|
217
|
+
try:
|
|
218
|
+
with os.fdopen(fd, "w", encoding="utf-8") as fh:
|
|
219
|
+
json.dump(state, fh)
|
|
220
|
+
os.replace(tmp, str(path))
|
|
221
|
+
except OSError:
|
|
222
|
+
try:
|
|
223
|
+
os.unlink(tmp)
|
|
224
|
+
except OSError:
|
|
225
|
+
pass
|
|
226
|
+
finally:
|
|
227
|
+
if lock_fd is not None:
|
|
228
|
+
try:
|
|
229
|
+
import fcntl
|
|
230
|
+
fcntl.flock(lock_fd, fcntl.LOCK_UN)
|
|
231
|
+
except Exception:
|
|
232
|
+
pass
|
|
233
|
+
try:
|
|
234
|
+
os.close(lock_fd)
|
|
235
|
+
except OSError:
|
|
236
|
+
pass
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _sweep_nudge_state(home: Path) -> None:
|
|
240
|
+
ndir = _to_dir(home) / "nudge-state"
|
|
241
|
+
try:
|
|
242
|
+
if not ndir.is_dir():
|
|
243
|
+
return
|
|
244
|
+
cutoff = time.time() - _NUDGE_STATE_TTL_SECONDS
|
|
245
|
+
for p in ndir.glob("*.json"):
|
|
246
|
+
try:
|
|
247
|
+
if p.stat().st_mtime < cutoff:
|
|
248
|
+
p.unlink()
|
|
249
|
+
except OSError:
|
|
250
|
+
continue
|
|
251
|
+
except OSError:
|
|
252
|
+
pass
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def handle_pre_invocation(payload: dict) -> dict:
|
|
256
|
+
try:
|
|
257
|
+
from runtime_env import antigravity_home
|
|
258
|
+
except Exception:
|
|
259
|
+
return {}
|
|
260
|
+
home = antigravity_home()
|
|
261
|
+
|
|
262
|
+
invocation_num = payload.get("invocationNum")
|
|
263
|
+
try:
|
|
264
|
+
invocation_num = int(invocation_num)
|
|
265
|
+
except (TypeError, ValueError):
|
|
266
|
+
invocation_num = 0
|
|
267
|
+
|
|
268
|
+
if invocation_num == 1:
|
|
269
|
+
message = _restore_message(home)
|
|
270
|
+
if message:
|
|
271
|
+
return {"injectSteps": [{"ephemeralMessage": message}]}
|
|
272
|
+
return {}
|
|
273
|
+
|
|
274
|
+
if invocation_num <= 1:
|
|
275
|
+
return {}
|
|
276
|
+
|
|
277
|
+
fill = _current_fill_from_payload(home, payload)
|
|
278
|
+
try:
|
|
279
|
+
if fill is None or not (0.0 <= fill <= 1.0):
|
|
280
|
+
return {}
|
|
281
|
+
except (TypeError, ValueError):
|
|
282
|
+
return {}
|
|
283
|
+
|
|
284
|
+
conversation_id = str(payload.get("conversationId") or "")
|
|
285
|
+
|
|
286
|
+
if fill >= 0.85:
|
|
287
|
+
if _nudge_already_sent(home, conversation_id, "85"):
|
|
288
|
+
return {}
|
|
289
|
+
_record_nudge(home, conversation_id, "85")
|
|
290
|
+
return {
|
|
291
|
+
"injectSteps": [
|
|
292
|
+
{
|
|
293
|
+
"ephemeralMessage": (
|
|
294
|
+
"[Token Optimizer] Context is above 85% full. Prefer small, focused "
|
|
295
|
+
"changes; start a fresh conversation soon to avoid truncation."
|
|
296
|
+
)
|
|
297
|
+
}
|
|
298
|
+
]
|
|
299
|
+
}
|
|
300
|
+
if fill >= 0.70:
|
|
301
|
+
if _nudge_already_sent(home, conversation_id, "70"):
|
|
302
|
+
return {}
|
|
303
|
+
_record_nudge(home, conversation_id, "70")
|
|
304
|
+
return {
|
|
305
|
+
"injectSteps": [
|
|
306
|
+
{
|
|
307
|
+
"ephemeralMessage": (
|
|
308
|
+
"[Token Optimizer] Context is above 70% full. Keep prompts tight."
|
|
309
|
+
)
|
|
310
|
+
}
|
|
311
|
+
]
|
|
312
|
+
}
|
|
313
|
+
return {}
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
# ---------------------------------------------------------------------------
|
|
317
|
+
# PreToolUse
|
|
318
|
+
# ---------------------------------------------------------------------------
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def handle_pre_tool_use(payload: dict) -> dict:
|
|
322
|
+
if os.name == "nt":
|
|
323
|
+
return {}
|
|
324
|
+
if os.environ.get("TOKEN_OPTIMIZER_BASH_COMPRESS", "").strip() == "0":
|
|
325
|
+
return {}
|
|
326
|
+
|
|
327
|
+
tool_call = payload.get("toolCall")
|
|
328
|
+
if not isinstance(tool_call, dict):
|
|
329
|
+
return {}
|
|
330
|
+
if tool_call.get("name") != "run_command":
|
|
331
|
+
return {}
|
|
332
|
+
args = tool_call.get("args")
|
|
333
|
+
if not isinstance(args, dict):
|
|
334
|
+
return {}
|
|
335
|
+
command = args.get("CommandLine")
|
|
336
|
+
if not isinstance(command, str) or not command:
|
|
337
|
+
return {}
|
|
338
|
+
|
|
339
|
+
try:
|
|
340
|
+
import bash_hook as _bash_hook
|
|
341
|
+
except Exception:
|
|
342
|
+
return {}
|
|
343
|
+
|
|
344
|
+
if _bash_hook._has_dangerous_chars(command):
|
|
345
|
+
return {}
|
|
346
|
+
if not _bash_hook._is_whitelisted(command):
|
|
347
|
+
return {}
|
|
348
|
+
|
|
349
|
+
compress_path = _SCRIPT_DIR / "bash_compress.py"
|
|
350
|
+
try:
|
|
351
|
+
if not compress_path.is_file():
|
|
352
|
+
return {}
|
|
353
|
+
original_tokens = shlex.split(command)
|
|
354
|
+
if not original_tokens:
|
|
355
|
+
return {}
|
|
356
|
+
except ValueError:
|
|
357
|
+
return {}
|
|
358
|
+
|
|
359
|
+
rewritten = (
|
|
360
|
+
shlex.quote(sys.executable)
|
|
361
|
+
+ " -E -s "
|
|
362
|
+
+ shlex.quote(str(compress_path))
|
|
363
|
+
+ " "
|
|
364
|
+
+ " ".join(shlex.quote(t) for t in original_tokens)
|
|
365
|
+
)
|
|
366
|
+
# decision "ask" defers to the user's permission mode + "always allow" cache
|
|
367
|
+
# (R13); we never emit allow/permissionOverrides or forward model fields.
|
|
368
|
+
return {"decision": "ask", "overwrite": {"CommandLine": rewritten}}
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
# ---------------------------------------------------------------------------
|
|
372
|
+
# Stop
|
|
373
|
+
# ---------------------------------------------------------------------------
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
def _locate_measure_py() -> Path | None:
|
|
377
|
+
if _MEASURE_LOCATOR.is_file():
|
|
378
|
+
try:
|
|
379
|
+
located = Path(_MEASURE_LOCATOR.read_text(encoding="utf-8").strip())
|
|
380
|
+
if located.is_file():
|
|
381
|
+
return located
|
|
382
|
+
except (OSError, ValueError):
|
|
383
|
+
pass
|
|
384
|
+
sibling = _SCRIPT_DIR / "measure.py"
|
|
385
|
+
if sibling.is_file():
|
|
386
|
+
return sibling
|
|
387
|
+
return None
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _rollup_lease_held(home: Path) -> bool:
|
|
391
|
+
lease = _to_dir(home) / "rollup.lease"
|
|
392
|
+
try:
|
|
393
|
+
if not lease.exists():
|
|
394
|
+
return False
|
|
395
|
+
if (time.time() - lease.stat().st_mtime) < _ROLLUP_LEASE_SECONDS:
|
|
396
|
+
return True
|
|
397
|
+
return False
|
|
398
|
+
except OSError:
|
|
399
|
+
return False
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def _touch_rollup_lease(home: Path) -> None:
|
|
403
|
+
lease = _to_dir(home) / "rollup.lease"
|
|
404
|
+
try:
|
|
405
|
+
lease.parent.mkdir(parents=True, exist_ok=True)
|
|
406
|
+
lease.touch()
|
|
407
|
+
except OSError:
|
|
408
|
+
pass
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def handle_stop(payload: dict) -> dict:
|
|
412
|
+
try:
|
|
413
|
+
from runtime_env import antigravity_home
|
|
414
|
+
except Exception:
|
|
415
|
+
return {}
|
|
416
|
+
home = antigravity_home()
|
|
417
|
+
if _rollup_lease_held(home):
|
|
418
|
+
return {}
|
|
419
|
+
|
|
420
|
+
measure_py = _locate_measure_py()
|
|
421
|
+
if measure_py is None:
|
|
422
|
+
return {}
|
|
423
|
+
|
|
424
|
+
_touch_rollup_lease(home)
|
|
425
|
+
|
|
426
|
+
try:
|
|
427
|
+
from spawn_utils import spawn_detached
|
|
428
|
+
except Exception:
|
|
429
|
+
return {}
|
|
430
|
+
|
|
431
|
+
env = {
|
|
432
|
+
**os.environ,
|
|
433
|
+
"TOKEN_OPTIMIZER_RUNTIME": "antigravity",
|
|
434
|
+
"PYTHONUTF8": "1",
|
|
435
|
+
"PYTHONIOENCODING": "utf-8",
|
|
436
|
+
}
|
|
437
|
+
try:
|
|
438
|
+
spawn_detached(
|
|
439
|
+
[sys.executable, str(measure_py), "antigravity-rollup", "--quiet"],
|
|
440
|
+
env=env,
|
|
441
|
+
stdout=subprocess.DEVNULL,
|
|
442
|
+
stderr=subprocess.DEVNULL,
|
|
443
|
+
)
|
|
444
|
+
except Exception:
|
|
445
|
+
pass
|
|
446
|
+
try:
|
|
447
|
+
spawn_detached(
|
|
448
|
+
[sys.executable, str(measure_py), "dashboard", "--quiet"],
|
|
449
|
+
env={**env, "TOKEN_OPTIMIZER_INTERACTIVE": "1"},
|
|
450
|
+
stdout=subprocess.DEVNULL,
|
|
451
|
+
stderr=subprocess.DEVNULL,
|
|
452
|
+
)
|
|
453
|
+
except Exception:
|
|
454
|
+
pass
|
|
455
|
+
return {}
|
|
456
|
+
|
|
457
|
+
|
|
458
|
+
# ---------------------------------------------------------------------------
|
|
459
|
+
# Entry point
|
|
460
|
+
# ---------------------------------------------------------------------------
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def main(argv=None) -> int:
|
|
464
|
+
try:
|
|
465
|
+
enforce_utf8_io()
|
|
466
|
+
except Exception:
|
|
467
|
+
pass
|
|
468
|
+
|
|
469
|
+
event = ""
|
|
470
|
+
if argv:
|
|
471
|
+
event = argv[0]
|
|
472
|
+
elif len(sys.argv) > 1:
|
|
473
|
+
event = sys.argv[1]
|
|
474
|
+
|
|
475
|
+
payload = _read_payload() or {}
|
|
476
|
+
|
|
477
|
+
try:
|
|
478
|
+
from runtime_env import antigravity_home
|
|
479
|
+
except Exception:
|
|
480
|
+
return 0
|
|
481
|
+
|
|
482
|
+
try:
|
|
483
|
+
if not _consent_ok(antigravity_home()):
|
|
484
|
+
_emit({})
|
|
485
|
+
return 0
|
|
486
|
+
|
|
487
|
+
if event == "pre-invocation":
|
|
488
|
+
out = handle_pre_invocation(payload)
|
|
489
|
+
elif event == "pre-tool-use":
|
|
490
|
+
out = handle_pre_tool_use(payload)
|
|
491
|
+
elif event == "stop":
|
|
492
|
+
out = handle_stop(payload)
|
|
493
|
+
else:
|
|
494
|
+
return 0
|
|
495
|
+
_emit(out)
|
|
496
|
+
except Exception:
|
|
497
|
+
# Fail open: never break the Antigravity loop (R15). But never
|
|
498
|
+
# silently: a hook that never fires is undiagnosable without a trace.
|
|
499
|
+
# Guarded — a closed/full stderr must not turn fail-open into
|
|
500
|
+
# fail-hung.
|
|
501
|
+
try:
|
|
502
|
+
import traceback
|
|
503
|
+
traceback.print_exc(file=sys.stderr)
|
|
504
|
+
except Exception:
|
|
505
|
+
pass
|
|
506
|
+
return 0
|
|
507
|
+
return 0
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
if __name__ == "__main__":
|
|
511
|
+
sys.exit(main(sys.argv[1:2]))
|