tokensafe 1.2.0 → 1.3.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.
@@ -0,0 +1,156 @@
1
+ """
2
+ TokenSafe Version Checker & Passive Nudge Engine.
3
+ Maintains a 24h cached version status to provide zero-latency terminal banners,
4
+ soft update recommendations, and critical forced update notifications.
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import json
10
+ import time
11
+ import re
12
+ import urllib.parse
13
+ import urllib.request
14
+ import urllib.error
15
+ from typing import Dict, Any, Optional, Tuple
16
+
17
+ CURRENT_VERSION = "1.3.1"
18
+ CACHE_TTL = 86400 # 24 hours
19
+
20
+ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ DATA_DIR = os.path.join(PROJECT_ROOT, "data")
22
+ CACHE_FILE = os.path.join(DATA_DIR, "version_cache.json")
23
+ CLOUD_CHECK_URL = os.environ.get("TOKENSAFE_VERSION_URL", "https://api.tokensafe.dev/api/version/check")
24
+
25
+ # ANSI color codes
26
+ RESET = "\033[0m"
27
+ BOLD = "\033[1m"
28
+ GREEN = "\033[32m"
29
+ CYAN = "\033[36m"
30
+ YELLOW = "\033[33m"
31
+ RED = "\033[31m"
32
+ DIM = "\033[2m"
33
+
34
+ def semver_tuple(v_str: str) -> Tuple[int, ...]:
35
+ """Parses semver string like '1.2.0' into numeric tuple (1, 2, 0)."""
36
+ if not v_str:
37
+ return (0, 0, 0)
38
+ clean = re.sub(r"^[^\d]*", "", str(v_str).strip())
39
+ parts = clean.split(".")
40
+ nums = []
41
+ for p in parts[:3]:
42
+ m = re.match(r"\d+", p)
43
+ nums.append(int(m.group(0)) if m else 0)
44
+ while len(nums) < 3:
45
+ nums.append(0)
46
+ return tuple(nums)
47
+
48
+ class VersionChecker:
49
+ """Manages cached client-side version discovery and CLI banners."""
50
+
51
+ @classmethod
52
+ def get_cache_path(cls) -> str:
53
+ os.makedirs(DATA_DIR, exist_ok=True)
54
+ return CACHE_FILE
55
+
56
+ @classmethod
57
+ def load_cache(cls) -> Optional[Dict[str, Any]]:
58
+ cache_path = cls.get_cache_path()
59
+ if not os.path.exists(cache_path):
60
+ return None
61
+ try:
62
+ with open(cache_path, "r", encoding="utf-8") as f:
63
+ return json.load(f)
64
+ except Exception:
65
+ return None
66
+
67
+ @classmethod
68
+ def save_cache(cls, data: Dict[str, Any]):
69
+ cache_path = cls.get_cache_path()
70
+ try:
71
+ with open(cache_path, "w", encoding="utf-8") as f:
72
+ json.dump(data, f, indent=2)
73
+ except Exception:
74
+ pass
75
+
76
+ @classmethod
77
+ def check_version(
78
+ cls,
79
+ current_version: str = CURRENT_VERSION,
80
+ license_key: str = "",
81
+ force_fetch: bool = False,
82
+ timeout: float = 1.5
83
+ ) -> Dict[str, Any]:
84
+ """
85
+ Retrieves version status. Returns cached result if within TTL,
86
+ otherwise makes a fast network request (< 1.5s timeout).
87
+ Falls back gracefully on network or offline scenarios.
88
+ """
89
+ now = int(time.time())
90
+ cached = cls.load_cache()
91
+
92
+ if not force_fetch and cached:
93
+ checked_at = cached.get("checked_at", 0)
94
+ if now - checked_at < CACHE_TTL:
95
+ return cached
96
+
97
+ # Default payload
98
+ payload = {
99
+ "checked_at": now,
100
+ "client_version": current_version,
101
+ "latest_version": current_version,
102
+ "min_supported_version": "1.1.0",
103
+ "update_available": False,
104
+ "force_update": False,
105
+ "message": f"TokenSafe is up to date (v{current_version}).",
106
+ "update_command": "tokensafe update"
107
+ }
108
+
109
+ try:
110
+ params = f"?version={urllib.parse.quote(current_version)}&license={urllib.parse.quote(license_key)}"
111
+ url = f"{CLOUD_CHECK_URL}{params}"
112
+ req = urllib.request.Request(
113
+ url,
114
+ headers={"User-Agent": f"TokenSafe-CLI/{current_version}"}
115
+ )
116
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
117
+ if resp.status == 200:
118
+ data = json.loads(resp.read().decode("utf-8"))
119
+ data["checked_at"] = now
120
+ cls.save_cache(data)
121
+ return data
122
+ except Exception:
123
+ pass
124
+
125
+ # Stale cache fallback if available
126
+ if cached:
127
+ return cached
128
+ cls.save_cache(payload)
129
+ return payload
130
+
131
+ @classmethod
132
+ def get_banner(cls, current_version: str = CURRENT_VERSION, license_key: str = "") -> Optional[str]:
133
+ """
134
+ Returns a styled ANSI banner string if an update is available or required,
135
+ or None if up to date.
136
+ """
137
+ info = cls.check_version(current_version=current_version, license_key=license_key)
138
+ force_update = info.get("force_update", False)
139
+ update_available = info.get("update_available", False)
140
+ latest = info.get("latest_version", current_version)
141
+ cmd = info.get("update_command", "tokensafe update")
142
+
143
+ if force_update:
144
+ return (
145
+ f"\n{RED}{BOLD}╔════════════════════════════════════════════════════════════════════════╗{RESET}\n"
146
+ f"{RED}{BOLD}║ 🚨 CRITICAL UPDATE REQUIRED: TokenSafe v{current_version} is deprecated! ║{RESET}\n"
147
+ f"{RED}║ Please run {BOLD}{cmd}{RESET}{RED} immediately to continue using TokenSafe. ║{RESET}\n"
148
+ f"{RED}{BOLD}╚════════════════════════════════════════════════════════════════════════╝{RESET}\n"
149
+ )
150
+ elif update_available:
151
+ return (
152
+ f"\n{CYAN}💡 TokenSafe update available: {DIM}v{current_version}{RESET}{CYAN} → {GREEN}{BOLD}v{latest}{RESET}{CYAN}"
153
+ f" (run {BOLD}{cmd}{RESET}{CYAN} to upgrade){RESET}\n"
154
+ )
155
+
156
+ return None
@@ -0,0 +1,305 @@
1
+ """
2
+ TokenSafe Weekly Team ROI Digest Engine.
3
+ Generates automated weekly performance digests for engineering teamleads every Friday.
4
+ Aggregates:
5
+ - Total team tokens and USD saved over the past 7 days
6
+ - Engineer leaderboard ranking team members by token economy contribution
7
+ - Optimization category breakdown (Skeletons, Compactor, Deduplication, Sanitization)
8
+ - Formats Apple-style responsive dark-mode email and plain text versions
9
+ """
10
+
11
+ import os
12
+ import sys
13
+ import time
14
+ import json
15
+ import sqlite3
16
+ from typing import Dict, List, Any, Optional, Tuple
17
+
18
+ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
+ DATA_DIR = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(PROJECT_ROOT, "data"))
20
+ CLOUD_DB_PATH = os.environ.get("TOKENSAFE_CLOUD_DB_PATH", os.path.join(DATA_DIR, "cloud.db"))
21
+
22
+ def format_token_number(n: int) -> str:
23
+ """Formats large token count into human-readable 1.2M, 450K, etc."""
24
+ if n >= 1_000_000:
25
+ return f"{n / 1_000_000:.1f}M"
26
+ if n >= 1_000:
27
+ return f"{n / 1_000:.1f}K"
28
+ return str(n)
29
+
30
+ class WeeklyDigestGenerator:
31
+ """Compiles weekly team ROI statistics and email templates."""
32
+
33
+ @classmethod
34
+ def get_team_weekly_stats(
35
+ cls,
36
+ owner_email: str,
37
+ now: Optional[int] = None,
38
+ db_path: str = CLOUD_DB_PATH
39
+ ) -> Optional[Dict[str, Any]]:
40
+ """
41
+ Retrieves 7-day telemetry for team owned by owner_email.
42
+ Returns aggregated digest data or None if no team records found.
43
+ """
44
+ now = now or int(time.time())
45
+ seven_days_ago = now - (7 * 86400)
46
+
47
+ if not os.path.exists(db_path):
48
+ return None
49
+
50
+ conn = sqlite3.connect(db_path)
51
+ conn.row_factory = sqlite3.Row
52
+ try:
53
+ # 1. Verify owner and tier
54
+ owner = conn.execute("""
55
+ SELECT * FROM customers
56
+ WHERE email = ? AND status = 'active';
57
+ """, (owner_email.lower(),)).fetchone()
58
+
59
+ if not owner or owner["tier"] not in ("team", "enterprise"):
60
+ return None
61
+
62
+ # 2. Find all member emails and license keys in this team
63
+ licenses = conn.execute("""
64
+ SELECT * FROM licenses
65
+ WHERE parent_email = ? OR customer_email = ?;
66
+ """, (owner_email.lower(), owner_email.lower())).fetchall()
67
+
68
+ team_emails = {owner_email.lower()}
69
+ for lic in licenses:
70
+ if lic["customer_email"]:
71
+ team_emails.add(lic["customer_email"].lower())
72
+
73
+ placeholders = ",".join(["?"] * len(team_emails))
74
+ params = list(team_emails) + [seven_days_ago]
75
+
76
+ # 3. Aggregate 7-day telemetry
77
+ events = conn.execute(f"""
78
+ SELECT * FROM telemetry
79
+ WHERE customer_email IN ({placeholders}) AND timestamp >= ?
80
+ ORDER BY timestamp DESC;
81
+ """, params).fetchall()
82
+
83
+ total_orig = sum(e["original_tokens"] for e in events)
84
+ total_saved = sum(e["saved_tokens"] for e in events)
85
+ total_usd = sum(e["usd_saved"] for e in events)
86
+ event_count = len(events)
87
+ reduction_pct = round((total_saved / total_orig * 100), 1) if total_orig > 0 else 76.5
88
+
89
+ # 4. Engineer leaderboard
90
+ engineer_stats: Dict[str, Dict[str, Any]] = {}
91
+ for em in team_emails:
92
+ engineer_stats[em] = {
93
+ "email": em,
94
+ "saved_tokens": 0,
95
+ "original_tokens": 0,
96
+ "usd_saved": 0.0,
97
+ "event_count": 0
98
+ }
99
+
100
+ category_breakdown: Dict[str, int] = {}
101
+
102
+ for e in events:
103
+ em = e["customer_email"].lower()
104
+ if em not in engineer_stats:
105
+ engineer_stats[em] = {
106
+ "email": em,
107
+ "saved_tokens": 0,
108
+ "original_tokens": 0,
109
+ "usd_saved": 0.0,
110
+ "event_count": 0
111
+ }
112
+ engineer_stats[em]["saved_tokens"] += e["saved_tokens"]
113
+ engineer_stats[em]["original_tokens"] += e["original_tokens"]
114
+ engineer_stats[em]["usd_saved"] += e["usd_saved"]
115
+ engineer_stats[em]["event_count"] += 1
116
+
117
+ ev_type = e["event_type"]
118
+ category_breakdown[ev_type] = category_breakdown.get(ev_type, 0) + e["saved_tokens"]
119
+
120
+ leaderboard = sorted(
121
+ engineer_stats.values(),
122
+ key=lambda x: x["saved_tokens"],
123
+ reverse=True
124
+ )
125
+
126
+ # Assign ranks
127
+ for idx, eng in enumerate(leaderboard, 1):
128
+ eng["rank"] = idx
129
+ eng["saved_tokens_human"] = format_token_number(eng["saved_tokens"])
130
+ eng["usd_saved_formatted"] = f"${eng['usd_saved']:.2f}"
131
+
132
+ return {
133
+ "owner_email": owner_email,
134
+ "tier": owner["tier"],
135
+ "seats_total": owner["seats_total"],
136
+ "active_members_count": len([e for e in leaderboard if e["event_count"] > 0]),
137
+ "total_members_count": len(team_emails),
138
+ "total_original_tokens": total_orig,
139
+ "total_saved_tokens": total_saved,
140
+ "total_saved_human": format_token_number(total_saved),
141
+ "total_usd_saved": round(total_usd, 2),
142
+ "total_events": event_count,
143
+ "reduction_pct": reduction_pct,
144
+ "leaderboard": leaderboard,
145
+ "category_breakdown": category_breakdown,
146
+ "start_time": seven_days_ago,
147
+ "end_time": now
148
+ }
149
+ finally:
150
+ conn.close()
151
+
152
+ @classmethod
153
+ def render_email_html(cls, digest: Dict[str, Any]) -> str:
154
+ """Generates Apple-style responsive dark-mode HTML email."""
155
+ owner_email = digest["owner_email"]
156
+ total_saved_human = digest["total_saved_human"]
157
+ usd_saved = f"${digest['total_usd_saved']:.2f}"
158
+ reduction_pct = digest["reduction_pct"]
159
+ leaderboard = digest["leaderboard"]
160
+ seats_total = digest["seats_total"]
161
+ active_count = digest["active_members_count"]
162
+
163
+ # Build leaderboard rows
164
+ rows_html = ""
165
+ for eng in leaderboard[:10]:
166
+ rank = eng["rank"]
167
+ medal = "🥇 " if rank == 1 else "🥈 " if rank == 2 else "🥉 " if rank == 3 else f"#{rank} "
168
+ email_mask = eng["email"].split("@")[0] + "@..."
169
+ rows_html += f"""
170
+ <tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.05);">
171
+ <td style="padding: 12px 8px; font-weight: 700; color: #10b981;">{medal}</td>
172
+ <td style="padding: 12px 8px; font-family: monospace; color: #e5e7eb; font-size: 13px;">{email_mask}</td>
173
+ <td style="padding: 12px 8px; text-align: right; font-weight: 700; color: #ffffff;">{eng['saved_tokens_human']}</td>
174
+ <td style="padding: 12px 8px; text-align: right; color: #10b981; font-weight: 600;">{eng['usd_saved_formatted']}</td>
175
+ </tr>
176
+ """
177
+
178
+ html = f"""<!DOCTYPE html>
179
+ <html>
180
+ <head>
181
+ <meta charset="utf-8">
182
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
183
+ <title>TokenSafe Weekly Team ROI Digest</title>
184
+ </head>
185
+ <body style="margin: 0; padding: 0; background-color: #030712; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: #f3f4f6;">
186
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #030712; padding: 40px 16px;">
187
+ <tr>
188
+ <td align="center">
189
+ <table role="presentation" width="100%" style="max-width: 600px; background-color: #0f172a; border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 16px; padding: 32px; box-shadow: 0 20px 40px rgba(0,0,0,0.5);">
190
+
191
+ <!-- Header -->
192
+ <tr>
193
+ <td style="padding-bottom: 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.08);">
194
+ <span style="font-size: 20px; font-weight: 800; color: #ffffff; letter-spacing: -0.5px;">
195
+ Token<span style="color: #10b981;">Safe</span>
196
+ </span>
197
+ <span style="float: right; font-size: 11px; font-weight: 700; color: #10b981; background: rgba(16, 185, 129, 0.12); border: 1px solid rgba(16, 185, 129, 0.25); padding: 4px 10px; border-radius: 999px;">
198
+ WEEKLY DIGEST • FRIDAY
199
+ </span>
200
+ </td>
201
+ </tr>
202
+
203
+ <!-- Hero Headline -->
204
+ <tr>
205
+ <td style="padding: 28px 0 16px;">
206
+ <h1 style="margin: 0 0 8px; font-size: 24px; font-weight: 800; color: #ffffff; line-height: 1.3;">
207
+ TokenSafe saved your team <span style="color: #10b981;">{total_saved_human} tokens</span> ({usd_saved}) this week
208
+ </h1>
209
+ <p style="margin: 0; font-size: 14px; color: #94a3b8; line-height: 1.5;">
210
+ Friday engineering summary for <strong>{owner_email}</strong>. Active seats: {active_count}/{seats_total}.
211
+ </p>
212
+ </td>
213
+ </tr>
214
+
215
+ <!-- Key Metrics Grid -->
216
+ <tr>
217
+ <td style="padding: 12px 0 24px;">
218
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0">
219
+ <tr>
220
+ <td width="32%" style="background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 16px; text-align: center;">
221
+ <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Tokens Saved</div>
222
+ <div style="font-size: 22px; font-weight: 800; color: #10b981; margin-top: 4px;">{total_saved_human}</div>
223
+ </td>
224
+ <td width="2%"></td>
225
+ <td width="32%" style="background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 16px; text-align: center;">
226
+ <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Est. Cost Saved</div>
227
+ <div style="font-size: 22px; font-weight: 800; color: #ffffff; margin-top: 4px;">{usd_saved}</div>
228
+ </td>
229
+ <td width="2%"></td>
230
+ <td width="32%" style="background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; padding: 16px; text-align: center;">
231
+ <div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Net Reduction</div>
232
+ <div style="font-size: 22px; font-weight: 800; color: #06b6d4; margin-top: 4px;">-{reduction_pct}%</div>
233
+ </td>
234
+ </tr>
235
+ </table>
236
+ </td>
237
+ </tr>
238
+
239
+ <!-- Leaderboard Table -->
240
+ <tr>
241
+ <td style="padding: 12px 0 20px;">
242
+ <h3 style="margin: 0 0 12px; font-size: 15px; font-weight: 700; color: #ffffff; text-transform: uppercase; letter-spacing: 0.5px;">
243
+ 🏆 Engineer Savings Leaderboard
244
+ </h3>
245
+ <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse: collapse; background: rgba(0,0,0,0.2); border-radius: 10px; overflow: hidden;">
246
+ <thead>
247
+ <tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.08); background: rgba(255, 255, 255, 0.02); font-size: 11px; color: #94a3b8; text-transform: uppercase;">
248
+ <th style="padding: 10px 8px; text-align: left;">Rank</th>
249
+ <th style="padding: 10px 8px; text-align: left;">Engineer</th>
250
+ <th style="padding: 10px 8px; text-align: right;">Saved</th>
251
+ <th style="padding: 10px 8px; text-align: right;">Value</th>
252
+ </tr>
253
+ </thead>
254
+ <tbody>
255
+ {rows_html}
256
+ </tbody>
257
+ </table>
258
+ </td>
259
+ </tr>
260
+
261
+ <!-- CTA Button -->
262
+ <tr>
263
+ <td style="padding: 24px 0 16px; text-align: center;">
264
+ <a href="https://tokensafe.dev/dashboard" style="display: inline-block; background: #10b981; color: #000000; font-weight: 700; font-size: 14px; text-decoration: none; padding: 14px 28px; border-radius: 10px; box-shadow: 0 4px 14px rgba(16, 185, 129, 0.35);">
265
+ Open Live Team Dashboard ➔
266
+ </a>
267
+ </td>
268
+ </tr>
269
+
270
+ <!-- Footer -->
271
+ <tr>
272
+ <td style="padding-top: 24px; border-top: 1px solid rgba(255, 255, 255, 0.06); font-size: 12px; color: #64748b; text-align: center;">
273
+ TokenSafe Enterprise • Automatic Friday ROI Digest • <a href="https://tokensafe.dev" style="color: #10b981; text-decoration: none;">tokensafe.dev</a>
274
+ </td>
275
+ </tr>
276
+
277
+ </table>
278
+ </td>
279
+ </tr>
280
+ </table>
281
+ </body>
282
+ </html>"""
283
+ return html
284
+
285
+ @classmethod
286
+ def render_email_text(cls, digest: Dict[str, Any]) -> str:
287
+ """Generates clean plain-text version for terminal or fallback."""
288
+ owner_email = digest["owner_email"]
289
+ total_saved = digest["total_saved_human"]
290
+ usd = f"${digest['total_usd_saved']:.2f}"
291
+ reduction = digest["reduction_pct"]
292
+
293
+ lines = [
294
+ f"⚡ TOKENSAFE WEEKLY TEAM ROI DIGEST",
295
+ f"Recipient: {owner_email}",
296
+ f"Period: Last 7 Days (Delivered Friday)\n",
297
+ f"TokenSafe saved your team {total_saved} tokens ({usd}) this week!",
298
+ f"Net Context Reduction: -{reduction}%\n",
299
+ f"--- 🏆 ENGINEER SAVINGS LEADERBOARD ---"
300
+ ]
301
+ for eng in digest["leaderboard"]:
302
+ lines.append(f"#{eng['rank']:<2} {eng['email']:<28} {eng['saved_tokens_human']:>8} ({eng['usd_saved_formatted']})")
303
+
304
+ lines.append(f"\nOpen your live dashboard: https://tokensafe.dev/dashboard")
305
+ return "\n".join(lines)