tokensafe 4.1.8 → 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.
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +2 -2
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +4 -4
- package/src/cli.py +27 -10
- package/src/dashboard.py +17 -6
- package/src/installer.py +44 -14
- package/src/license_manager.py +76 -23
- package/src/mcp_server.py +37 -6
- package/src/metrics.py +2 -2
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
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,
|
|
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
|
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.1.
|
|
3
|
+
"version": "4.1.9",
|
|
4
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
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.1.
|
|
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": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.1.
|
|
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
|
"logo": "https://tokensafe.dev/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
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": "Your
|
|
6
|
-
"version": "4.1.
|
|
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.
|
|
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.
|
|
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 == "
|
|
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
|
|
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 == "
|
|
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 × $
|
|
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")
|
|
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 —
|
|
193
|
-
md.append(f"> **Plan:**
|
|
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
|
@@ -617,7 +617,9 @@ WantedBy=default.target
|
|
|
617
617
|
try:
|
|
618
618
|
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
|
619
619
|
return
|
|
620
|
-
if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes")
|
|
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"):
|
|
621
623
|
return
|
|
622
624
|
st = cls.proxy_status()
|
|
623
625
|
if st.get("claude_code_wired"):
|
|
@@ -644,41 +646,69 @@ WantedBy=default.target
|
|
|
644
646
|
@classmethod
|
|
645
647
|
def maybe_prompt_account_login(cls, context: str = "install") -> None:
|
|
646
648
|
"""
|
|
647
|
-
Interactive prompt to connect TokenSafe account and unlock web dashboard.
|
|
648
|
-
Migrates anonymous community@tokensafe.dev
|
|
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.
|
|
649
653
|
Fail-open: skips quietly on non-interactive environments (CI, scripts).
|
|
650
654
|
"""
|
|
651
655
|
try:
|
|
652
656
|
from src.license_manager import LicenseManager
|
|
653
|
-
|
|
657
|
+
tier, lic = LicenseManager.get_active_license()
|
|
654
658
|
email = lic.get("email", "")
|
|
655
659
|
|
|
656
660
|
# If user already has a real personal account (not the legacy anonymous key), nothing to prompt
|
|
657
661
|
if email and email != "community@tokensafe.dev":
|
|
658
662
|
return
|
|
659
663
|
|
|
660
|
-
|
|
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
|
|
661
668
|
|
|
662
|
-
|
|
669
|
+
has_tty = sys.stdin.isatty() or (os.path.exists("/dev/tty") and sys.stdout.isatty())
|
|
670
|
+
if not has_tty:
|
|
663
671
|
print(f" {CYAN}ℹ{RESET} Run {BOLD}tokensafe login{RESET} anytime to activate your Community license & web dashboard.\n")
|
|
664
672
|
return
|
|
665
673
|
|
|
666
|
-
|
|
667
|
-
|
|
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")
|
|
668
683
|
|
|
669
684
|
if context == "update":
|
|
670
|
-
|
|
671
|
-
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")
|
|
672
686
|
return
|
|
673
687
|
|
|
674
|
-
print(f"\n
|
|
675
|
-
print(f"
|
|
676
|
-
|
|
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()
|
|
677
699
|
if answer in ("", "y", "yes"):
|
|
678
700
|
from src.cli import main as cli_main
|
|
679
701
|
cli_main(["login"])
|
|
680
702
|
else:
|
|
681
|
-
|
|
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")
|
|
682
712
|
except (EOFError, KeyboardInterrupt):
|
|
683
713
|
print()
|
|
684
714
|
return
|
package/src/license_manager.py
CHANGED
|
@@ -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
|
-
"""
|
|
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
|
-
|
|
486
|
-
|
|
487
|
-
|
|
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
|
|
629
|
-
#
|
|
630
|
-
if
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
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.
|
|
45
|
+
"version": "4.1.9"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -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
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
|
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 =
|
|
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 (~$
|
|
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
|
}
|
package/src/telemetry_sync.py
CHANGED
|
@@ -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.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.1.9"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -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.
|
|
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
|