tokensafe 4.5.1 → 4.5.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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.5.1",
2
+ "version": "4.5.2",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.5.1",
3
+ "version": "4.5.2",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.5.1",
4
+ "version": "4.5.2",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "4.5.1",
4
+ "version": "4.5.2",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "logo": "assets/logo.png",
7
7
  "developerName": "TokenSafe",
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.5.1",
6
+ "version": "4.5.2",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -23,7 +23,7 @@
23
23
  "registryType": "npm",
24
24
  "registryBaseUrl": "https://registry.npmjs.org",
25
25
  "identifier": "tokensafe",
26
- "version": "4.5.1",
26
+ "version": "4.5.2",
27
27
  "runtimeHint": "npx",
28
28
  "transport": {
29
29
  "type": "stdio"
@@ -39,7 +39,7 @@
39
39
  "registryType": "pypi",
40
40
  "registryBaseUrl": "https://pypi.org",
41
41
  "identifier": "tokensafe",
42
- "version": "4.5.1",
42
+ "version": "4.5.2",
43
43
  "runtimeHint": "uvx",
44
44
  "transport": {
45
45
  "type": "stdio"
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.5.1"
45
+ "version": "4.5.2"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
package/src/metrics.py CHANGED
@@ -150,22 +150,32 @@ class MetricsTracker:
150
150
  user_ver = int(uv_row[0]) if uv_row else 0
151
151
  except Exception:
152
152
  user_ver = 0
153
- if user_ver >= 3:
153
+ if user_ver >= 4:
154
154
  _INITIALIZED_METRICS_DBS.add(self.db_path)
155
155
  return
156
156
  if user_ver >= 2:
157
157
  tbl = cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='events';").fetchone()
158
158
  if tbl is not None:
159
- cursor.execute(
160
- "UPDATE events SET measurement = 'estimated' "
161
- "WHERE measurement = 'measured' AND event_type IN "
162
- "('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME', "
163
- "'COMMAND_FILTER', 'LOOP_GUARD', 'SCOPED_SEARCH', 'DIR_LIST', "
164
- "'GUARD_SECRET', 'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
165
- "'GUARD_JUNK_READ', 'GUARD_INFINITE', 'GUARD_RAW_CODE_SEARCH');"
166
- )
159
+ if user_ver < 3:
160
+ cursor.execute(
161
+ "UPDATE events SET measurement = 'estimated' "
162
+ "WHERE measurement = 'measured' AND event_type IN "
163
+ "('GRAPH_TOPOLOGY', 'HISTORY_FOLD', 'PROMPT', 'ROLLUP_LIFETIME', "
164
+ "'COMMAND_FILTER', 'LOOP_GUARD', 'SCOPED_SEARCH', 'DIR_LIST', "
165
+ "'GUARD_SECRET', 'GUARD_DESTRUCTIVE', 'GUARD_TLS_VERIFY_BYPASS', "
166
+ "'GUARD_JUNK_READ', 'GUARD_INFINITE', 'GUARD_RAW_CODE_SEARCH');"
167
+ )
168
+ for alter_sql in (
169
+ "ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_orig_tokens INTEGER NOT NULL DEFAULT 0;",
170
+ "ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_saved_tokens INTEGER NOT NULL DEFAULT 0;",
171
+ "ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_usd REAL NOT NULL DEFAULT 0.0;",
172
+ ):
173
+ try:
174
+ cursor.execute(alter_sql)
175
+ except sqlite3.OperationalError:
176
+ pass
167
177
  try:
168
- cursor.execute("PRAGMA user_version = 3;")
178
+ cursor.execute("PRAGMA user_version = 4;")
169
179
  except sqlite3.Error:
170
180
  pass
171
181
  _INITIALIZED_METRICS_DBS.add(self.db_path)
@@ -226,9 +236,21 @@ class MetricsTracker:
226
236
  total_optimized_tokens INTEGER DEFAULT 0,
227
237
  total_saved_tokens INTEGER DEFAULT 0,
228
238
  total_usd_saved REAL DEFAULT 0.0,
229
- breakdown TEXT DEFAULT '{}'
239
+ breakdown TEXT DEFAULT '{}',
240
+ pruned_synced_orig_tokens INTEGER NOT NULL DEFAULT 0,
241
+ pruned_synced_saved_tokens INTEGER NOT NULL DEFAULT 0,
242
+ pruned_synced_usd REAL NOT NULL DEFAULT 0.0
230
243
  )
231
244
  """)
245
+ for alter_sql in (
246
+ "ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_orig_tokens INTEGER NOT NULL DEFAULT 0;",
247
+ "ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_saved_tokens INTEGER NOT NULL DEFAULT 0;",
248
+ "ALTER TABLE lifetime_aggregates ADD COLUMN pruned_synced_usd REAL NOT NULL DEFAULT 0.0;",
249
+ ):
250
+ try:
251
+ cursor.execute(alter_sql)
252
+ except sqlite3.OperationalError:
253
+ pass
232
254
  cursor.execute("""
233
255
  INSERT OR IGNORE INTO lifetime_aggregates (
234
256
  id, total_events, total_original_tokens, total_optimized_tokens,
@@ -257,7 +279,7 @@ class MetricsTracker:
257
279
  GROUP BY substr(timestamp, 1, 10)
258
280
  """, (cutoff_30,))
259
281
  try:
260
- cursor.execute("PRAGMA user_version = 3;")
282
+ cursor.execute("PRAGMA user_version = 4;")
261
283
  except sqlite3.Error:
262
284
  pass
263
285
  _INITIALIZED_METRICS_DBS.add(self.db_path)
@@ -883,6 +905,33 @@ class MetricsTracker:
883
905
  current_breakdown[ev_type]["saved"] += vals["saved"]
884
906
  current_breakdown[ev_type]["estimated_saved"] += vals["estimated_saved"]
885
907
 
908
+ # Track how much of the pruned mass was already synced individually to Cloud
909
+ last_synced_id = 0
910
+ sync_state_path = os.path.join(os.path.dirname(self.db_path), "sync_state.json")
911
+ if os.path.exists(sync_state_path):
912
+ try:
913
+ with open(sync_state_path, "r", encoding="utf-8") as sf:
914
+ sdata = json.load(sf)
915
+ if isinstance(sdata, dict):
916
+ last_synced_id = int(sdata.get("last_synced_event_id", 0) or 0)
917
+ except Exception:
918
+ last_synced_id = 0
919
+ synced_orig, synced_saved, synced_usd = 0, 0, 0.0
920
+ if last_synced_id > 0:
921
+ cursor.execute(f"""
922
+ SELECT
923
+ COALESCE(SUM(original_tokens), 0),
924
+ COALESCE(SUM(saved_tokens), 0),
925
+ COALESCE(SUM(est_usd_saved), 0.0)
926
+ FROM events
927
+ WHERE ({combined_where}) AND id <= ?
928
+ """, [*params, last_synced_id])
929
+ s_row = cursor.fetchone()
930
+ if s_row:
931
+ synced_orig = int(s_row[0] or 0)
932
+ synced_saved = int(s_row[1] or 0)
933
+ synced_usd = float(s_row[2] or 0.0)
934
+
886
935
  # 4. Update lifetime_aggregates
887
936
  cursor.execute("""
888
937
  UPDATE lifetime_aggregates SET
@@ -891,12 +940,16 @@ class MetricsTracker:
891
940
  total_optimized_tokens = total_optimized_tokens + ?,
892
941
  total_saved_tokens = total_saved_tokens + ?,
893
942
  total_usd_saved = total_usd_saved + ?,
894
- breakdown = ?
943
+ breakdown = ?,
944
+ pruned_synced_orig_tokens = COALESCE(pruned_synced_orig_tokens, 0) + ?,
945
+ pruned_synced_saved_tokens = COALESCE(pruned_synced_saved_tokens, 0) + ?,
946
+ pruned_synced_usd = COALESCE(pruned_synced_usd, 0.0) + ?
895
947
  WHERE id = 1
896
948
  """, (
897
949
  agg_row["cnt"], agg_row["orig"], agg_row["opt"],
898
950
  agg_row["saved"], agg_row["usd"],
899
- json.dumps(current_breakdown, ensure_ascii=False)
951
+ json.dumps(current_breakdown, ensure_ascii=False),
952
+ synced_orig, synced_saved, synced_usd,
900
953
  ))
901
954
 
902
955
  # 5. Delete pruned events
@@ -944,7 +997,10 @@ class MetricsTracker:
944
997
  total_optimized_tokens = 0,
945
998
  total_saved_tokens = 0,
946
999
  total_usd_saved = 0.0,
947
- breakdown = '{}'
1000
+ breakdown = '{}',
1001
+ pruned_synced_orig_tokens = 0,
1002
+ pruned_synced_saved_tokens = 0,
1003
+ pruned_synced_usd = 0.0
948
1004
  WHERE id = 1
949
1005
  """)
950
1006
  self.vacuum()
@@ -239,10 +239,17 @@ class TelemetrySync:
239
239
  total_sent = 0
240
240
  cumulative_synced = state.get("total_synced_events", 0)
241
241
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
242
+ has_rollup_watermark = "last_synced_rollup_tokens" in state
243
+ last_synced_rollup = int(state.get("last_synced_rollup_tokens", 0) or 0)
244
+ last_synced_rollup_orig = int(state.get("last_synced_rollup_orig", 0) or 0)
245
+ last_synced_rollup_usd = float(state.get("last_synced_rollup_usd", 0.0) or 0.0)
246
+ current_rollup_tokens = last_synced_rollup
247
+ current_rollup_orig = last_synced_rollup_orig
248
+ current_rollup_usd = last_synced_rollup_usd
242
249
  current_last_id = last_id
243
250
  headers = {
244
251
  "Content-Type": "application/json",
245
- "User-Agent": "TokenSafe-Sync/4.5.1"
252
+ "User-Agent": "TokenSafe-Sync/4.5.2"
246
253
  }
247
254
  if active_key:
248
255
  headers["Authorization"] = f"Bearer {active_key}"
@@ -255,7 +262,10 @@ class TelemetrySync:
255
262
  "last_quota_sync_at": state.get("last_quota_sync_at", 0),
256
263
  "consecutive_failures": int(state.get("consecutive_failures", 0) or 0) + 1,
257
264
  "total_synced_events": cumulative_synced,
258
- "lifetime_rollup_synced": rollup_synced
265
+ "lifetime_rollup_synced": rollup_synced,
266
+ "last_synced_rollup_tokens": last_synced_rollup,
267
+ "last_synced_rollup_orig": last_synced_rollup_orig,
268
+ "last_synced_rollup_usd": last_synced_rollup_usd,
259
269
  }
260
270
  cls.save_state(fail_state)
261
271
  return {
@@ -267,8 +277,6 @@ class TelemetrySync:
267
277
  page_limit = 2000
268
278
  max_pages = 25
269
279
  batch_size = min(max(1, int(batch_size or 50)), 200)
270
- last_synced_rollup = int(state.get("last_synced_rollup_tokens", 0) or 0)
271
- current_rollup_tokens = last_synced_rollup
272
280
  for page_idx in range(max_pages):
273
281
  try:
274
282
  with closing(sqlite3.connect(db_path, timeout=5.0)) as conn:
@@ -279,20 +287,37 @@ class TelemetrySync:
279
287
  if page_idx == 0:
280
288
  try:
281
289
  life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
282
- if life_row and int(life_row["total_saved_tokens"] or 0) > last_synced_rollup:
283
- current_rollup_tokens = int(life_row["total_saved_tokens"])
284
- delta_orig = max(0, int(life_row["total_original_tokens"]) - int(state.get("last_synced_rollup_orig", 0) or 0))
285
- delta_saved = current_rollup_tokens - last_synced_rollup
286
- synthetic_events.append({
287
- "event_type": "ROLLUP_LIFETIME",
288
- "original_tokens": delta_orig or int(life_row["total_original_tokens"]),
289
- "saved_tokens": delta_saved,
290
- "usd_saved": max(0.0, float(life_row["total_usd_saved"]) - float(state.get("last_synced_rollup_usd", 0.0) or 0.0)),
291
- "model": "aggregate",
292
- "timestamp": int(time.time()),
293
- # Rolled-up historical mass of mixed provenance: conservatively estimated.
294
- "measurement": "estimated"
295
- })
290
+ if life_row:
291
+ life_dict = dict(life_row)
292
+ syncable_orig = max(0, int(life_dict.get("total_original_tokens") or 0) - int(life_dict.get("pruned_synced_orig_tokens") or 0))
293
+ syncable_saved = max(0, int(life_dict.get("total_saved_tokens") or 0) - int(life_dict.get("pruned_synced_saved_tokens") or 0))
294
+ syncable_usd = max(0.0, float(life_dict.get("total_usd_saved") or 0.0) - float(life_dict.get("pruned_synced_usd") or 0.0))
295
+ # Upgrade migration from pre-watermark sync_state.json: do not re-emit already synced rollup
296
+ if rollup_synced and not has_rollup_watermark:
297
+ last_synced_rollup = syncable_saved
298
+ last_synced_rollup_orig = syncable_orig
299
+ last_synced_rollup_usd = syncable_usd
300
+ current_rollup_tokens = syncable_saved
301
+ current_rollup_orig = syncable_orig
302
+ current_rollup_usd = syncable_usd
303
+ has_rollup_watermark = True
304
+ elif syncable_saved > last_synced_rollup:
305
+ current_rollup_tokens = syncable_saved
306
+ current_rollup_orig = syncable_orig
307
+ current_rollup_usd = syncable_usd
308
+ delta_orig = max(0, syncable_orig - last_synced_rollup_orig)
309
+ delta_saved = syncable_saved - last_synced_rollup
310
+ delta_usd = max(0.0, syncable_usd - last_synced_rollup_usd)
311
+ synthetic_events.append({
312
+ "event_type": "ROLLUP_LIFETIME",
313
+ "original_tokens": delta_orig or delta_saved,
314
+ "saved_tokens": delta_saved,
315
+ "usd_saved": delta_usd,
316
+ "model": "aggregate",
317
+ "timestamp": int(time.time()),
318
+ # Rolled-up historical mass of mixed provenance: conservatively estimated.
319
+ "measurement": "estimated"
320
+ })
296
321
  except Exception:
297
322
  pass
298
323
 
@@ -441,6 +466,8 @@ class TelemetrySync:
441
466
  if ev_payload and ev_payload.get("event_type") == "ROLLUP_LIFETIME":
442
467
  rollup_synced = True
443
468
  last_synced_rollup = current_rollup_tokens
469
+ last_synced_rollup_orig = current_rollup_orig
470
+ last_synced_rollup_usd = current_rollup_usd
444
471
  cls.save_state({
445
472
  "last_synced_event_id": current_last_id,
446
473
  "last_synced_at": int(time.time()),
@@ -450,6 +477,8 @@ class TelemetrySync:
450
477
  "total_synced_events": cumulative_synced,
451
478
  "lifetime_rollup_synced": rollup_synced,
452
479
  "last_synced_rollup_tokens": last_synced_rollup,
480
+ "last_synced_rollup_orig": last_synced_rollup_orig,
481
+ "last_synced_rollup_usd": last_synced_rollup_usd,
453
482
  })
454
483
  else:
455
484
  return _record_failure(f"Server returned HTTP {resp.status}")
@@ -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.5.1"
20
+ CURRENT_VERSION = "4.5.2"
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