tokensafe 3.1.5 → 3.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/README.md CHANGED
@@ -6,9 +6,9 @@
6
6
  <!-- mcp-name: dev.tokensafe/tokensafe -->
7
7
 
8
8
  <p align="center">
9
- <b>Local-First Context Control, Prompt Caching &amp; Secret Guardrails for Coding Agents</b><br>
10
- Reduce your AI bills by up to 99%. Let your team ship clean code faster and cheaper.<br>
11
- Your coding agents read only the code each task needs and keep prompt caches intact across turns. Everything runs locally on your machine, so your team fixes fewer broken edits and keeps secrets out of git.<br>
9
+ <b>Make AI coding agents 3x faster without burning team quotas.</b><br>
10
+ Exact code context. Fewer tokens. Safer changes.<br>
11
+ TokenSafe intercepts AI tool calls locally, replacing thousands of lines of irrelevant code with precise function bodies and typed signatures. Preserve prompt caches and protect secrets before they reach your AI transcripts.<br>
12
12
  Works with <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Gemini CLI, and ChatGPT</b>.
13
13
  </p>
14
14
 
@@ -159,33 +159,24 @@ When an operation is blocked, the agent sees an explicit, constructive message:
159
159
  Leave the default empty or read from os.environ at runtime.
160
160
  ```
161
161
 
162
- ## What TokenSafe Does
162
+ ## 10 Core Engine Capabilities
163
163
 
164
- **Clean context, better code**
164
+ Why TokenSafe agents ship working code on the first pass without burning quotas or leaking keys:
165
165
 
166
- - `tokensafe:smart_read_file` returns the target function plus its 1-hop dependencies instead of the whole file. 11 languages (Python, TypeScript/JavaScript, Go, Rust, Java, C#, C/C++, PHP, Kotlin, Ruby, Swift), with CSS design tokens preserved so agents never invent colors or font rules.
167
- - `tokensafe:smart_bundle` reads 3–8 related symbols across files as one merged bundle — shared imports deduplicated, 1-hop signatures unified, a single roundtrip instead of chained reads.
168
- - OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced: pass a spec path, model, type, or table as `symbol` and get that entry plus its 1-hop references — a 5,000-line migration drops from ~30k tokens to a few hundred.
169
- - `tokensafe:graph` maps architectural hotspots and dependency topology in under 250 tokens instead of a full repository crawl — and teams share the result: the indexed graph and API surface are cached per repo state in the Team Symbol Index, so the 19 developers after the first one skip the crawl entirely.
170
- - The command sanitizer strips lockfile noise and stack dumps down to the failing assertion, caps `git status`/`git diff` floods and docker build tails, and forces JS test runners into run-once mode so background tests never hang. Malformed JSON tool arguments from small local models are repaired in-flight instead of failing the call.
171
- - The loop guard halts agents stuck repeating the same broken edit.
172
-
173
- **Local-first guardrails**
174
-
175
- - Blocks live provider secrets, hardcoded fallback credentials, and raw private keys before they reach disk or git.
176
- - Blocks TLS bypasses (`verify=False`, `rejectUnauthorized: false`), interpolated SQL, and CORS wildcards with credentials.
177
- - Blocks `.env` and key files from staging, including blanket `git add .` when sensitive files exist in the working tree.
178
- - Blocks destructive deletes and exfiltration pipes (`curl -d @.env https://...`), and warns on known typosquat packages.
179
-
180
- **Auditable team ROI**
181
-
182
- - The Context Budget HUD shows live window usage with a breakdown (tools / history / prompts) before quality drops.
183
- - The shared L3 team cache gives teammates and CI runners warm 0ms hits on repeated reads and prompts.
184
- - Managed cloud distillation compacts prompts with zero API keys for developers.
185
- - The dashboard's live savings strip streams anonymized per-machine savings (tokens and USD) over SSE — you see what the team saves right now, not at the end of the week.
186
- - The Friday per-seat ROI digest reports each engineer's savings with the `measured` / `estimated` split; inactive seats show `—`, never guessed figures.
187
-
188
- Deeper mechanics (language matrix, context tax math, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
166
+ | Capability | What it solves | How it works | Impact |
167
+ |---|---|---|---|
168
+ | **1. Architecture Graph**<br>`get_architecture_graph` | Agents open an unfamiliar repo and burn 45k tokens blindly crawling files. | Analyzes dependency centrality, import hubs, and critical call paths in memory. | **< 250 tokens** to map God Nodes (vs ~45k blind crawl) |
169
+ | **2. Smart Code Slicing**<br>`smart_read_file` | Feeding 3,000 lines into context causes models to hallucinate fake methods. | Preserves target method logic while folding uncalled helpers into typed contracts. | **-95.0% tokens** (192 vs 3,840) across 11 languages |
170
+ | **3. Pre-Git Security Guard**<br>`guard_inspect` | Autonomous agents read `.env` secrets or hardcode fallback keys in edits. | Sub-millisecond pre-flight interception blocks secrets, TLS bypasses, and dangerous commands. | **0 leaked keys** in LLM logs or git history |
171
+ | **4. Lockfile & Noise Shield**<br>`schema_slicer` | Reading `package-lock.json` or `uv.lock` dumps 360k+ tokens in one turn. | Intercepts lockfiles and massive schemas, returning a queryable dependency summary. | **-99.8% tokens** (855 vs 367,410 tokens) |
172
+ | **5. Monorepo API Surface Map**<br>`get_api_surface` | Agents guess interfaces or crawl dozens of modules to find exported types. | Extracts all exported types, interfaces, and contracts across the repo in one pass. | **1 tool call** vs 50 separate file reads |
173
+ | **6. Subagent Pointer Cache**<br>`SUBAGENT_DEDUP` | Multi-turn chats and swarms pay full price to re-read the same shared utilities. | In-memory content hashes return 1-line pointer hits for unchanged files. | **0 tokens wasted** on repeat file reads |
174
+ | **7. Shared Team Cache**<br>`team_cache` | 10 to 50 engineers repeatedly parse the same core libraries from scratch. | L3 monorepo pool shares stripped signatures and package contracts across teammates. | **72% team hits** with 0ms turnaround |
175
+ | **8. KV-Cache Prefix Locking**<br>`cache_normalizer` | Shifting timestamps and reordered tools break provider prompt cache hits. | Locks prefix order, sorts schemas, and injects breakpoints for Anthropic, DeepSeek, and OpenAI. | **92% cache hit rate** at 0.10x provider rates |
176
+ | **9. Compact Test Runner**<br>`sanitize_command` | Test suites spew 1,000 lines of passing dots that crowd out instructions. | Forces run-once mode (`CI=true`) and collapses passing runs to a single line. | **1 line vs 1,200 lines** (traces kept on failure) |
177
+ | **10. Context Governor & Ledger**<br>`compact_conversation` | Models suffer needle-in-a-haystack amnesia after 70% context saturation. | Monitors context thresholds and compacts chat sprawl into an actionable State Ledger. | **50+ turns** without regression or amnesia |
178
+
179
+ Deeper mechanics (language matrix, AST syntax trees, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
189
180
 
190
181
  ## Benchmarks
191
182
 
@@ -275,8 +266,6 @@ tokensafe bench --real --here # your current repository
275
266
 
276
267
  ## Metrics Honesty
277
268
 
278
- ## Metrics Honesty
279
-
280
269
  TokenSafe labels every savings event as one of:
281
270
 
282
271
  - **`measured`**: the model literally received fewer bytes than the tool produced (sliced file reads, filtered command output, AST skeletons).
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "3.1.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.",
4
+ "version": "3.2.0",
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": {
8
8
  "tokensafe": "bin/tokensafe.js"
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "3.1.5",
4
+ "version": "3.2.0",
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": "3.1.5",
6
+ "version": "3.2.0",
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": "3.1.5",
33
+ "version": "3.2.0",
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": "3.1.5",
49
+ "version": "3.2.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
package/src/cli.py CHANGED
@@ -10,6 +10,7 @@ Used by:
10
10
  import sys
11
11
  import os
12
12
  import subprocess
13
+ from typing import Optional, List, Dict, Any
13
14
 
14
15
  SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
15
16
  PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
@@ -113,13 +114,15 @@ def _print_help():
113
114
  print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
114
115
  print(" check-update Check for a newer published version")
115
116
  print(" activate / license License activation and status")
117
+ print(" login / auth Authorize this device via browser login")
118
+ print(" logout / unlink Unlink this device and remove local license")
116
119
  print(" sync Sync telemetry with the cloud backend")
117
120
  print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
118
121
  print(" --version Print version and exit")
119
122
 
120
123
 
121
- def main():
122
- args = sys.argv[1:]
124
+ def main(argv: Optional[List[str]] = None):
125
+ args = sys.argv[1:] if argv is None else list(argv)
123
126
  command = args[0] if args else "stats"
124
127
 
125
128
  if command in ("--help", "-h", "help"):
@@ -515,6 +518,192 @@ def main():
515
518
  res = graph.graph_guided_skeletonize(file_path, target_symbol)
516
519
  print(res)
517
520
 
521
+ elif command in ("login", "auth", "connect"):
522
+ from src.license_manager import LicenseManager
523
+ import json
524
+ import time
525
+ import urllib.request
526
+ import webbrowser
527
+ import platform
528
+
529
+ cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
530
+ active_tier, active_lic = LicenseManager.get_active_license()
531
+ active_email = active_lic.get("email", "")
532
+
533
+ print("\n\033[1m\033[36m╔════════════════════════════════════════════════════════════════════╗\033[0m")
534
+ print("\033[1m\033[36m║ ⚡ TOKENSAFE ACCOUNT AUTHORIZATION ⚡ ║\033[0m")
535
+ print("\033[1m\033[36m╚════════════════════════════════════════════════════════════════════╝\033[0m\n")
536
+
537
+ if active_email and active_email != "community@tokensafe.dev":
538
+ print(f" Currently logged in as: \033[32m{active_email}\033[0m (Tier: {active_tier.upper()})")
539
+ if sys.stdin.isatty():
540
+ ans = input(" Do you want to re-authenticate or switch accounts? [y/N]: ").strip().lower()
541
+ if ans not in ("y", "yes"):
542
+ print(" Keeping current authorization.\n")
543
+ sys.exit(0)
544
+
545
+ # 1. Request device code
546
+ machine_fp = LicenseManager.get_machine_fingerprint()
547
+ payload = {
548
+ "machine_fp": machine_fp,
549
+ "platform": platform.system()[:32],
550
+ "arch": platform.machine()[:32],
551
+ "agent": str(LicenseManager.detect_agent())[:32],
552
+ "version": "",
553
+ "hostname": platform.node()[:64]
554
+ }
555
+ try:
556
+ req = urllib.request.Request(
557
+ f"{cloud_url}/api/auth/device/code",
558
+ data=json.dumps(payload).encode("utf-8"),
559
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Login"},
560
+ method="POST"
561
+ )
562
+ with urllib.request.urlopen(req, timeout=5.0) as resp:
563
+ init_data = json.loads(resp.read().decode("utf-8") or "{}")
564
+ except Exception as exc:
565
+ print(f"\033[31m✖ Could not connect to {cloud_url}: {exc}\033[0m")
566
+ print(" Check your internet connection and try again.\n")
567
+ sys.exit(1)
568
+
569
+ if not init_data.get("success"):
570
+ print(f"\033[31m✖ Authorization initiation failed: {init_data.get('error')}\033[0m\n")
571
+ sys.exit(1)
572
+
573
+ user_code = init_data["user_code"]
574
+ device_code = init_data["device_code"]
575
+ verif_url = init_data.get("verification_uri_complete") or f"{init_data['verification_uri']}?code={user_code}"
576
+ interval = init_data.get("interval", 3)
577
+
578
+ print(" To authorize this device and connect your account:")
579
+ print(f" 1. Confirm code: \033[1m\033[33m{user_code}\033[0m")
580
+ print(f" 2. In browser at: \033[36m{verif_url}\033[0m\n")
581
+
582
+ # Attempt to open browser automatically
583
+ try:
584
+ webbrowser.open(verif_url)
585
+ print(" \033[2m(Opened verification page in your default browser)\033[0m")
586
+ except Exception:
587
+ pass
588
+
589
+ print(" Waiting for authorization in browser (Ctrl+C to abort)...", end="", flush=True)
590
+
591
+ # 2. Polling loop
592
+ spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
593
+ spin_idx = 0
594
+ approved_data = None
595
+
596
+ try:
597
+ start_time = time.time()
598
+ while time.time() - start_time < 600:
599
+ time.sleep(interval)
600
+ spin_char = spinner[spin_idx % len(spinner)]
601
+ spin_idx += 1
602
+ print(f"\r {spin_char} Waiting for authorization in browser (Ctrl+C to abort)...", end="", flush=True)
603
+
604
+ try:
605
+ poll_req = urllib.request.Request(
606
+ f"{cloud_url}/api/auth/device/poll",
607
+ data=json.dumps({"device_code": device_code}).encode("utf-8"),
608
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Login"},
609
+ method="POST"
610
+ )
611
+ with urllib.request.urlopen(poll_req, timeout=4.0) as resp:
612
+ poll_data = json.loads(resp.read().decode("utf-8") or "{}")
613
+ except Exception:
614
+ continue
615
+
616
+ status = poll_data.get("status")
617
+ if status == "approved":
618
+ approved_data = poll_data
619
+ break
620
+ elif status == "quota_exhausted":
621
+ print(f"\n\n\033[31m✖ {poll_data.get('error')}\033[0m\n")
622
+ sys.exit(1)
623
+ elif status in ("expired", "denied"):
624
+ print(f"\n\n\033[31m✖ Authorization {status}.\033[0m\n")
625
+ sys.exit(1)
626
+
627
+ except KeyboardInterrupt:
628
+ print("\n\n\033[33m Authorization cancelled by user.\033[0m")
629
+ print(" Run 'tokensafe login' whenever you are ready.\n")
630
+ sys.exit(130)
631
+
632
+ if not approved_data:
633
+ print("\n\n\033[31m✖ Authorization timed out. Please try again.\033[0m\n")
634
+ sys.exit(1)
635
+
636
+ # 3. Save license and device token
637
+ lic_key = approved_data.get("license_key", "")
638
+ dev_tok = approved_data.get("device_token", "")
639
+ auth_email = approved_data.get("email", "")
640
+
641
+ ok, msg = LicenseManager.save_license(lic_key, device_token=dev_tok)
642
+ if ok:
643
+ valid, lic_meta, _ = LicenseManager.validate_license(lic_key)
644
+ detected_tier = (lic_meta.get("tier") or approved_data.get("tier") or "free").lower()
645
+ org_id = lic_meta.get("org")
646
+
647
+ print(f"\r\033[K \033[32m\033[1m✔ Successfully authenticated as {auth_email}!\033[0m")
648
+ if detected_tier == "solo":
649
+ print(" \033[32m✔ Solo Pro license activated (Unlimited tokens).\033[0m")
650
+ elif detected_tier in ("team", "enterprise"):
651
+ org_msg = f" [{org_id}]" if org_id else ""
652
+ print(f" \033[32m✔ Team license activated (Unlimited tokens, organization workspace{org_msg}).\033[0m")
653
+ else:
654
+ print(" \033[32m✔ Community Edition license activated (500,000 free tokens/month).\033[0m")
655
+ print(f" \033[36m✔ Web dashboard unlocked at: https://tokensafe.dev/dashboard\033[0m\n")
656
+
657
+ # Sync local token metrics
658
+ try:
659
+ from src.telemetry_sync import TelemetrySync
660
+ sync_res = TelemetrySync.sync(license_key=lic_key, timeout=3.0)
661
+ if sync_res.get("success") and sync_res.get("synced_events", 0) > 0:
662
+ print(f" \033[36m✔ Synced {sync_res['synced_events']:,} optimization events to your cloud dashboard.\033[0m\n")
663
+ except Exception:
664
+ pass
665
+ else:
666
+ print(f"\n\033[31m✖ Failed to save license: {msg}\033[0m\n")
667
+ sys.exit(1)
668
+
669
+ elif command in ("logout", "unlink", "disconnect"):
670
+ from src.license_manager import LicenseManager, LICENSE_FILE, GLOBAL_LICENSE_FILE
671
+ import json
672
+ import urllib.request
673
+
674
+ cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
675
+ machine_fp = LicenseManager.get_machine_fingerprint()
676
+ _, active_lic = LicenseManager.get_active_license()
677
+ active_email = active_lic.get("email", "")
678
+
679
+ # 1. Unlink on server to free up device slot
680
+ if active_email and machine_fp and active_email != "community@tokensafe.dev":
681
+ try:
682
+ req = urllib.request.Request(
683
+ f"{cloud_url}/api/auth/device/unlink",
684
+ data=json.dumps({"email": active_email, "machine_fp": machine_fp}).encode("utf-8"),
685
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Logout"},
686
+ method="POST"
687
+ )
688
+ with urllib.request.urlopen(req, timeout=4.0):
689
+ pass
690
+ except Exception:
691
+ pass
692
+
693
+ # 2. Remove local license files
694
+ for p in (LICENSE_FILE, GLOBAL_LICENSE_FILE):
695
+ try:
696
+ if os.path.exists(p):
697
+ os.remove(p)
698
+ except Exception:
699
+ pass
700
+
701
+ print("\n\033[32m✔ Successfully unlinked this device and logged out.\033[0m")
702
+ if active_email and active_email != "community@tokensafe.dev":
703
+ print(f" Disconnected account: {active_email}")
704
+ print(" Your device slot has been freed.")
705
+ print(" Run \033[36mtokensafe login\033[0m anytime to connect again.\n")
706
+
518
707
  elif command == "activate":
519
708
  from src.license_manager import LicenseManager
520
709
  if len(args) < 2:
package/src/compactor.py CHANGED
@@ -267,7 +267,7 @@ class PromptCompactor:
267
267
  )
268
268
  FILE_REGEX = re.compile(
269
269
  r'(?:'
270
- r'(?:[\w\-\./\\@+()()][\w\-\./\\@+()() ]*[\/\\])?[\w\-\.+()()]+\.(?:' + "|".join(_FILE_EXTS) + r')\b'
270
+ r'(?:[\w\-\./\\@+()()][\w\-\./\\@+()() ]*[\/\\])?[\w\-\.+()()@]+\.(?:' + "|".join(_FILE_EXTS) + r')\b'
271
271
  r'|(?:\.env(?:\.[\w\-]+)?|\.gitignore|\.dockerignore|\.prettierrc[\w\.\-]*|\.eslintrc[\w\.\-]*|\.npmignore|\.npmrc|\.yarnrc)'
272
272
  r'|\b(?:Dockerfile(?:\.[\w\-]+)?|Makefile|Procfile|Gemfile|Vagrantfile|Containerfile)\b'
273
273
  r'|\b(?:README(?:\.md)?|LICENSE|CHANGELOG(?:\.md)?)\b'
package/src/installer.py CHANGED
@@ -550,7 +550,7 @@ WantedBy=default.target
550
550
  try:
551
551
  if not (sys.stdin.isatty() and sys.stdout.isatty()):
552
552
  return
553
- if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes"):
553
+ if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes") or "unittest" in sys.modules:
554
554
  return
555
555
  st = cls.proxy_status()
556
556
  if st.get("claude_code_wired"):
@@ -574,6 +574,50 @@ WantedBy=default.target
574
574
  except Exception:
575
575
  return # fail-open: a prompt problem never breaks install/update
576
576
 
577
+ @classmethod
578
+ def maybe_prompt_account_login(cls, context: str = "install") -> None:
579
+ """
580
+ Interactive prompt to connect TokenSafe account and unlock web dashboard.
581
+ Migrates anonymous community@tokensafe.dev licenses to verified user accounts.
582
+ Fail-open: skips quietly on non-interactive environments (CI, scripts).
583
+ """
584
+ try:
585
+ from src.license_manager import LicenseManager
586
+ _, lic = LicenseManager.get_active_license()
587
+ email = lic.get("email", "")
588
+
589
+ # If user already has a real personal account (not the legacy anonymous key), nothing to prompt
590
+ if email and email != "community@tokensafe.dev":
591
+ return
592
+
593
+ is_anonymous = (email == "community@tokensafe.dev")
594
+
595
+ if not (sys.stdin.isatty() and sys.stdout.isatty()):
596
+ print(f" {CYAN}ℹ{RESET} Run {BOLD}tokensafe login{RESET} anytime to activate your Community license & web dashboard.\n")
597
+ return
598
+
599
+ if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes") or "unittest" in sys.modules:
600
+ return
601
+
602
+ if context == "update" and is_anonymous:
603
+ print(f"\n {YELLOW}→ Anonymous Community license detected (migrating to verified personal account).{RESET}")
604
+ print(f" Connect your free account at {CYAN}https://tokensafe.dev{RESET} to unlock your web dashboard.")
605
+ else:
606
+ print(f"\n {CYAN}→ Connect your free TokenSafe account (500,000 tokens/mo) to unlock your web dashboard:{RESET}")
607
+
608
+ print(f" Open browser to authorize? [{GREEN}Y{RESET}/n] ", end="", flush=True)
609
+ answer = input().strip().lower()
610
+ if answer in ("", "y", "yes"):
611
+ from src.cli import main as cli_main
612
+ cli_main(["login"])
613
+ else:
614
+ print(f" {CYAN}ℹ{RESET} You can run {BOLD}tokensafe login{RESET} anytime to activate your account.\n")
615
+ except (EOFError, KeyboardInterrupt):
616
+ print()
617
+ return
618
+ except Exception:
619
+ return
620
+
577
621
  @classmethod
578
622
  def install_mcp_config(cls, agent_key: str) -> Tuple[bool, str]:
579
623
  """Injects TokenSafe MCP config into target agent."""
@@ -1073,6 +1117,7 @@ WantedBy=default.target
1073
1117
 
1074
1118
  print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
1075
1119
  print(" Restart your IDE / Agent to start saving tokens automatically.\n")
1120
+ cls.maybe_prompt_account_login(context="install")
1076
1121
  cls.maybe_prompt_proxy_enable(context="install")
1077
1122
 
1078
1123
  @staticmethod
@@ -1419,6 +1464,7 @@ WantedBy=default.target
1419
1464
  print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
1420
1465
  print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
1421
1466
  print(f" {CYAN}ℹ{RESET} If your terminal still shows the old version, open a new window or run {BOLD}hash -r{RESET}.")
1467
+ cls.maybe_prompt_account_login(context="update")
1422
1468
  cls.maybe_prompt_proxy_enable(context="update")
1423
1469
 
1424
1470
  def main():
@@ -91,9 +91,58 @@ class LicenseManager:
91
91
 
92
92
  @classmethod
93
93
  def get_machine_fingerprint(cls) -> str:
94
- """One-way anonymized machine identifier for server-side free-tier quota continuity."""
95
- raw = f"ts:{platform.system()}:{platform.node()}:{uuid.getnode()}:{os.path.expanduser('~')}"
96
- return hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
94
+ """
95
+ One-way anonymized machine identifier for server-side quota continuity.
96
+ Uses persistent ~/.tokensafe/data/.machine_id backed by hardware UUID
97
+ (IOPlatformUUID on macOS / /etc/machine-id on Linux) to prevent Wi-Fi/DHCP drift.
98
+ """
99
+ try:
100
+ data_dir = resolve_data_dir()
101
+ mid_file = os.path.join(data_dir, ".machine_id")
102
+ if os.path.exists(mid_file):
103
+ with open(mid_file, "r", encoding="utf-8") as f:
104
+ content = f.read().strip().lower()
105
+ if re.fullmatch(r"[0-9a-f]{32}", content):
106
+ return content
107
+ except Exception:
108
+ pass
109
+
110
+ hw_uuid = ""
111
+ try:
112
+ if platform.system() == "Darwin":
113
+ import subprocess
114
+ cmd = ["ioreg", "-rd1", "-c", "IOPlatformExpertDevice"]
115
+ res = subprocess.run(cmd, capture_output=True, text=True, timeout=2)
116
+ if res.returncode == 0:
117
+ for line in res.stdout.splitlines():
118
+ if "IOPlatformUUID" in line:
119
+ parts = line.split("=")
120
+ if len(parts) > 1:
121
+ hw_uuid = parts[1].strip().strip('"')
122
+ break
123
+ elif platform.system() == "Linux":
124
+ for p in ("/etc/machine-id", "/var/lib/dbus/machine-id"):
125
+ if os.path.exists(p):
126
+ with open(p, "r", encoding="utf-8") as f:
127
+ hw_uuid = f.read().strip()
128
+ if hw_uuid:
129
+ break
130
+ except Exception:
131
+ hw_uuid = ""
132
+
133
+ raw = f"ts:{platform.system()}:{hw_uuid or uuid.getnode()}"
134
+ fp = hashlib.sha256(raw.encode("utf-8")).hexdigest()[:32]
135
+
136
+ try:
137
+ data_dir = resolve_data_dir()
138
+ os.makedirs(data_dir, exist_ok=True)
139
+ mid_file = os.path.join(data_dir, ".machine_id")
140
+ with open(mid_file, "w", encoding="utf-8") as f:
141
+ f.write(fp)
142
+ except Exception:
143
+ pass
144
+
145
+ return fp
97
146
 
98
147
  @classmethod
99
148
  def detect_agent(cls) -> str:
@@ -444,18 +493,64 @@ class LicenseManager:
444
493
  return key
445
494
 
446
495
  @classmethod
447
- def save_license(cls, license_key: str) -> Tuple[bool, str]:
448
- """Saves a verified license key to local and user global persistent storage."""
496
+ def get_device_token(cls) -> str:
497
+ """Retrieves stored device refresh token."""
498
+ for target_file in cls._candidate_license_files():
499
+ if os.path.exists(target_file):
500
+ try:
501
+ with open(target_file, "r", encoding="utf-8") as f:
502
+ tok = json.load(f).get("device_token", "")
503
+ if tok:
504
+ return str(tok).strip()
505
+ except Exception:
506
+ pass
507
+ return ""
508
+
509
+ @classmethod
510
+ def refresh_device_license(cls) -> Tuple[bool, str]:
511
+ """Silently refreshes signed Community license via saved device_token without user interaction."""
512
+ device_token = cls.get_device_token()
513
+ if not device_token:
514
+ return False, "no_device_token"
515
+ try:
516
+ import urllib.request
517
+ cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
518
+ req = urllib.request.Request(
519
+ f"{cloud_url}/api/auth/device/refresh",
520
+ data=json.dumps({
521
+ "device_token": device_token,
522
+ "machine_fp": cls.get_machine_fingerprint()
523
+ }).encode("utf-8"),
524
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/Refresh"},
525
+ method="POST"
526
+ )
527
+ with urllib.request.urlopen(req, timeout=3.5) as resp:
528
+ data = json.loads(resp.read().decode("utf-8") or "{}")
529
+ new_key = data.get("license_key", "")
530
+ if resp.status == 200 and data.get("success") and new_key:
531
+ ok, msg = cls.save_license(new_key, device_token=device_token)
532
+ return ok, msg
533
+ return False, str(data.get("error") or "refresh_failed")
534
+ except Exception as exc:
535
+ return False, str(exc)
536
+
537
+ @classmethod
538
+ def save_license(cls, license_key: str, device_token: str = "") -> Tuple[bool, str]:
539
+ """Saves a verified license key and optional device refresh token to persistent storage."""
449
540
  valid, payload, msg = cls.validate_license(license_key)
450
541
  if not valid:
451
542
  return False, f"Cannot save invalid license: {msg}"
452
543
 
544
+ # Preserve existing device_token if none provided
545
+ resolved_device_token = device_token or cls.get_device_token()
546
+
453
547
  record = {
454
548
  "license_key": license_key,
455
549
  "tier": payload.get("tier"),
456
550
  "email": payload.get("email"),
457
551
  "expires_at": payload.get("expires_at"),
458
552
  "trial": payload.get("trial", False),
553
+ "device_token": resolved_device_token,
459
554
  "saved_at": int(time.time())
460
555
  }
461
556
 
@@ -497,8 +592,9 @@ class LicenseManager:
497
592
  )
498
593
  if base_dir:
499
594
  mirror_paths.append(os.path.join(base_dir, ".qledger.json"))
500
- mirror_paths.append(os.path.join(os.path.dirname(DATA_DIR), ".qledger.json"))
501
- mirror_paths.append(os.path.join(DATA_DIR, ".qledger.json"))
595
+ else:
596
+ mirror_paths.append(os.path.join(os.path.dirname(DATA_DIR), ".qledger.json"))
597
+ mirror_paths.append(os.path.join(DATA_DIR, ".qledger.json"))
502
598
 
503
599
  for mirror_path in mirror_paths:
504
600
  if os.path.exists(mirror_path):
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": "3.1.5"
45
+ "version": "3.2.0"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -186,6 +186,19 @@ class TelemetrySync:
186
186
  target_url = f"{base_url}/api/telemetry/sync"
187
187
  active_key = license_key or LicenseManager.get_active_license_key()
188
188
 
189
+ # Silent license renewal: if device has a device_token and license expires in < 7 days (or expired), refresh
190
+ try:
191
+ dev_tok = LicenseManager.get_device_token()
192
+ if dev_tok:
193
+ _, active_lic = LicenseManager.get_active_license()
194
+ exp_ts = int(active_lic.get("expires_at") or 0)
195
+ if not active_key or (exp_ts and (exp_ts - time.time()) < 7 * 86400):
196
+ refreshed, _ = LicenseManager.refresh_device_license()
197
+ if refreshed:
198
+ active_key = LicenseManager.get_active_license_key()
199
+ except Exception:
200
+ pass
201
+
189
202
  target_email = (email or "").strip().lower()
190
203
  if active_key and not active_key.startswith("ts_live_"):
191
204
  is_valid, payload, _ = LicenseManager.validate_license(active_key)
@@ -228,7 +241,7 @@ class TelemetrySync:
228
241
  current_last_id = last_id
229
242
  headers = {
230
243
  "Content-Type": "application/json",
231
- "User-Agent": "TokenSafe-Sync/3.1.5"
244
+ "User-Agent": "TokenSafe-Sync/3.2.0"
232
245
  }
233
246
  if active_key:
234
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -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 = "3.1.5"
20
+ CURRENT_VERSION = "3.2.0"
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