tokensafe 4.1.10 → 4.1.12

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.1.10",
2
+ "version": "4.1.12",
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.10",
3
+ "version": "4.1.12",
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.10",
4
+ "version": "4.1.12",
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.10",
4
+ "version": "4.1.12",
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.10",
6
+ "version": "4.1.12",
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.10",
33
+ "version": "4.1.12",
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.10",
49
+ "version": "4.1.12",
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()
@@ -842,6 +899,10 @@ def main(argv: Optional[List[str]] = None):
842
899
  print(" \033[32m✔ Community Edition license activated (500,000 free tokens/month).\033[0m")
843
900
  print(f" \033[36m✔ Web dashboard unlocked at:\033[0m https://tokensafe.dev/dashboard\n")
844
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
+
845
906
  # Sync local token metrics
846
907
  try:
847
908
  from src.telemetry_sync import TelemetrySync
@@ -901,6 +962,13 @@ def main(argv: Optional[List[str]] = None):
901
962
  ok, msg = LicenseManager.save_license(key)
902
963
  if ok:
903
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
904
972
  # Automatically report version and seat activation to cloud
905
973
  try:
906
974
  from src.version_checker import VersionChecker
@@ -970,22 +1038,66 @@ def main(argv: Optional[List[str]] = None):
970
1038
  print(f" Expires: Never (Lifetime)")
971
1039
  print()
972
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
+
973
1076
  elif command in ("providers", "models", "keys"):
974
1077
  from src.license_manager import LicenseManager
975
1078
  from src.distiller import UniversalDistiller
976
1079
  tier, _ = LicenseManager.get_active_license()
977
1080
  print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
978
- if tier == "free":
979
- print(" \033[33mTier: Free Community Edition\033[0m")
980
- print(" Managed Cloud Distillation (zero API keys) is reserved for Solo, Team, and Enterprise tiers.")
981
- print(" Free Community Edition operates with the zero-latency, zero-cost Local Regex Compactor.\n")
982
- print(" \033[1mTo unlock Cloud Distillation:\033[0m")
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")
983
1087
  print(" 1. Start 7-day free trial or upgrade at: https://tokensafe.dev")
984
1088
  print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
985
1089
  elif not UniversalDistiller.is_self_hosted():
986
- print(f" \033[32m✔\033[0m \033[1mTokenSafe Cloud Distiller\033[0m [Active: gemini-flash-lite-latest via Managed Cloud]")
987
- print(" Zero API keys required — managed centrally by your TokenSafe subscription.")
988
- print(" Shared Team Cache & sub-millisecond cloud cache active.\n")
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()
989
1101
  print(" \033[2m💡 Tip: To run self-hosted with custom BYOK keys in Docker, export TOKENSAFE_SELF_HOSTED=1.\033[0m\n")
990
1102
  else:
991
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 TokenSafe Solo, Team, and Enterprise (or active trials)
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 != "free":
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?key={key}"
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
- payload = {"prompt": raw_text.strip()}
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/1.3.7"
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 == "free":
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 == "free":
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": "TokenSafe Cloud Distiller",
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 TokenSafe Solo or Team subscription.
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 == "free":
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,11 @@ Rules:
351
416
 
352
417
  @classmethod
353
418
  def _call_gemini(cls, conf: Dict[str, Any], raw_text: str) -> Optional[str]:
354
- endpoint = conf["endpoint"].format(model=conf["model"], key=conf["api_key"])
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). Legacy endpoint templates that still
421
+ # embed {key} are tolerated: the placeholder is stripped, never filled.
422
+ endpoint_template = conf["endpoint"].replace("?key={key}", "").replace("{key}", "")
423
+ endpoint = endpoint_template.format(model=conf["model"])
355
424
  payload = {
356
425
  "systemInstruction": {
357
426
  "parts": [{"text": cls.SYSTEM_PROMPT}]
@@ -370,7 +439,8 @@ Rules:
370
439
  data=json.dumps(payload).encode("utf-8"),
371
440
  headers={
372
441
  "Content-Type": "application/json",
373
- "User-Agent": "TokenSafe/1.0"
442
+ "User-Agent": "TokenSafe/1.0",
443
+ "x-goog-api-key": conf["api_key"]
374
444
  }
375
445
  )
376
446
 
@@ -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/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.10"
45
+ "version": "4.1.12"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -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.10"
244
+ "User-Agent": "TokenSafe-Sync/4.1.12"
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:
@@ -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.10"
20
+ CURRENT_VERSION = "4.1.12"
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