tokensafe 1.3.0 → 1.3.2

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/src/proxy.py CHANGED
@@ -8,10 +8,12 @@ Endpoint: http://127.0.0.1:8765/v1
8
8
  import sys
9
9
  import os
10
10
  import json
11
+ import queue
12
+ import threading
11
13
  import urllib.request
12
14
  import urllib.error
13
15
  from http.server import HTTPServer, BaseHTTPRequestHandler
14
- from typing import Dict, Any
16
+ from typing import Dict, Any, List
15
17
 
16
18
  BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
19
  sys.path.insert(0, BASE_DIR)
@@ -22,10 +24,44 @@ from src.dashboard import Dashboard
22
24
  from src.loop_detector import LoopDetector
23
25
  from src.secret_redactor import SecretRedactor
24
26
  from src.graph_engine import GraphEngine
27
+ from src.cache_normalizer import PromptCacheNormalizer
28
+ from src.governor import ContextGovernor
25
29
 
26
30
  DEFAULT_PORT = 8765
31
+ DEFAULT_HOST = os.environ.get("HOST", os.environ.get("TOKENSAFE_HOST", "0.0.0.0"))
27
32
  DEFAULT_UPSTREAM = "https://api.deepseek.com/v1"
28
33
 
34
+ class EventBroadcaster:
35
+ """Thread-safe pub/sub for Server-Sent Events (SSE) streaming."""
36
+ def __init__(self):
37
+ self._subscribers: List[queue.Queue] = []
38
+ self._lock = threading.Lock()
39
+
40
+ def subscribe(self) -> queue.Queue:
41
+ q = queue.Queue(maxsize=50)
42
+ with self._lock:
43
+ self._subscribers.append(q)
44
+ return q
45
+
46
+ def unsubscribe(self, q: queue.Queue):
47
+ with self._lock:
48
+ if q in self._subscribers:
49
+ self._subscribers.remove(q)
50
+
51
+ def publish(self, event_type: str, data: Dict[str, Any]):
52
+ payload = f"event: {event_type}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
53
+ with self._lock:
54
+ dead = []
55
+ for q in self._subscribers:
56
+ try:
57
+ q.put_nowait(payload)
58
+ except queue.Full:
59
+ dead.append(q)
60
+ for d in dead:
61
+ self._subscribers.remove(d)
62
+
63
+ BROADCASTER = EventBroadcaster()
64
+
29
65
  class TokenSafeProxyHandler(BaseHTTPRequestHandler):
30
66
  """Handles HTTP requests and proxies /v1/chat/completions with token optimization."""
31
67
 
@@ -37,7 +73,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
37
73
  """Protects against DNS rebinding and cross-origin attacks from arbitrary browser origins."""
38
74
  origin = self.headers.get("Origin", "")
39
75
  if origin:
40
- allowed_prefixes = ("http://127.0.0.1", "http://localhost", "https://tokensafe.dev")
76
+ allowed_prefixes = ["http://127.0.0.1", "http://localhost", "http://0.0.0.0", "https://tokensafe.dev"]
77
+ custom_origins = os.environ.get("TOKENSAFE_ALLOWED_ORIGINS", "")
78
+ if custom_origins:
79
+ allowed_prefixes.extend([o.strip() for o in custom_origins.split(",") if o.strip()])
41
80
  if not any(origin.startswith(a) for a in allowed_prefixes):
42
81
  self.send_response(403)
43
82
  self.send_header("Content-Type", "application/json")
@@ -67,6 +106,35 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
67
106
  self.end_headers()
68
107
  self.wfile.write(json.dumps(summary, indent=2).encode("utf-8"))
69
108
 
109
+ elif self.path in ("/api/events", "/events"):
110
+ self.send_response(200)
111
+ self.send_header("Content-Type", "text/event-stream")
112
+ self.send_header("Cache-Control", "no-cache")
113
+ self.send_header("Connection", "keep-alive")
114
+ self.send_header("Access-Control-Allow-Origin", "*")
115
+ self.end_headers()
116
+
117
+ q = BROADCASTER.subscribe()
118
+ try:
119
+ initial_summary = tracker.get_summary()
120
+ init_msg = f"event: init\ndata: {json.dumps(initial_summary, ensure_ascii=False)}\n\n"
121
+ self.wfile.write(init_msg.encode("utf-8"))
122
+ self.wfile.flush()
123
+
124
+ while True:
125
+ try:
126
+ msg = q.get(timeout=15.0)
127
+ self.wfile.write(msg.encode("utf-8"))
128
+ self.wfile.flush()
129
+ except queue.Empty:
130
+ self.wfile.write(b": heartbeat\n\n")
131
+ self.wfile.flush()
132
+ except (BrokenPipeError, ConnectionResetError):
133
+ pass
134
+ finally:
135
+ BROADCASTER.unsubscribe(q)
136
+ return
137
+
70
138
  elif self.path == "/health":
71
139
  self.send_response(200)
72
140
  self.send_header("Content-Type", "application/json")
@@ -130,29 +198,75 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
130
198
  except Exception:
131
199
  pass
132
200
 
133
- # 4. Forward to Upstream
201
+ # 4. Prompt Cache Prefix Normalization (100% Cache Hits)
202
+ if messages:
203
+ messages, cache_meta = PromptCacheNormalizer.normalize_messages(messages)
204
+ payload["messages"] = messages
205
+
206
+ # 5. Context Window Governor (Budget Autothrottle)
207
+ if messages:
208
+ messages, gov_stats = ContextGovernor.govern_messages(messages, session_id="proxy_session")
209
+ payload["messages"] = messages
210
+ if gov_stats.get("throttled"):
211
+ BROADCASTER.publish("governor_throttle", gov_stats)
212
+
213
+ # 6. Resolve Multi-Provider Upstream & API Key
134
214
  auth_header = self.headers.get("Authorization", "")
135
- # Check if local config has deepseek key
136
- config_path = os.path.join(BASE_DIR, "data", "config.json")
137
- upstream_key = ""
215
+ custom_url = os.environ.get("TOKENSAFE_UPSTREAM_URL", "")
216
+
217
+ # Supported keys from environment or config
218
+ data_dir = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(BASE_DIR, "data"))
219
+ conf_keys = {}
220
+ config_path = os.path.join(data_dir, "config.json")
138
221
  if os.path.exists(config_path):
139
222
  try:
140
223
  with open(config_path) as f:
141
- conf = json.load(f)
142
- upstream_key = conf.get("deepseek_api_key", "")
224
+ conf_keys = json.load(f)
143
225
  except Exception:
144
226
  pass
145
227
 
146
- final_auth = auth_header or (f"Bearer {upstream_key}" if upstream_key else "")
147
- upstream_url = os.environ.get("TOKENSAFE_UPSTREAM_URL", "https://api.deepseek.com/chat/completions")
228
+ deepseek_key = os.environ.get("DEEPSEEK_API_KEY", "") or conf_keys.get("deepseek_api_key", "")
229
+ openai_key = os.environ.get("OPENAI_API_KEY", "") or conf_keys.get("openai_api_key", "")
230
+ gemini_key = os.environ.get("GEMINI_API_KEY", "") or conf_keys.get("gemini_api_key", "")
231
+ anthropic_key = os.environ.get("ANTHROPIC_API_KEY", "") or conf_keys.get("anthropic_api_key", "")
232
+ generic_upstream_key = os.environ.get("TOKENSAFE_UPSTREAM_KEY", "")
233
+
234
+ # Infer upstream URL if not provided
235
+ if not custom_url:
236
+ if openai_key and not deepseek_key:
237
+ upstream_url = "https://api.openai.com/v1/chat/completions"
238
+ resolved_key = openai_key
239
+ elif anthropic_key and not deepseek_key:
240
+ upstream_url = "https://api.anthropic.com/v1/messages"
241
+ resolved_key = anthropic_key
242
+ else:
243
+ upstream_url = "https://api.deepseek.com/chat/completions"
244
+ resolved_key = deepseek_key or generic_upstream_key
245
+ else:
246
+ upstream_url = custom_url
247
+ if "openai.com" in upstream_url:
248
+ resolved_key = openai_key or generic_upstream_key or deepseek_key
249
+ elif "anthropic.com" in upstream_url:
250
+ resolved_key = anthropic_key or generic_upstream_key
251
+ elif "googleapis.com" in upstream_url:
252
+ resolved_key = gemini_key or generic_upstream_key
253
+ else:
254
+ resolved_key = deepseek_key or generic_upstream_key or openai_key
255
+
256
+ headers = {"Content-Type": "application/json"}
257
+ if auth_header:
258
+ headers["Authorization"] = auth_header
259
+ elif resolved_key:
260
+ if "anthropic.com" in upstream_url:
261
+ headers["x-api-key"] = resolved_key
262
+ headers["anthropic-version"] = "2023-06-01"
263
+ else:
264
+ headers["Authorization"] = f"Bearer {resolved_key}"
148
265
 
149
266
  req = urllib.request.Request(
150
267
  upstream_url,
151
268
  data=json.dumps(payload).encode("utf-8"),
152
- headers={
153
- "Authorization": final_auth,
154
- "Content-Type": "application/json"
155
- }
269
+ headers=headers
156
270
  )
157
271
 
158
272
  try:
@@ -164,6 +278,14 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
164
278
  self.send_header(k, v)
165
279
  self.end_headers()
166
280
  self.wfile.write(resp_data)
281
+
282
+ # Broadcast live telemetry update to SSE dashboard subscribers
283
+ try:
284
+ tracker = MetricsTracker()
285
+ summary = tracker.get_summary()
286
+ BROADCASTER.publish("stats_update", summary)
287
+ except Exception:
288
+ pass
167
289
  except urllib.error.HTTPError as e:
168
290
  self.send_response(e.code)
169
291
  self.end_headers()
@@ -173,7 +295,7 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
173
295
  self.end_headers()
174
296
  self.wfile.write(json.dumps({"error": f"Upstream proxy error: {str(e)}"}).encode("utf-8"))
175
297
 
176
- def run_proxy(port: int = DEFAULT_PORT):
298
+ def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
177
299
  # Auto-initialize Knowledge Graph & API Surface on startup
178
300
  hubs_summary = "active"
179
301
  try:
@@ -185,11 +307,12 @@ def run_proxy(port: int = DEFAULT_PORT):
185
307
  except Exception as e:
186
308
  hubs_summary = f"initialized ({e})"
187
309
 
188
- server_address = ("127.0.0.1", port)
310
+ server_address = (host, port)
189
311
  httpd = HTTPServer(server_address, TokenSafeProxyHandler)
190
- print(f"\n⚡ TokenSafe Local AI Proxy running on: http://127.0.0.1:{port}")
191
- print(f" Dashboard: http://127.0.0.1:{port}/dashboard")
192
- print(f" OpenAI-compatible URL: http://127.0.0.1:{port}/v1")
312
+ display_host = "localhost" if host in ("0.0.0.0", "", "127.0.0.1") else host
313
+ print(f"\n⚡ TokenSafe Local AI Proxy running on: http://{display_host}:{port} (bound to {host})")
314
+ print(f" Dashboard: http://{display_host}:{port}/dashboard")
315
+ print(f" OpenAI-compatible URL: http://{display_host}:{port}/v1")
193
316
  print(f" Auto-Graph: {hubs_summary}")
194
317
  print(f" API Surface: tokensafe-out/API_SURFACE.md")
195
318
  try:
@@ -14,7 +14,7 @@ import urllib.request
14
14
  import urllib.error
15
15
  from typing import Dict, Any, Optional, Tuple
16
16
 
17
- CURRENT_VERSION = "1.3.0"
17
+ CURRENT_VERSION = "1.3.2"
18
18
  CACHE_TTL = 86400 # 24 hours
19
19
 
20
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -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)