tokensafe 4.1.7 → 4.1.9

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.
@@ -0,0 +1,36 @@
1
+ {
2
+ "version": "4.1.9",
3
+ "name": "tokensafe",
4
+ "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
5
+ "author": {
6
+ "name": "TokenSafe",
7
+ "url": "https://tokensafe.dev"
8
+ },
9
+ "homepage": "https://tokensafe.dev",
10
+ "repository": "https://github.com/tokensafe-dev/tokensafe",
11
+ "license": "MIT",
12
+ "keywords": [
13
+ "tokensafe",
14
+ "token-optimizer",
15
+ "mcp",
16
+ "compression",
17
+ "ast-slicer",
18
+ "context-window"
19
+ ],
20
+ "skills": "./skills/",
21
+ "interface": {
22
+ "displayName": "TokenSafe",
23
+ "shortDescription": "Stop coding agent context rot, destructive rewrites & secret leaks",
24
+ "longDescription": "TokenSafe is a local context firewall that strips massive lockfiles, verbose build logs, and repetitive file reads before they reach model attention. Zero-loss AST slicing, prompt cache prefix locking, and pre-commit secret guard for AI coding agents.",
25
+ "developerName": "TokenSafe",
26
+ "category": "Engineering",
27
+ "capabilities": [
28
+ "Read",
29
+ "Write",
30
+ "Analyze"
31
+ ],
32
+ "websiteURL": "https://tokensafe.dev",
33
+ "brandColor": "#10B981",
34
+ "logo": "https://tokensafe.dev/logo.png"
35
+ }
36
+ }
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  <b>Your coding agent isn't getting dumber. Your context is just full of trash.</b><br>
10
10
  When chat sessions fill up with massive lockfiles and endless build logs, your AI loses focus.<br>
11
11
  TokenSafe strips the noise with Tree-sitter AST slicing so your agent stays razor-sharp, changes only the lines you asked for, and never leaks your secrets.<br>
12
- Works with <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Gemini CLI, and ChatGPT</b>.
12
+ Works with <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Kimi Code, and ChatGPT</b>.
13
13
  </p>
14
14
 
15
15
  <p align="center">
@@ -80,8 +80,8 @@ The installer detects which agents live on your machine, registers the TokenSafe
80
80
  | **Cline / Roo Code** | MCP registration (VS Code) |
81
81
  | **GitHub Copilot** | MCP registration |
82
82
  | **Z.ai Code** | MCP registration |
83
+ | **Kimi Code** | Native Plugin (`kimi.plugin.json`) + MCP + `PreToolUse` / `SessionStart` hooks |
83
84
  | **ChatGPT** | Cloud connector, nothing to install |
84
- | **Gemini CLI** | MCP registration |
85
85
 
86
86
  Claude Desktop / Cursor MCP config:
87
87
 
Binary file
@@ -0,0 +1,13 @@
1
+ <svg width="256" height="256" viewBox="0 0 256 256" fill="none" xmlns="http://www.w3.org/2000/svg">
2
+ <!-- Clean Obsidian Slate Squircle -->
3
+ <rect x="8" y="8" width="240" height="240" rx="52" fill="#090C10"/>
4
+ <rect x="8" y="8" width="240" height="240" rx="52" stroke="#1E293B" stroke-width="4"/>
5
+
6
+ <!-- Geometric Protective Vault Shield -->
7
+ <path d="M128 42 L194 68 V128 C194 170 166 204 128 218 C90 204 62 170 62 128 V68 L128 42 Z"
8
+ fill="#11161E" stroke="#10B981" stroke-width="10" stroke-linejoin="round"/>
9
+
10
+ <!-- Crisp Compression Bolt (High Contrast, 16px-ready) -->
11
+ <path d="M137 74 L97 132 H125 L119 182 L159 124 H131 L137 74 Z"
12
+ fill="#F3F4F6"/>
13
+ </svg>
@@ -0,0 +1,237 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ TokenSafe adapter for Kimi Code lifecycle hooks.
4
+
5
+ Registered via kimi.plugin.json or ~/.kimi-code/config.toml:
6
+ SessionStart -> injects TokenSafe protocol directives once per session.
7
+ UserPromptSubmit -> compacts prompt into TOCP intent expression.
8
+ PreToolUse (Bash/Write/Read) -> denies secret leaks, destructive commands,
9
+ and unindexed lockfile/bundle reads.
10
+
11
+ Contract: stdin = one JSON payload, stdout = one JSON response.
12
+ Fail-open: any internal error emits `{}`.
13
+ """
14
+
15
+ import sys
16
+ import json
17
+ import os
18
+
19
+ HOOK_DIR = os.path.dirname(os.path.realpath(__file__))
20
+ PROJECT_ROOT = os.path.dirname(HOOK_DIR)
21
+ if PROJECT_ROOT not in sys.path:
22
+ sys.path.insert(0, PROJECT_ROOT)
23
+
24
+ from src.adapter_core import (
25
+ TOKENSAFE_DIRECTIVES,
26
+ compact_for_injection,
27
+ guard_command,
28
+ guard_read,
29
+ guard_write,
30
+ )
31
+
32
+ AGENT = "kimi_code"
33
+
34
+
35
+ def handle(event: str, payload: dict) -> dict:
36
+ session_id = str(payload.get("session_id") or "") or f"hook_{AGENT}"
37
+
38
+ if event == "SessionStart":
39
+ extra = TOKENSAFE_DIRECTIVES
40
+ try:
41
+ from src.version_checker import VersionChecker
42
+ VersionChecker.notify_os_update_background()
43
+ except Exception:
44
+ pass
45
+ try:
46
+ from src.metrics import MetricsTracker
47
+ from src.license_manager import LicenseManager
48
+ quota = LicenseManager.check_quota(MetricsTracker())
49
+ if quota.get("warning"):
50
+ extra = f"{extra}\n\n{quota['warning']}"
51
+ except Exception:
52
+ pass
53
+ try:
54
+ from src.mistakes import MistakesLedger
55
+ guard = MistakesLedger.get_guard_prompt(project_root=str(payload.get("cwd") or os.getcwd()))
56
+ if guard:
57
+ extra = f"{extra}\n\n{guard}"
58
+ except Exception:
59
+ pass
60
+ return {
61
+ "hookSpecificOutput": {
62
+ "hookEventName": "SessionStart",
63
+ "additionalContext": extra,
64
+ }
65
+ }
66
+
67
+ if event == "UserPromptSubmit":
68
+ prompt = str(payload.get("prompt") or "")
69
+ parts = []
70
+ quota = {"is_quota_exceeded": False, "warning": None}
71
+ tracker = None
72
+ try:
73
+ from src.metrics import MetricsTracker
74
+ from src.license_manager import LicenseManager
75
+ tracker = MetricsTracker()
76
+ quota = LicenseManager.check_quota(tracker)
77
+ except Exception:
78
+ pass
79
+
80
+ if quota.get("is_quota_exceeded"):
81
+ try:
82
+ from src.license_manager import LicenseManager
83
+ if LicenseManager.should_emit_quota_banner(tracker, session_id, every_n_turns=5) and quota.get("warning"):
84
+ parts.append(quota["warning"])
85
+ except Exception:
86
+ pass
87
+ if parts:
88
+ return {
89
+ "hookSpecificOutput": {
90
+ "hookEventName": "UserPromptSubmit",
91
+ "additionalContext": "\n\n".join(parts),
92
+ }
93
+ }
94
+ return {}
95
+
96
+ context, meta = compact_for_injection(prompt, AGENT, session_id)
97
+ if context and meta.get("compacted"):
98
+ parts.append(
99
+ f"{context}\n"
100
+ f"(TokenSafe: compacted ~{meta['saved_tokens']} prompt tokens, "
101
+ f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
102
+ )
103
+
104
+ if parts:
105
+ return {
106
+ "hookSpecificOutput": {
107
+ "hookEventName": "UserPromptSubmit",
108
+ "additionalContext": "\n\n".join(parts),
109
+ }
110
+ }
111
+ return {}
112
+
113
+ if event == "PreToolUse":
114
+ tool = str(payload.get("tool_name") or "")
115
+ tool_input = payload.get("tool_input")
116
+ if not isinstance(tool_input, dict):
117
+ tool_input = {}
118
+
119
+ if tool in ("Bash", "Shell", "bash"):
120
+ command = str(tool_input.get("command") or "")
121
+ verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
122
+ if verdict["decision"] == "deny":
123
+ return {
124
+ "hookSpecificOutput": {
125
+ "hookEventName": "PreToolUse",
126
+ "permissionDecision": "deny",
127
+ "permissionDecisionReason": verdict["reason"],
128
+ }
129
+ }
130
+ if verdict["decision"] == "ask":
131
+ return {
132
+ "hookSpecificOutput": {
133
+ "hookEventName": "PreToolUse",
134
+ "permissionDecision": "ask",
135
+ "permissionDecisionReason": verdict["reason"],
136
+ }
137
+ }
138
+
139
+ elif tool in ("Write", "write_file", "replace_file_content"):
140
+ file_path = str(tool_input.get("file_path") or tool_input.get("Path") or tool_input.get("path") or "")
141
+ content = tool_input.get("content") or tool_input.get("Content") or tool_input.get("file_text") or ""
142
+ append = bool(tool_input.get("append") or tool_input.get("Append") or False)
143
+ verdict = guard_write(file_path, str(content or ""), append, AGENT, session_id)
144
+ if verdict["decision"] == "deny":
145
+ return {
146
+ "hookSpecificOutput": {
147
+ "hookEventName": "PreToolUse",
148
+ "permissionDecision": "deny",
149
+ "permissionDecisionReason": verdict["reason"],
150
+ }
151
+ }
152
+ if verdict["decision"] == "ask":
153
+ return {
154
+ "hookSpecificOutput": {
155
+ "hookEventName": "PreToolUse",
156
+ "permissionDecision": "ask",
157
+ "permissionDecisionReason": verdict["reason"],
158
+ }
159
+ }
160
+
161
+ elif tool in ("Read", "read_file", "view_file"):
162
+ file_path = str(tool_input.get("file_path") or tool_input.get("path") or tool_input.get("Path") or "")
163
+ verdict = guard_read(file_path, AGENT, session_id)
164
+ if verdict["decision"] == "deny":
165
+ return {
166
+ "hookSpecificOutput": {
167
+ "hookEventName": "PreToolUse",
168
+ "permissionDecision": "deny",
169
+ "permissionDecisionReason": verdict["reason"],
170
+ }
171
+ }
172
+
173
+ return {}
174
+
175
+ if event == "PostToolUse":
176
+ tool = str(payload.get("tool_name") or "")
177
+ compacted, orig, new = None, 0, 0
178
+ try:
179
+ from src.command_sanitizer import CommandSanitizer
180
+ res = CommandSanitizer.compact_tool_output(tool, payload.get("tool_response"))
181
+ if res:
182
+ compacted, orig, new = res
183
+ except Exception:
184
+ compacted = None
185
+ if compacted:
186
+ try:
187
+ from src.metrics import MetricsTracker
188
+ from src.tokenizer import count_tokens
189
+ MetricsTracker().record_event(
190
+ session_id=session_id,
191
+ event_type="TOOL_OUTPUT_COMPACT",
192
+ original_tokens=count_tokens(str(payload.get("tool_response") or "")),
193
+ optimized_tokens=count_tokens(compacted),
194
+ details={"agent": AGENT, "tool": tool, "chars": f"{orig}->{new}"},
195
+ )
196
+ except Exception:
197
+ pass
198
+ return {
199
+ "decision": "block",
200
+ "reason": (
201
+ f"[TokenSafe] {tool} output auto-compacted "
202
+ f"({orig:,} → {new:,} chars). Output summary:\n{compacted}"
203
+ ),
204
+ }
205
+ return {}
206
+
207
+ return {}
208
+
209
+
210
+ def main():
211
+ try:
212
+ raw = sys.stdin.read()
213
+ payload = json.loads(raw) if raw.strip() else {}
214
+ if not isinstance(payload, dict):
215
+ payload = {}
216
+ except Exception:
217
+ print(json.dumps({}))
218
+ return
219
+ event = ""
220
+ try:
221
+ event = str(payload.get("hook_event_name") or "")
222
+ response = handle(event, payload)
223
+ if not isinstance(response, dict):
224
+ response = {}
225
+ except Exception:
226
+ response = {}
227
+ if event in ("UserPromptSubmit", "PreToolUse", "PostToolUse", "Stop"):
228
+ try:
229
+ from src.telemetry_sync import TelemetrySync
230
+ TelemetrySync.sync_background(throttle_seconds=0.0 if event == "Stop" else 20.0)
231
+ except Exception:
232
+ pass
233
+ print(json.dumps(response))
234
+
235
+
236
+ if __name__ == "__main__":
237
+ main()
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "tokensafe",
3
+ "version": "4.1.9",
4
+ "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
5
+ "homepage": "https://tokensafe.dev",
6
+ "license": "MIT",
7
+ "logo": "https://tokensafe.dev/logo.png",
8
+ "icon": "https://tokensafe.dev/logo.png",
9
+ "iconUrl": "https://tokensafe.dev/logo.png",
10
+ "author": {
11
+ "name": "TokenSafe"
12
+ },
13
+ "interface": {
14
+ "displayName": "TokenSafe",
15
+ "shortDescription": "Stop coding agent context rot, destructive rewrites & secret leaks",
16
+ "developerName": "TokenSafe",
17
+ "websiteURL": "https://tokensafe.dev",
18
+ "logo": "https://tokensafe.dev/logo.png",
19
+ "iconUrl": "https://tokensafe.dev/logo.png"
20
+ },
21
+ "skills": [
22
+ "skills/token-optimizer"
23
+ ],
24
+ "mcpServers": {
25
+ "tokensafe": {
26
+ "command": "python3",
27
+ "args": [
28
+ "src/mcp_server.py"
29
+ ]
30
+ }
31
+ },
32
+ "hooks": [
33
+ {
34
+ "event": "SessionStart",
35
+ "command": "python3 hooks/kimi_hook.py",
36
+ "timeout": 10
37
+ },
38
+ {
39
+ "event": "UserPromptSubmit",
40
+ "command": "python3 hooks/kimi_hook.py",
41
+ "timeout": 10
42
+ },
43
+ {
44
+ "event": "PreToolUse",
45
+ "matcher": "Bash",
46
+ "command": "python3 hooks/kimi_hook.py",
47
+ "timeout": 10
48
+ },
49
+ {
50
+ "event": "PreToolUse",
51
+ "matcher": "Write",
52
+ "command": "python3 hooks/kimi_hook.py",
53
+ "timeout": 10
54
+ },
55
+ {
56
+ "event": "PreToolUse",
57
+ "matcher": "Read",
58
+ "command": "python3 hooks/kimi_hook.py",
59
+ "timeout": 10
60
+ }
61
+ ]
62
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.1.7",
4
+ "version": "4.1.9",
5
5
  "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
@@ -16,6 +16,7 @@
16
16
  "!src/mailer.py",
17
17
  "!src/weekly_digest.py",
18
18
  "!**/__pycache__/**",
19
+ "!hooks/__pycache__/**",
19
20
  "!**/*.pyc",
20
21
  "rules/",
21
22
  "skills/",
@@ -24,7 +25,10 @@
24
25
  "mcp_config.json",
25
26
  "proto/",
26
27
  "extensions/",
28
+ "assets/",
29
+ ".codex-plugin/",
27
30
  "plugin.json",
31
+ "kimi.plugin.json",
28
32
  "server.json",
29
33
  "README.md",
30
34
  "LICENSE"
package/plugin.json CHANGED
@@ -1,12 +1,13 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.1.7",
5
- "description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
6
- "logo": "assets/logo.svg",
4
+ "version": "4.1.9",
5
+ "description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
6
+ "logo": "https://tokensafe.dev/logo.png",
7
+ "developerName": "TokenSafe",
7
8
  "author": {
8
- "name": "Oleg Savelev",
9
- "url": "https://github.com/NekoSin4eG"
9
+ "name": "TokenSafe",
10
+ "url": "https://tokensafe.dev"
10
11
  },
11
12
  "homepage": "https://tokensafe.dev",
12
13
  "repository": {
package/server.json CHANGED
@@ -2,8 +2,8 @@
2
2
  "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
- "description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
6
- "version": "4.1.7",
5
+ "description": "Your agent isn't getting dumber, your context is full of trash. Local firewall & zero-loss runtime.",
6
+ "version": "4.1.9",
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": "4.1.7",
33
+ "version": "4.1.9",
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": "4.1.7",
49
+ "version": "4.1.9",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
package/src/cli.py CHANGED
@@ -188,12 +188,19 @@ def main(argv: Optional[List[str]] = None):
188
188
  # Tier + quota state
189
189
  tier, payload = LicenseManager.get_active_license()
190
190
  quota = LicenseManager.check_quota(tracker)
191
- if tier == "free":
191
+ if tier == "guest":
192
+ q_saved = int(quota.get("monthly_saved", 0))
193
+ q_limit = int(quota.get("monthly_limit") or 50_000)
194
+ q_pct = min(100, int(q_saved / q_limit * 100)) if q_limit else 0
195
+ q_state = "\033[31mQUOTA REACHED (Optimizers paused)\033[0m" if quota.get("is_quota_exceeded") else f"{q_pct}% of monthly guest limit"
196
+ print(f" Tier: \033[33mGUEST (Offline)\033[0m — {q_saved:,} / {q_limit:,} tokens ({q_state})")
197
+ print(" Unlock 500k: Run \033[36mtokensafe login\033[0m for free Community account & Web Dashboard")
198
+ elif tier == "free":
192
199
  q_saved = int(quota.get("monthly_saved", 0))
193
200
  q_limit = int(quota.get("monthly_limit") or 500_000)
194
201
  q_pct = min(100, int(q_saved / q_limit * 100)) if q_limit else 0
195
202
  q_state = "\033[31mQUOTA REACHED — Pro optimizations paused\033[0m" if quota.get("is_quota_exceeded") else f"{q_pct}% of monthly measured quota"
196
- print(f" Tier: \033[33mCOMMUNITY (Free)\033[0m — {q_saved:,} / {q_limit:,} tokens ({q_state})")
203
+ print(f" Tier: \033[33mCOMMUNITY (Free Account)\033[0m — {q_saved:,} / {q_limit:,} tokens ({q_state})")
197
204
  print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo · 7-Day Team Trial)")
198
205
  else:
199
206
  print(f" Tier: \033[32m{tier.upper()}\033[0m (Unlimited)")
@@ -922,7 +929,24 @@ def main(argv: Optional[List[str]] = None):
922
929
  tier, payload = LicenseManager.get_active_license()
923
930
  print("\n\033[1m\033[36m⚡ TOKENSAFE LICENSE STATUS ⚡\033[0m\n")
924
931
  print(f" Tier: \033[32m\033[1m{tier.upper()}\033[0m")
925
- if tier != "free":
932
+ if tier == "guest":
933
+ quota = LicenseManager.check_quota()
934
+ q_saved = int(quota.get("monthly_saved", 0))
935
+ q_limit = int(quota.get("monthly_limit") or 50_000)
936
+ q_state = "\033[31mQUOTA REACHED (Optimizers paused)\033[0m" if quota.get("is_quota_exceeded") else "\033[32mActive\033[0m"
937
+ print(f" Status: Guest Mode ({q_saved:,} / {q_limit:,} tokens this month · {q_state})")
938
+ print(" Mode: Local Offline (No account connected)")
939
+ print(" Unlock 500k: \033[36mtokensafe login\033[0m (Free Community license + Web Dashboard)")
940
+ print(" Solo Pro: https://tokensafe.dev/signup (Unlimited tokens)\n")
941
+ elif tier == "free":
942
+ quota = LicenseManager.check_quota()
943
+ q_saved = int(quota.get("monthly_saved", 0))
944
+ q_limit = int(quota.get("monthly_limit") or 500_000)
945
+ q_state = "\033[31mQUOTA REACHED (Pro optimizations paused)\033[0m" if quota.get("is_quota_exceeded") else "\033[32mActive\033[0m"
946
+ print(f" Email: {payload.get('email', 'community@tokensafe.dev')}")
947
+ print(f" Status: Community Account ({q_saved:,} / {q_limit:,} measured tokens this month · {q_state})")
948
+ print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo with 7-Day Free Trial)\n")
949
+ else:
926
950
  print(f" Email: {payload.get('email', 'N/A')}")
927
951
  if payload.get("trial"):
928
952
  print(f" Mode: \033[33m7-Day Free Trial\033[0m")
@@ -933,13 +957,6 @@ def main(argv: Optional[List[str]] = None):
933
957
  print(f" Expires: {dt}")
934
958
  else:
935
959
  print(f" Expires: Never (Lifetime)")
936
- else:
937
- quota = LicenseManager.check_quota()
938
- q_saved = int(quota.get("monthly_saved", 0))
939
- q_limit = int(quota.get("monthly_limit") or 500_000)
940
- q_state = "\033[31mQUOTA REACHED (Pro optimizations paused)\033[0m" if quota.get("is_quota_exceeded") else "\033[32mActive\033[0m"
941
- print(f" Status: Free Tier ({q_saved:,} / {q_limit:,} measured tokens this month · {q_state})")
942
- print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo with 7-Day Free Trial)\n")
943
960
  print()
944
961
 
945
962
  elif command in ("providers", "models", "keys"):
package/src/dashboard.py CHANGED
@@ -82,7 +82,17 @@ class Dashboard:
82
82
  # Top summary cards
83
83
  tier, payload = LicenseManager.get_active_license()
84
84
  tier_upper = tier.upper()
85
- if tier == "free":
85
+ if tier == "guest":
86
+ monthly_saved = self.tracker.get_monthly_saved_tokens()
87
+ limit = 50_000
88
+ q_pct = min(100.0, (monthly_saved / limit * 100.0))
89
+ if monthly_saved >= limit:
90
+ out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}GUEST (Offline){RESET} • {RED}{BOLD}50k Monthly Limit Reached ({monthly_saved:,}/{limit:,}){RESET}")
91
+ out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Optimizers paused · Unlock 500k: run 'tokensafe login')")
92
+ else:
93
+ out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}GUEST (Offline){RESET} • {monthly_saved:,} / {limit:,} tokens this month")
94
+ out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Unlock 500k: run 'tokensafe login')")
95
+ elif tier == "free":
86
96
  monthly_saved = self.tracker.get_monthly_saved_tokens()
87
97
  limit = 500_000
88
98
  q_pct = min(100.0, (monthly_saved / limit * 100.0))
@@ -99,7 +109,7 @@ class Dashboard:
99
109
 
100
110
  out.append(f" {BOLD}Total Tokens Saved:{RESET} {GREEN}{BOLD}{total_saved:,}{RESET} tokens")
101
111
  out.append(f" {BOLD}Efficiency Gain:{RESET} {YELLOW}{BOLD}{render_bar(pct)}{RESET}")
102
- out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}≈${usd:.4f} USD{RESET} {DIM}(derived: tokens × $1.5/M — approximation, not a bill){RESET}")
112
+ out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}≈${usd:.4f} USD{RESET} {DIM}(derived: tokens × $3.0/M Claude Sonnet baseline — approximation, not a bill){RESET}")
103
113
  weekly = self.tracker.get_weekly_saved()
104
114
  out.append(f" {BOLD}This Week:{RESET} {GREEN}{BOLD}{weekly['saved_tokens']:,}{RESET} tokens saved across {weekly['events']:,} events (≈${weekly['usd_saved']:.2f})")
105
115
 
@@ -186,11 +196,12 @@ class Dashboard:
186
196
  md = []
187
197
  md.append("# ⚡ TokenSafe Context & Token Optimizer Report\n")
188
198
  quota = LicenseManager.check_quota(self.tracker)
189
- if quota.get("tier") == "free":
199
+ if quota.get("tier") in ("free", "guest"):
200
+ plan_name = "Guest" if quota.get("tier") == "guest" else "Community"
190
201
  m_saved = int(quota.get("monthly_saved", 0))
191
- m_limit = int(quota.get("monthly_limit") or 500_000)
192
- status_tag = "QUOTA REACHED — Pro optimizers paused" if quota.get("is_quota_exceeded") else "Active"
193
- md.append(f"> **Plan:** Community (`{m_saved:,} / {m_limit:,}` measured tokens/mo · **{status_tag}**)\n")
202
+ m_limit = int(quota.get("monthly_limit") or (50_000 if quota.get("tier") == "guest" else 500_000))
203
+ status_tag = "QUOTA REACHED — Optimizers paused" if quota.get("is_quota_exceeded") else "Active"
204
+ md.append(f"> **Plan:** {plan_name} (`{m_saved:,} / {m_limit:,}` measured tokens/mo · **{status_tag}**)\n")
194
205
  md.append(f"> **Cumulative Resource Efficiency:** **{pct:.1f}% Reduction** across {summary['total_events']} events.\n")
195
206
  md.append("| Metric | Value |")
196
207
  md.append("| :--- | :--- |")
package/src/installer.py CHANGED
@@ -70,7 +70,7 @@ UNIFIED_TOKENSAFE_RULE = (
70
70
  POINTER_RULE = (
71
71
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
72
72
  "The full 12-point protocol is installed globally in the agent-level instructions "
73
- "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md) and applies to this project. "
73
+ "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
74
74
  "Core rules: never raw grep/find or `ls -la` — use `tokensafe:scoped_search`, "
75
75
  "`tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
76
76
  "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
@@ -146,6 +146,16 @@ AGENTS_REGISTRY = {
146
146
  "plugin_path": os.path.join(HOME, ".zcode", "cli", "plugins", "tokensafe"),
147
147
  "agents_md_path": os.path.join(HOME, ".zcode", "AGENTS.md"),
148
148
  "detect_path": os.path.join(HOME, ".zcode")
149
+ },
150
+ "kimi": {
151
+ "name": "Kimi Code",
152
+ "type": "kimi_plugin",
153
+ "config_path": os.path.join(HOME, ".kimi-code", "mcp.json"),
154
+ "installed_json_path": os.path.join(HOME, ".kimi-code", "plugins", "installed.json"),
155
+ "managed_plugin_path": os.path.join(HOME, ".kimi-code", "plugins", "managed", "tokensafe"),
156
+ "skills_path": os.path.join(HOME, ".kimi-code", "skills", "token-optimizer"),
157
+ "agents_md_path": os.path.join(HOME, ".kimi-code", "AGENTS.md"),
158
+ "detect_path": os.path.join(HOME, ".kimi-code")
149
159
  }
150
160
  }
151
161
 
@@ -161,6 +171,12 @@ class AgentInstaller:
161
171
  # Fallback for cursor / windsurf on macOS
162
172
  if not is_present and key == "cursor":
163
173
  is_present = os.path.exists(os.path.join(HOME, "Library", "Application Support", "Cursor"))
174
+ if not is_present and key == "kimi":
175
+ is_present = (
176
+ os.path.exists("/Applications/Kimi Code.app")
177
+ or os.path.exists(os.path.join(HOME, "Applications", "Kimi Code.app"))
178
+ or shutil.which("kimi") is not None
179
+ )
164
180
  detected[key] = {
165
181
  **info,
166
182
  "installed": is_present
@@ -211,11 +227,62 @@ class AgentInstaller:
211
227
  Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
212
228
  if agent_key == "codex":
213
229
  return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
214
- if agent_key not in ("claude_code", "cursor"):
230
+ if agent_key not in ("claude_code", "cursor", "kimi"):
215
231
  return False, "hooks not applicable for this agent"
216
232
 
217
233
  claude_cmd = cls._tokensafe_hook_command("claude_code_hook.py")
218
234
  cursor_cmd = cls._tokensafe_hook_command("cursor_hook.py")
235
+ kimi_cmd = cls._tokensafe_hook_command("kimi_hook.py")
236
+
237
+ if agent_key == "kimi":
238
+ config_file = os.path.join(HOME, ".kimi-code", "config.toml")
239
+ os.makedirs(os.path.dirname(config_file), exist_ok=True)
240
+ content = ""
241
+ if os.path.exists(config_file):
242
+ try:
243
+ shutil.copy2(config_file, f"{config_file}.backup")
244
+ except Exception:
245
+ pass
246
+ try:
247
+ with open(config_file, "r", encoding="utf-8") as f:
248
+ content = f.read()
249
+ except Exception:
250
+ pass
251
+
252
+ if "kimi_hook.py" in content:
253
+ return True, "TokenSafe Kimi Code hooks already registered in config.toml"
254
+
255
+ toml_hook_cmd = json.dumps(kimi_cmd)
256
+ hook_sections = (
257
+ f'\n# TokenSafe Lifecycle Hooks\n'
258
+ f'[[hooks]]\n'
259
+ f'event = "SessionStart"\n'
260
+ f'command = {toml_hook_cmd}\n'
261
+ f'timeout = 10\n\n'
262
+ f'[[hooks]]\n'
263
+ f'event = "UserPromptSubmit"\n'
264
+ f'command = {toml_hook_cmd}\n'
265
+ f'timeout = 10\n\n'
266
+ f'[[hooks]]\n'
267
+ f'event = "PreToolUse"\n'
268
+ f'matcher = "Bash"\n'
269
+ f'command = {toml_hook_cmd}\n'
270
+ f'timeout = 10\n\n'
271
+ f'[[hooks]]\n'
272
+ f'event = "PreToolUse"\n'
273
+ f'matcher = "Write"\n'
274
+ f'command = {toml_hook_cmd}\n'
275
+ f'timeout = 10\n\n'
276
+ f'[[hooks]]\n'
277
+ f'event = "PreToolUse"\n'
278
+ f'matcher = "Read"\n'
279
+ f'command = {toml_hook_cmd}\n'
280
+ f'timeout = 10\n'
281
+ )
282
+ content = (content.rstrip() + "\n" + hook_sections) if content.strip() else hook_sections.lstrip()
283
+ with open(config_file, "w", encoding="utf-8") as f:
284
+ f.write(content)
285
+ return True, "hooks registered in ~/.kimi-code/config.toml (SessionStart + UserPromptSubmit + PreToolUse Bash/Write/Read)"
219
286
 
220
287
  if agent_key == "claude_code":
221
288
  config_file = os.path.join(HOME, ".claude", "settings.json")
@@ -550,7 +617,9 @@ WantedBy=default.target
550
617
  try:
551
618
  if not (sys.stdin.isatty() and sys.stdout.isatty()):
552
619
  return
553
- if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes") or "unittest" in sys.modules:
620
+ if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes"):
621
+ return
622
+ if "unittest" in sys.modules and not os.environ.get("TOKENSAFE_TEST_PROMPT"):
554
623
  return
555
624
  st = cls.proxy_status()
556
625
  if st.get("claude_code_wired"):
@@ -577,41 +646,69 @@ WantedBy=default.target
577
646
  @classmethod
578
647
  def maybe_prompt_account_login(cls, context: str = "install") -> None:
579
648
  """
580
- Interactive prompt to connect TokenSafe account and unlock web dashboard.
581
- Migrates anonymous community@tokensafe.dev licenses to verified user accounts.
649
+ Interactive prompt to connect TokenSafe account and unlock 500k free quota + web dashboard.
650
+ Migrates anonymous community@tokensafe.dev and guest installations to verified user accounts.
651
+ Features a resilient /dev/tty fallback for piped 'curl | bash' installations and an
652
+ intelligent one-more-chance nudge on decline.
582
653
  Fail-open: skips quietly on non-interactive environments (CI, scripts).
583
654
  """
584
655
  try:
585
656
  from src.license_manager import LicenseManager
586
- _, lic = LicenseManager.get_active_license()
657
+ tier, lic = LicenseManager.get_active_license()
587
658
  email = lic.get("email", "")
588
659
 
589
660
  # If user already has a real personal account (not the legacy anonymous key), nothing to prompt
590
661
  if email and email != "community@tokensafe.dev":
591
662
  return
592
663
 
593
- is_anonymous = (email == "community@tokensafe.dev")
664
+ if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes"):
665
+ return
666
+ if "unittest" in sys.modules and not os.environ.get("TOKENSAFE_TEST_PROMPT"):
667
+ return
594
668
 
595
- if not (sys.stdin.isatty() and sys.stdout.isatty()):
669
+ has_tty = sys.stdin.isatty() or (os.path.exists("/dev/tty") and sys.stdout.isatty())
670
+ if not has_tty:
596
671
  print(f" {CYAN}ℹ{RESET} Run {BOLD}tokensafe login{RESET} anytime to activate your Community license & web dashboard.\n")
597
672
  return
598
673
 
599
- if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes") or "unittest" in sys.modules:
600
- return
674
+ def _read_input(prompt_text: str) -> str:
675
+ sys.stdout.write(prompt_text)
676
+ sys.stdout.flush()
677
+ if sys.stdin.isatty():
678
+ return sys.stdin.readline().strip()
679
+ if os.path.exists("/dev/tty"):
680
+ with open("/dev/tty", "r") as tty_in:
681
+ return tty_in.readline().strip()
682
+ raise EOFError("No interactive TTY")
601
683
 
602
684
  if context == "update":
603
- if is_anonymous or not email:
604
- print(f" {CYAN}ℹ{RESET} Connect your account anytime with {BOLD}tokensafe login{RESET} to view your cloud dashboard.\n")
685
+ print(f" {CYAN}ℹ{RESET} Connect your account anytime with {BOLD}tokensafe login{RESET} to upgrade from 50k to 500k tokens/mo.\n")
605
686
  return
606
687
 
607
- print(f"\n {CYAN}→ Connect your free TokenSafe account (500,000 tokens/mo) to unlock your web dashboard:{RESET}")
608
- print(f" Open browser to authorize? [{GREEN}Y{RESET}/n] ", end="", flush=True)
609
- answer = input().strip().lower()
688
+ print(f"\n{BOLD}{CYAN}╔════════════════════════════════════════════════════════════════════╗{RESET}")
689
+ print(f"{BOLD}{CYAN}║ ⚡ TOKENSAFE TIERS & LIMITS ║{RESET}")
690
+ print(f"{BOLD}{CYAN}╚════════════════════════════════════════════════════════════════════╝{RESET}\n")
691
+ print(f" • Local Guest (No account): 50,000 tokens/month [{GREEN}Active Now{RESET}]")
692
+ print(f" • Free Community Account: 500,000 tokens/month ({CYAN}10x Boost + Dashboard{RESET})\n")
693
+ print(" Authorizing takes 5 seconds (opens your browser) and gives you:")
694
+ print(" ✔ 500,000 free tokens every month")
695
+ print(" ✔ Cloud Web Dashboard & live analytics (tokensafe.dev/dashboard)")
696
+ print(" ✔ Full code search (scoped_search) & AST slicing\n")
697
+
698
+ answer = _read_input(f" {CYAN}→ Activate your free 500k Community license now? [{GREEN}Y{RESET}/n]: {RESET}").lower()
610
699
  if answer in ("", "y", "yes"):
611
700
  from src.cli import main as cli_main
612
701
  cli_main(["login"])
613
702
  else:
614
- print(f" {CYAN}ℹ{RESET} You can run {BOLD}tokensafe login{RESET} anytime to activate your account.\n")
703
+ # Intelligent One-More-Chance nudge highlighting quick exhaustion of guest quota
704
+ print(f"\n {YELLOW}⚠️ Are you sure?{RESET} In Guest mode, optimizations pause after only 50,000 tokens (~1-2 days of coding).")
705
+ second_chance = _read_input(f" {CYAN}→ Connect your free account now for 500,000 tokens/month? [{GREEN}y{RESET}/N]: {RESET}").lower()
706
+ if second_chance in ("y", "yes"):
707
+ from src.cli import main as cli_main
708
+ cli_main(["login"])
709
+ else:
710
+ print(f"\n {CYAN}ℹ{RESET} Continuing in Guest Mode (50,000 tokens/mo limit).")
711
+ print(f" Run {BOLD}tokensafe login{RESET} anytime in your terminal to unlock 500,000 free tokens/mo!\n")
615
712
  except (EOFError, KeyboardInterrupt):
616
713
  print()
617
714
  return
@@ -834,6 +931,71 @@ WantedBy=default.target
834
931
 
835
932
  return True, f"Configured MCP, Plugin, Skill & AGENTS.md in {config_file}"
836
933
 
934
+ elif info["type"] == "kimi_plugin":
935
+ mcp_file = info.get("config_path")
936
+ if mcp_file:
937
+ os.makedirs(os.path.dirname(mcp_file), exist_ok=True)
938
+ data, err = cls._load_json_with_backup(mcp_file)
939
+ if err or data is None:
940
+ data = {}
941
+ if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
942
+ data["mcpServers"] = {}
943
+ data["mcpServers"]["tokensafe"] = {
944
+ "command": PYTHON_BIN,
945
+ "args": [MCP_SERVER_PATH]
946
+ }
947
+ cls._atomic_write_json(mcp_file, data)
948
+
949
+ managed_plugin_path = info.get("managed_plugin_path")
950
+ if managed_plugin_path:
951
+ cls._symlink_dir(PROJECT_ROOT, managed_plugin_path)
952
+
953
+ installed_json = info.get("installed_json_path")
954
+ if installed_json:
955
+ os.makedirs(os.path.dirname(installed_json), exist_ok=True)
956
+ inst_data, err = cls._load_json_with_backup(installed_json)
957
+ if err or inst_data is None:
958
+ inst_data = {"version": 1, "plugins": []}
959
+ if "plugins" not in inst_data or not isinstance(inst_data["plugins"], list):
960
+ inst_data["plugins"] = []
961
+
962
+ import datetime
963
+ iso_now = datetime.datetime.now(datetime.timezone.utc).isoformat()
964
+ plugin_root = managed_plugin_path or PROJECT_ROOT
965
+
966
+ entry_found = False
967
+ for p in inst_data["plugins"]:
968
+ if isinstance(p, dict) and p.get("id") == "tokensafe":
969
+ p["root"] = plugin_root
970
+ p["enabled"] = True
971
+ p["updatedAt"] = iso_now
972
+ p["originalSource"] = PROJECT_ROOT
973
+ p["iconUrl"] = "https://tokensafe.dev/logo.png"
974
+ p["logo"] = "https://tokensafe.dev/logo.png"
975
+ entry_found = True
976
+ break
977
+ if not entry_found:
978
+ inst_data["plugins"].append({
979
+ "id": "tokensafe",
980
+ "root": plugin_root,
981
+ "enabled": True,
982
+ "installedAt": iso_now,
983
+ "updatedAt": iso_now,
984
+ "originalSource": PROJECT_ROOT,
985
+ "origin": "custom",
986
+ "iconUrl": "https://tokensafe.dev/logo.png",
987
+ "logo": "https://tokensafe.dev/logo.png"
988
+ })
989
+ cls._atomic_write_json(installed_json, inst_data)
990
+
991
+ if "skills_path" in info:
992
+ cls._symlink_skill(info["skills_path"])
993
+
994
+ if "agents_md_path" in info:
995
+ cls._inject_global_rule(info["agents_md_path"], UNIFIED_TOKENSAFE_RULE)
996
+
997
+ return True, f"Configured MCP, Plugin, Skill & AGENTS.md for Kimi Code"
998
+
837
999
  return False, "Unsupported type"
838
1000
 
839
1001
  @staticmethod
@@ -83,6 +83,7 @@ class LicenseManager:
83
83
  _QUOTA_TURN_COUNTERS: Dict[str, int] = {}
84
84
 
85
85
  TIERS = {
86
+ "guest": {"max_tokens_monthly": 50_000, "team_analytics": False},
86
87
  "free": {"max_tokens_monthly": 500_000, "team_analytics": False},
87
88
  "solo": {"max_tokens_monthly": None, "team_analytics": False},
88
89
  "team": {"max_tokens_monthly": None, "team_analytics": True},
@@ -478,13 +479,26 @@ class LicenseManager:
478
479
 
479
480
  @classmethod
480
481
  def get_active_license(cls) -> Tuple[str, Dict[str, Any]]:
481
- """Retrieves active license from env or persistent license.json files, falling back to free tier."""
482
+ """
483
+ Retrieves active license from env or persistent license.json files.
484
+ Falls back to 'guest' tier (50,000 tokens/month) if no license is present.
485
+ Legacy anonymous licenses (email == 'community@tokensafe.dev') are mapped to 'guest'.
486
+ Verified personal licenses (tier == 'free' with user email) get 'free' (500,000 tokens/month).
487
+ """
482
488
  resolved, _ = cls._resolve_active_license_record()
483
489
  if resolved is not None:
484
490
  _, payload = resolved
485
- return payload.get("tier", "solo"), payload
486
-
487
- return "free", {"tier": "free", "max_tokens_monthly": 500_000}
491
+ tier = payload.get("tier", "solo")
492
+ email = str(payload.get("email") or "").strip().lower()
493
+ if tier == "free" and email == "community@tokensafe.dev":
494
+ guest_payload = dict(payload)
495
+ guest_payload["tier"] = "guest"
496
+ guest_payload["max_tokens_monthly"] = 50_000
497
+ guest_payload["is_legacy_community"] = True
498
+ return "guest", guest_payload
499
+ return tier, payload
500
+
501
+ return "guest", {"tier": "guest", "max_tokens_monthly": 50_000}
488
502
 
489
503
  @classmethod
490
504
  def get_active_license_key(cls) -> str:
@@ -622,12 +636,14 @@ class LicenseManager:
622
636
  }
623
637
  """
624
638
  tier, payload = cls.get_active_license()
625
- tier_cfg = cls.TIERS.get(tier, cls.TIERS["free"])
639
+ tier_cfg = cls.TIERS.get(tier, cls.TIERS["guest"] if tier == "guest" else cls.TIERS["free"])
626
640
  max_tokens = tier_cfg.get("max_tokens_monthly")
627
641
 
628
- # Server-issued quota (community license payload) overrides the embedded
629
- # default — enables remote quota control without a client release.
630
- if max_tokens is not None and isinstance(payload, dict):
642
+ # Server-issued quota (community license payload) overrides embedded default for verified accounts.
643
+ # Guest tier is strictly capped to the guest limit (50,000).
644
+ if tier == "guest":
645
+ max_tokens = 50_000
646
+ elif max_tokens is not None and isinstance(payload, dict):
631
647
  try:
632
648
  server_quota = int(payload.get("max_tokens_monthly") or 0)
633
649
  if server_quota > 0:
@@ -645,7 +661,7 @@ class LicenseManager:
645
661
  "warning": None
646
662
  }
647
663
 
648
- # For free tier, calculate trailing 30 days saved tokens
664
+ # For guest / free tier, calculate monthly saved tokens
649
665
  if tracker is None:
650
666
  try:
651
667
  from src.metrics import MetricsTracker
@@ -655,24 +671,61 @@ class LicenseManager:
655
671
 
656
672
  local_saved = tracker.get_monthly_saved_tokens() if tracker else 0
657
673
  server_floor = cls._get_server_quota_floor(tracker)
658
- monthly_saved = max(local_saved, server_floor)
674
+
675
+ # Guest state backup floor (prevents simple metrics.db deletion within same calendar month)
676
+ guest_floor = 0
677
+ if tier == "guest":
678
+ try:
679
+ data_dir = resolve_data_dir()
680
+ gstate_file = os.path.join(data_dir, "guest_state.json")
681
+ cur_month = time.strftime("%Y-%m")
682
+ if os.path.exists(gstate_file):
683
+ with open(gstate_file, "r", encoding="utf-8") as gf:
684
+ gdata = json.load(gf)
685
+ if gdata.get("month") == cur_month:
686
+ guest_floor = int(gdata.get("saved_tokens", 0) or 0)
687
+ if local_saved > guest_floor:
688
+ os.makedirs(data_dir, exist_ok=True)
689
+ with open(gstate_file, "w", encoding="utf-8") as gf:
690
+ json.dump({"month": cur_month, "saved_tokens": local_saved}, gf)
691
+ except Exception:
692
+ pass
693
+
694
+ monthly_saved = max(local_saved, server_floor, guest_floor)
659
695
  exceeded = monthly_saved >= max_tokens
660
696
 
661
697
  warning = None
662
698
  if exceeded:
663
- warning = (
664
- f"⚡ **TokenSafe Quota Alert**: Community Edition limit reached "
665
- f"({monthly_saved:,}/{max_tokens:,} measured tokens saved this month). "
666
- f"Graph/signature AST slicing, pointer dedup, history compaction & KV-cache prefix locking are paused "
667
- f"(Security Guard stays active). Upgrade to Solo ($9/mo) or 7-Day Team Trial: "
668
- f"`tokensafe activate <key>` or create your account at https://tokensafe.dev/signup"
669
- )
670
- elif monthly_saved >= int(max_tokens * 0.85):
671
- warning = (
672
- f"⚡ **TokenSafe Quota Notice**: Community Edition is at {int(monthly_saved / max_tokens * 100)}% of monthly limit "
673
- f"({monthly_saved:,}/{max_tokens:,} measured tokens). "
674
- f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev/signup"
675
- )
699
+ if tier == "guest":
700
+ warning = (
701
+ f"⚡ **TokenSafe Quota Alert**: Guest limit reached "
702
+ f"({monthly_saved:,}/{max_tokens:,} measured tokens saved this month). "
703
+ f"Optimizers & code search are paused (Security Guard stays active). "
704
+ f"Run `tokensafe login` in your terminal for 500,000 free tokens/month, "
705
+ f"or upgrade to Solo ($9/mo) at https://tokensafe.dev/pricing"
706
+ )
707
+ else:
708
+ warning = (
709
+ f"⚡ **TokenSafe Quota Alert**: Community Edition limit reached "
710
+ f"({monthly_saved:,}/{max_tokens:,} measured tokens saved this month). "
711
+ f"Graph/signature AST slicing, pointer dedup, history compaction & KV-cache prefix locking are paused "
712
+ f"(Security Guard stays active). Upgrade to Solo ($9/mo) or 7-Day Team Trial: "
713
+ f"`tokensafe activate <key>` or create your account at https://tokensafe.dev/signup"
714
+ )
715
+ elif monthly_saved >= int(max_tokens * 0.80):
716
+ pct = int(monthly_saved / max_tokens * 100)
717
+ if tier == "guest":
718
+ warning = (
719
+ f"⚡ **TokenSafe Quota Notice**: Guest mode is at {pct}% of monthly limit "
720
+ f"({monthly_saved:,}/{max_tokens:,} measured tokens). "
721
+ f"Run `tokensafe login` in your terminal to unlock 500,000 free tokens/month!"
722
+ )
723
+ else:
724
+ warning = (
725
+ f"⚡ **TokenSafe Quota Notice**: Community Edition is at {pct}% of monthly limit "
726
+ f"({monthly_saved:,}/{max_tokens:,} measured tokens). "
727
+ f"Upgrade to Solo for unlimited optimization: `tokensafe activate <key>` or https://tokensafe.dev/signup"
728
+ )
676
729
 
677
730
  return {
678
731
  "tier": tier,
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.1.7"
45
+ "version": "4.1.9"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -54,7 +54,7 @@ _EPOCH_GEN = 0
54
54
  _IN_PROCESS_DELIVERED = {}
55
55
  _KNOWN_POINTER_CLIENTS = (
56
56
  "antigravity", "claude", "cursor", "windsurf", "cline", "roo",
57
- "codex", "zcode", "copilot", "gemini", "zed", "vscode",
57
+ "codex", "zcode", "kimi", "copilot", "gemini", "zed", "vscode",
58
58
  )
59
59
 
60
60
 
@@ -766,7 +766,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
766
766
 
767
767
 
768
768
  def _quota_banner_if_due(quota: dict, tracker, session_id: str) -> str:
769
- """Emits a concise Community 500k quota CTA on turn #1 of exceedance and every 5 turns."""
769
+ """Emits a concise quota CTA on turn #1 of exceedance and every 5 turns."""
770
770
  if not quota.get("is_quota_exceeded"):
771
771
  return ""
772
772
  if LicenseManager.should_emit_quota_banner(tracker, session_id=session_id, every_n_turns=5):
@@ -774,6 +774,15 @@ def _quota_banner_if_due(quota: dict, tracker, session_id: str) -> str:
774
774
  return ""
775
775
 
776
776
 
777
+ def _tier_quota_limit_msg(quota: dict) -> str:
778
+ """Returns a concise description of the active tier's quota limit and activation CTA."""
779
+ tier = str(quota.get("tier") or "guest").lower()
780
+ limit = int(quota.get("monthly_limit") or (50000 if tier == "guest" else 500000))
781
+ tier_name = "Guest 50k" if tier == "guest" else "Community 500k"
782
+ cta = "Run 'tokensafe login' in your terminal for 500,000 free tokens/month." if tier == "guest" else "Upgrade to Solo: https://tokensafe.dev/pricing"
783
+ return f"{tier_name} monthly limit ({limit:,} tokens) reached; optimizations paused ({cta})."
784
+
785
+
777
786
  def _dispatch_tool_call(name: str, args: dict) -> dict:
778
787
  global _EPOCH_GEN
779
788
  tracker = _get_safe_tracker()
@@ -962,7 +971,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
962
971
  raw_lines.append(line)
963
972
  raw_chunk = "".join(raw_lines)
964
973
  if total_seen > cap:
965
- raw_chunk += f"\n// [TokenSafe Community 500k limit reached: showing raw lines 1-{cap} of {total_seen}. AST/graph slicing & pointer dedup are paused.]\n"
974
+ raw_chunk += f"\n// [TokenSafe {_tier_quota_limit_msg(quota)} Showing raw lines 1-{cap} of {total_seen}. AST/graph slicing & pointer dedup are paused.]\n"
966
975
  banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
967
976
  return {"content": [{"type": "text", "text": banner + (raw_chunk or "")}]}
968
977
 
@@ -1111,7 +1120,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1111
1120
  return _fallback_error("smart_bundle", "too many targets (max 8)")
1112
1121
  if is_quota_exceeded:
1113
1122
  LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
1114
- return {"content": [{"type": "text", "text": f"{quota.get('warning', '')}\n\nsmart_bundle is paused over the 500k Community limit. Use single smart_read_file calls, or activate a subscription at https://tokensafe.dev/#pricing."}]}
1123
+ tier_msg = _tier_quota_limit_msg(quota)
1124
+ return {"content": [{"type": "text", "text": f"{quota.get('warning', '')}\n\nsmart_bundle is paused: {tier_msg}"}]}
1115
1125
 
1116
1126
  inc_deps, _eff_dep_mode = _resolve_dep_mode(args)
1117
1127
  max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
@@ -1232,7 +1242,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1232
1242
  "saved_tokens": 0,
1233
1243
  "tier": "QUOTA_EXCEEDED",
1234
1244
  "quota_exceeded": True,
1235
- "warning": quota.get("warning") if emit_warn else "Community 500k monthly limit reached; prompt compaction paused.",
1245
+ "warning": quota.get("warning") if emit_warn else _tier_quota_limit_msg(quota),
1236
1246
  }
1237
1247
  return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
1238
1248
  res = PromptCompactor.compact(prompt, enable_distill=True)
@@ -1349,7 +1359,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1349
1359
  "blocked": False,
1350
1360
  "tokens_saved": 0,
1351
1361
  "quota_exceeded": True,
1352
- "reason": quota.get("warning") if emit_note else "Community 500k monthly limit reached; command output compression paused (Security Guard active).",
1362
+ "reason": quota.get("warning") if emit_note else _tier_quota_limit_msg(quota),
1353
1363
  }
1354
1364
  if guard_res.warning_only:
1355
1365
  result["warning"] = guard_res.reason
@@ -1708,6 +1718,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1708
1718
  raw_regex = args.get("use_regex")
1709
1719
  u_regex = None if raw_regex is None else bool(raw_regex)
1710
1720
 
1721
+ # Quota degradation: when monthly quota is reached, softly degrade scoped_search
1722
+ # to top 3 matches with an upgrade header rather than returning an empty block,
1723
+ # preventing the agent from deadlocking or panicking into blocked raw terminal grep.
1724
+ if is_quota_exceeded:
1725
+ max_res = min(max_res, 3)
1726
+
1711
1727
  res = ScopedSearch.search(
1712
1728
  query=query,
1713
1729
  project_path=target_path,
@@ -1720,6 +1736,21 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1720
1736
  if not res.get("success", True):
1721
1737
  return _fallback_error("scoped_search", md_text)
1722
1738
 
1739
+ if is_quota_exceeded:
1740
+ banner = _quota_banner_if_due(quota, tracker, _mcp_session_id())
1741
+ current_tier = str(quota.get("tier") or "guest").lower()
1742
+ limit_val = int(quota.get("monthly_limit") or (50000 if current_tier == "guest" else 500000))
1743
+ if current_tier == "guest":
1744
+ cta_note = "Run 'tokensafe login' in your terminal to unlock 500,000 free tokens/month!"
1745
+ else:
1746
+ cta_note = "Upgrade to Solo for unlimited optimization: https://tokensafe.dev/pricing"
1747
+ degraded_header = (
1748
+ f"// [TokenSafe Quota Notice: {current_tier.upper()} limit of {limit_val:,} tokens reached. "
1749
+ f"Showing top {max_res} matches in degraded mode.]\n"
1750
+ f"// [{cta_note}]\n\n"
1751
+ )
1752
+ return {"content": [{"type": "text", "text": banner + degraded_header + md_text}]}
1753
+
1723
1754
  res_tokens = count_tokens(md_text)
1724
1755
  est_orig = max(1500, res_tokens * 8)
1725
1756
  tracker.record_event(
package/src/metrics.py CHANGED
@@ -15,7 +15,7 @@ from typing import Dict, List, Optional, Any, Generator
15
15
 
16
16
  from src.paths import resolve_data_dir
17
17
 
18
- USD_PER_TOKEN = 1.50 / 1_000_000.0
18
+ USD_PER_TOKEN = 3.00 / 1_000_000.0 # Claude Sonnet baseline ($3.00 / 1M tokens)
19
19
 
20
20
  # Event types whose `original_tokens` baseline is a counterfactual estimate rather
21
21
  # than literally metered I/O (see METRICS.md). Everything else counts as measured.
@@ -618,7 +618,7 @@ class MetricsTracker:
618
618
  "total_saved_tokens_estimated": saved_estimated,
619
619
  "overall_reduction_pct": round(overall_reduction, 1),
620
620
  "total_usd_saved": round(total_usd, 4),
621
- "total_usd_saved_approx": True, # USD is a derived estimate (~$1.5/M blended), never a bill
621
+ "total_usd_saved_approx": True, # USD is a derived estimate (~$3.0/M Claude Sonnet baseline), never a bill
622
622
  "by_agent": self.get_by_agent(),
623
623
  "breakdown": combined_breakdown
624
624
  }
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.1.7"
244
+ "User-Agent": "TokenSafe-Sync/4.1.9"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.1.7"
20
+ CURRENT_VERSION = "4.1.9"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage