tokensafe 1.8.0 → 2.0.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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "1.8.0",
4
+ "version": "2.0.1",
5
5
  "description": "Autonomous Zero-Loss Token Economy & 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": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.8.0",
4
+ "version": "2.0.1",
5
5
  "description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/rules/AGENTS.md CHANGED
@@ -34,11 +34,11 @@ Execute the specified action directly based on these extracted parameters.
34
34
  6. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens).
35
35
  7. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
36
36
 
37
- ### 4. Turn Token Savings Footer (Proof-of-Savings)
37
+ ### 4. Turn Token Savings Footer (Proof-of-Savings — always in English)
38
38
  At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer:
39
- `⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens`
39
+ `⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`
40
40
  Example:
41
- `⚡ **TokenSafe Turn Savings**: +3,520 tokens (~88%) | Cumulative Total: 3.04M tokens ($4.56)`
41
+ `⚡ **TokenSafe Turn Savings**: +3,520 tokens (~88%) | Cumulative Total: 3.04M tokens (≈$4.56 approx)`
42
42
 
43
43
  ### 5. Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)
44
44
  1. **Never Hardcode Credential Fallbacks**: Never provide real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Real credentials must exist strictly in environment variables.
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
6
- "version": "1.8.0",
6
+ "version": "2.0.1",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/NekoSin4eG/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "1.8.0",
33
+ "version": "2.0.1",
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": "1.8.0",
49
+ "version": "2.0.1",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
package/src/dashboard.py CHANGED
@@ -93,7 +93,19 @@ class Dashboard:
93
93
 
94
94
  out.append(f" {BOLD}Total Tokens Saved:{RESET} {GREEN}{BOLD}{total_saved:,}{RESET} tokens")
95
95
  out.append(f" {BOLD}Efficiency Gain:{RESET} {YELLOW}{BOLD}{render_bar(pct)}{RESET}")
96
- out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}${usd:.4f} USD{RESET}")
96
+ out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}≈${usd:.4f} USD{RESET} {DIM}(derived: tokens × $1.5/M — approximation, not a bill){RESET}")
97
+
98
+ # Per-agent breakdown (honest Cumulative Total across ALL agents)
99
+ by_agent = summary.get("by_agent") or {}
100
+ if by_agent:
101
+ out.append(f"\n {BOLD}By Agent:{RESET}")
102
+ for agent, stats in by_agent.items():
103
+ out.append(
104
+ f" • {agent:<14} {stats['saved_tokens']:>12,} tok "
105
+ f"({stats['saved_tokens_measured']:,} metered / {stats['saved_tokens_estimated']:,} est.) "
106
+ f"≈${stats['est_usd_saved']:.2f}"
107
+ )
108
+ out.append("")
97
109
  out.append(f" {BOLD}Context Traffic:{RESET} {orig:,} raw ➔ {opt:,} optimized ({events_count} events)\n")
98
110
 
99
111
  # Breakdown by category
@@ -155,7 +167,7 @@ class Dashboard:
155
167
  md.append(f"| **Total Tokens Saved** | **{total_saved:,} tokens** |")
156
168
  md.append(f"| **Context Ratio** | {orig:,} raw ➔ {opt:,} optimized |")
157
169
  md.append(f"| **Net Efficiency Gain** | `{render_bar(pct)}` |")
158
- md.append(f"| **Estimated Value Saved** | **${usd:.4f} USD** |\n")
170
+ md.append(f"| **Estimated Value Saved** | **≈${usd:.4f} USD** (derived approximation) |\n")
159
171
 
160
172
  md.append("### Source Breakdown\n")
161
173
  md.append("| Pipeline Stage | Events | Tokens Saved |")
@@ -373,7 +385,7 @@ class Dashboard:
373
385
  }}
374
386
  if (data.total_usd_saved !== undefined) {{
375
387
  const el = document.getElementById('val-usd-saved');
376
- if (el) el.innerText = '$' + data.total_usd_saved.toFixed(4);
388
+ if (el) el.innerText = '≈$' + data.total_usd_saved.toFixed(4);
377
389
  }}
378
390
  if (data.total_original_tokens !== undefined && data.total_optimized_tokens !== undefined) {{
379
391
  const el = document.getElementById('val-traffic');
package/src/installer.py CHANGED
@@ -41,9 +41,9 @@ UNIFIED_TOKENSAFE_RULE = (
41
41
  "3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
42
42
  "4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
43
43
  "5. **Command Sanitization**: Use `sanitize_command` on high-output terminal commands (`git diff`, `pytest`, `find`, `grep`) to prevent lockfile or test log context contamination.\n"
44
- "6. **Proof-of-Savings Turn Footer (English default)**:\n"
44
+ "6. **Proof-of-Savings Turn Footer (always in English)**:\n"
45
45
  "At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
46
- "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens ($<usd>)`\n"
46
+ "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
47
47
  )
48
48
 
49
49
  AGENTS_REGISTRY = {
package/src/mcp_server.py CHANGED
@@ -9,6 +9,7 @@ import os
9
9
  import stat
10
10
  import time
11
11
  import json
12
+ import re
12
13
  import threading
13
14
  import traceback
14
15
  import fnmatch
@@ -38,9 +39,22 @@ from src.scoped_search import ScopedSearch
38
39
 
39
40
  SERVER_INFO = {
40
41
  "name": "tokensafe-mcp",
41
- "version": "1.8.0"
42
+ "version": "2.0.1"
42
43
  }
43
44
 
45
+ # MCP client attribution: the initialize handshake carries clientInfo, which
46
+ # lets every session-scoped metric name the REAL agent instead of a shared
47
+ # anonymous bucket (see METRICS.md by_agent).
48
+ _MCP_CLIENT_NAME = ""
49
+
50
+ def _set_mcp_client(name: str):
51
+ global _MCP_CLIENT_NAME
52
+ clean = re.sub(r"[^a-z0-9_-]", "", str(name or "").lower())[:30]
53
+ _MCP_CLIENT_NAME = clean
54
+
55
+ def _mcp_session_id() -> str:
56
+ return f"mcp:{_MCP_CLIENT_NAME}" if _MCP_CLIENT_NAME else "mcp_session"
57
+
44
58
  TOOLS = [
45
59
  {
46
60
  "name": "smart_read_file",
@@ -454,7 +468,7 @@ def handle_tool_call(name: str, args: dict) -> dict:
454
468
  if text_out:
455
469
  try:
456
470
  AgentFirewall.record_cache(
457
- session_id="mcp_session",
471
+ session_id=_mcp_session_id(),
458
472
  file_path=args.get("path", ""),
459
473
  content=text_out,
460
474
  symbol=(args.get("symbol") or "").strip(),
@@ -494,12 +508,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
494
508
  return _fallback_error("smart_read_file", f"cannot stat path: {e}")
495
509
 
496
510
  # Check Subagent Firewall dedup cache
497
- is_hit, cached_text, saved_dedup = AgentFirewall.check_cache("mcp_session", path, symbol=symbol or "", tracker=tracker)
511
+ is_hit, cached_text, saved_dedup = AgentFirewall.check_cache(_mcp_session_id(), path, symbol=symbol or "", tracker=tracker)
498
512
  if is_hit and cached_text:
499
513
  return {"content": [{"type": "text", "text": cached_text}]}
500
514
 
501
515
  # Check loop detector
502
- is_loop, repeats, msg = LoopDetector.check_loop("mcp_session", "smart_read_file", args)
516
+ is_loop, repeats, msg = LoopDetector.check_loop(_mcp_session_id(), "smart_read_file", args)
503
517
  if is_loop:
504
518
  return {"isError": True, "content": [{"type": "text", "text": f"⚠️ {msg}"}]}
505
519
 
@@ -525,7 +539,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
525
539
  orig_t = count_tokens(raw_code)
526
540
  skel_t = count_tokens(team_skel)
527
541
  tracker.record_event(
528
- session_id="mcp_session",
542
+ session_id=_mcp_session_id(),
529
543
  event_type="TEAM_CACHE_HIT",
530
544
  original_tokens=orig_t,
531
545
  optimized_tokens=skel_t,
@@ -545,7 +559,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
545
559
  skel_t = count_tokens(graph_skel)
546
560
  saved = max(0, orig_t - skel_t)
547
561
  tracker.record_event(
548
- session_id="mcp_session",
562
+ session_id=_mcp_session_id(),
549
563
  event_type="GRAPH_SKELETON",
550
564
  original_tokens=orig_t,
551
565
  optimized_tokens=skel_t,
@@ -588,7 +602,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
588
602
  elif name == "context_budget":
589
603
  model = str(args.get("model") or "")
590
604
  window_tokens = args.get("window_tokens")
591
- session_id = str(args.get("session_id") or "mcp_session")
605
+ session_id = str(args.get("session_id") or _mcp_session_id())
592
606
  try:
593
607
  if window_tokens is not None:
594
608
  window_tokens = int(window_tokens)
@@ -613,7 +627,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
613
627
  }, indent=2)}]}
614
628
  saved = max(0, orig_t - folded_t)
615
629
  tracker.record_event(
616
- session_id="mcp_session",
630
+ session_id=_mcp_session_id(),
617
631
  event_type="HISTORY_FOLD",
618
632
  original_tokens=orig_t,
619
633
  optimized_tokens=folded_t,
@@ -635,7 +649,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
635
649
  guard_res = TokenSafeGuard.inspect_command(cmd)
636
650
  if guard_res.blocked:
637
651
  tracker.record_event(
638
- session_id="mcp_session",
652
+ session_id=_mcp_session_id(),
639
653
  event_type=f"GUARD_{guard_res.check_name}",
640
654
  original_tokens=count_tokens(cmd),
641
655
  optimized_tokens=0,
@@ -683,7 +697,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
683
697
  })
684
698
  if c_res.blocked:
685
699
  tracker.record_event(
686
- session_id="mcp_session",
700
+ session_id=_mcp_session_id(),
687
701
  event_type=f"GUARD_{c_res.check_name}",
688
702
  original_tokens=count_tokens(cmd),
689
703
  optimized_tokens=0,
@@ -703,7 +717,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
703
717
  })
704
718
  if w_res.blocked:
705
719
  tracker.record_event(
706
- session_id="mcp_session",
720
+ session_id=_mcp_session_id(),
707
721
  event_type=f"GUARD_{w_res.check_name}",
708
722
  original_tokens=count_tokens(code),
709
723
  optimized_tokens=0,
@@ -731,7 +745,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
731
745
  saved = max(0, orig_t - opt_t)
732
746
  if saved > 0:
733
747
  tracker.record_event(
734
- session_id="mcp_session",
748
+ session_id=_mcp_session_id(),
735
749
  event_type="DIFF_SLICER",
736
750
  original_tokens=orig_t,
737
751
  optimized_tokens=opt_t,
@@ -765,7 +779,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
765
779
  est_crawl_tokens = min(50000, max(5000, capped_files * 600))
766
780
  topo_tokens = 250
767
781
  tracker.record_event(
768
- session_id="mcp_session",
782
+ session_id=_mcp_session_id(),
769
783
  event_type="GRAPH_TOPOLOGY",
770
784
  original_tokens=est_crawl_tokens,
771
785
  optimized_tokens=topo_tokens,
@@ -787,7 +801,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
787
801
  capped_files = min(100, len(graph.file_symbols))
788
802
  est_orig_tokens = min(60000, max(10000, capped_files * 600))
789
803
  tracker.record_event(
790
- session_id="mcp_session",
804
+ session_id=_mcp_session_id(),
791
805
  event_type="GRAPH_TOPOLOGY",
792
806
  original_tokens=est_orig_tokens,
793
807
  optimized_tokens=surface_tokens,
@@ -814,7 +828,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
814
828
  # Estimate equivalent tokens from multiple verbose ls -la calls (at least ~800 tokens)
815
829
  est_orig_tokens = max(800, tree_tokens * 6)
816
830
  tracker.record_event(
817
- session_id="mcp_session",
831
+ session_id=_mcp_session_id(),
818
832
  event_type="DIR_LIST",
819
833
  original_tokens=est_orig_tokens,
820
834
  optimized_tokens=tree_tokens,
@@ -858,7 +872,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
858
872
  res_tokens = count_tokens(md_text)
859
873
  est_orig = max(1500, res_tokens * 8)
860
874
  tracker.record_event(
861
- session_id="mcp_session",
875
+ session_id=_mcp_session_id(),
862
876
  event_type="SCOPED_SEARCH",
863
877
  original_tokens=est_orig,
864
878
  optimized_tokens=res_tokens,
@@ -940,6 +954,11 @@ def run_mcp_server():
940
954
  response = {"jsonrpc": "2.0", "id": msg_id}
941
955
 
942
956
  if method == "initialize":
957
+ try:
958
+ client_info = (params or {}).get("clientInfo") or {}
959
+ _set_mcp_client(str(client_info.get("name") or ""))
960
+ except Exception:
961
+ pass
943
962
  try:
944
963
  from src.telemetry_sync import TelemetrySync
945
964
  TelemetrySync.sync_background()
package/src/metrics.py CHANGED
@@ -247,6 +247,61 @@ class MetricsTracker:
247
247
  "measurement": measurement_label
248
248
  }
249
249
 
250
+ @staticmethod
251
+ def _infer_agent(session_id: str, details: Dict[str, Any]) -> str:
252
+ """Best-effort attribution of an event to the agent that produced it.
253
+ Explicit details.agent (new adapters) wins; session_id prefixes cover
254
+ the historic naming conventions."""
255
+ explicit = details.get("agent")
256
+ if explicit:
257
+ return str(explicit)
258
+ sid = session_id or ""
259
+ if sid == "mcp_session":
260
+ return "mcp"
261
+ if sid == "proxy_session":
262
+ return "proxy"
263
+ if sid.startswith("hook_"):
264
+ return sid[len("hook_"):] or "hook"
265
+ if sid.startswith("mcp:"):
266
+ return sid[4:] or "mcp"
267
+ return "antigravity"
268
+
269
+ def get_by_agent(self) -> Dict[str, Dict[str, Any]]:
270
+ """Per-agent savings breakdown for the honest Cumulative Total:
271
+ aggregates events by the agent that produced them, with the
272
+ measured/estimated split (see METRICS.md)."""
273
+ by_agent: Dict[str, Dict[str, Any]] = {}
274
+ try:
275
+ with self._get_connection() as conn:
276
+ cursor = conn.cursor()
277
+ cursor.execute("""
278
+ SELECT session_id, saved_tokens, est_usd_saved, measurement, details
279
+ FROM events
280
+ """)
281
+ for row in cursor.fetchall():
282
+ try:
283
+ details = json.loads(row["details"] or "{}")
284
+ if not isinstance(details, dict):
285
+ details = {}
286
+ except Exception:
287
+ details = {}
288
+ agent = self._infer_agent(row["session_id"], details)
289
+ bucket = by_agent.setdefault(agent, {
290
+ "events": 0, "saved_tokens": 0, "saved_tokens_measured": 0,
291
+ "saved_tokens_estimated": 0, "est_usd_saved": 0.0,
292
+ })
293
+ saved = int(row["saved_tokens"] or 0)
294
+ measurement = row["measurement"] or "measured"
295
+ bucket["events"] += 1
296
+ bucket["saved_tokens"] += saved
297
+ bucket["saved_tokens_measured"] += saved if measurement == "measured" else 0
298
+ bucket["saved_tokens_estimated"] += saved if measurement == "estimated" else 0
299
+ bucket["est_usd_saved"] = round(bucket["est_usd_saved"] + float(row["est_usd_saved"] or 0.0), 4)
300
+ except Exception:
301
+ pass
302
+ # Largest contributor first
303
+ return dict(sorted(by_agent.items(), key=lambda kv: kv[1]["saved_tokens"], reverse=True))
304
+
250
305
  def get_summary(self) -> Dict[str, Any]:
251
306
  """Returns cumulative statistics across all sessions, including lifetime rollups."""
252
307
  with self._get_connection() as conn:
@@ -324,6 +379,8 @@ class MetricsTracker:
324
379
  "total_saved_tokens_estimated": saved_estimated,
325
380
  "overall_reduction_pct": round(overall_reduction, 1),
326
381
  "total_usd_saved": round(total_usd, 4),
382
+ "total_usd_saved_approx": True, # USD is a derived estimate (~$1.5/M blended), never a bill
383
+ "by_agent": self.get_by_agent(),
327
384
  "breakdown": combined_breakdown
328
385
  }
329
386
 
@@ -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/1.8.0"
267
+ "User-Agent": "TokenSafe-Sync/2.0.1"
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 = "1.8.0"
19
+ CURRENT_VERSION = "2.0.1"
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
@@ -331,15 +331,44 @@ class VersionChecker:
331
331
  if not force and last_notified_ver == latest and (now - last_notified_at) < CACHE_TTL:
332
332
  return False
333
333
 
334
- cached["last_os_notify_version"] = latest
335
- cached["last_os_notify_at"] = now
336
- cls.save_cache(cached)
334
+ # Cross-process claim: several agent hook processes can pass the 24h
335
+ # cache check simultaneously (Antigravity + ZCode + adapters), which
336
+ # rendered the update dialog TWICE. Only the process that wins the
337
+ # O_EXCL claim shows the dialog; the claim self-expires.
338
+ claim_path = os.path.join(DATA_DIR, ".update_dialog.claim")
339
+ try:
340
+ if os.path.exists(claim_path):
341
+ if (now - os.path.getmtime(claim_path)) < 60:
342
+ return False
343
+ os.remove(claim_path) # stale claim: safe to reclaim (O_EXCL guards the race)
344
+ fd = os.open(claim_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
345
+ os.write(fd, str(os.getpid()).encode("utf-8"))
346
+ os.close(fd)
347
+ except FileExistsError:
348
+ return False
349
+ except OSError:
350
+ pass # claim is best-effort; never block the dialog entirely on fs errors
351
+
352
+ try:
353
+ cached["last_os_notify_version"] = latest
354
+ cached["last_os_notify_at"] = now
355
+ cls.save_cache(cached)
356
+ except Exception:
357
+ pass
337
358
 
338
- return cls.show_os_dialog(
339
- current_version=current_version,
340
- latest_version=latest,
341
- update_command=cmd
342
- )
359
+ try:
360
+ dispatched = cls.show_os_dialog(
361
+ current_version=current_version,
362
+ latest_version=latest,
363
+ update_command=cmd
364
+ )
365
+ return dispatched
366
+ finally:
367
+ # Release the dialog claim so a future version can notify again.
368
+ try:
369
+ os.remove(claim_path)
370
+ except OSError:
371
+ pass
343
372
 
344
373
  @classmethod
345
374
  def notify_os_update_background(