tokensafe 2.0.1 → 2.2.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.
package/src/slicer.py CHANGED
@@ -5,7 +5,7 @@ Prevents context window bloat from full-file reads (800+ lines) and noisy termin
5
5
 
6
6
  import os
7
7
  import re
8
- from typing import Dict, Any, Optional, Tuple
8
+ from typing import Dict, Any, List, Optional, Tuple
9
9
  from src.tokenizer import count_tokens
10
10
 
11
11
  class ToolSlicer:
@@ -14,6 +14,64 @@ class ToolSlicer:
14
14
  # Default max lines to read when no range is specified on large files
15
15
  DEFAULT_MAX_WINDOW = 350
16
16
 
17
+ # When a target symbol is found, the slice must contain the WHOLE
18
+ # enclosing definition — a fixed tail used to cut long function bodies in
19
+ # half. Definitions longer than this cap are better served by the AST
20
+ # skeleton path, so the window stays bounded.
21
+ MAX_SYMBOL_WINDOW = 400
22
+
23
+ @classmethod
24
+ def _find_definition_end(cls, lines: List[str], def_line_no: int) -> Optional[int]:
25
+ """
26
+ Returns the 1-based last line of the definition whose declaration sits
27
+ on def_line_no, or None when it cannot be determined reliably.
28
+
29
+ Python (def/class): the body ends at the last non-blank line before a
30
+ line dedented to <= the declaration's indent.
31
+ C-family (function/const/func/fn/impl/struct/...): brace balance from
32
+ the first '{' within the declaration or the next 10 lines. Naive
33
+ counting is safe here: a brace inside a string can only skew the end
34
+ within the cap, and the caller keeps the legacy tail as a floor.
35
+ """
36
+ if def_line_no < 1 or def_line_no > len(lines):
37
+ return None
38
+ def_line = lines[def_line_no - 1]
39
+
40
+ py_match = re.match(r"^(\s*)(?:async\s+)?(?:def|class)\b", def_line)
41
+ if py_match:
42
+ base_indent = len(py_match.group(1).expandtabs(8))
43
+ end = def_line_no
44
+ for idx in range(def_line_no, len(lines)):
45
+ line = lines[idx]
46
+ if not line.strip():
47
+ continue
48
+ expanded = line.expandtabs(8)
49
+ indent = len(expanded) - len(expanded.lstrip())
50
+ if indent <= base_indent:
51
+ break
52
+ end = idx + 1
53
+ return end
54
+
55
+ # C-family: locate the opening brace within the declaration head
56
+ # (first 10 lines), then balance braces across the capped window.
57
+ window_end = min(len(lines), def_line_no - 1 + cls.MAX_SYMBOL_WINDOW)
58
+ text = "".join(lines[def_line_no - 1:window_end])
59
+ head = "".join(lines[def_line_no - 1:min(len(lines), def_line_no + 10)])
60
+ offset = head.find("{")
61
+ if offset == -1:
62
+ return None
63
+
64
+ depth = 0
65
+ for i, ch in enumerate(text[offset:]):
66
+ if ch == "{":
67
+ depth += 1
68
+ elif ch == "}":
69
+ depth -= 1
70
+ if depth == 0:
71
+ return def_line_no + text[:offset + i + 1].count("\n")
72
+ # Unbalanced within the cap: report the cap boundary as the end
73
+ return window_end
74
+
17
75
  @classmethod
18
76
  def optimize_read_file(cls, args: Dict[str, Any], context_hint: str = "") -> Tuple[Dict[str, Any], Dict[str, Any]]:
19
77
  """
@@ -58,7 +116,7 @@ class ToolSlicer:
58
116
  # regex scans per read_file hook call on large files).
59
117
  unique_candidates = list(dict.fromkeys(candidates))
60
118
  combined = re.compile(
61
- r'\b(?:def|function|class|const|let|var|type|interface)\s+('
119
+ r'\b(?:def|function|class|const|let|var|type|interface|func|fn|impl|struct|enum|trait)\s+('
62
120
  + "|".join(re.escape(c) for c in unique_candidates) + r')\b'
63
121
  )
64
122
  first_hit: Dict[str, int] = {}
@@ -77,9 +135,17 @@ class ToolSlicer:
77
135
  new_end = total_lines
78
136
 
79
137
  if found_line:
80
- # Slice: 20 lines before, 80 lines after
138
+ # Slice: 20-line lead-in before the declaration, then enough tail
139
+ # to contain the WHOLE enclosing definition (short definitions keep
140
+ # the legacy 80-line tail; long ones extend to their real end).
81
141
  new_start = max(1, found_line - 20)
82
142
  new_end = min(total_lines, found_line + 80)
143
+ def_end = cls._find_definition_end(lines, found_line)
144
+ if def_end:
145
+ new_end = min(
146
+ total_lines,
147
+ max(new_end, min(def_end, found_line + cls.MAX_SYMBOL_WINDOW)),
148
+ )
83
149
 
84
150
  # If no symbol found and file is large (> 400 lines), apply safety window
85
151
  if not target_symbol and total_lines > 400 and (end_line is None or end_line > cls.DEFAULT_MAX_WINDOW):
@@ -264,7 +264,7 @@ class TelemetrySync:
264
264
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
265
265
  headers = {
266
266
  "Content-Type": "application/json",
267
- "User-Agent": "TokenSafe-Sync/2.0.1"
267
+ "User-Agent": "TokenSafe-Sync/2.2.0"
268
268
  }
269
269
  if active_key:
270
270
  headers["Authorization"] = f"Bearer {active_key}"
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "2.0.1"
19
+ CURRENT_VERSION = "2.2.0"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage
@@ -10,15 +10,46 @@ Aggregates:
10
10
 
11
11
  import os
12
12
  import sys
13
+ import html as _html
13
14
  import time
14
15
  import json
15
16
  import sqlite3
17
+ from contextlib import contextmanager
16
18
  from typing import Dict, List, Any, Optional, Tuple
17
19
 
18
20
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
21
  DATA_DIR = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(PROJECT_ROOT, "data"))
20
22
  CLOUD_DB_PATH = os.environ.get("TOKENSAFE_CLOUD_DB_PATH", os.path.join(DATA_DIR, "cloud.db"))
21
23
 
24
+
25
+ @contextmanager
26
+ def _open_digest_db(db_path: str):
27
+ """Yields BunnyDB/cloud connection for default DB path, or local sqlite3 for custom paths."""
28
+ if db_path == CLOUD_DB_PATH:
29
+ try:
30
+ from src.cloud.db import get_db_connection
31
+ from src.cloud.config import BUNNY_DB_URL, BUNNY_DB_TOKEN, CLOUD_DB_PATH as CLOUD_CFG_DB_PATH
32
+
33
+ if (BUNNY_DB_URL and BUNNY_DB_TOKEN) or os.path.exists(CLOUD_CFG_DB_PATH):
34
+ with get_db_connection() as conn:
35
+ yield conn
36
+ return
37
+ yield None
38
+ return
39
+ except ImportError:
40
+ pass
41
+
42
+ if not os.path.exists(db_path):
43
+ yield None
44
+ return
45
+
46
+ conn = sqlite3.connect(db_path)
47
+ conn.row_factory = sqlite3.Row
48
+ try:
49
+ yield conn
50
+ finally:
51
+ conn.close()
52
+
22
53
  def format_token_number(n: int) -> str:
23
54
  """Formats large token count into human-readable 1.2M, 450K, etc."""
24
55
  if n >= 1_000_000:
@@ -35,56 +66,100 @@ class WeeklyDigestGenerator:
35
66
  cls,
36
67
  owner_email: str,
37
68
  now: Optional[int] = None,
38
- db_path: str = CLOUD_DB_PATH
69
+ db_path: str = CLOUD_DB_PATH,
70
+ allow_any_tier: bool = False
39
71
  ) -> Optional[Dict[str, Any]]:
40
72
  """
41
73
  Retrieves 7-day telemetry for team owned by owner_email.
42
- Returns aggregated digest data or None if no team records found.
74
+ Supports both BunnyDB (cloud) and local SQLite databases.
75
+ Returns aggregated digest data or None if no eligible records found.
43
76
  """
77
+ clean_email = (owner_email or "").strip().lower()
78
+ if not clean_email or "@" not in clean_email:
79
+ return None
80
+
44
81
  now = now or int(time.time())
45
82
  seven_days_ago = now - (7 * 86400)
46
83
 
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()
84
+ with _open_digest_db(db_path) as conn:
85
+ if conn is None:
86
+ return None
58
87
 
59
- if not owner or owner["tier"] not in ("team", "enterprise"):
88
+ # 1. Verify owner and active team/enterprise entitlement across customers & organizations
89
+ owner = conn.execute(
90
+ "SELECT * FROM customers WHERE email = ?;",
91
+ (clean_email,),
92
+ ).fetchone()
93
+
94
+ orgs = []
95
+ try:
96
+ orgs = conn.execute(
97
+ "SELECT * FROM organizations WHERE owner_email = ? AND status = 'active' ORDER BY is_primary DESC, created_at ASC;",
98
+ (clean_email,),
99
+ ).fetchall()
100
+ except sqlite3.OperationalError:
101
+ orgs = []
102
+
103
+ cust_active = bool(owner and str(owner["status"] or "").lower() == "active")
104
+ cust_tier = str(owner["tier"] or "").lower() if owner else ""
105
+ team_orgs = [o for o in orgs if str(o["tier"] or "").lower() in ("team", "enterprise")]
106
+
107
+ if team_orgs:
108
+ effective_tier = str(team_orgs[0]["tier"] or "team").lower()
109
+ effective_seats = sum(int(o["seats_total"] or 1) for o in team_orgs)
110
+ elif cust_active and cust_tier in ("team", "enterprise"):
111
+ effective_tier = cust_tier
112
+ effective_seats = int(owner["seats_total"] or 1)
113
+ elif allow_any_tier and (cust_active or orgs):
114
+ if orgs:
115
+ effective_tier = str(orgs[0]["tier"] or cust_tier or "solo").lower()
116
+ effective_seats = int(orgs[0]["seats_total"] or 1)
117
+ else:
118
+ effective_tier = cust_tier or "solo"
119
+ effective_seats = int(owner["seats_total"] or 1)
120
+ else:
60
121
  return None
61
122
 
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()
123
+ # 2. Find all member emails and license keys in this team / owned organizations
124
+ licenses = conn.execute(
125
+ "SELECT * FROM licenses WHERE parent_email = ? OR customer_email = ?;",
126
+ (clean_email, clean_email),
127
+ ).fetchall()
67
128
 
68
- team_emails = {owner_email.lower()}
129
+ team_emails = {clean_email}
69
130
  for lic in licenses:
70
131
  if lic["customer_email"]:
71
- team_emails.add(lic["customer_email"].lower())
132
+ team_emails.add(str(lic["customer_email"]).strip().lower())
133
+
134
+ org_ids = [o["id"] for o in (team_orgs if team_orgs else orgs) if o["id"]]
135
+ if org_ids:
136
+ org_placeholders = ",".join(["?"] * len(org_ids))
137
+ org_lics = conn.execute(
138
+ f"SELECT customer_email FROM licenses WHERE org_id IN ({org_placeholders});",
139
+ org_ids,
140
+ ).fetchall()
141
+ for lic in org_lics:
142
+ if lic["customer_email"]:
143
+ team_emails.add(str(lic["customer_email"]).strip().lower())
72
144
 
73
145
  placeholders = ",".join(["?"] * len(team_emails))
74
146
  params = list(team_emails) + [seven_days_ago]
75
147
 
76
148
  # 3. Aggregate 7-day telemetry
77
- events = conn.execute(f"""
78
- SELECT * FROM telemetry
149
+ events = conn.execute(
150
+ f"""
151
+ SELECT * FROM telemetry
79
152
  WHERE customer_email IN ({placeholders}) AND timestamp >= ?
80
153
  ORDER BY timestamp DESC;
81
- """, params).fetchall()
154
+ """,
155
+ params,
156
+ ).fetchall()
82
157
 
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)
158
+ total_orig = sum(int(e["original_tokens"] or 0) for e in events)
159
+ total_saved = sum(int(e["saved_tokens"] or 0) for e in events)
160
+ total_usd = sum(float(e["usd_saved"] or 0.0) for e in events)
86
161
  event_count = len(events)
87
- reduction_pct = round((total_saved / total_orig * 100), 1) if total_orig > 0 else 76.5
162
+ reduction_pct = round((total_saved / total_orig * 100), 1) if total_orig > 0 else 0.0
88
163
 
89
164
  # 4. Engineer leaderboard
90
165
  engineer_stats: Dict[str, Dict[str, Any]] = {}
@@ -100,7 +175,7 @@ class WeeklyDigestGenerator:
100
175
  category_breakdown: Dict[str, int] = {}
101
176
 
102
177
  for e in events:
103
- em = e["customer_email"].lower()
178
+ em = str(e["customer_email"] or clean_email).strip().lower()
104
179
  if em not in engineer_stats:
105
180
  engineer_stats[em] = {
106
181
  "email": em,
@@ -109,13 +184,16 @@ class WeeklyDigestGenerator:
109
184
  "usd_saved": 0.0,
110
185
  "event_count": 0
111
186
  }
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"]
187
+ saved_toks = int(e["saved_tokens"] or 0)
188
+ orig_toks = int(e["original_tokens"] or 0)
189
+ usd_val = float(e["usd_saved"] or 0.0)
190
+ engineer_stats[em]["saved_tokens"] += saved_toks
191
+ engineer_stats[em]["original_tokens"] += orig_toks
192
+ engineer_stats[em]["usd_saved"] += usd_val
115
193
  engineer_stats[em]["event_count"] += 1
116
194
 
117
- ev_type = e["event_type"]
118
- category_breakdown[ev_type] = category_breakdown.get(ev_type, 0) + e["saved_tokens"]
195
+ ev_type = str(e["event_type"] or "PROMPT")
196
+ category_breakdown[ev_type] = category_breakdown.get(ev_type, 0) + saved_toks
119
197
 
120
198
  leaderboard = sorted(
121
199
  engineer_stats.values(),
@@ -130,9 +208,9 @@ class WeeklyDigestGenerator:
130
208
  eng["usd_saved_formatted"] = f"${eng['usd_saved']:.2f}"
131
209
 
132
210
  return {
133
- "owner_email": owner_email,
134
- "tier": owner["tier"],
135
- "seats_total": owner["seats_total"],
211
+ "owner_email": clean_email,
212
+ "tier": effective_tier,
213
+ "seats_total": effective_seats,
136
214
  "active_members_count": len([e for e in leaderboard if e["event_count"] > 0]),
137
215
  "total_members_count": len(team_emails),
138
216
  "total_original_tokens": total_orig,
@@ -146,14 +224,12 @@ class WeeklyDigestGenerator:
146
224
  "start_time": seven_days_ago,
147
225
  "end_time": now
148
226
  }
149
- finally:
150
- conn.close()
151
227
 
152
228
  @classmethod
153
229
  def render_email_html(cls, digest: Dict[str, Any]) -> str:
154
230
  """Generates Apple-style responsive dark-mode HTML email."""
155
- owner_email = digest["owner_email"]
156
- total_saved_human = digest["total_saved_human"]
231
+ owner_email = _html.escape(str(digest["owner_email"]))
232
+ total_saved_human = _html.escape(str(digest["total_saved_human"]))
157
233
  usd_saved = f"${digest['total_usd_saved']:.2f}"
158
234
  reduction_pct = digest["reduction_pct"]
159
235
  leaderboard = digest["leaderboard"]
@@ -165,7 +241,7 @@ class WeeklyDigestGenerator:
165
241
  for eng in leaderboard[:10]:
166
242
  rank = eng["rank"]
167
243
  medal = "🥇 " if rank == 1 else "🥈 " if rank == 2 else "🥉 " if rank == 3 else f"#{rank} "
168
- email_mask = eng["email"].split("@")[0] + "@..."
244
+ email_mask = _html.escape(eng["email"].split("@")[0] + "@...")
169
245
  rows_html += f"""
170
246
  <tr style="border-bottom: 1px solid rgba(255, 255, 255, 0.05);">
171
247
  <td style="padding: 12px 8px; font-weight: 700; color: #10b981;">{medal}</td>