tokensafe 4.1.9 → 4.1.11
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/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/cli.py +131 -8
- package/src/compactor.py +3 -2
- package/src/distiller.py +79 -11
- package/src/egress_counter.py +72 -0
- package/src/environment_auditor.py +10 -0
- package/src/installer.py +33 -1
- package/src/mcp_server.py +1 -1
- package/src/telemetry_sync.py +3 -1
- package/src/version_checker.py +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "4.1.
|
|
2
|
+
"version": "4.1.11",
|
|
3
3
|
"name": "tokensafe",
|
|
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
|
"author": {
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.1.
|
|
3
|
+
"version": "4.1.11",
|
|
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.11",
|
|
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.11",
|
|
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
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your agent isn't getting dumber, your context is full of trash. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.1.
|
|
6
|
+
"version": "4.1.11",
|
|
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.11",
|
|
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.11",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
package/src/cli.py
CHANGED
|
@@ -118,6 +118,7 @@ def _print_help():
|
|
|
118
118
|
print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
|
|
119
119
|
print(" check-update Check for a newer published version")
|
|
120
120
|
print(" activate / license License activation and status")
|
|
121
|
+
print(" booster on|off|status Cloud Prompt Booster control (paid tiers)")
|
|
121
122
|
print(" login / auth Authorize this device via browser login")
|
|
122
123
|
print(" logout / unlink Unlink this device and remove local license")
|
|
123
124
|
print(" sync Sync telemetry with the cloud backend")
|
|
@@ -125,6 +126,46 @@ def _print_help():
|
|
|
125
126
|
print(" --version Print version and exit")
|
|
126
127
|
|
|
127
128
|
|
|
129
|
+
def _booster_consent_prompt() -> None:
|
|
130
|
+
"""One-time Cloud Prompt Booster consent after a PAID license activation.
|
|
131
|
+
|
|
132
|
+
Asks [Y/n] with an honest data-flow disclosure (default Y). Non-TTY runs
|
|
133
|
+
keep the legacy default (on) and print a disable hint instead of blocking.
|
|
134
|
+
Users who already chose (config/env) are never re-asked. Fail-open: a
|
|
135
|
+
broken TTY never blocks activation.
|
|
136
|
+
"""
|
|
137
|
+
try:
|
|
138
|
+
from src.distiller import UniversalDistiller
|
|
139
|
+
if UniversalDistiller.is_self_hosted():
|
|
140
|
+
return # BYOK self-hosted: own keys are their own explicit opt-in
|
|
141
|
+
_enabled, explicitly_set = UniversalDistiller.cloud_booster_enabled()
|
|
142
|
+
if explicitly_set:
|
|
143
|
+
return
|
|
144
|
+
interactive = sys.stdin.isatty() and sys.stdout.isatty()
|
|
145
|
+
if interactive:
|
|
146
|
+
print("\n \033[1m⚡ Cloud Prompt Booster\033[0m — distills long prompts (100+ tokens) cloud-side,")
|
|
147
|
+
print(" ~5x deeper compression than the local engine (measured median 71% vs 14%).")
|
|
148
|
+
print(" \033[2mWhat leaves this machine:\033[0m the prompt text (may include code snippets or stack")
|
|
149
|
+
print(" \033[2mtraces) with secrets automatically scrubbed. Processed transiently via TokenSafe")
|
|
150
|
+
print(" \033[2mCloud (Google Gemini Flash-Lite); raw text is never stored and not used for training.\033[0m")
|
|
151
|
+
try:
|
|
152
|
+
answer = input(" Enable Cloud Prompt Booster? [Y/n]: ").strip().lower()
|
|
153
|
+
except (EOFError, KeyboardInterrupt):
|
|
154
|
+
answer = ""
|
|
155
|
+
print()
|
|
156
|
+
chosen = answer in ("", "y", "yes")
|
|
157
|
+
else:
|
|
158
|
+
chosen = True # non-interactive: keep the legacy default + hint
|
|
159
|
+
UniversalDistiller.write_config_value("cloud_distill", chosen)
|
|
160
|
+
if chosen:
|
|
161
|
+
suffix = "" if interactive else " \033[2m(default — run \033[36mtokensafe booster off\033[0m \033[2mto disable)\033[0m"
|
|
162
|
+
print(f" \033[32m✔ Cloud Prompt Booster enabled.\033[0m{suffix}")
|
|
163
|
+
else:
|
|
164
|
+
print(" \033[33m○ Cloud Prompt Booster off — all prompt processing stays 100% local.\033[0m")
|
|
165
|
+
except Exception:
|
|
166
|
+
pass
|
|
167
|
+
|
|
168
|
+
|
|
128
169
|
def main(argv: Optional[List[str]] = None):
|
|
129
170
|
args = sys.argv[1:] if argv is None else list(argv)
|
|
130
171
|
command = args[0] if args else "stats"
|
|
@@ -204,6 +245,22 @@ def main(argv: Optional[List[str]] = None):
|
|
|
204
245
|
print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo · 7-Day Team Trial)")
|
|
205
246
|
else:
|
|
206
247
|
print(f" Tier: \033[32m{tier.upper()}\033[0m (Unlimited)")
|
|
248
|
+
try:
|
|
249
|
+
from src.distiller import UniversalDistiller
|
|
250
|
+
enabled, explicitly_set = UniversalDistiller.cloud_booster_enabled(tier)
|
|
251
|
+
state = "\033[32mon\033[0m" if enabled else "\033[33moff\033[0m"
|
|
252
|
+
if not explicitly_set:
|
|
253
|
+
state += " \033[2m(active by default — choose: \033[36mtokensafe booster on|off\033[0m\033[2m)\033[0m"
|
|
254
|
+
print(f" Booster: Cloud Prompt Booster {state}")
|
|
255
|
+
except Exception:
|
|
256
|
+
pass
|
|
257
|
+
# Verifiable egress transparency: what left this machine today
|
|
258
|
+
try:
|
|
259
|
+
from src.egress_counter import today_counts
|
|
260
|
+
_eg = today_counts()
|
|
261
|
+
print(f" Egress: today — {_eg['booster']} booster · {_eg['telemetry']} telemetry outbound requests")
|
|
262
|
+
except Exception:
|
|
263
|
+
pass
|
|
207
264
|
# Cloud heartbeat (non-blocking; keeps the machine visible server-side)
|
|
208
265
|
try:
|
|
209
266
|
TelemetrySync.sync_background()
|
|
@@ -371,6 +428,17 @@ def main(argv: Optional[List[str]] = None):
|
|
|
371
428
|
latest = info.get("latest_version", CURRENT_VERSION)
|
|
372
429
|
avail = info.get("update_available", False)
|
|
373
430
|
print(f" Latest version: v{latest}")
|
|
431
|
+
try:
|
|
432
|
+
from src.license_manager import LicenseManager
|
|
433
|
+
tier, lic = LicenseManager.get_active_license()
|
|
434
|
+
if tier == "guest":
|
|
435
|
+
from src.metrics import MetricsTracker
|
|
436
|
+
quota = LicenseManager.check_quota(MetricsTracker())
|
|
437
|
+
saved = int(quota.get("monthly_saved", 0))
|
|
438
|
+
pct = min(100.0, (saved / 50_000) * 100) if 50_000 > 0 else 0.0
|
|
439
|
+
print(f" \033[2mQuota:\033[0m \033[33mGuest Mode\033[0m ({saved:,} / 50,000 tokens used, {pct:.1f}%) • Run '\033[36mtokensafe login\033[0m' for 500k/mo.")
|
|
440
|
+
except Exception:
|
|
441
|
+
pass
|
|
374
442
|
banner = VersionChecker.get_banner()
|
|
375
443
|
if banner:
|
|
376
444
|
print(banner)
|
|
@@ -831,6 +899,10 @@ def main(argv: Optional[List[str]] = None):
|
|
|
831
899
|
print(" \033[32m✔ Community Edition license activated (500,000 free tokens/month).\033[0m")
|
|
832
900
|
print(f" \033[36m✔ Web dashboard unlocked at:\033[0m https://tokensafe.dev/dashboard\n")
|
|
833
901
|
|
|
902
|
+
# Cloud Prompt Booster consent (paid tiers only; already-chosen users skipped)
|
|
903
|
+
if detected_tier in ("solo", "team", "enterprise"):
|
|
904
|
+
_booster_consent_prompt()
|
|
905
|
+
|
|
834
906
|
# Sync local token metrics
|
|
835
907
|
try:
|
|
836
908
|
from src.telemetry_sync import TelemetrySync
|
|
@@ -890,6 +962,13 @@ def main(argv: Optional[List[str]] = None):
|
|
|
890
962
|
ok, msg = LicenseManager.save_license(key)
|
|
891
963
|
if ok:
|
|
892
964
|
print(f"\n\033[32m\033[1m✔ {msg}\033[0m")
|
|
965
|
+
# Cloud Prompt Booster consent (paid tiers only; already-chosen users skipped)
|
|
966
|
+
try:
|
|
967
|
+
valid, lic_meta, _ = LicenseManager.validate_license(key)
|
|
968
|
+
if valid and str(lic_meta.get("tier", "")).lower() in ("solo", "team", "enterprise"):
|
|
969
|
+
_booster_consent_prompt()
|
|
970
|
+
except Exception:
|
|
971
|
+
pass
|
|
893
972
|
# Automatically report version and seat activation to cloud
|
|
894
973
|
try:
|
|
895
974
|
from src.version_checker import VersionChecker
|
|
@@ -959,22 +1038,66 @@ def main(argv: Optional[List[str]] = None):
|
|
|
959
1038
|
print(f" Expires: Never (Lifetime)")
|
|
960
1039
|
print()
|
|
961
1040
|
|
|
1041
|
+
elif command in ("booster",):
|
|
1042
|
+
from src.license_manager import LicenseManager
|
|
1043
|
+
from src.distiller import UniversalDistiller
|
|
1044
|
+
from src.egress_counter import today_counts
|
|
1045
|
+
sub = args[1].strip().lower() if len(args) > 1 else "status"
|
|
1046
|
+
tier, _ = LicenseManager.get_active_license()
|
|
1047
|
+
print("\n\033[1m\033[36m⚡ CLOUD PROMPT BOOSTER ⚡\033[0m\n")
|
|
1048
|
+
if tier not in UniversalDistiller.PAID_TIERS:
|
|
1049
|
+
print(" Cloud Prompt Booster distills long prompts (100+ tokens) cloud-side with")
|
|
1050
|
+
print(" ~5x deeper compression than the local engine. Available on Solo, Team, and Enterprise.")
|
|
1051
|
+
print(" Guest and Community tiers keep all prompt processing 100% local by design.\n")
|
|
1052
|
+
elif sub in ("on", "enable", "off", "disable"):
|
|
1053
|
+
value = sub in ("on", "enable")
|
|
1054
|
+
if UniversalDistiller.write_config_value("cloud_distill", value):
|
|
1055
|
+
if value:
|
|
1056
|
+
print(" \033[32m✔ Booster enabled\033[0m — long prompts are distilled via TokenSafe Cloud")
|
|
1057
|
+
print(" (secrets scrubbed before egress; raw text never stored; not used for training).")
|
|
1058
|
+
else:
|
|
1059
|
+
print(" \033[33m○ Booster disabled\033[0m — all prompt processing stays 100% local.")
|
|
1060
|
+
else:
|
|
1061
|
+
print(" \033[31m✖ Failed to write data/config.json — check permissions.\033[0m")
|
|
1062
|
+
print()
|
|
1063
|
+
else:
|
|
1064
|
+
enabled, explicitly_set = UniversalDistiller.cloud_booster_enabled(tier)
|
|
1065
|
+
eg = today_counts()
|
|
1066
|
+
state = "\033[32mon\033[0m" if enabled else "\033[33moff\033[0m"
|
|
1067
|
+
if not explicitly_set:
|
|
1068
|
+
state += " \033[2m(active by default — make an explicit choice below)\033[0m"
|
|
1069
|
+
print(f" Status: {state}")
|
|
1070
|
+
print(f" Egress: today — {eg['booster']} booster · {eg['telemetry']} telemetry outbound requests")
|
|
1071
|
+
print(" What it sends when on: prompt text (code snippets/stack traces possible) with secrets")
|
|
1072
|
+
print(" scrubbed → TokenSafe Cloud → Google Gemini Flash-Lite. Transient processing;")
|
|
1073
|
+
print(" raw text never stored, not used for training.")
|
|
1074
|
+
print(" Toggle: \033[36mtokensafe booster on|off\033[0m\n")
|
|
1075
|
+
|
|
962
1076
|
elif command in ("providers", "models", "keys"):
|
|
963
1077
|
from src.license_manager import LicenseManager
|
|
964
1078
|
from src.distiller import UniversalDistiller
|
|
965
1079
|
tier, _ = LicenseManager.get_active_license()
|
|
966
1080
|
print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
|
|
967
|
-
if tier
|
|
968
|
-
|
|
969
|
-
print("
|
|
970
|
-
print("
|
|
971
|
-
print("
|
|
1081
|
+
if tier not in UniversalDistiller.PAID_TIERS:
|
|
1082
|
+
tier_label = "Guest (Offline)" if tier == "guest" else "Free Community Edition"
|
|
1083
|
+
print(f" \033[33mTier: {tier_label}\033[0m")
|
|
1084
|
+
print(" Cloud Prompt Booster (managed distillation, zero API keys) is reserved for Solo, Team, and Enterprise tiers.")
|
|
1085
|
+
print(" Guest and Community Editions operate with the zero-latency, zero-cost Local Regex Compactor.\n")
|
|
1086
|
+
print(" \033[1mTo unlock the Cloud Prompt Booster:\033[0m")
|
|
972
1087
|
print(" 1. Start 7-day free trial or upgrade at: https://tokensafe.dev")
|
|
973
1088
|
print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
|
|
974
1089
|
elif not UniversalDistiller.is_self_hosted():
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
1090
|
+
enabled, explicitly_set = UniversalDistiller.cloud_booster_enabled(tier)
|
|
1091
|
+
if enabled:
|
|
1092
|
+
print(f" \033[32m✔\033[0m \033[1mCloud Prompt Booster\033[0m [Active: gemini-flash-lite-latest via TokenSafe Cloud]")
|
|
1093
|
+
print(" Long prompts (100+ tokens) are distilled cloud-side. Secrets are scrubbed before")
|
|
1094
|
+
print(" egress; raw text is never stored and is not used for training. Zero API keys required.")
|
|
1095
|
+
if not explicitly_set:
|
|
1096
|
+
print(" \033[2mActive by default for your plan — make an explicit choice: tokensafe booster on|off\033[0m")
|
|
1097
|
+
else:
|
|
1098
|
+
print(" \033[33m○ Cloud Prompt Booster: off\033[0m — long prompts stay on the local regex compactor.")
|
|
1099
|
+
print(" Enable anytime: \033[36mtokensafe booster on\033[0m")
|
|
1100
|
+
print()
|
|
978
1101
|
print(" \033[2m💡 Tip: To run self-hosted with custom BYOK keys in Docker, export TOKENSAFE_SELF_HOSTED=1.\033[0m\n")
|
|
979
1102
|
else:
|
|
980
1103
|
print(" \033[36mMode: Self-Hosted Docker (Custom BYOK Keys)\033[0m\n")
|
package/src/compactor.py
CHANGED
|
@@ -448,11 +448,12 @@ class PromptCompactor:
|
|
|
448
448
|
}
|
|
449
449
|
|
|
450
450
|
# Tier 2: Managed Cloud Intent Distiller (BYOK Gemini / OpenAI / DeepSeek for self-hosted)
|
|
451
|
-
# Exclusive to
|
|
451
|
+
# Exclusive to paid tiers (solo/team/enterprise); guest and community-free
|
|
452
|
+
# are hard-off — explicit paid set, not a != "free" string check.
|
|
452
453
|
min_distill = min_distill_tokens if min_distill_tokens is not None else cls._get_min_distill_tokens()
|
|
453
454
|
if enable_distill and original_tokens >= min_distill:
|
|
454
455
|
active_tier, _ = LicenseManager.get_active_license()
|
|
455
|
-
if active_tier
|
|
456
|
+
if active_tier in UniversalDistiller.PAID_TIERS:
|
|
456
457
|
distilled = UniversalDistiller.distill(raw_text)
|
|
457
458
|
if distilled:
|
|
458
459
|
dist_tokens = count_tokens(distilled)
|
package/src/distiller.py
CHANGED
|
@@ -25,6 +25,9 @@ class UniversalDistiller:
|
|
|
25
25
|
# distill() runs synchronously inside the PreInvocation lifecycle hook, so a
|
|
26
26
|
# dead/slow provider must not add seconds of latency to every single prompt.
|
|
27
27
|
FAILURE_COOLDOWN_SECONDS = 180.0
|
|
28
|
+
# Explicit paid set: 'guest' (offline 50k) and 'free' (community 500k) are both
|
|
29
|
+
# hard-off for ALL distillation — managed cloud AND BYOK env keys.
|
|
30
|
+
PAID_TIERS = ("solo", "team", "enterprise")
|
|
28
31
|
|
|
29
32
|
@classmethod
|
|
30
33
|
def _failure_state_path(cls) -> str:
|
|
@@ -59,6 +62,53 @@ class UniversalDistiller:
|
|
|
59
62
|
except Exception:
|
|
60
63
|
pass
|
|
61
64
|
|
|
65
|
+
@classmethod
|
|
66
|
+
def _read_config(cls) -> Dict[str, Any]:
|
|
67
|
+
config_path = os.path.join(resolve_data_dir(), "config.json")
|
|
68
|
+
try:
|
|
69
|
+
with open(config_path, "r", encoding="utf-8") as f:
|
|
70
|
+
data = json.load(f)
|
|
71
|
+
return data if isinstance(data, dict) else {}
|
|
72
|
+
except Exception:
|
|
73
|
+
return {}
|
|
74
|
+
|
|
75
|
+
@classmethod
|
|
76
|
+
def write_config_value(cls, key: str, value: Any) -> bool:
|
|
77
|
+
"""Atomic read-modify-write of a single data/config.json key."""
|
|
78
|
+
try:
|
|
79
|
+
config_path = os.path.join(resolve_data_dir(), "config.json")
|
|
80
|
+
data = cls._read_config()
|
|
81
|
+
data[key] = value
|
|
82
|
+
os.makedirs(os.path.dirname(config_path) or ".", exist_ok=True)
|
|
83
|
+
tmp = config_path + ".tmp"
|
|
84
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
85
|
+
json.dump(data, f, indent=1)
|
|
86
|
+
os.replace(tmp, config_path)
|
|
87
|
+
return True
|
|
88
|
+
except Exception:
|
|
89
|
+
return False
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def cloud_booster_enabled(cls, tier: str = "") -> Tuple[bool, bool]:
|
|
93
|
+
"""Returns (enabled, explicitly_set) for the Cloud Prompt Booster.
|
|
94
|
+
|
|
95
|
+
- guest / free tiers: always (False, True) — hard-off, env keys ignored.
|
|
96
|
+
- paid tiers: env TOKENSAFE_CLOUD_DISTILL wins, then config.json
|
|
97
|
+
`cloud_distill`; an UNSET flag defaults to ON (legacy behavior — the
|
|
98
|
+
CLI surfaces a disclosure so nobody's behavior changes silently).
|
|
99
|
+
"""
|
|
100
|
+
if not tier:
|
|
101
|
+
tier, _ = LicenseManager.get_active_license()
|
|
102
|
+
if tier not in cls.PAID_TIERS:
|
|
103
|
+
return (False, True)
|
|
104
|
+
env = os.environ.get("TOKENSAFE_CLOUD_DISTILL", "").strip().lower()
|
|
105
|
+
if env:
|
|
106
|
+
return (env in ("1", "true", "yes", "on"), True)
|
|
107
|
+
cfg_value = cls._read_config().get("cloud_distill")
|
|
108
|
+
if cfg_value is None:
|
|
109
|
+
return (True, False)
|
|
110
|
+
return (bool(cfg_value), True)
|
|
111
|
+
|
|
62
112
|
SYSTEM_PROMPT = """You are a multilingual semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
|
|
63
113
|
(ACTION [filepath] [symbol] [[traits...]] ["minimal_intent"])
|
|
64
114
|
|
|
@@ -99,7 +149,7 @@ Rules:
|
|
|
99
149
|
"env_key": "GEMINI_API_KEY",
|
|
100
150
|
"config_key": "gemini_api_key",
|
|
101
151
|
"default_model": "gemini-flash-lite-latest",
|
|
102
|
-
"endpoint": "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent
|
|
152
|
+
"endpoint": "https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent"
|
|
103
153
|
}
|
|
104
154
|
}
|
|
105
155
|
|
|
@@ -110,9 +160,15 @@ Rules:
|
|
|
110
160
|
|
|
111
161
|
@classmethod
|
|
112
162
|
def _call_cloud_distill(cls, raw_text: str, lic_key: str, mode: str = "") -> Optional[str]:
|
|
163
|
+
from src.secret_redactor import SecretRedactor
|
|
164
|
+
from src.egress_counter import increment as _egress_increment
|
|
165
|
+
from src.version_checker import CURRENT_VERSION
|
|
113
166
|
cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
|
|
114
167
|
endpoint = f"{cloud_url}/api/distill"
|
|
115
|
-
|
|
168
|
+
# Egress hygiene: scrub secrets from whatever leaves this machine. Idempotent
|
|
169
|
+
# with the compactor's own redaction pass (anchors are not re-matched).
|
|
170
|
+
scrubbed_text, _, _ = SecretRedactor.redact_text(raw_text)
|
|
171
|
+
payload = {"prompt": scrubbed_text.strip()}
|
|
116
172
|
if mode:
|
|
117
173
|
payload["mode"] = mode
|
|
118
174
|
timeout = cls.HISTORY_DISTILL_TIMEOUT if mode == "history" else cls.DEFAULT_TIMEOUT
|
|
@@ -122,10 +178,11 @@ Rules:
|
|
|
122
178
|
headers={
|
|
123
179
|
"Authorization": f"Bearer {lic_key}",
|
|
124
180
|
"Content-Type": "application/json",
|
|
125
|
-
"User-Agent": "TokenSafe/
|
|
181
|
+
"User-Agent": f"TokenSafe/{CURRENT_VERSION}"
|
|
126
182
|
}
|
|
127
183
|
)
|
|
128
184
|
try:
|
|
185
|
+
_egress_increment("booster")
|
|
129
186
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
130
187
|
if resp.status == 200:
|
|
131
188
|
data = json.loads(resp.read().decode("utf-8"))
|
|
@@ -155,7 +212,7 @@ Rules:
|
|
|
155
212
|
if cached:
|
|
156
213
|
return cached
|
|
157
214
|
tier, _ = LicenseManager.get_active_license()
|
|
158
|
-
if tier
|
|
215
|
+
if tier not in cls.PAID_TIERS:
|
|
159
216
|
return None
|
|
160
217
|
providers = cls.get_configured_providers()
|
|
161
218
|
if "cloud" not in providers:
|
|
@@ -173,16 +230,24 @@ Rules:
|
|
|
173
230
|
|
|
174
231
|
@classmethod
|
|
175
232
|
def get_configured_providers(cls) -> Dict[str, Dict[str, Any]]:
|
|
176
|
-
"""Scans environment and data/config.json for configured LLM distillation keys.
|
|
233
|
+
"""Scans environment and data/config.json for configured LLM distillation keys.
|
|
234
|
+
|
|
235
|
+
Cloud Prompt Booster (managed cloud) requires a PAID tier — guest and
|
|
236
|
+
community-free are hard-off — AND the booster consent flag (config.json
|
|
237
|
+
`cloud_distill` or env TOKENSAFE_CLOUD_DISTILL); unset defaults to ON
|
|
238
|
+
for paid tiers (legacy behavior, disclosed by the CLI)."""
|
|
177
239
|
tier, _ = LicenseManager.get_active_license()
|
|
178
|
-
if tier
|
|
240
|
+
if tier not in cls.PAID_TIERS:
|
|
179
241
|
return {}
|
|
180
242
|
|
|
181
243
|
if not cls.is_self_hosted():
|
|
244
|
+
enabled, _explicitly_set = cls.cloud_booster_enabled(tier)
|
|
245
|
+
if not enabled:
|
|
246
|
+
return {}
|
|
182
247
|
return {
|
|
183
248
|
"cloud": {
|
|
184
249
|
"provider": "cloud",
|
|
185
|
-
"name": "
|
|
250
|
+
"name": "Cloud Prompt Booster",
|
|
186
251
|
"model": "gemini-flash-lite-latest",
|
|
187
252
|
"status": "managed"
|
|
188
253
|
}
|
|
@@ -236,10 +301,10 @@ Rules:
|
|
|
236
301
|
"""
|
|
237
302
|
Distills raw conversational text into an S-Expression using the best available provider.
|
|
238
303
|
Priority: Managed Cloud (license-auth, zero keys) -> Explicit preferred -> Gemini -> OpenAI -> DeepSeek.
|
|
239
|
-
Requires active
|
|
304
|
+
Requires an active paid subscription (solo/team/enterprise; guest & free are hard-off).
|
|
240
305
|
"""
|
|
241
306
|
tier, _ = LicenseManager.get_active_license()
|
|
242
|
-
if tier
|
|
307
|
+
if tier not in cls.PAID_TIERS:
|
|
243
308
|
return None
|
|
244
309
|
|
|
245
310
|
if not raw_text or len(raw_text.strip()) < 10:
|
|
@@ -351,7 +416,9 @@ Rules:
|
|
|
351
416
|
|
|
352
417
|
@classmethod
|
|
353
418
|
def _call_gemini(cls, conf: Dict[str, Any], raw_text: str) -> Optional[str]:
|
|
354
|
-
|
|
419
|
+
# Key goes in the x-goog-api-key header, never in the URL (URLs end up in
|
|
420
|
+
# proxy/access logs; headers do not).
|
|
421
|
+
endpoint = conf["endpoint"].format(model=conf["model"])
|
|
355
422
|
payload = {
|
|
356
423
|
"systemInstruction": {
|
|
357
424
|
"parts": [{"text": cls.SYSTEM_PROMPT}]
|
|
@@ -370,7 +437,8 @@ Rules:
|
|
|
370
437
|
data=json.dumps(payload).encode("utf-8"),
|
|
371
438
|
headers={
|
|
372
439
|
"Content-Type": "application/json",
|
|
373
|
-
"User-Agent": "TokenSafe/1.0"
|
|
440
|
+
"User-Agent": "TokenSafe/1.0",
|
|
441
|
+
"x-goog-api-key": conf["api_key"]
|
|
374
442
|
}
|
|
375
443
|
)
|
|
376
444
|
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Egress Counter: day-keyed outbound-request transparency ledger.
|
|
3
|
+
|
|
4
|
+
Tracks HTTP requests that carry user content or machine metadata off the
|
|
5
|
+
device (Cloud Prompt Booster distillation, telemetry sync) so
|
|
6
|
+
`tokensafe status` can show a verifiable "what left this machine today" line.
|
|
7
|
+
Deliberately local-only, dependency-free, and fail-open: a counter failure
|
|
8
|
+
must never break the network path it observes.
|
|
9
|
+
|
|
10
|
+
Storage: <data_dir>/egress.json — {"YYYY-MM-DD": {"booster": N, "telemetry": M}}
|
|
11
|
+
(only the trailing 14 days are kept to bound the file size).
|
|
12
|
+
"""
|
|
13
|
+
import datetime
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import threading
|
|
17
|
+
from typing import Dict
|
|
18
|
+
|
|
19
|
+
from src.paths import resolve_data_dir
|
|
20
|
+
|
|
21
|
+
_LOCK = threading.Lock()
|
|
22
|
+
KINDS = ("booster", "telemetry")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _egress_path() -> str:
|
|
26
|
+
return os.path.join(resolve_data_dir(), "egress.json")
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _load(path: str) -> Dict[str, Dict[str, int]]:
|
|
30
|
+
try:
|
|
31
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
32
|
+
data = json.load(f)
|
|
33
|
+
return data if isinstance(data, dict) else {}
|
|
34
|
+
except Exception:
|
|
35
|
+
return {}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def increment(kind: str) -> None:
|
|
39
|
+
"""Records one outbound request of `kind` for today (fail-open, never raises)."""
|
|
40
|
+
if kind not in KINDS:
|
|
41
|
+
return
|
|
42
|
+
with _LOCK:
|
|
43
|
+
try:
|
|
44
|
+
path = _egress_path()
|
|
45
|
+
day = datetime.date.today().isoformat()
|
|
46
|
+
data = _load(path)
|
|
47
|
+
day_row = data.get(day) or {}
|
|
48
|
+
if not isinstance(day_row, dict):
|
|
49
|
+
day_row = {}
|
|
50
|
+
day_row[kind] = int(day_row.get(kind, 0)) + 1
|
|
51
|
+
data[day] = day_row
|
|
52
|
+
for stale_day in sorted(k for k in data if k != day)[:-14]:
|
|
53
|
+
data.pop(stale_day, None)
|
|
54
|
+
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
|
|
55
|
+
tmp = path + ".tmp"
|
|
56
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
57
|
+
json.dump(data, f)
|
|
58
|
+
os.replace(tmp, path)
|
|
59
|
+
except Exception:
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def today_counts() -> Dict[str, int]:
|
|
64
|
+
"""Returns {"booster": N, "telemetry": M} for today (zeros on any failure)."""
|
|
65
|
+
try:
|
|
66
|
+
day = datetime.date.today().isoformat()
|
|
67
|
+
row = _load(_egress_path()).get(day) or {}
|
|
68
|
+
if not isinstance(row, dict):
|
|
69
|
+
row = {}
|
|
70
|
+
return {kind: int(row.get(kind, 0)) for kind in KINDS}
|
|
71
|
+
except Exception:
|
|
72
|
+
return {kind: 0 for kind in KINDS}
|
|
@@ -17,6 +17,11 @@ EST_TOKENS_PER_TOOL = 25
|
|
|
17
17
|
EST_TOKENS_PER_SKILL = 180
|
|
18
18
|
CRITICAL_TOOL_COUNT_THRESHOLD = 40
|
|
19
19
|
|
|
20
|
+
# Cross-IDE rule files at or below this size that mention AGENTS.md are pointer
|
|
21
|
+
# stubs ("rules live in AGENTS.md") — the canonical dedup pattern written by the
|
|
22
|
+
# installer and repo hygiene, not ghost mass.
|
|
23
|
+
POINTER_RULE_MAX_TOKENS = 250
|
|
24
|
+
|
|
20
25
|
# rules.md contract limits
|
|
21
26
|
RULE_FILE_LIMIT_BYTES = 24000 # per rule file, after @[label](path) expansion
|
|
22
27
|
RULES_BUDGET_TOKENS = 20000 # shared always-on/global rules budget
|
|
@@ -362,6 +367,11 @@ class EnvironmentAuditor:
|
|
|
362
367
|
canonical = next((r for r in found_rules if r["name"] in ("AGENTS.md", "CLAUDE.md")), found_rules[0])
|
|
363
368
|
for r in found_rules:
|
|
364
369
|
if r != canonical:
|
|
370
|
+
if (
|
|
371
|
+
r["tokens"] <= POINTER_RULE_MAX_TOKENS
|
|
372
|
+
and "agents.md" in r["content"].lower()
|
|
373
|
+
):
|
|
374
|
+
continue
|
|
365
375
|
ghost_files.append({
|
|
366
376
|
"file": r["rel_path"],
|
|
367
377
|
"type": "DUPLICATE_CROSS_IDE_RULE",
|
package/src/installer.py
CHANGED
|
@@ -682,7 +682,39 @@ WantedBy=default.target
|
|
|
682
682
|
raise EOFError("No interactive TTY")
|
|
683
683
|
|
|
684
684
|
if context == "update":
|
|
685
|
-
|
|
685
|
+
used_tokens = 0
|
|
686
|
+
try:
|
|
687
|
+
from src.metrics import MetricsTracker
|
|
688
|
+
quota = LicenseManager.check_quota(MetricsTracker())
|
|
689
|
+
used_tokens = int(quota.get("monthly_saved", 0))
|
|
690
|
+
except Exception:
|
|
691
|
+
used_tokens = 0
|
|
692
|
+
pct = min(100.0, (used_tokens / 50_000) * 100) if 50_000 > 0 else 0.0
|
|
693
|
+
try:
|
|
694
|
+
from src.version_checker import CURRENT_VERSION
|
|
695
|
+
ver_label = f"v{CURRENT_VERSION}"
|
|
696
|
+
except Exception:
|
|
697
|
+
ver_label = ""
|
|
698
|
+
header_text = f"⚡ TOKENSAFE UPDATED {ver_label} ⚡".strip()
|
|
699
|
+
|
|
700
|
+
print(f"\n{BOLD}{CYAN}╔════════════════════════════════════════════════════════════════════╗{RESET}")
|
|
701
|
+
print(f"{BOLD}{CYAN}║{header_text.center(68)}║{RESET}")
|
|
702
|
+
print(f"{BOLD}{CYAN}╚════════════════════════════════════════════════════════════════════╝{RESET}\n")
|
|
703
|
+
print(f" • Current Status: Local Guest (50,000 tokens/month) [{GREEN}Active Now{RESET}]")
|
|
704
|
+
print(f" • Monthly Usage: {used_tokens:,} / 50,000 tokens used ({pct:.1f}%)\n")
|
|
705
|
+
print(" Connect your free account to unlock:")
|
|
706
|
+
print(" ✔ 500,000 free tokens every month (10x boost)")
|
|
707
|
+
print(" ✔ Cloud Web Dashboard & live analytics (tokensafe.dev/dashboard)")
|
|
708
|
+
print(" ✔ Full code search & AST slicing across all AI agents\n")
|
|
709
|
+
|
|
710
|
+
answer = _read_input(f" {CYAN}→ Activate your free 500k Community license now? [{GREEN}Y{RESET}/n]: {RESET}").lower()
|
|
711
|
+
if answer in ("", "y", "yes"):
|
|
712
|
+
from src.cli import main as cli_main
|
|
713
|
+
cli_main(["login"])
|
|
714
|
+
else:
|
|
715
|
+
# Strict 1-step polite decline (no nagging on update)
|
|
716
|
+
print(f"\n {CYAN}ℹ{RESET} Continuing in Guest Mode (50,000 tokens/mo limit).")
|
|
717
|
+
print(f" Run {BOLD}tokensafe login{RESET} anytime in your terminal to unlock 500,000 free tokens/mo!\n")
|
|
686
718
|
return
|
|
687
719
|
|
|
688
720
|
print(f"\n{BOLD}{CYAN}╔════════════════════════════════════════════════════════════════════╗{RESET}")
|
package/src/mcp_server.py
CHANGED
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.11"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
|
@@ -384,6 +384,8 @@ class TelemetrySync:
|
|
|
384
384
|
|
|
385
385
|
req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
|
|
386
386
|
try:
|
|
387
|
+
from src.egress_counter import increment as _egress_increment
|
|
388
|
+
_egress_increment("telemetry")
|
|
387
389
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
388
390
|
if resp.status == 200:
|
|
389
391
|
try:
|
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.11"
|
|
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
|