tokensafe 2.2.0 → 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 CHANGED
@@ -12,11 +12,11 @@
12
12
  </p>
13
13
 
14
14
  <p align="center">
15
- <a href="https://github.com/NekoSin4eG/tokensafe/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/NekoSin4eG/tokensafe/test.yml?branch=main&label=tests&style=flat-square&color=10B981" alt="Tests"></a>
15
+ <a href="https://github.com/tokensafe-dev/tokensafe/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/tokensafe-dev/tokensafe/test.yml?branch=main&label=tests&style=flat-square&color=10B981" alt="Tests"></a>
16
16
  <a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/v/tokensafe.svg?color=38BDF8&style=flat-square" alt="npm"></a>
17
17
  <a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/dw/tokensafe.svg?color=10B981&label=npm%20downloads&style=flat-square" alt="npm downloads"></a>
18
18
  <a href="https://pypi.org/project/tokensafe/"><img src="https://img.shields.io/pypi/v/tokensafe.svg?color=38BDF8&style=flat-square" alt="PyPI"></a>
19
- <a href="https://github.com/NekoSin4eG/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/NekoSin4eG/tokensafe?style=flat-square&color=334155" alt="Stars"></a>
19
+ <a href="https://github.com/tokensafe-dev/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/tokensafe-dev/tokensafe?style=flat-square&color=334155" alt="Stars"></a>
20
20
  <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-0F766E?style=flat-square" alt="License"></a>
21
21
  <a href="https://tokensafe.dev#pricing"><img src="https://img.shields.io/badge/Team_Trial-7_Days_Free-10B981?style=flat-square" alt="Trial"></a>
22
22
  </p>
@@ -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/agy-token-optimizer` — Antigravity loads it automatically on startup.
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 `data/metrics.db` across restarts so repeated workflows (`git commit`, `run tests`, `fix lint`) cost 0 tokens.
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)
@@ -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)
@@ -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 and Environment Audits (Fires on first invocation)
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
- # 1. Prompt Compaction (Tier 2 LLM Distillation paused if community quota exceeded).
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.get("model") or os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
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
- # 2. Multi-turn History Compaction (Paused when community quota is exceeded)
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.get("model") or os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or "gemini-3.8-flash"
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
- # 3. Adaptive Protocol Enforcement Reminder (Dynamic Deduplication)
194
- # Injects full directives on initial turns, after history folding, or upon guard violations.
195
- # Otherwise suppresses repetitive blocks, saving ~60 tokens per invocation.
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
- should_inject_full = (
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
- response = {}
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.get("model") or os.environ.get("AGY_MODEL") or os.environ.get("MODEL") or ""
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
 
@@ -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
- elif tool_name == "read_file":
134
- path = args.get("Path", "")
135
- start_line = args.get("StartLine")
136
- end_line = args.get("EndLine")
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
  }
@@ -0,0 +1,11 @@
1
+ {
2
+ "mcpServers": {
3
+ "tokensafe": {
4
+ "command": "sh",
5
+ "args": [
6
+ "-c",
7
+ "exec \"${TOKENSAFE_PYTHON:-python3}\" \"$PLUGIN_ROOT/src/mcp_server.py\""
8
+ ]
9
+ }
10
+ }
11
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.2.0",
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",
@@ -52,10 +53,10 @@
52
53
  "license": "MIT",
53
54
  "repository": {
54
55
  "type": "git",
55
- "url": "git+https://github.com/NekoSin4eG/tokensafe.git"
56
+ "url": "git+https://github.com/tokensafe-dev/tokensafe.git"
56
57
  },
57
58
  "bugs": {
58
- "url": "https://github.com/NekoSin4eG/tokensafe/issues"
59
+ "url": "https://github.com/tokensafe-dev/tokensafe/issues"
59
60
  },
60
61
  "homepage": "https://tokensafe.dev",
61
62
  "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
package/plugin.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
- "name": "agy-token-optimizer",
2
+ "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.2.0",
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": {
8
8
  "name": "Oleg Savelev",
9
9
  "url": "https://github.com/NekoSin4eG"
10
10
  },
11
- "homepage": "https://github.com/NekoSin4eG/tokensafe-cloud",
11
+ "homepage": "https://github.com/tokensafe-dev/tokensafe-cloud",
12
12
  "repository": {
13
13
  "type": "git",
14
- "url": "https://github.com/NekoSin4eG/tokensafe-cloud"
14
+ "url": "https://github.com/tokensafe-dev/tokensafe-cloud"
15
15
  }
16
16
  }
package/server.json CHANGED
@@ -3,10 +3,10 @@
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.2.0",
6
+ "version": "2.3.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
- "url": "https://github.com/NekoSin4eG/tokensafe",
9
+ "url": "https://github.com/tokensafe-dev/tokensafe",
10
10
  "source": "github"
11
11
  },
12
12
  "icons": [
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "2.2.0",
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.2.0",
49
+ "version": "2.3.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"