tokensafe 4.1.3 → 4.1.5
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/package.json +2 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/cli.py +4 -68
- package/src/dashboard.py +2 -2
- package/src/mcp_server.py +1 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/src/weekly_digest.py +0 -386
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.1.
|
|
4
|
+
"version": "4.1.5",
|
|
5
5
|
"description": "Make AI coding agents 3x faster without burning team quotas. Exact code context. Fewer tokens. Safer changes.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
"src/",
|
|
15
15
|
"!src/cloud_backend.py",
|
|
16
16
|
"!src/mailer.py",
|
|
17
|
+
"!src/weekly_digest.py",
|
|
17
18
|
"!**/__pycache__/**",
|
|
18
19
|
"!**/*.pyc",
|
|
19
20
|
"rules/",
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.1.
|
|
4
|
+
"version": "4.1.5",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
|
|
6
|
-
"version": "4.1.
|
|
6
|
+
"version": "4.1.5",
|
|
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.
|
|
33
|
+
"version": "4.1.5",
|
|
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.
|
|
49
|
+
"version": "4.1.5",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
package/src/cli.py
CHANGED
|
@@ -105,7 +105,6 @@ def _print_help():
|
|
|
105
105
|
print(" bench --real [--repo=key|--here] Measured benchmark on real repos (zero-loss gates)")
|
|
106
106
|
print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
|
|
107
107
|
print(" test <prompt> Preview TOCP S-expression prompt compaction")
|
|
108
|
-
print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
|
|
109
108
|
print(" guard <command> Pre-flight safety check for a shell command")
|
|
110
109
|
print(" expand-ref <hash> Restore folded tool/command/file result by its 8-char hash")
|
|
111
110
|
print(" wrap <command> Run command with compact output folding (e.g. tests/logs)")
|
|
@@ -195,7 +194,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
195
194
|
q_pct = min(100, int(q_saved / q_limit * 100)) if q_limit else 0
|
|
196
195
|
q_state = "\033[31mQUOTA REACHED — Pro optimizations paused\033[0m" if quota.get("is_quota_exceeded") else f"{q_pct}% of monthly measured quota"
|
|
197
196
|
print(f" Tier: \033[33mCOMMUNITY (Free)\033[0m — {q_saved:,} / {q_limit:,} tokens ({q_state})")
|
|
198
|
-
print(" Upgrade:
|
|
197
|
+
print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo · 7-Day Team Trial)")
|
|
199
198
|
else:
|
|
200
199
|
print(f" Tier: \033[32m{tier.upper()}\033[0m (Unlimited)")
|
|
201
200
|
# Cloud heartbeat (non-blocking; keeps the machine visible server-side)
|
|
@@ -748,7 +747,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
748
747
|
|
|
749
748
|
print(" To authorize this device and connect your account:")
|
|
750
749
|
print(f" 1. Confirm code: \033[1m\033[33m{user_code}\033[0m")
|
|
751
|
-
print(f" 2. In browser at:
|
|
750
|
+
print(f" 2. In browser at: {verif_url}\n")
|
|
752
751
|
|
|
753
752
|
# Attempt to open browser automatically
|
|
754
753
|
try:
|
|
@@ -823,7 +822,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
823
822
|
print(f" \033[32m✔ Team license activated (Unlimited tokens, organization workspace{org_msg}).\033[0m")
|
|
824
823
|
else:
|
|
825
824
|
print(" \033[32m✔ Community Edition license activated (500,000 free tokens/month).\033[0m")
|
|
826
|
-
print(f" \033[36m✔ Web dashboard unlocked at
|
|
825
|
+
print(f" \033[36m✔ Web dashboard unlocked at:\033[0m https://tokensafe.dev/dashboard\n")
|
|
827
826
|
|
|
828
827
|
# Sync local token metrics
|
|
829
828
|
try:
|
|
@@ -953,7 +952,7 @@ def main(argv: Optional[List[str]] = None):
|
|
|
953
952
|
print(" Managed Cloud Distillation (zero API keys) is reserved for Solo, Team, and Enterprise tiers.")
|
|
954
953
|
print(" Free Community Edition operates with the zero-latency, zero-cost Local Regex Compactor.\n")
|
|
955
954
|
print(" \033[1mTo unlock Cloud Distillation:\033[0m")
|
|
956
|
-
print(" 1. Start 7-day free trial or upgrade at:
|
|
955
|
+
print(" 1. Start 7-day free trial or upgrade at: https://tokensafe.dev")
|
|
957
956
|
print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
|
|
958
957
|
elif not UniversalDistiller.is_self_hosted():
|
|
959
958
|
print(f" \033[32m✔\033[0m \033[1mTokenSafe Cloud Distiller\033[0m [Active: gemini-flash-lite-latest via Managed Cloud]")
|
|
@@ -1110,69 +1109,6 @@ def main(argv: Optional[List[str]] = None):
|
|
|
1110
1109
|
b_after = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
|
|
1111
1110
|
print(f"\033[32m✔ Database compacted + session aggregates rebuilt. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
|
|
1112
1111
|
|
|
1113
|
-
elif command in ("digest", "weekly-digest"):
|
|
1114
|
-
from src.weekly_digest import WeeklyDigestGenerator
|
|
1115
|
-
|
|
1116
|
-
target_email = None
|
|
1117
|
-
do_send = "--send" in args
|
|
1118
|
-
|
|
1119
|
-
idx = 1
|
|
1120
|
-
while idx < len(args):
|
|
1121
|
-
a = args[idx]
|
|
1122
|
-
if a.startswith("--email="):
|
|
1123
|
-
target_email = a.split("=", 1)[1].strip()
|
|
1124
|
-
elif a == "--email" and idx + 1 < len(args):
|
|
1125
|
-
target_email = args[idx + 1].strip()
|
|
1126
|
-
idx += 1
|
|
1127
|
-
idx += 1
|
|
1128
|
-
|
|
1129
|
-
if not target_email:
|
|
1130
|
-
from src.license_manager import LicenseManager
|
|
1131
|
-
_, payload = LicenseManager.get_active_license()
|
|
1132
|
-
target_email = payload.get("email") or "teamlead@example.com"
|
|
1133
|
-
|
|
1134
|
-
print(f"\n\033[1m\033[36m⚡ COMPILING FRIDAY TEAM ROI DIGEST ⚡\033[0m")
|
|
1135
|
-
print(f"Target Teamlead: {target_email}")
|
|
1136
|
-
|
|
1137
|
-
stats = WeeklyDigestGenerator.get_team_weekly_stats(target_email)
|
|
1138
|
-
if not stats:
|
|
1139
|
-
stats = {
|
|
1140
|
-
"owner_email": target_email,
|
|
1141
|
-
"tier": "team",
|
|
1142
|
-
"seats_total": 1,
|
|
1143
|
-
"active_members_count": 0,
|
|
1144
|
-
"total_members_count": 0,
|
|
1145
|
-
"total_original_tokens": 0,
|
|
1146
|
-
"total_saved_tokens": 0,
|
|
1147
|
-
"total_saved_human": "0",
|
|
1148
|
-
"total_usd_saved": 0.0,
|
|
1149
|
-
"total_events": 0,
|
|
1150
|
-
"reduction_pct": 0.0,
|
|
1151
|
-
"leaderboard": [],
|
|
1152
|
-
}
|
|
1153
|
-
|
|
1154
|
-
print(WeeklyDigestGenerator.render_email_text(stats))
|
|
1155
|
-
|
|
1156
|
-
from src.paths import resolve_data_dir
|
|
1157
|
-
out_html = os.path.join(resolve_data_dir(), "weekly_digest_preview.html")
|
|
1158
|
-
os.makedirs(os.path.dirname(out_html), exist_ok=True)
|
|
1159
|
-
with open(out_html, "w", encoding="utf-8") as f:
|
|
1160
|
-
f.write(WeeklyDigestGenerator.render_email_html(stats))
|
|
1161
|
-
print(f"\n📧 Apple-style email HTML preview generated at: {out_html}")
|
|
1162
|
-
|
|
1163
|
-
if do_send:
|
|
1164
|
-
try:
|
|
1165
|
-
from src.mailer import TokenSafeMailer
|
|
1166
|
-
ok = TokenSafeMailer.send_weekly_digest(target_email, stats, sync=True)
|
|
1167
|
-
if ok:
|
|
1168
|
-
print(f"\033[32m✔ Weekly digest successfully dispatched to {target_email}!\033[0m\n")
|
|
1169
|
-
else:
|
|
1170
|
-
print(f"\033[33m○ Digest dispatch queued (SMTP_PASS not configured in local environment).\033[0m\n")
|
|
1171
|
-
except ImportError:
|
|
1172
|
-
print("\n\033[33m○ Email delivery is handled by TokenSafe Cloud; preview HTML saved locally.\033[0m\n")
|
|
1173
|
-
else:
|
|
1174
|
-
print("Tip: Run with --send to dispatch email, or --email=<addr> to target specific team.\n")
|
|
1175
|
-
|
|
1176
1112
|
elif command in ("expand-ref", "expand_ref", "expand"):
|
|
1177
1113
|
if len(args) < 2:
|
|
1178
1114
|
print("Usage: tokensafe expand-ref <hash8>")
|
package/src/dashboard.py
CHANGED
|
@@ -88,10 +88,10 @@ class Dashboard:
|
|
|
88
88
|
q_pct = min(100.0, (monthly_saved / limit * 100.0))
|
|
89
89
|
if monthly_saved >= limit:
|
|
90
90
|
out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {RED}{BOLD}500k Monthly Measured Quota Reached ({monthly_saved:,}/{limit:,}){RESET}")
|
|
91
|
-
out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Pro optimizations paused · Upgrade: tokensafe activate <key> |
|
|
91
|
+
out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Pro optimizations paused · Upgrade: tokensafe activate <key> | https://tokensafe.dev/signup)")
|
|
92
92
|
else:
|
|
93
93
|
out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {monthly_saved:,} / {limit:,} measured tokens this month")
|
|
94
|
-
out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited ·
|
|
94
|
+
out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited · https://tokensafe.dev/signup)")
|
|
95
95
|
else:
|
|
96
96
|
email_info = f" ({payload.get('email', '')})" if payload.get('email') else ""
|
|
97
97
|
out.append(f" {BOLD}Subscription Tier:{RESET} {GREEN}{BOLD}{tier_upper} (Unlimited){RESET}{email_info}")
|
package/src/mcp_server.py
CHANGED
package/src/telemetry_sync.py
CHANGED
|
@@ -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.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.1.5"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -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.
|
|
20
|
+
CURRENT_VERSION = "4.1.5"
|
|
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
|
package/src/weekly_digest.py
DELETED
|
@@ -1,386 +0,0 @@
|
|
|
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 html as _html
|
|
14
|
-
import time
|
|
15
|
-
import json
|
|
16
|
-
import sqlite3
|
|
17
|
-
from contextlib import contextmanager
|
|
18
|
-
from typing import Dict, List, Any, Optional, Tuple
|
|
19
|
-
|
|
20
|
-
from src.paths import resolve_data_dir
|
|
21
|
-
|
|
22
|
-
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
23
|
-
DATA_DIR = resolve_data_dir()
|
|
24
|
-
CLOUD_DB_PATH = os.environ.get("TOKENSAFE_CLOUD_DB_PATH", os.path.join(DATA_DIR, "cloud.db"))
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
@contextmanager
|
|
28
|
-
def _open_digest_db(db_path: str):
|
|
29
|
-
"""Yields Cloud DB/cloud connection for default DB path, or local sqlite3 for custom paths."""
|
|
30
|
-
if db_path == CLOUD_DB_PATH:
|
|
31
|
-
try:
|
|
32
|
-
from src.cloud.db import get_db_connection
|
|
33
|
-
from src.cloud.config import CLOUD_DB_URL, CLOUD_DB_TOKEN, CLOUD_DB_PATH as CLOUD_CFG_DB_PATH
|
|
34
|
-
|
|
35
|
-
if (CLOUD_DB_URL and CLOUD_DB_TOKEN) or os.path.exists(CLOUD_CFG_DB_PATH):
|
|
36
|
-
with get_db_connection() as conn:
|
|
37
|
-
yield conn
|
|
38
|
-
return
|
|
39
|
-
yield None
|
|
40
|
-
return
|
|
41
|
-
except ImportError:
|
|
42
|
-
pass
|
|
43
|
-
|
|
44
|
-
if not os.path.exists(db_path):
|
|
45
|
-
yield None
|
|
46
|
-
return
|
|
47
|
-
|
|
48
|
-
conn = sqlite3.connect(db_path)
|
|
49
|
-
conn.row_factory = sqlite3.Row
|
|
50
|
-
try:
|
|
51
|
-
yield conn
|
|
52
|
-
finally:
|
|
53
|
-
conn.close()
|
|
54
|
-
|
|
55
|
-
def format_token_number(n: int) -> str:
|
|
56
|
-
"""Formats large token count into human-readable 1.2M, 450K, etc."""
|
|
57
|
-
if n >= 1_000_000:
|
|
58
|
-
return f"{n / 1_000_000:.1f}M"
|
|
59
|
-
if n >= 1_000:
|
|
60
|
-
return f"{n / 1_000:.1f}K"
|
|
61
|
-
return str(n)
|
|
62
|
-
|
|
63
|
-
class WeeklyDigestGenerator:
|
|
64
|
-
"""Compiles weekly team ROI statistics and email templates."""
|
|
65
|
-
|
|
66
|
-
@classmethod
|
|
67
|
-
def get_team_weekly_stats(
|
|
68
|
-
cls,
|
|
69
|
-
owner_email: str,
|
|
70
|
-
now: Optional[int] = None,
|
|
71
|
-
db_path: str = CLOUD_DB_PATH,
|
|
72
|
-
allow_any_tier: bool = False
|
|
73
|
-
) -> Optional[Dict[str, Any]]:
|
|
74
|
-
"""
|
|
75
|
-
Retrieves 7-day telemetry for team owned by owner_email.
|
|
76
|
-
Supports both Cloud DB (cloud) and local SQLite databases.
|
|
77
|
-
Returns aggregated digest data or None if no eligible records found.
|
|
78
|
-
"""
|
|
79
|
-
clean_email = (owner_email or "").strip().lower()
|
|
80
|
-
if not clean_email or "@" not in clean_email:
|
|
81
|
-
return None
|
|
82
|
-
|
|
83
|
-
now = now or int(time.time())
|
|
84
|
-
seven_days_ago = now - (7 * 86400)
|
|
85
|
-
|
|
86
|
-
with _open_digest_db(db_path) as conn:
|
|
87
|
-
if conn is None:
|
|
88
|
-
return None
|
|
89
|
-
|
|
90
|
-
# 1. Verify owner and active team/enterprise entitlement across customers & organizations
|
|
91
|
-
owner = conn.execute(
|
|
92
|
-
"SELECT * FROM customers WHERE email = ?;",
|
|
93
|
-
(clean_email,),
|
|
94
|
-
).fetchone()
|
|
95
|
-
|
|
96
|
-
orgs = []
|
|
97
|
-
try:
|
|
98
|
-
orgs = conn.execute(
|
|
99
|
-
"SELECT * FROM organizations WHERE owner_email = ? AND status = 'active' ORDER BY is_primary DESC, created_at ASC;",
|
|
100
|
-
(clean_email,),
|
|
101
|
-
).fetchall()
|
|
102
|
-
except sqlite3.OperationalError:
|
|
103
|
-
orgs = []
|
|
104
|
-
|
|
105
|
-
cust_active = bool(owner and str(owner["status"] or "").lower() == "active")
|
|
106
|
-
cust_tier = str(owner["tier"] or "").lower() if owner else ""
|
|
107
|
-
team_orgs = [o for o in orgs if str(o["tier"] or "").lower() in ("team", "enterprise")]
|
|
108
|
-
|
|
109
|
-
if team_orgs:
|
|
110
|
-
effective_tier = str(team_orgs[0]["tier"] or "team").lower()
|
|
111
|
-
effective_seats = sum(int(o["seats_total"] or 1) for o in team_orgs)
|
|
112
|
-
elif cust_active and cust_tier in ("team", "enterprise"):
|
|
113
|
-
effective_tier = cust_tier
|
|
114
|
-
effective_seats = int(owner["seats_total"] or 1)
|
|
115
|
-
elif allow_any_tier and (cust_active or orgs):
|
|
116
|
-
if orgs:
|
|
117
|
-
effective_tier = str(orgs[0]["tier"] or cust_tier or "solo").lower()
|
|
118
|
-
effective_seats = int(orgs[0]["seats_total"] or 1)
|
|
119
|
-
else:
|
|
120
|
-
effective_tier = cust_tier or "solo"
|
|
121
|
-
effective_seats = int(owner["seats_total"] or 1)
|
|
122
|
-
else:
|
|
123
|
-
return None
|
|
124
|
-
|
|
125
|
-
# 2. Find all member emails and license keys in this team / owned organizations
|
|
126
|
-
licenses = conn.execute(
|
|
127
|
-
"SELECT * FROM licenses WHERE parent_email = ? OR customer_email = ?;",
|
|
128
|
-
(clean_email, clean_email),
|
|
129
|
-
).fetchall()
|
|
130
|
-
|
|
131
|
-
team_emails = {clean_email}
|
|
132
|
-
for lic in licenses:
|
|
133
|
-
if lic["customer_email"]:
|
|
134
|
-
team_emails.add(str(lic["customer_email"]).strip().lower())
|
|
135
|
-
|
|
136
|
-
org_ids = [o["id"] for o in (team_orgs if team_orgs else orgs) if o["id"]]
|
|
137
|
-
if org_ids:
|
|
138
|
-
org_placeholders = ",".join(["?"] * len(org_ids))
|
|
139
|
-
org_lics = conn.execute(
|
|
140
|
-
f"SELECT customer_email FROM licenses WHERE org_id IN ({org_placeholders});",
|
|
141
|
-
org_ids,
|
|
142
|
-
).fetchall()
|
|
143
|
-
for lic in org_lics:
|
|
144
|
-
if lic["customer_email"]:
|
|
145
|
-
team_emails.add(str(lic["customer_email"]).strip().lower())
|
|
146
|
-
|
|
147
|
-
placeholders = ",".join(["?"] * len(team_emails))
|
|
148
|
-
params = list(team_emails) + [seven_days_ago, now]
|
|
149
|
-
|
|
150
|
-
# 3. Aggregate 7-day telemetry (bounded [seven_days_ago, now], excluding synthetic ROLLUP_LIFETIME)
|
|
151
|
-
events = conn.execute(
|
|
152
|
-
f"""
|
|
153
|
-
SELECT * FROM telemetry
|
|
154
|
-
WHERE customer_email IN ({placeholders})
|
|
155
|
-
AND timestamp >= ?
|
|
156
|
-
AND timestamp <= ?
|
|
157
|
-
AND COALESCE(event_type, '') != 'ROLLUP_LIFETIME'
|
|
158
|
-
ORDER BY timestamp DESC;
|
|
159
|
-
""",
|
|
160
|
-
params,
|
|
161
|
-
).fetchall()
|
|
162
|
-
|
|
163
|
-
total_orig = sum(int(e["original_tokens"] or 0) for e in events)
|
|
164
|
-
total_saved = sum(int(e["saved_tokens"] or 0) for e in events)
|
|
165
|
-
total_usd = sum(float(e["usd_saved"] or 0.0) for e in events)
|
|
166
|
-
event_count = len(events)
|
|
167
|
-
reduction_pct = round((total_saved / total_orig * 100), 1) if total_orig > 0 else 0.0
|
|
168
|
-
|
|
169
|
-
# 4. Engineer leaderboard
|
|
170
|
-
engineer_stats: Dict[str, Dict[str, Any]] = {}
|
|
171
|
-
for em in team_emails:
|
|
172
|
-
engineer_stats[em] = {
|
|
173
|
-
"email": em,
|
|
174
|
-
"saved_tokens": 0,
|
|
175
|
-
"original_tokens": 0,
|
|
176
|
-
"usd_saved": 0.0,
|
|
177
|
-
"event_count": 0
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
category_breakdown: Dict[str, int] = {}
|
|
181
|
-
|
|
182
|
-
for e in events:
|
|
183
|
-
em = str(e["customer_email"] or clean_email).strip().lower()
|
|
184
|
-
if em not in engineer_stats:
|
|
185
|
-
engineer_stats[em] = {
|
|
186
|
-
"email": em,
|
|
187
|
-
"saved_tokens": 0,
|
|
188
|
-
"original_tokens": 0,
|
|
189
|
-
"usd_saved": 0.0,
|
|
190
|
-
"event_count": 0
|
|
191
|
-
}
|
|
192
|
-
saved_toks = int(e["saved_tokens"] or 0)
|
|
193
|
-
orig_toks = int(e["original_tokens"] or 0)
|
|
194
|
-
usd_val = float(e["usd_saved"] or 0.0)
|
|
195
|
-
engineer_stats[em]["saved_tokens"] += saved_toks
|
|
196
|
-
engineer_stats[em]["original_tokens"] += orig_toks
|
|
197
|
-
engineer_stats[em]["usd_saved"] += usd_val
|
|
198
|
-
engineer_stats[em]["event_count"] += 1
|
|
199
|
-
|
|
200
|
-
ev_type = str(e["event_type"] or "PROMPT")
|
|
201
|
-
category_breakdown[ev_type] = category_breakdown.get(ev_type, 0) + saved_toks
|
|
202
|
-
|
|
203
|
-
leaderboard = sorted(
|
|
204
|
-
engineer_stats.values(),
|
|
205
|
-
key=lambda x: x["saved_tokens"],
|
|
206
|
-
reverse=True
|
|
207
|
-
)
|
|
208
|
-
|
|
209
|
-
# Assign ranks
|
|
210
|
-
for idx, eng in enumerate(leaderboard, 1):
|
|
211
|
-
eng["rank"] = idx
|
|
212
|
-
eng["saved_tokens_human"] = format_token_number(eng["saved_tokens"])
|
|
213
|
-
eng["usd_saved_formatted"] = f"${eng['usd_saved']:.2f}"
|
|
214
|
-
|
|
215
|
-
return {
|
|
216
|
-
"owner_email": clean_email,
|
|
217
|
-
"tier": effective_tier,
|
|
218
|
-
"seats_total": effective_seats,
|
|
219
|
-
"active_members_count": len([e for e in leaderboard if e["event_count"] > 0]),
|
|
220
|
-
"total_members_count": len(team_emails),
|
|
221
|
-
"total_original_tokens": total_orig,
|
|
222
|
-
"total_saved_tokens": total_saved,
|
|
223
|
-
"total_saved_human": format_token_number(total_saved),
|
|
224
|
-
"total_usd_saved": round(total_usd, 2),
|
|
225
|
-
"total_events": event_count,
|
|
226
|
-
"reduction_pct": reduction_pct,
|
|
227
|
-
"leaderboard": leaderboard,
|
|
228
|
-
"category_breakdown": category_breakdown,
|
|
229
|
-
"start_time": seven_days_ago,
|
|
230
|
-
"end_time": now
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
@classmethod
|
|
234
|
-
def render_email_html(cls, digest: Dict[str, Any]) -> str:
|
|
235
|
-
"""Generates Apple-style responsive dark-mode HTML email."""
|
|
236
|
-
owner_email = _html.escape(str(digest["owner_email"]))
|
|
237
|
-
total_saved_human = _html.escape(str(digest["total_saved_human"]))
|
|
238
|
-
usd_saved = f"${digest['total_usd_saved']:.2f}"
|
|
239
|
-
reduction_pct = digest["reduction_pct"]
|
|
240
|
-
leaderboard = digest["leaderboard"]
|
|
241
|
-
seats_total = digest["seats_total"]
|
|
242
|
-
active_count = digest["active_members_count"]
|
|
243
|
-
|
|
244
|
-
# Build leaderboard rows
|
|
245
|
-
rows_html = ""
|
|
246
|
-
for eng in leaderboard[:10]:
|
|
247
|
-
rank = eng["rank"]
|
|
248
|
-
medal = "🥇 " if rank == 1 else "🥈 " if rank == 2 else "🥉 " if rank == 3 else f"#{rank} "
|
|
249
|
-
email_mask = _html.escape(eng["email"].split("@")[0] + "@...")
|
|
250
|
-
rows_html += f"""
|
|
251
|
-
<tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.05);">
|
|
252
|
-
<td style="padding: 12px 8px; font-weight: 700; color: #10b981;">{medal}</td>
|
|
253
|
-
<td style="padding: 12px 8px; font-family: monospace; color: #e5e7eb; font-size: 13px;">{email_mask}</td>
|
|
254
|
-
<td style="padding: 12px 8px; text-align: right; font-weight: 700; color: #ffffff;">{eng['saved_tokens_human']}</td>
|
|
255
|
-
<td style="padding: 12px 8px; text-align: right; color: #10b981; font-weight: 600;">{eng['usd_saved_formatted']}</td>
|
|
256
|
-
</tr>
|
|
257
|
-
"""
|
|
258
|
-
|
|
259
|
-
html = f"""<!DOCTYPE html>
|
|
260
|
-
<html>
|
|
261
|
-
<head>
|
|
262
|
-
<meta charset="utf-8">
|
|
263
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
264
|
-
<title>TokenSafe Weekly Team ROI Digest</title>
|
|
265
|
-
</head>
|
|
266
|
-
<body style="margin: 0; padding: 0; background-color: #030712; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; color: #f3f4f6;">
|
|
267
|
-
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color: #030712; padding: 40px 16px;">
|
|
268
|
-
<tr>
|
|
269
|
-
<td align="center">
|
|
270
|
-
<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);">
|
|
271
|
-
|
|
272
|
-
<!-- Header -->
|
|
273
|
-
<tr>
|
|
274
|
-
<td style="padding-bottom: 20px; border-bottom: 1px solid rgba(255, 255, 255, 0.08);">
|
|
275
|
-
<span style="font-size: 20px; font-weight: 800; color: #ffffff; letter-spacing: -0.5px;">
|
|
276
|
-
Token<span style="color: #10b981;">Safe</span>
|
|
277
|
-
</span>
|
|
278
|
-
<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;">
|
|
279
|
-
WEEKLY DIGEST • FRIDAY
|
|
280
|
-
</span>
|
|
281
|
-
</td>
|
|
282
|
-
</tr>
|
|
283
|
-
|
|
284
|
-
<!-- Hero Headline -->
|
|
285
|
-
<tr>
|
|
286
|
-
<td style="padding: 28px 0 16px;">
|
|
287
|
-
<h1 style="margin: 0 0 8px; font-size: 24px; font-weight: 800; color: #ffffff; line-height: 1.3;">
|
|
288
|
-
TokenSafe saved your team <span style="color: #10b981;">{total_saved_human} tokens</span> ({usd_saved}) this week
|
|
289
|
-
</h1>
|
|
290
|
-
<p style="margin: 0; font-size: 14px; color: #94a3b8; line-height: 1.5;">
|
|
291
|
-
Friday engineering summary for <strong>{owner_email}</strong>. Active seats: {active_count}/{seats_total}.
|
|
292
|
-
</p>
|
|
293
|
-
</td>
|
|
294
|
-
</tr>
|
|
295
|
-
|
|
296
|
-
<!-- Key Metrics Grid -->
|
|
297
|
-
<tr>
|
|
298
|
-
<td style="padding: 12px 0 24px;">
|
|
299
|
-
<table role="presentation" width="100%" cellspacing="0" cellpadding="0">
|
|
300
|
-
<tr>
|
|
301
|
-
<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;">
|
|
302
|
-
<div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Tokens Saved</div>
|
|
303
|
-
<div style="font-size: 22px; font-weight: 800; color: #10b981; margin-top: 4px;">{total_saved_human}</div>
|
|
304
|
-
</td>
|
|
305
|
-
<td width="2%"></td>
|
|
306
|
-
<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;">
|
|
307
|
-
<div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Est. Cost Saved</div>
|
|
308
|
-
<div style="font-size: 22px; font-weight: 800; color: #ffffff; margin-top: 4px;">{usd_saved}</div>
|
|
309
|
-
</td>
|
|
310
|
-
<td width="2%"></td>
|
|
311
|
-
<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;">
|
|
312
|
-
<div style="font-size: 11px; color: #94a3b8; text-transform: uppercase; font-weight: 600;">Net Reduction</div>
|
|
313
|
-
<div style="font-size: 22px; font-weight: 800; color: #06b6d4; margin-top: 4px;">-{reduction_pct}%</div>
|
|
314
|
-
</td>
|
|
315
|
-
</tr>
|
|
316
|
-
</table>
|
|
317
|
-
</td>
|
|
318
|
-
</tr>
|
|
319
|
-
|
|
320
|
-
<!-- Leaderboard Table -->
|
|
321
|
-
<tr>
|
|
322
|
-
<td style="padding: 12px 0 20px;">
|
|
323
|
-
<h3 style="margin: 0 0 12px; font-size: 15px; font-weight: 700; color: #ffffff; text-transform: uppercase; letter-spacing: 0.5px;">
|
|
324
|
-
🏆 Engineer Savings Leaderboard
|
|
325
|
-
</h3>
|
|
326
|
-
<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;">
|
|
327
|
-
<thead>
|
|
328
|
-
<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;">
|
|
329
|
-
<th style="padding: 10px 8px; text-align: left;">Rank</th>
|
|
330
|
-
<th style="padding: 10px 8px; text-align: left;">Engineer</th>
|
|
331
|
-
<th style="padding: 10px 8px; text-align: right;">Saved</th>
|
|
332
|
-
<th style="padding: 10px 8px; text-align: right;">Value</th>
|
|
333
|
-
</tr>
|
|
334
|
-
</thead>
|
|
335
|
-
<tbody>
|
|
336
|
-
{rows_html}
|
|
337
|
-
</tbody>
|
|
338
|
-
</table>
|
|
339
|
-
</td>
|
|
340
|
-
</tr>
|
|
341
|
-
|
|
342
|
-
<!-- CTA Button -->
|
|
343
|
-
<tr>
|
|
344
|
-
<td style="padding: 24px 0 16px; text-align: center;">
|
|
345
|
-
<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);">
|
|
346
|
-
Open Live Team Dashboard ➔
|
|
347
|
-
</a>
|
|
348
|
-
</td>
|
|
349
|
-
</tr>
|
|
350
|
-
|
|
351
|
-
<!-- Footer -->
|
|
352
|
-
<tr>
|
|
353
|
-
<td style="padding-top: 24px; border-top: 1px solid rgba(255, 255, 255, 0.06); font-size: 12px; color: #64748b; text-align: center;">
|
|
354
|
-
TokenSafe Enterprise • Automatic Friday ROI Digest • <a href="https://tokensafe.dev" style="color: #10b981; text-decoration: none;">tokensafe.dev</a>
|
|
355
|
-
</td>
|
|
356
|
-
</tr>
|
|
357
|
-
|
|
358
|
-
</table>
|
|
359
|
-
</td>
|
|
360
|
-
</tr>
|
|
361
|
-
</table>
|
|
362
|
-
</body>
|
|
363
|
-
</html>"""
|
|
364
|
-
return html
|
|
365
|
-
|
|
366
|
-
@classmethod
|
|
367
|
-
def render_email_text(cls, digest: Dict[str, Any]) -> str:
|
|
368
|
-
"""Generates clean plain-text version for terminal or fallback."""
|
|
369
|
-
owner_email = digest["owner_email"]
|
|
370
|
-
total_saved = digest["total_saved_human"]
|
|
371
|
-
usd = f"${digest['total_usd_saved']:.2f}"
|
|
372
|
-
reduction = digest["reduction_pct"]
|
|
373
|
-
|
|
374
|
-
lines = [
|
|
375
|
-
f"⚡ TOKENSAFE WEEKLY TEAM ROI DIGEST",
|
|
376
|
-
f"Recipient: {owner_email}",
|
|
377
|
-
f"Period: Last 7 Days (Delivered Friday)\n",
|
|
378
|
-
f"TokenSafe saved your team {total_saved} tokens ({usd}) this week!",
|
|
379
|
-
f"Net Context Reduction: -{reduction}%\n",
|
|
380
|
-
f"--- 🏆 ENGINEER SAVINGS LEADERBOARD ---"
|
|
381
|
-
]
|
|
382
|
-
for eng in digest["leaderboard"]:
|
|
383
|
-
lines.append(f"#{eng['rank']:<2} {eng['email']:<28} {eng['saved_tokens_human']:>8} ({eng['usd_saved_formatted']})")
|
|
384
|
-
|
|
385
|
-
lines.append(f"\nOpen your live dashboard: https://tokensafe.dev/dashboard")
|
|
386
|
-
return "\n".join(lines)
|