tokensafe 2.7.3 → 2.8.1

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.
@@ -83,10 +83,10 @@ class LicenseManager:
83
83
  _QUOTA_TURN_COUNTERS: Dict[str, int] = {}
84
84
 
85
85
  TIERS = {
86
- "free": {"max_tokens_monthly": 500_000, "deepseek_cloud": False, "team_analytics": False},
87
- "solo": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": False},
88
- "team": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": True},
89
- "enterprise": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": True, "self_hosted": True}
86
+ "free": {"max_tokens_monthly": 500_000, "team_analytics": False},
87
+ "solo": {"max_tokens_monthly": None, "team_analytics": False},
88
+ "team": {"max_tokens_monthly": None, "team_analytics": True},
89
+ "enterprise": {"max_tokens_monthly": None, "team_analytics": True, "self_hosted": True}
90
90
  }
91
91
 
92
92
  @classmethod
@@ -95,6 +95,87 @@ class LicenseManager:
95
95
  raw = f"ts:{platform.system()}:{platform.node()}:{uuid.getnode()}:{os.path.expanduser('~')}"
96
96
  return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
97
97
 
98
+ @classmethod
99
+ def ensure_community_license(cls) -> Dict[str, Any]:
100
+ """
101
+ Fetches a signed Community Edition license (tier 'free') bound to this
102
+ machine's anonymized fingerprint. Zero-config: no keys, no user action.
103
+
104
+ Contract:
105
+ - Skipped when any real license is already active (any tier).
106
+ - Honors TOKENSAFE_TELEMETRY_DISABLED (same global consent switch as
107
+ telemetry sync — no new flag).
108
+ - Fully fail-open: any network/validation error leaves the embedded
109
+ free-tier defaults untouched; nothing ever raises.
110
+ - 24h retry cooldown so a server outage doesn't ping on every session.
111
+ """
112
+ state_path = ""
113
+ try:
114
+ state_path = os.path.join(resolve_data_dir(), "community_license_state.json")
115
+ if os.environ.get("TOKENSAFE_TELEMETRY_DISABLED") in ("1", "true", "yes"):
116
+ return {"success": False, "reason": "telemetry_disabled"}
117
+ if cls.get_active_license_key():
118
+ return {"success": False, "reason": "license_present"}
119
+
120
+ try:
121
+ with open(state_path, "r", encoding="utf-8") as f:
122
+ last_attempt = int(json.load(f).get("last_attempt", 0))
123
+ if time.time() - last_attempt < 86400:
124
+ return {"success": False, "reason": "cooldown"}
125
+ except Exception:
126
+ pass
127
+
128
+ plugin_version = ""
129
+ try:
130
+ manifest_path = os.path.join(PROJECT_ROOT, "plugin.json")
131
+ if os.path.exists(manifest_path):
132
+ with open(manifest_path, "r", encoding="utf-8") as mf:
133
+ plugin_version = str(json.load(mf).get("version", "") or "")
134
+ except Exception:
135
+ plugin_version = ""
136
+
137
+ import urllib.request
138
+
139
+ cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
140
+ req = urllib.request.Request(
141
+ f"{cloud_url}/api/community/license",
142
+ data=json.dumps({
143
+ "machine_fp": cls.get_machine_fingerprint(),
144
+ "platform": platform.system()[:32],
145
+ "arch": platform.machine()[:32],
146
+ "agent": os.environ.get("TOKENSAFE_AGENT", "")[:32],
147
+ "version": plugin_version[:32],
148
+ }).encode("utf-8"),
149
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/Community-License"},
150
+ method="POST"
151
+ )
152
+ with urllib.request.urlopen(req, timeout=2.5) as resp:
153
+ data = json.loads(resp.read().decode("utf-8") or "{}")
154
+ license_key = str(data.get("license_key", "") or "")
155
+ if resp.status != 200 or not data.get("success") or not license_key:
156
+ raise ValueError(str(data.get("error") or "empty community license response"))
157
+
158
+ ok, msg = cls.save_license(license_key)
159
+ if not ok:
160
+ raise ValueError(msg)
161
+
162
+ try:
163
+ os.makedirs(os.path.dirname(state_path) or ".", exist_ok=True)
164
+ with open(state_path, "w", encoding="utf-8") as f:
165
+ json.dump({"last_attempt": int(time.time()), "issued": True}, f)
166
+ except Exception:
167
+ pass
168
+ return {"success": True, "reason": "issued"}
169
+ except Exception as exc:
170
+ try:
171
+ if state_path:
172
+ os.makedirs(os.path.dirname(state_path) or ".", exist_ok=True)
173
+ with open(state_path, "w", encoding="utf-8") as f:
174
+ json.dump({"last_attempt": int(time.time()), "error": str(exc)[:200]}, f)
175
+ except Exception:
176
+ pass
177
+ return {"success": False, "reason": "error"}
178
+
98
179
  @classmethod
99
180
  def generate_license(
100
181
  cls,
@@ -105,12 +186,15 @@ class LicenseManager:
105
186
  is_trial: bool = False,
106
187
  version: int = 2,
107
188
  org_id: Optional[str] = None,
108
- jti: Optional[str] = None
189
+ jti: Optional[str] = None,
190
+ quota_monthly: Optional[int] = None
109
191
  ) -> str:
110
192
  """
111
193
  Generates a tamper-proof cryptographically signed license key.
112
194
  - Version 2 (Default): Asymmetric Ed25519 signed (Format: TS2.<b64_payload>.<b64_sig>)
113
195
  - Version 1: Legacy HMAC-SHA256 signed (Format: TS1.<b64_payload>.<sig_hex>)
196
+ quota_monthly: optional server-managed monthly token quota embedded into
197
+ the signed payload (used for Community Edition remote quota control).
114
198
  """
115
199
  now = int(time.time())
116
200
  expires_at = 0 if duration_days == 0 else now + (duration_days * 86400)
@@ -127,6 +211,8 @@ class LicenseManager:
127
211
  payload["org"] = org_id.strip()
128
212
  if jti:
129
213
  payload["jti"] = jti.strip()
214
+ if quota_monthly:
215
+ payload["max_tokens_monthly"] = int(quota_monthly)
130
216
 
131
217
  payload_bytes = json.dumps(payload, sort_keys=True, separators=(',', ':')).encode("utf-8")
132
218
  payload_b64 = base64.urlsafe_b64encode(payload_bytes).decode("ascii").rstrip("=")
@@ -362,6 +448,43 @@ class LicenseManager:
362
448
  trial_note = " (7-Day Trial)" if payload.get("trial") else ""
363
449
  return True, f"Successfully activated TokenSafe {tier_name}{trial_note}!"
364
450
 
451
+ @classmethod
452
+ def _get_server_quota_floor(cls, tracker: Optional[Any] = None) -> int:
453
+ """Reads server-verified quota floor from mirror ledger (.qledger.json) within 30-day window."""
454
+ if tracker and hasattr(tracker, "get_server_quota_floor"):
455
+ try:
456
+ floor = int(tracker.get_server_quota_floor() or 0)
457
+ if floor > 0:
458
+ return floor
459
+ except Exception:
460
+ pass
461
+ try:
462
+ mirror_paths = []
463
+ if tracker and hasattr(tracker, "_quota_mirror_path"):
464
+ try:
465
+ mirror_paths.append(tracker._quota_mirror_path())
466
+ except Exception:
467
+ pass
468
+ base_dir = os.environ.get("TOKENSAFE_DATA_DIR") or (
469
+ os.path.dirname(os.environ["TOKENSAFE_DB_PATH"]) if os.environ.get("TOKENSAFE_DB_PATH") else None
470
+ )
471
+ if base_dir:
472
+ mirror_paths.append(os.path.join(base_dir, ".qledger.json"))
473
+ mirror_paths.append(os.path.join(os.path.dirname(DATA_DIR), ".qledger.json"))
474
+ mirror_paths.append(os.path.join(DATA_DIR, ".qledger.json"))
475
+
476
+ for mirror_path in mirror_paths:
477
+ if os.path.exists(mirror_path):
478
+ with open(mirror_path, "r", encoding="utf-8") as f:
479
+ data = json.load(f)
480
+ if isinstance(data, dict) and time.time() - float(data.get("server_floor_ts", 0)) <= 30 * 86400:
481
+ floor = int(data.get("server_floor", 0) or 0)
482
+ if floor > 0:
483
+ return floor
484
+ except Exception:
485
+ pass
486
+ return 0
487
+
365
488
  @classmethod
366
489
  def check_quota(cls, tracker: Optional[Any] = None) -> Dict[str, Any]:
367
490
  """
@@ -379,6 +502,16 @@ class LicenseManager:
379
502
  tier_cfg = cls.TIERS.get(tier, cls.TIERS["free"])
380
503
  max_tokens = tier_cfg.get("max_tokens_monthly")
381
504
 
505
+ # Server-issued quota (community license payload) overrides the embedded
506
+ # default — enables remote quota control without a client release.
507
+ if max_tokens is not None and isinstance(payload, dict):
508
+ try:
509
+ server_quota = int(payload.get("max_tokens_monthly") or 0)
510
+ if server_quota > 0:
511
+ max_tokens = server_quota
512
+ except (TypeError, ValueError):
513
+ pass
514
+
382
515
  # Paid tiers (solo, team, enterprise) have unlimited local optimization
383
516
  if max_tokens is None:
384
517
  return {
@@ -397,7 +530,9 @@ class LicenseManager:
397
530
  except Exception:
398
531
  tracker = None
399
532
 
400
- monthly_saved = tracker.get_monthly_saved_tokens() if tracker else 0
533
+ local_saved = tracker.get_monthly_saved_tokens() if tracker else 0
534
+ server_floor = cls._get_server_quota_floor(tracker)
535
+ monthly_saved = max(local_saved, server_floor)
401
536
  exceeded = monthly_saved >= max_tokens
402
537
 
403
538
  warning = None
@@ -0,0 +1,105 @@
1
+ """Live relay: ships anonymized proxy events to the TokenSafe cloud live view.
2
+
3
+ Only metadata ever leaves the machine — saved tokens, USD estimate, model name
4
+ and a machine hash. No prompts, no file paths, no content. Batches flush at
5
+ most every TOKENSAFE_LIVE_FLUSH_SECONDS (default 5s) from a daemon thread; a
6
+ license-less (Community) install never transmits.
7
+ """
8
+
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import threading
13
+ import time
14
+ import urllib.request
15
+ from collections import deque
16
+ from typing import Dict
17
+
18
+ from src.license_manager import LicenseManager
19
+
20
+ _MACHINE_HASH = ""
21
+
22
+
23
+ def _machine_hash() -> str:
24
+ global _MACHINE_HASH
25
+ if _MACHINE_HASH:
26
+ return _MACHINE_HASH
27
+ try:
28
+ import socket
29
+ uid = os.getuid() if hasattr(os, "getuid") else 0
30
+ raw = f"{socket.gethostname()}|{uid}"
31
+ except Exception:
32
+ raw = "tokensafe"
33
+ _MACHINE_HASH = hashlib.sha256(raw.encode("utf-8", "ignore")).hexdigest()[:16]
34
+ return _MACHINE_HASH
35
+
36
+
37
+ class LiveRelay:
38
+ """Records anonymized live events and flushes bounded batches to the cloud."""
39
+
40
+ RING_MAX = 600
41
+ FLUSH_SECONDS = float(os.environ.get("TOKENSAFE_LIVE_FLUSH_SECONDS", "5"))
42
+
43
+ def __init__(self):
44
+ self._ring: deque = deque(maxlen=self.RING_MAX)
45
+ self._lock = threading.Lock()
46
+ self._last_flush = time.time() # grace window before the first flush
47
+ self._flushing = False
48
+
49
+ def record(self, event_type: str, data: Dict) -> None:
50
+ """Queues a whitelisted, clamped event; flushes when the window elapses."""
51
+ try:
52
+ ev = {
53
+ "type": str(event_type or "session")[:40],
54
+ "saved_tokens": min(10_000_000, max(0, int(data.get("saved_tokens") or data.get("tokens_saved") or 0))),
55
+ "usd_saved": min(10000.0, max(0.0, float(data.get("usd_saved") or data.get("usd") or 0.0))),
56
+ "model": str(data.get("model") or "")[:40],
57
+ "machine": str(data.get("machine") or _machine_hash())[:64],
58
+ "ts": time.time(),
59
+ }
60
+ except Exception:
61
+ return
62
+ with self._lock:
63
+ self._ring.append(ev)
64
+ due = bool(self._ring) and (time.time() - self._last_flush) >= self.FLUSH_SECONDS
65
+ if due:
66
+ self.flush_async()
67
+
68
+ def flush_async(self) -> None:
69
+ if self._flushing:
70
+ return
71
+ self._flushing = True
72
+ threading.Thread(target=self._flush, daemon=True).start()
73
+
74
+ def _flush(self) -> None:
75
+ try:
76
+ with self._lock:
77
+ batch = list(self._ring)
78
+ self._ring.clear()
79
+ self._last_flush = time.time()
80
+ if not batch:
81
+ return
82
+ key = ""
83
+ try:
84
+ key = LicenseManager.get_active_license_key() or ""
85
+ except Exception:
86
+ key = ""
87
+ if not key:
88
+ return # Community installs never transmit live events
89
+ base = os.environ.get("TOKENSAFE_CLOUD_URL", "").rstrip("/") or "https://api.tokensafe.dev"
90
+ url = os.environ.get("TOKENSAFE_LIVE_URL", f"{base}/api/live/relay")
91
+ body = json.dumps({"license_key": key, "machine": _machine_hash(), "events": batch[:100]}).encode("utf-8")
92
+ req = urllib.request.Request(url, data=body, headers={
93
+ "Content-Type": "application/json",
94
+ "Authorization": f"Bearer {key}",
95
+ "User-Agent": "TokenSafe-LiveRelay/2.8",
96
+ }, method="POST")
97
+ with urllib.request.urlopen(req, timeout=4.0) as resp:
98
+ resp.read()
99
+ except Exception:
100
+ pass # live telemetry is best-effort and must never block the proxy
101
+ finally:
102
+ self._flushing = False
103
+
104
+
105
+ LIVE_RELAY = LiveRelay()
package/src/mcp_server.py CHANGED
@@ -22,6 +22,7 @@ sys.path.insert(0, BASE_DIR)
22
22
  from src.compactor import PromptCompactor
23
23
  from src.skeletonizer import Skeletonizer
24
24
  from src.slicer import ToolSlicer
25
+ from src.schema_slicer import SchemaSlicer
25
26
  from src.dependency_prefetcher import DependencyPrefetcher
26
27
  from src.command_sanitizer import CommandSanitizer
27
28
  from src.loop_detector import LoopDetector
@@ -40,7 +41,7 @@ from src.license_manager import LicenseManager
40
41
 
41
42
  SERVER_INFO = {
42
43
  "name": "tokensafe-mcp",
43
- "version": "2.7.3"
44
+ "version": "2.8.1"
44
45
  }
45
46
 
46
47
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -78,7 +79,7 @@ def _client_supports_pointers() -> bool:
78
79
  TOOLS = [
79
80
  {
80
81
  "name": "smart_read_file",
81
- "description": "Reads a code file using AST skeletonization and graph-guided slicing to save 90-99% context tokens.",
82
+ "description": "Reads a code file using AST skeletonization and graph-guided slicing to save 90-99% context tokens. OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced instead: pass the spec path/model/type/table as 'symbol', or omit it for a compact overview. For 3+ related symbols across files prefer smart_bundle.",
82
83
  "inputSchema": {
83
84
  "type": "object",
84
85
  "properties": {
@@ -93,6 +94,32 @@ TOOLS = [
93
94
  "required": ["path"]
94
95
  }
95
96
  },
97
+ {
98
+ "name": "smart_bundle",
99
+ "description": "Reads 2-8 related symbols across multiple files as ONE merged context bundle: per-file AST skeletons with shared import lines deduplicated and merged 1-hop dependency signatures. Use it instead of 3+ separate smart_read_file calls on related code (one roundtrip, no duplicated imports/types).",
100
+ "inputSchema": {
101
+ "type": "object",
102
+ "properties": {
103
+ "targets": {
104
+ "type": "array",
105
+ "maxItems": 8,
106
+ "items": {
107
+ "type": "object",
108
+ "properties": {
109
+ "path": {"type": "string", "description": "Absolute path to the code file"},
110
+ "symbol": {"type": "string", "description": "Optional symbol to keep unfolded (class/function name)"}
111
+ },
112
+ "required": ["path"]
113
+ },
114
+ "description": "Up to 8 {path, symbol} targets; list several symbols of the same file as separate entries"
115
+ },
116
+ "include_deps": {"type": "boolean", "description": "Optional: include merged 1-hop dependency signatures (default: true)"},
117
+ "dep_mode": {"type": "string", "enum": ["signature", "full"], "description": "Optional: kept for parity with smart_read_file; signatures are always merged for bundles"},
118
+ "force_full": {"type": "boolean", "description": "Optional: bypass session pointer deduplication"}
119
+ },
120
+ "required": ["targets"]
121
+ }
122
+ },
96
123
  {
97
124
  "name": "get_architecture_graph",
98
125
  "description": "Returns top architectural God Nodes and dependency topology for the target project. Call this BEFORE reading files or searching.",
@@ -610,6 +637,23 @@ def _resolve_dep_mode(args: dict) -> Tuple[bool, str]:
610
637
  return True, "signature"
611
638
 
612
639
 
640
+ def _repo_fingerprint(graph) -> str:
641
+ """Stable Shared-Team-Symbol-Index cache key for an indexed repo: repo name +
642
+ per-file relative paths + sizes. Machine-independent on purpose (mtimes differ
643
+ across clones, sizes survive them); a 7-day TTL bounds staleness on the cloud."""
644
+ import hashlib
645
+ h = hashlib.sha256()
646
+ root = os.path.abspath(getattr(graph, "root_dir", "") or "")
647
+ h.update(os.path.basename(root).encode("utf-8", "ignore"))
648
+ stats = getattr(graph, "file_stats", {}) or {}
649
+ for rel in sorted(stats.keys()):
650
+ _m, s = stats[rel]
651
+ h.update(f"{rel}:{int(s)};".encode("utf-8", "ignore"))
652
+ if not stats:
653
+ h.update(f"symbols:{len(getattr(graph, 'symbols', {}) or {})}".encode("utf-8", "ignore"))
654
+ return h.hexdigest()[:40]
655
+
656
+
613
657
  def handle_tool_call(name: str, args: dict) -> dict:
614
658
  if args is None or not isinstance(args, dict):
615
659
  args = {}
@@ -699,6 +743,26 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
699
743
  if _is_binary_file(path):
700
744
  return _fallback_error("smart_read_file", f"'{os.path.basename(path)}' appears to be a binary file")
701
745
 
746
+ # Heavy declarative schema files (OpenAPI/Swagger/Prisma/GraphQL/SQL DDL):
747
+ # generic AST skeletonization does not apply — route to the schema slicer.
748
+ # `symbol` carries the target (a spec path, model, type or table); an empty
749
+ # symbol yields a compact overview instead of a 20k-50k token dump.
750
+ schema_kind = SchemaSlicer.detect(os.path.abspath(path))
751
+ if schema_kind:
752
+ sliced, sinfo = SchemaSlicer.slice_file(os.path.abspath(path), target=(symbol or ""))
753
+ if sliced:
754
+ orig_t = max(1000, st.st_size // 4)
755
+ sliced_t = count_tokens(sliced)
756
+ tracker.record_event(
757
+ session_id=_mcp_session_id(),
758
+ event_type="SCHEMA_SLICE",
759
+ original_tokens=orig_t,
760
+ optimized_tokens=sliced_t,
761
+ details={"kind": sinfo.get("kind"), "mode": sinfo.get("mode"), "target": (symbol or "")[:120]}
762
+ )
763
+ header = f"// [TokenSafe Schema Slice: {sinfo.get('kind')} | mode={sinfo.get('mode')} | target='{(symbol or '')[:80]}']\n"
764
+ return {"content": [{"type": "text", "text": header + sliced}]}
765
+
702
766
  # Community 500k quota reached: soft-degrade to bounded raw read (disable Graph/AST/Pointer/Team Cache)
703
767
  if is_quota_exceeded:
704
768
  if start_line is not None or end_line is not None:
@@ -857,6 +921,117 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
857
921
  content = f.read()
858
922
  return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
859
923
 
924
+ elif name == "smart_bundle":
925
+ targets = args.get("targets")
926
+ if not isinstance(targets, list) or not targets:
927
+ return _fallback_error("smart_bundle", "missing required 'targets' array of {path, symbol} objects")
928
+ if len(targets) > 8:
929
+ return _fallback_error("smart_bundle", "too many targets (max 8)")
930
+ if is_quota_exceeded:
931
+ LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
932
+ 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."}]}
933
+
934
+ inc_deps, _eff_dep_mode = _resolve_dep_mode(args)
935
+ max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
936
+
937
+ by_file: Dict[str, List[str]] = {}
938
+ for t in targets:
939
+ if not isinstance(t, dict) or not str(t.get("path") or "").strip():
940
+ return _fallback_error("smart_bundle", "each target must be {path: str, symbol?: str}")
941
+ by_file.setdefault(os.path.abspath(str(t["path"])), []).append(str(t.get("symbol") or "").strip())
942
+
943
+ missing = [p for p in by_file if not os.path.isfile(p)]
944
+ if missing:
945
+ return {"isError": True, "content": [{"type": "text", "text": f"File(s) not found: {', '.join(missing)}"}]}
946
+
947
+ bundle_max_bytes = 512 * 1024
948
+ file_sections: List[Tuple[str, str, List[str]]] = [] # (abs_path, skeleton, import_lines)
949
+ dep_lines: List[str] = []
950
+ seen_dep_lines: set = set()
951
+ orig_tokens_est = 0
952
+
953
+ _imp_line_re = re.compile(r"^\s*(?:import\s|from\s+\S+\s+import\b|use\s|using\s|#include|require(?:_relative)?\s|extern crate\s).*$", re.MULTILINE)
954
+
955
+ for p, symbols in by_file.items():
956
+ try:
957
+ st_b = os.stat(p)
958
+ with open(p, "r", encoding="utf-8", errors="replace") as f:
959
+ code = f.read(bundle_max_bytes)
960
+ except OSError as e:
961
+ return _fallback_error("smart_bundle", f"cannot read {p}: {e}")
962
+ orig_tokens_est += max(200, st_b.st_size // 4)
963
+ ext = os.path.splitext(p)[1].lower()
964
+ keep = {s for s in symbols if s} or None
965
+ skel = Skeletonizer.skeletonize_code(code, ext, keep_symbols=keep)
966
+ imp_lines = sorted({m.group(0).strip() for m in _imp_line_re.finditer(skel)})
967
+ file_sections.append((p, skel, imp_lines))
968
+
969
+ if inc_deps and keep:
970
+ try:
971
+ graph, rel = GraphEngine.for_file(p)
972
+ if graph and rel:
973
+ for sym in keep:
974
+ # A class target's call edges live on its methods:
975
+ # resolve every qual key under the target symbol.
976
+ keys = [k for k in graph.symbols if k == f"{rel}::{sym}" or k.startswith(f"{rel}::{sym}::")]
977
+ for key in keys[:12]:
978
+ qual = key[len(rel) + 2:]
979
+ nb = graph.get_neighborhood(qual, target_file=rel)
980
+ for dep_key in sorted(nb.get("one_hop", [])):
981
+ dep_sym = graph.symbols.get(dep_key)
982
+ if not dep_sym:
983
+ continue
984
+ line = f" {qual} -> {dep_key[len(rel) + 2:]}: {dep_sym.signature.strip()[:160]}"
985
+ if line not in seen_dep_lines:
986
+ seen_dep_lines.add(line)
987
+ dep_lines.append(line)
988
+ except Exception:
989
+ pass
990
+
991
+ # Shared imports: lines present in 2+ files are emitted once
992
+ from collections import Counter
993
+ imp_counter = Counter()
994
+ for _p, _skel, imps in file_sections:
995
+ imp_counter.update(set(imps))
996
+ shared = sorted({ln for ln, cnt in imp_counter.items() if cnt >= 2 and len(ln) > 4})
997
+
998
+ parts: List[str] = []
999
+ if shared:
1000
+ parts.append("// [Shared imports — deduplicated across files]")
1001
+ parts.extend(f" {ln}" for ln in shared[:40])
1002
+ for p, skel, imps in file_sections:
1003
+ body = skel
1004
+ if shared:
1005
+ body = "\n".join(ln for ln in body.splitlines() if ln.strip() not in shared)
1006
+ parts.append(f"\n// ===== {os.path.basename(p)} ({len(by_file[p])} symbol target(s)) =====")
1007
+ parts.append(body)
1008
+ if dep_lines:
1009
+ parts.append("\n// [Merged 1-hop dependency signatures (deduplicated)]")
1010
+ parts.extend(dep_lines)
1011
+ bundle = "\n".join(parts)
1012
+
1013
+ bundle_t = count_tokens(bundle)
1014
+ if bundle_t > max_tokens and dep_lines:
1015
+ # Graceful degradation: drop the merged dependency signatures first
1016
+ deps_idx = bundle.find("\n// [Merged 1-hop dependency signatures")
1017
+ if deps_idx > 0:
1018
+ bundle = bundle[:deps_idx] + (
1019
+ f"\n// [TokenSafe smart_bundle: dependency signatures omitted (output cap {max_tokens} tokens)"
1020
+ " — narrow the 'targets' list for deeper detail.]"
1021
+ )
1022
+ bundle_t = count_tokens(bundle)
1023
+ if bundle_t > max_tokens:
1024
+ bundle += f"\n// [TokenSafe smart_bundle: output exceeds the {max_tokens}-token cap — narrow the 'targets' list.]"
1025
+
1026
+ tracker.record_event(
1027
+ session_id=_mcp_session_id(),
1028
+ event_type="BUNDLE",
1029
+ original_tokens=min(orig_tokens_est, 200000),
1030
+ optimized_tokens=bundle_t,
1031
+ details={"files": len(by_file), "targets": len(targets), "shared_imports": len(shared), "dep_lines": len(dep_lines)}
1032
+ )
1033
+ return {"content": [{"type": "text", "text": bundle}]}
1034
+
860
1035
  elif name == "compress_prompt":
861
1036
  prompt = args.get("prompt", "")
862
1037
  if is_quota_exceeded:
@@ -870,7 +1045,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
870
1045
  "warning": quota.get("warning") if emit_warn else "Community 500k monthly limit reached; prompt compaction paused.",
871
1046
  }
872
1047
  return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
873
- res = PromptCompactor.compact(prompt, enable_deepseek=True)
1048
+ res = PromptCompactor.compact(prompt, enable_distill=True)
874
1049
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
875
1050
 
876
1051
  elif name == "context_budget":
@@ -1152,6 +1327,34 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1152
1327
  "warning": quota.get("warning"),
1153
1328
  }, indent=2, ensure_ascii=False)}]}
1154
1329
  graph = GraphEngine.get_instance(target_abs)
1330
+ # Cap estimated crawl tokens to max 50,000 to prevent runaway spikes on large/root dirs
1331
+ capped_files = min(80, len(graph.file_symbols))
1332
+ est_crawl_tokens = min(50000, max(5000, capped_files * 600))
1333
+ topo_tokens = 250
1334
+
1335
+ # Shared Team Symbol Index: reuse a teammate's graph for the exact same
1336
+ # repo state (key = rel paths + sizes, so clones with identical trees hit).
1337
+ fp = _repo_fingerprint(graph)
1338
+ team_cached = None
1339
+ try:
1340
+ raw_cached = TeamCache.get("arch_index", fp)
1341
+ if raw_cached:
1342
+ team_cached = json.loads(raw_cached)
1343
+ except Exception:
1344
+ team_cached = None
1345
+ if isinstance(team_cached, dict) and team_cached.get("god_nodes") is not None:
1346
+ payload = dict(team_cached)
1347
+ payload["source"] = "team_symbol_index"
1348
+ hit_text = json.dumps(payload, indent=2, ensure_ascii=False)
1349
+ tracker.record_event(
1350
+ session_id=_mcp_session_id(),
1351
+ event_type="TEAM_CACHE_HIT",
1352
+ original_tokens=est_crawl_tokens,
1353
+ optimized_tokens=topo_tokens,
1354
+ details={"source": "team_symbol_index", "indexed_files": len(graph.file_symbols)}
1355
+ )
1356
+ return {"content": [{"type": "text", "text": hit_text}]}
1357
+
1155
1358
  god_nodes = graph.get_god_nodes(7)
1156
1359
  banner = graph.format_topology_banner()
1157
1360
  payload = {
@@ -1161,10 +1364,6 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1161
1364
  "total_symbols": len(graph.symbols),
1162
1365
  "god_nodes": god_nodes
1163
1366
  }
1164
- # Cap estimated crawl tokens to max 50,000 to prevent runaway spikes on large/root dirs
1165
- capped_files = min(80, len(graph.file_symbols))
1166
- est_crawl_tokens = min(50000, max(5000, capped_files * 600))
1167
- topo_tokens = 250
1168
1367
  tracker.record_event(
1169
1368
  session_id=_mcp_session_id(),
1170
1369
  event_type="GRAPH_TOPOLOGY",
@@ -1172,6 +1371,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1172
1371
  optimized_tokens=topo_tokens,
1173
1372
  details={"hubs_count": len(god_nodes), "indexed_files": len(graph.file_symbols)}
1174
1373
  )
1374
+ try:
1375
+ TeamCache.put("arch_index", fp, json.dumps(payload, ensure_ascii=False, default=str))
1376
+ except Exception:
1377
+ pass
1175
1378
  return {"content": [{"type": "text", "text": json.dumps(payload, indent=2, ensure_ascii=False)}]}
1176
1379
 
1177
1380
  elif name == "get_api_surface":
@@ -1185,11 +1388,29 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1185
1388
  LicenseManager.should_emit_quota_banner(tracker, session_id=_mcp_session_id(), every_n_turns=5)
1186
1389
  return {"content": [{"type": "text", "text": f"{quota.get('warning', '')}\n\nAPI surface map generation is paused over the 500k Community limit. Use scoped_search or list_dir, or activate a subscription at https://tokensafe.dev/#pricing."}]}
1187
1390
  graph = GraphEngine.get_instance(target_abs)
1188
- surface_md = graph.generate_api_surface()
1189
- surface_tokens = count_tokens(surface_md)
1190
1391
  # Cap estimated crawl tokens to max 60,000
1191
1392
  capped_files = min(100, len(graph.file_symbols))
1192
1393
  est_orig_tokens = min(60000, max(10000, capped_files * 600))
1394
+
1395
+ # Shared Team Symbol Index surface variant (separate key from the graph payload)
1396
+ fp = _repo_fingerprint(graph) + ":surface"
1397
+ team_cached_md = None
1398
+ try:
1399
+ team_cached_md = TeamCache.get("arch_index", fp)
1400
+ except Exception:
1401
+ team_cached_md = None
1402
+ if team_cached_md:
1403
+ tracker.record_event(
1404
+ session_id=_mcp_session_id(),
1405
+ event_type="TEAM_CACHE_HIT",
1406
+ original_tokens=est_orig_tokens,
1407
+ optimized_tokens=count_tokens(team_cached_md),
1408
+ details={"source": "team_symbol_index", "type": "API_SURFACE"}
1409
+ )
1410
+ return {"content": [{"type": "text", "text": team_cached_md}]}
1411
+
1412
+ surface_md = graph.generate_api_surface()
1413
+ surface_tokens = count_tokens(surface_md)
1193
1414
  tracker.record_event(
1194
1415
  session_id=_mcp_session_id(),
1195
1416
  event_type="GRAPH_TOPOLOGY",
@@ -1197,6 +1418,10 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
1197
1418
  optimized_tokens=surface_tokens,
1198
1419
  details={"type": "API_SURFACE", "symbols_count": len(graph.symbols)}
1199
1420
  )
1421
+ try:
1422
+ TeamCache.put("arch_index", fp, surface_md[:200000])
1423
+ except Exception:
1424
+ pass
1200
1425
  return {"content": [{"type": "text", "text": surface_md}]}
1201
1426
 
1202
1427
  elif name == "list_dir":
@@ -1382,6 +1607,11 @@ def run_mcp_server():
1382
1607
  tool_name = str(params.get("name") or "")
1383
1608
  raw_tool_args = params.get("arguments")
1384
1609
  tool_args = raw_tool_args if isinstance(raw_tool_args, dict) else {}
1610
+ if not tool_args and raw_tool_args:
1611
+ # Self-healing: hosts on small/local models intermittently send
1612
+ # arguments as a malformed JSON string — repair before failing.
1613
+ from src.json_repair import parse_tool_arguments
1614
+ tool_args = parse_tool_arguments(raw_tool_args) or {}
1385
1615
  try:
1386
1616
  response["result"] = _execute_with_timeout(tool_name, tool_args)
1387
1617
  except Exception as e:
package/src/metrics.py CHANGED
@@ -372,6 +372,20 @@ class MetricsTracker:
372
372
  except Exception:
373
373
  _do()
374
374
 
375
+ def get_server_quota_floor(self) -> int:
376
+ """Returns the active server-verified measured quota floor from mirror ledger (within 30-day window)."""
377
+ mirror_path = self._quota_mirror_path()
378
+ try:
379
+ if os.path.exists(mirror_path):
380
+ with open(mirror_path, "r", encoding="utf-8") as f:
381
+ data = json.load(f)
382
+ if isinstance(data, dict):
383
+ if time.time() - float(data.get("server_floor_ts", 0)) <= 30 * 86400:
384
+ return int(data.get("server_floor", 0) or 0)
385
+ except Exception:
386
+ pass
387
+ return 0
388
+
375
389
  def record_event(
376
390
  self,
377
391
  session_id: str,