tokensafe 2.2.1 → 2.3.0
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/README.md +6 -5
- package/hooks/__pycache__/pre_invocation.cpython-313.pyc +0 -0
- package/hooks/__pycache__/pre_tool_use.cpython-313.pyc +0 -0
- package/hooks/__pycache__/session_start.cpython-313.pyc +0 -0
- package/hooks/__pycache__/stop_hook.cpython-313.pyc +0 -0
- package/hooks/claude_code_hook.py +13 -1
- package/hooks/pre_invocation.py +31 -58
- package/hooks/pre_tool_use.py +12 -7
- package/hooks/session_start.py +88 -0
- package/hooks/stop_hook.py +86 -0
- package/hooks.json +15 -1
- package/mcp_config.json +11 -0
- package/package.json +2 -1
- package/plugin.json +2 -2
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +9 -151
- package/skills/token-optimizer/references/cli-reference.md +31 -0
- package/skills/token-optimizer/references/guard-checks.md +17 -0
- package/skills/token-optimizer/references/mcp-tools.md +101 -0
- package/src/adapter_core.py +13 -0
- package/src/cli.py +12 -4
- package/src/command_sanitizer.py +155 -3
- package/src/compactor.py +0 -1
- package/src/distiller_cache.py +3 -2
- package/src/environment_auditor.py +147 -22
- package/src/history_compactor.py +4 -2
- package/src/installer.py +107 -12
- package/src/license_manager.py +3 -1
- package/src/mcp_server.py +16 -7
- package/src/metrics.py +3 -4
- package/src/paths.py +86 -0
- package/src/proxy.py +3 -5
- package/src/team_cache.py +2 -1
- package/src/telemetry_sync.py +4 -2
- package/src/version_checker.py +4 -2
- package/src/weekly_digest.py +7 -5
package/README.md
CHANGED
|
@@ -48,7 +48,7 @@ pip install tokensafe && tokensafe
|
|
|
48
48
|
curl -fsSL https://tokensafe.dev/install.sh | bash
|
|
49
49
|
```
|
|
50
50
|
|
|
51
|
-
On **Google Antigravity**, the installer additionally symlinks the plugin into `~/.gemini/config/plugins/
|
|
51
|
+
On **Google Antigravity**, the installer additionally symlinks the plugin into `~/.gemini/config/plugins/tokensafe` — Antigravity loads it automatically on startup (stale `agy-token-optimizer` symlinks from older versions are removed, since Antigravity keys plugin enable-state by folder name and would run every hook twice). Once the plugin ships its own `mcp_config.json`, any leftover user-level `tokensafe` MCP entry in Antigravity's configs is migrated away (backed up first) so the server is not registered twice.
|
|
52
52
|
|
|
53
53
|
### Optional Dependency: `cryptography` (Recommended)
|
|
54
54
|
|
|
@@ -75,6 +75,7 @@ Beyond MCP, TokenSafe installs native lifecycle-hook adapters inside your agent
|
|
|
75
75
|
|
|
76
76
|
| Agent | Hook | What it does |
|
|
77
77
|
|---|---|---|
|
|
78
|
+
| **Claude Code** | `SessionStart` | Injects the TokenSafe protocol directives once per session as `additionalContext` (mirrors the Antigravity SessionStart hook) |
|
|
78
79
|
| **Claude Code** | `UserPromptSubmit` | Compacts the prompt into a TOCP S-expression and injects it as `additionalContext` (labeled *estimated* per [METRICS.md](METRICS.md)) |
|
|
79
80
|
| **Claude Code** | `PreToolUse` (Bash) | Blocks secret-bearing and destructive commands; prompts for confirmation on TLS-verification bypasses |
|
|
80
81
|
| **Cursor** | `beforeShellExecution` | Same shell guard: blocks secret leaks and destructive actions, asks on `-k` or `--insecure` |
|
|
@@ -83,6 +84,8 @@ Beyond MCP, TokenSafe installs native lifecycle-hook adapters inside your agent
|
|
|
83
84
|
|
|
84
85
|
All adapters **fail open**: an internal error never stalls the host agent. Cursor's strict valid-JSON response contract is preserved on every error path.
|
|
85
86
|
|
|
87
|
+
For **team workspaces on Antigravity**, `tokensafe install --project --agents-plugin <path-to-tokensafe>` additionally declares the plugin in the project's `.agents/plugins.json`, so teammates load hooks, skills, and the MCP server straight from the shared repo without running the installer.
|
|
88
|
+
|
|
86
89
|
## Context Budget HUD & Governor
|
|
87
90
|
|
|
88
91
|
Teams usually notice context exhaustion only when code quality drops mid-task. TokenSafe exposes live window usage as a native MCP tool:
|
|
@@ -156,6 +159,7 @@ Once engineering teams tested it, lower bills turned out to be the secondary ben
|
|
|
156
159
|
| :--- | :--- | :--- |
|
|
157
160
|
| **"Lost in the Middle" context fade**<br>An agent reads a 2,000-line file to change one 10-line helper, forgets imports, and invents methods. | **AST Skeletonizer** (`src/slicer.py`) folds inert bodies into typed signatures while keeping the target symbol and 1-hop callees intact. | **Focused signal.** The model keeps full type contracts without drowning in unrelated logic. |
|
|
158
161
|
| **Terminal log flooding**<br>`npm test` or `pytest` fails and dumps 4,000 lines of stack traces and lockfile diffs into context. | **Command Sanitizer** (`src/command_sanitizer.py`) strips lockfile noise and trims output to the failing assertion and stack frame. | **Root-cause fixes.** The agent repairs the actual bug instead of rewriting unrelated files. |
|
|
162
|
+
| **Infinite wait on background tests**<br>An agent launches `yarn test` in the background and blocks forever: `--watchAll=false` no-ops against a watch-mode script, CRA turns watch on by default outside CI, or jest finishes but unclosed handles keep the process alive. | **Test-Runner Guard** (`src/command_sanitizer.py`) forces run-once mode on every JS test command — `CI=true`, `--watch=false`, `--forceExit` — and peeks at `<cwd>/package.json` (hook payload or MCP `cwd` argument) to identify the runner behind opaque `yarn/npm test` scripts. | **No more hangs.** The test run terminates with an exit code and the agent moves on. |
|
|
159
163
|
| **5-attempt retry loops**<br>An agent repeats the same broken edit five times in a row until the context budget runs dry. | **Loop Guard** (`src/loop_detector.py`) detects repeated identical tool calls and halts the cycle. | **Fewer regressions.** Stuck loops stop before damaging working modules. |
|
|
160
164
|
| **Verbose prompts & token arbitrage**<br>Loose phrasing like *"fix auth without breaking cache"* leads to wide, risky rewrites. | **TOCP Intent Compactor** (`src/compactor.py`) distills instructions into compact S-expressions (`-40% to -70%`) with strict scope bounds. | **Clear scope.** Example: `(DEBUG auth.ts [jwt] "fix 401 token expiry")`. |
|
|
161
165
|
| **Unsafe edits & secret leaks**<br>An agent hardcodes fallback keys, sets `verify=False`, builds SQL with f-strings, or runs `git add .` with `.env` present. | **TokenSafe Guard** (`src/guard.py`) audits writes and shell commands locally before execution. | **Protected repositories.** Credentials, SQLi patterns, and destructive commands are blocked locally. |
|
|
@@ -302,7 +306,7 @@ To keep distillation overhead lower than the tokens it saves:
|
|
|
302
306
|
2. **Output Token Ceiling (`distill_max_tokens: 60`)**: Caps compiled output at 60 tokens to prevent compiler arbitrage loss.
|
|
303
307
|
3. **Three-Tier Cache**:
|
|
304
308
|
- **L1 (In-Memory LRU)**: Sub-millisecond hits inside active sessions.
|
|
305
|
-
- **L2 (Persistent SQLite)**: Stores normalized SHA-256 prompt hashes in
|
|
309
|
+
- **L2 (Persistent SQLite)**: Stores normalized SHA-256 prompt hashes in `~/.tokensafe/data/metrics.db` across restarts so repeated workflows (`git commit`, `run tests`, `fix lint`) cost 0 tokens. The directory is shared by all agents on the machine (override with `TOKENSAFE_DATA_DIR`; Docker uses `/app/data`).
|
|
306
310
|
- **L3 (Shared Team Cache)**: *Team Tier.* Syncs distilled intents and AST skeletons across teammates and CI runners (`/api/team/cache`) for warm 0ms team cache hits.
|
|
307
311
|
|
|
308
312
|
### 3. Provider & Cache Inspection
|
|
@@ -528,15 +532,12 @@ agy-token-optimizer/
|
|
|
528
532
|
│ ├── metrics.py # Persistent SQLite metrics engine
|
|
529
533
|
│ ├── dashboard.py # Visual ANSI terminal, Markdown & reactive SSE web dashboard
|
|
530
534
|
│ ├── license_manager.py # Ed25519 cryptographic license verification
|
|
531
|
-
│ ├── mailer.py # Transactional email & Friday ROI digest dispatcher
|
|
532
535
|
│ ├── mcp_server.py # Native Model Context Protocol (MCP) server
|
|
533
536
|
│ ├── installer.py # Multi-IDE agent auto-installer & config wizard
|
|
534
|
-
│ └── cloud_backend.py # Cloud REST backend & team telemetry API
|
|
535
537
|
├── hooks/
|
|
536
538
|
│ ├── pre_invocation.py # PreInvocation hook entry point
|
|
537
539
|
│ ├── pre_tool_use.py # PreToolUse hook entry point
|
|
538
540
|
│ └── post_tool_use.py # PostToolUse hook entry point
|
|
539
|
-
├── frontend/ # React / Vite / Tailwind Web App & Dashboard
|
|
540
541
|
├── bin/
|
|
541
542
|
│ ├── tokensafe.js # Node.js npm launcher (npx tokensafe)
|
|
542
543
|
│ └── tokensafe # Python CLI launcher (pip / standalone)
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -22,7 +22,7 @@ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
|
22
22
|
if PROJECT_ROOT not in sys.path:
|
|
23
23
|
sys.path.insert(0, PROJECT_ROOT)
|
|
24
24
|
|
|
25
|
-
from src.adapter_core import compact_for_injection, guard_command
|
|
25
|
+
from src.adapter_core import TOKENSAFE_DIRECTIVES, compact_for_injection, guard_command
|
|
26
26
|
|
|
27
27
|
AGENT = "claude_code"
|
|
28
28
|
|
|
@@ -30,6 +30,18 @@ AGENT = "claude_code"
|
|
|
30
30
|
def handle(event: str, payload: dict) -> dict:
|
|
31
31
|
session_id = str(payload.get("session_id") or "") or f"hook_{AGENT}"
|
|
32
32
|
|
|
33
|
+
if event == "SessionStart":
|
|
34
|
+
# One-shot session injection (mirrors the Antigravity SessionStart
|
|
35
|
+
# hook): persistent directives instead of per-turn re-injection.
|
|
36
|
+
# No matcher on `source` — inject for startup/resume/clear/compact.
|
|
37
|
+
# Well under the 10k-char additionalContext cap.
|
|
38
|
+
return {
|
|
39
|
+
"hookSpecificOutput": {
|
|
40
|
+
"hookEventName": "SessionStart",
|
|
41
|
+
"additionalContext": TOKENSAFE_DIRECTIVES,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
33
45
|
if event == "UserPromptSubmit":
|
|
34
46
|
prompt = str(payload.get("prompt") or "")
|
|
35
47
|
context, meta = compact_for_injection(prompt, AGENT, session_id)
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -6,6 +6,10 @@ Fires before the LLM is invoked.
|
|
|
6
6
|
2. Folds multi-turn history into Consolidated State Ledger if turns >= 3
|
|
7
7
|
3. Records metrics in SQLite
|
|
8
8
|
4. Injects compressed context and visual savings badge
|
|
9
|
+
|
|
10
|
+
One-shot session concerns (quota/bloat banners, protocol directives, version
|
|
11
|
+
check) live in session_start.py per the SessionStart hook contract — this
|
|
12
|
+
hook stays per-turn lean.
|
|
9
13
|
"""
|
|
10
14
|
|
|
11
15
|
import sys
|
|
@@ -20,8 +24,19 @@ from src.compactor import PromptCompactor
|
|
|
20
24
|
from src.history_compactor import HistoryCompactor
|
|
21
25
|
from src.metrics import MetricsTracker
|
|
22
26
|
from src.governor import ContextBudget
|
|
23
|
-
from src.environment_auditor import EnvironmentAuditor
|
|
24
27
|
from src.license_manager import LicenseManager
|
|
28
|
+
from src.paths import resolve_data_dir
|
|
29
|
+
|
|
30
|
+
def _model_name(payload: dict) -> str:
|
|
31
|
+
"""hooks.md contract: all payload keys are camelCase, the model arrives as
|
|
32
|
+
'modelName'. Tolerate the legacy 'model' key and env fallbacks."""
|
|
33
|
+
return (
|
|
34
|
+
payload.get("modelName")
|
|
35
|
+
or payload.get("model")
|
|
36
|
+
or os.environ.get("AGY_MODEL")
|
|
37
|
+
or os.environ.get("MODEL")
|
|
38
|
+
or ""
|
|
39
|
+
)
|
|
25
40
|
|
|
26
41
|
def _proxy_is_active() -> bool:
|
|
27
42
|
"""True when the local tokensafe-proxy recently served agent traffic.
|
|
@@ -31,10 +46,7 @@ def _proxy_is_active() -> bool:
|
|
|
31
46
|
duplicate the optimization and double-count it in metrics."""
|
|
32
47
|
try:
|
|
33
48
|
import time as _time
|
|
34
|
-
marker = os.path.join(
|
|
35
|
-
os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(PROJECT_ROOT, "data")),
|
|
36
|
-
".proxy_active",
|
|
37
|
-
)
|
|
49
|
+
marker = os.path.join(resolve_data_dir(), ".proxy_active")
|
|
38
50
|
if os.path.exists(marker):
|
|
39
51
|
return _time.time() - os.path.getmtime(marker) < 120.0
|
|
40
52
|
except Exception:
|
|
@@ -68,38 +80,11 @@ def main():
|
|
|
68
80
|
except Exception:
|
|
69
81
|
pass
|
|
70
82
|
|
|
71
|
-
# 1. Quota
|
|
83
|
+
# 1. Quota check gates compaction tiers. Its warning banner is injected
|
|
84
|
+
# once per session by session_start.py, not on every turn here.
|
|
72
85
|
quota = LicenseManager.check_quota(tracker)
|
|
73
|
-
if invocation_num <= 1:
|
|
74
|
-
try:
|
|
75
|
-
from src.version_checker import VersionChecker
|
|
76
|
-
VersionChecker.notify_os_update_background()
|
|
77
|
-
except Exception:
|
|
78
|
-
pass
|
|
79
|
-
if quota.get("warning"):
|
|
80
|
-
inject_steps.append({
|
|
81
|
-
"systemMessage": {
|
|
82
|
-
"systemMessage": "",
|
|
83
|
-
"metadata": {
|
|
84
|
-
"user_markdown": quota["warning"]
|
|
85
|
-
}
|
|
86
|
-
}
|
|
87
|
-
})
|
|
88
|
-
try:
|
|
89
|
-
bloat_warning = EnvironmentAuditor.get_bloat_warning()
|
|
90
|
-
if bloat_warning:
|
|
91
|
-
inject_steps.append({
|
|
92
|
-
"systemMessage": {
|
|
93
|
-
"systemMessage": "",
|
|
94
|
-
"metadata": {
|
|
95
|
-
"user_markdown": bloat_warning
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
})
|
|
99
|
-
except Exception:
|
|
100
|
-
pass
|
|
101
86
|
|
|
102
|
-
#
|
|
87
|
+
# 2. Prompt Compaction (Tier 2 LLM Distillation paused if community quota exceeded).
|
|
103
88
|
# Skipped while the proxy is in the loop: it already replaced the prompt.
|
|
104
89
|
if last_user_input and len(last_user_input.strip()) >= 5 and not _proxy_is_active():
|
|
105
90
|
enable_distill = not quota.get("is_quota_exceeded", False)
|
|
@@ -120,7 +105,7 @@ def main():
|
|
|
120
105
|
"symbol": compaction["symbol"],
|
|
121
106
|
"traits": compaction["traits"],
|
|
122
107
|
"tier": tier,
|
|
123
|
-
"model": payload
|
|
108
|
+
"model": _model_name(payload) or "gemini-3.8-flash"
|
|
124
109
|
}
|
|
125
110
|
)
|
|
126
111
|
|
|
@@ -144,7 +129,7 @@ def main():
|
|
|
144
129
|
}
|
|
145
130
|
})
|
|
146
131
|
|
|
147
|
-
#
|
|
132
|
+
# 3. Multi-turn History Compaction (Paused when community quota is exceeded)
|
|
148
133
|
folded_text = None
|
|
149
134
|
if not quota.get("is_quota_exceeded", False) and invocation_num >= 3 and transcript_path:
|
|
150
135
|
folded_text, orig_hist_tokens, folded_tokens, stats = HistoryCompactor.fold_transcript(
|
|
@@ -172,7 +157,7 @@ def main():
|
|
|
172
157
|
"total_accum_orig": orig_hist_tokens,
|
|
173
158
|
"read_files": stats.get("read_files_count", 0),
|
|
174
159
|
"edited_files": stats.get("edited_files_count", 0),
|
|
175
|
-
"model": payload
|
|
160
|
+
"model": _model_name(payload) or "gemini-3.8-flash"
|
|
176
161
|
}
|
|
177
162
|
)
|
|
178
163
|
|
|
@@ -190,17 +175,12 @@ def main():
|
|
|
190
175
|
}
|
|
191
176
|
})
|
|
192
177
|
|
|
193
|
-
#
|
|
194
|
-
#
|
|
195
|
-
#
|
|
178
|
+
# 4. Adaptive Protocol Enforcement Reminder (Guard-triggered only).
|
|
179
|
+
# Full directives are injected once per session by session_start.py as a
|
|
180
|
+
# persistent systemMessage; here they are re-shown only when the guard
|
|
181
|
+
# just fired or fresh history was folded.
|
|
196
182
|
recent_guard = tracker.get_last_event(conversation_id, "GUARD_RAW_CODE_SEARCH")
|
|
197
|
-
|
|
198
|
-
invocation_num <= 2 or
|
|
199
|
-
folded_text is not None or
|
|
200
|
-
recent_guard is not None
|
|
201
|
-
)
|
|
202
|
-
|
|
203
|
-
if should_inject_full:
|
|
183
|
+
if folded_text is not None or recent_guard is not None:
|
|
204
184
|
protocol_reminder = (
|
|
205
185
|
"[TokenSafe Mandatory Directives]:\n"
|
|
206
186
|
"• Terminal code searches (grep/rg/find on source files) are BLOCKED by TokenSafe Guard.\n"
|
|
@@ -213,21 +193,13 @@ def main():
|
|
|
213
193
|
inject_steps.append({
|
|
214
194
|
"ephemeralMessage": protocol_reminder
|
|
215
195
|
})
|
|
216
|
-
elif invocation_num % 5 == 0:
|
|
217
|
-
inject_steps.append({
|
|
218
|
-
"ephemeralMessage": "[Protocol: TokenSafe Active | Use 'tokensafe:scoped_search' & 'smart_read_file']"
|
|
219
|
-
})
|
|
220
196
|
|
|
221
|
-
|
|
222
|
-
if inject_steps:
|
|
223
|
-
response["injectSteps"] = inject_steps
|
|
224
|
-
|
|
225
|
-
# 4. Context Budget HUD warning: inject once per session when the
|
|
197
|
+
# 5. Context Budget HUD warning: inject once per session when the
|
|
226
198
|
# instrumented context crosses 80% of the estimated window.
|
|
227
199
|
try:
|
|
228
200
|
budget = ContextBudget.estimate(
|
|
229
201
|
tracker, session_id=conversation_id,
|
|
230
|
-
model=payload
|
|
202
|
+
model=_model_name(payload)
|
|
231
203
|
)
|
|
232
204
|
if budget["used_pct"] >= 80 and budget["instrumented_events"] >= 3:
|
|
233
205
|
already = tracker.get_last_event(conversation_id, "BUDGET_WARNING")
|
|
@@ -253,6 +225,7 @@ def main():
|
|
|
253
225
|
except Exception:
|
|
254
226
|
pass
|
|
255
227
|
|
|
228
|
+
response = {}
|
|
256
229
|
if inject_steps:
|
|
257
230
|
response["injectSteps"] = inject_steps
|
|
258
231
|
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -45,6 +45,9 @@ def main():
|
|
|
45
45
|
args = tool_call.get("args", {})
|
|
46
46
|
conversation_id = payload.get("conversationId", "default_session")
|
|
47
47
|
last_user_input = payload.get("lastUserInput", "")
|
|
48
|
+
# Working directory of the tool call: lets the Command Sanitizer peek at
|
|
49
|
+
# package.json to identify the runner behind opaque `yarn/npm test` scripts
|
|
50
|
+
hook_cwd = payload.get("cwd") or os.getcwd()
|
|
48
51
|
|
|
49
52
|
tracker = MetricsTracker()
|
|
50
53
|
quota = LicenseManager.check_quota(tracker)
|
|
@@ -129,11 +132,13 @@ def main():
|
|
|
129
132
|
}))
|
|
130
133
|
return
|
|
131
134
|
|
|
132
|
-
# 3. read_file Optimization (AST Windowing & Skeletonization)
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
135
|
+
# 3. read_file Optimization (AST Windowing & Skeletonization).
|
|
136
|
+
# 'view_file' is the IDE-surface name for the same tool (hooks.md) —
|
|
137
|
+
# route it through the same optimization pipeline.
|
|
138
|
+
elif tool_name in ("read_file", "view_file"):
|
|
139
|
+
path = args.get("Path") or args.get("path") or args.get("FilePath") or ""
|
|
140
|
+
start_line = args.get("StartLine") or args.get("startLine")
|
|
141
|
+
end_line = args.get("EndLine") or args.get("endLine")
|
|
137
142
|
|
|
138
143
|
if is_quota_exceeded:
|
|
139
144
|
# Free tier quota reached: pass through raw read_file without AST skeletonization
|
|
@@ -245,7 +250,7 @@ def main():
|
|
|
245
250
|
|
|
246
251
|
if is_quota_exceeded:
|
|
247
252
|
# Free tier quota reached: pass through without AST diff slicing or savings tracking
|
|
248
|
-
new_cmd, est_saved, reason = CommandSanitizer.sanitize(cmd)
|
|
253
|
+
new_cmd, est_saved, reason = CommandSanitizer.sanitize(cmd, cwd=hook_cwd)
|
|
249
254
|
if new_cmd and est_saved > 0:
|
|
250
255
|
response["overwrite"] = {"CommandLine": new_cmd}
|
|
251
256
|
print(json.dumps(response))
|
|
@@ -258,7 +263,7 @@ def main():
|
|
|
258
263
|
diff_cmd, diff_saved, diff_reason = DiffSlicer.optimize_git_diff_command(cmd)
|
|
259
264
|
if diff_cmd:
|
|
260
265
|
cmd = diff_cmd
|
|
261
|
-
new_cmd, san_saved, san_reason = CommandSanitizer.sanitize(cmd)
|
|
266
|
+
new_cmd, san_saved, san_reason = CommandSanitizer.sanitize(cmd, cwd=hook_cwd)
|
|
262
267
|
if new_cmd:
|
|
263
268
|
est_saved = san_saved + (diff_saved if diff_cmd else 0)
|
|
264
269
|
reason = (f"{diff_reason}; {san_reason}" if diff_cmd else san_reason)
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Antigravity Lifecycle Hook: SessionStart
|
|
4
|
+
Fires once when a new session starts. Accepts the same injectSteps step types
|
|
5
|
+
as PreInvocation (hooks.md contract) and carries the one-shot context that
|
|
6
|
+
used to run inside PreInvocation on every turn — mirroring the SessionStart
|
|
7
|
+
pattern of Claude Code / Cursor / Gemini CLI: session-scoped state is injected
|
|
8
|
+
once as a persistent systemMessage, not re-sent on every turn.
|
|
9
|
+
|
|
10
|
+
Injects:
|
|
11
|
+
1. TokenSafe protocol directives (persistent systemMessage — replaces the
|
|
12
|
+
per-turn ephemeral reminders and the every-5th-turn re-nudge)
|
|
13
|
+
2. Quota / community-limit warning banner (user-facing markdown)
|
|
14
|
+
3. Environment bloat warning (heavy MCP servers, oversized rule files)
|
|
15
|
+
Also kicks off the background OS update notification check.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import sys
|
|
19
|
+
import os
|
|
20
|
+
import json
|
|
21
|
+
|
|
22
|
+
HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
23
|
+
PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
24
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
25
|
+
|
|
26
|
+
from src.metrics import MetricsTracker
|
|
27
|
+
from src.license_manager import LicenseManager
|
|
28
|
+
from src.environment_auditor import EnvironmentAuditor
|
|
29
|
+
from src.adapter_core import TOKENSAFE_DIRECTIVES as PROTOCOL_DIRECTIVES
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _user_markdown(markdown: str) -> dict:
|
|
33
|
+
"""systemMessage step rendered as inline markdown to the user; per the
|
|
34
|
+
hooks.md contract the model sees only the systemMessage text (empty here)."""
|
|
35
|
+
return {
|
|
36
|
+
"systemMessage": {
|
|
37
|
+
"systemMessage": "",
|
|
38
|
+
"metadata": {"user_markdown": markdown},
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def main():
|
|
44
|
+
try:
|
|
45
|
+
raw_input = sys.stdin.read()
|
|
46
|
+
if not raw_input.strip():
|
|
47
|
+
print(json.dumps({}))
|
|
48
|
+
return
|
|
49
|
+
payload = json.loads(raw_input)
|
|
50
|
+
except Exception:
|
|
51
|
+
print(json.dumps({}))
|
|
52
|
+
return
|
|
53
|
+
|
|
54
|
+
# hooks.md: hook CWD is the plugin directory, not the workspace — use the
|
|
55
|
+
# workspacePaths from the payload for project-scoped audits.
|
|
56
|
+
workspace_paths = payload.get("workspacePaths") or []
|
|
57
|
+
workspace_root = workspace_paths[0] if workspace_paths else os.getcwd()
|
|
58
|
+
|
|
59
|
+
inject_steps = [
|
|
60
|
+
{"systemMessage": {"systemMessage": PROTOCOL_DIRECTIVES, "metadata": {}}}
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
try:
|
|
64
|
+
tracker = MetricsTracker()
|
|
65
|
+
quota = LicenseManager.check_quota(tracker)
|
|
66
|
+
if quota.get("warning"):
|
|
67
|
+
inject_steps.append(_user_markdown(quota["warning"]))
|
|
68
|
+
except Exception:
|
|
69
|
+
pass
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
from src.version_checker import VersionChecker
|
|
73
|
+
VersionChecker.notify_os_update_background()
|
|
74
|
+
except Exception:
|
|
75
|
+
pass
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
bloat_warning = EnvironmentAuditor.get_bloat_warning(workspace_root=workspace_root)
|
|
79
|
+
if bloat_warning:
|
|
80
|
+
inject_steps.append(_user_markdown(bloat_warning))
|
|
81
|
+
except Exception:
|
|
82
|
+
pass
|
|
83
|
+
|
|
84
|
+
print(json.dumps({"injectSteps": inject_steps}))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
if __name__ == "__main__":
|
|
88
|
+
main()
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""
|
|
3
|
+
Antigravity Lifecycle Hook: Stop
|
|
4
|
+
Fires when the execution loop terminates (hooks.md: payload carries
|
|
5
|
+
terminationReason and fullyIdle). Minimal, loop-safe epilogue:
|
|
6
|
+
|
|
7
|
+
1. fullyIdle → final cloud telemetry flush + metrics retention prune,
|
|
8
|
+
once per session instead of on every PostToolUse.
|
|
9
|
+
2. terminationReason == MAX_TOKEN_BUDGET_EXCEEDED → a single 'continue'
|
|
10
|
+
nudge suggesting compaction, guarded by a one-shot metrics event so the
|
|
11
|
+
hook can never ping-pong the loop (mirrors the BUDGET_WARNING dedup).
|
|
12
|
+
|
|
13
|
+
Any other reason returns {} (allow stop). PostInvocation/force_continue is
|
|
14
|
+
deliberately not used — continuation loops need a real use case first.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import sys
|
|
18
|
+
import os
|
|
19
|
+
import json
|
|
20
|
+
|
|
21
|
+
HOOK_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
22
|
+
PROJECT_ROOT = os.path.dirname(HOOK_DIR)
|
|
23
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
24
|
+
|
|
25
|
+
BUDGET_NUDGE_EVENT = "STOP_BUDGET_NUDGE"
|
|
26
|
+
|
|
27
|
+
BUDGET_NUDGE_REASON = (
|
|
28
|
+
"[TokenSafe] Context budget exceeded for this session. Before continuing, "
|
|
29
|
+
"reclaim context: summarize the state so far, avoid re-reading files "
|
|
30
|
+
"(use 'tokensafe:smart_read_file' with a symbol), and keep the next step small."
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def main():
|
|
35
|
+
try:
|
|
36
|
+
raw_input = sys.stdin.read()
|
|
37
|
+
if not raw_input.strip():
|
|
38
|
+
print(json.dumps({}))
|
|
39
|
+
return
|
|
40
|
+
payload = json.loads(raw_input)
|
|
41
|
+
except Exception:
|
|
42
|
+
print(json.dumps({}))
|
|
43
|
+
return
|
|
44
|
+
|
|
45
|
+
conversation_id = payload.get("conversationId", "default_session")
|
|
46
|
+
termination_reason = payload.get("terminationReason", "")
|
|
47
|
+
fully_idle = bool(payload.get("fullyIdle", False))
|
|
48
|
+
|
|
49
|
+
response = {}
|
|
50
|
+
|
|
51
|
+
try:
|
|
52
|
+
from src.metrics import MetricsTracker
|
|
53
|
+
tracker = MetricsTracker()
|
|
54
|
+
|
|
55
|
+
# 1. Idle epilogue: final cloud sync + retention prune.
|
|
56
|
+
if fully_idle:
|
|
57
|
+
try:
|
|
58
|
+
from src.telemetry_sync import TelemetrySync
|
|
59
|
+
TelemetrySync.sync_background(throttle_seconds=0.0)
|
|
60
|
+
except Exception:
|
|
61
|
+
pass
|
|
62
|
+
try:
|
|
63
|
+
tracker.prune()
|
|
64
|
+
except Exception:
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
# 2. One-shot continuation nudge on token-budget exhaustion.
|
|
68
|
+
if termination_reason == "MAX_TOKEN_BUDGET_EXCEEDED":
|
|
69
|
+
already = tracker.get_last_event(conversation_id, BUDGET_NUDGE_EVENT)
|
|
70
|
+
if not already:
|
|
71
|
+
tracker.record_event(
|
|
72
|
+
session_id=conversation_id,
|
|
73
|
+
event_type=BUDGET_NUDGE_EVENT,
|
|
74
|
+
original_tokens=0,
|
|
75
|
+
optimized_tokens=0,
|
|
76
|
+
details={"terminationReason": termination_reason},
|
|
77
|
+
)
|
|
78
|
+
response = {"decision": "continue", "reason": BUDGET_NUDGE_REASON}
|
|
79
|
+
except Exception:
|
|
80
|
+
response = {}
|
|
81
|
+
|
|
82
|
+
print(json.dumps(response))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if __name__ == "__main__":
|
|
86
|
+
main()
|
package/hooks.json
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"token-optimizer": {
|
|
3
3
|
"enabled": true,
|
|
4
|
+
"SessionStart": [
|
|
5
|
+
{
|
|
6
|
+
"type": "command",
|
|
7
|
+
"command": "python3 hooks/session_start.py",
|
|
8
|
+
"timeout": 10
|
|
9
|
+
}
|
|
10
|
+
],
|
|
4
11
|
"PreInvocation": [
|
|
5
12
|
{
|
|
6
13
|
"type": "command",
|
|
@@ -10,7 +17,7 @@
|
|
|
10
17
|
],
|
|
11
18
|
"PreToolUse": [
|
|
12
19
|
{
|
|
13
|
-
"matcher": "read_file|run_command|write_file",
|
|
20
|
+
"matcher": "read_file|view_file|run_command|write_file|edit_file",
|
|
14
21
|
"hooks": [
|
|
15
22
|
{
|
|
16
23
|
"type": "command",
|
|
@@ -31,6 +38,13 @@
|
|
|
31
38
|
}
|
|
32
39
|
]
|
|
33
40
|
}
|
|
41
|
+
],
|
|
42
|
+
"Stop": [
|
|
43
|
+
{
|
|
44
|
+
"type": "command",
|
|
45
|
+
"command": "python3 hooks/stop_hook.py",
|
|
46
|
+
"timeout": 10
|
|
47
|
+
}
|
|
34
48
|
]
|
|
35
49
|
}
|
|
36
50
|
}
|
package/mcp_config.json
ADDED
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.3.0",
|
|
5
5
|
"description": "Local-first AI coding guardrails, context slicing, and team ROI telemetry for AI coding agents",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
"skills/",
|
|
21
21
|
"hooks/",
|
|
22
22
|
"hooks.json",
|
|
23
|
+
"mcp_config.json",
|
|
23
24
|
"proto/",
|
|
24
25
|
"extensions/",
|
|
25
26
|
"plugin.json",
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"name": "
|
|
2
|
+
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.3.0",
|
|
5
5
|
"description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
|
|
6
|
-
"version": "2.
|
|
6
|
+
"version": "2.3.0",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "2.
|
|
33
|
+
"version": "2.3.0",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "2.
|
|
49
|
+
"version": "2.3.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|