tokensafe 2.7.2 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,165 @@
1
+ """Heuristic JSON repair for malformed tool-call arguments.
2
+
3
+ Small/local models (Haiku, Llama, Qwen) intermittently emit broken JSON in
4
+ tool-call argument strings: a missing closing bracket, trailing commas,
5
+ Python literals, raw newlines inside strings, or single quotes. Instead of
6
+ failing the tool call and burning a full retry roundtrip, the MCP server and
7
+ the proxy run the payload through this best-effort repairer first.
8
+
9
+ Standard library only. Every stage is tried strictly: a repaired candidate is
10
+ accepted only when `json.loads` really accepts it — no fabricated output.
11
+ """
12
+
13
+ import json
14
+ import re
15
+ from typing import Any, List, Optional
16
+
17
+
18
+ def parse_tool_arguments(raw: Any) -> Optional[dict]:
19
+ """Parses tool-call arguments. Dicts pass through; strings go through strict
20
+ json.loads first, then heuristic repair. Returns None when unrepairable."""
21
+ if isinstance(raw, dict):
22
+ return raw
23
+ if not isinstance(raw, str):
24
+ return None
25
+ s = raw.strip()
26
+ if not s:
27
+ return None
28
+ try:
29
+ val = json.loads(s)
30
+ return val if isinstance(val, dict) else None
31
+ except Exception:
32
+ pass
33
+ repaired = repair_json(s)
34
+ if repaired is None:
35
+ return None
36
+ try:
37
+ val = json.loads(repaired)
38
+ return val if isinstance(val, dict) else None
39
+ except Exception:
40
+ return None
41
+
42
+
43
+ def repair_json(s: str) -> Optional[str]:
44
+ """Best-effort repair of a broken JSON string. Returns repaired text that
45
+ strict json.loads accepts, or None when nothing sensible can be produced."""
46
+ s = s.strip().lstrip("\ufeff")
47
+ if not s:
48
+ return None
49
+
50
+ py_fixed = re.sub(r"\bTrue\b", "true", s)
51
+ py_fixed = re.sub(r"\bFalse\b", "false", py_fixed)
52
+ py_fixed = re.sub(r"\bNone\b", "null", py_fixed)
53
+
54
+ ctrl_fixed = _escape_control_chars_in_strings(py_fixed)
55
+
56
+ def _strip_trailing_commas(text: str) -> str:
57
+ return re.sub(r",(\s*[}\]])", r"\1", text)
58
+
59
+ candidates: List[Optional[str]] = [py_fixed, ctrl_fixed, _strip_trailing_commas(ctrl_fixed)]
60
+
61
+ # Balance missing closers, then strip trailing commas AGAIN — appending a
62
+ # closer can leave a dangling comma right before it (e.g. '{"a": 1,').
63
+ balanced0 = _balance_brackets(ctrl_fixed)
64
+ for base in (balanced0, _balance_brackets(_strip_trailing_commas(ctrl_fixed))):
65
+ if base is not None:
66
+ candidates.append(base)
67
+ candidates.append(_strip_trailing_commas(base))
68
+
69
+ # Single-quote conversion only as a late resort (apostrophe risk)
70
+ for base in list(candidates):
71
+ sq = _single_to_double_quotes(base) if base else None
72
+ if sq:
73
+ candidates.append(sq)
74
+ sb = _balance_brackets(sq)
75
+ if sb:
76
+ candidates.append(sb)
77
+
78
+ for cand in candidates:
79
+ if cand is None:
80
+ continue
81
+ try:
82
+ json.loads(cand)
83
+ return cand
84
+ except Exception:
85
+ continue
86
+ return None
87
+
88
+
89
+ def _escape_control_chars_in_strings(s: str) -> str:
90
+ """Escapes raw newlines/tabs/CRs that appear inside string literals."""
91
+ out: List[str] = []
92
+ in_str = False
93
+ quote = ""
94
+ escaped = False
95
+ for ch in s:
96
+ if in_str:
97
+ if escaped:
98
+ out.append(ch)
99
+ escaped = False
100
+ continue
101
+ if ch == "\\":
102
+ out.append(ch)
103
+ escaped = True
104
+ continue
105
+ if ch == quote:
106
+ in_str = False
107
+ out.append(ch)
108
+ continue
109
+ if ch == "\n":
110
+ out.append("\\n")
111
+ continue
112
+ if ch == "\r":
113
+ out.append("\\r")
114
+ continue
115
+ if ch == "\t":
116
+ out.append("\\t")
117
+ continue
118
+ out.append(ch)
119
+ else:
120
+ if ch in ('"', "'"):
121
+ in_str = True
122
+ quote = ch
123
+ out.append(ch)
124
+ return "".join(out)
125
+
126
+
127
+ def _balance_brackets(s: str) -> Optional[str]:
128
+ """Appends missing closing brackets/braces (string-aware). Returns None when
129
+ the structure cannot be balanced by appending closers alone."""
130
+ if not s:
131
+ return None
132
+ stack: List[str] = []
133
+ in_str = False
134
+ quote = ""
135
+ escaped = False
136
+ for ch in s:
137
+ if in_str:
138
+ if escaped:
139
+ escaped = False
140
+ elif ch == "\\":
141
+ escaped = True
142
+ elif ch == quote:
143
+ in_str = False
144
+ continue
145
+ if ch in ('"', "'"):
146
+ in_str = True
147
+ quote = ch
148
+ elif ch in "{[":
149
+ stack.append("}" if ch == "{" else "]")
150
+ elif ch in "}]":
151
+ if not stack or stack[-1] != ch:
152
+ return None
153
+ stack.pop()
154
+ if in_str:
155
+ # Unterminated string: close it before the pending brackets
156
+ return s + '"' + "".join(reversed(stack))
157
+ return s + "".join(reversed(stack))
158
+
159
+
160
+ def _single_to_double_quotes(s: str) -> Optional[str]:
161
+ """Converts single-quoted strings to double quotes. Only safe when the text
162
+ contains no double quotes at all (so an unambiguous dialect is broken)."""
163
+ if '"' in s or "'" not in s:
164
+ return None
165
+ return s.replace("'", '"')
@@ -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("=")
@@ -379,6 +465,16 @@ class LicenseManager:
379
465
  tier_cfg = cls.TIERS.get(tier, cls.TIERS["free"])
380
466
  max_tokens = tier_cfg.get("max_tokens_monthly")
381
467
 
468
+ # Server-issued quota (community license payload) overrides the embedded
469
+ # default — enables remote quota control without a client release.
470
+ if max_tokens is not None and isinstance(payload, dict):
471
+ try:
472
+ server_quota = int(payload.get("max_tokens_monthly") or 0)
473
+ if server_quota > 0:
474
+ max_tokens = server_quota
475
+ except (TypeError, ValueError):
476
+ pass
477
+
382
478
  # Paid tiers (solo, team, enterprise) have unlimited local optimization
383
479
  if max_tokens is None:
384
480
  return {
@@ -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()