tokensafe 4.1.12 → 4.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/.codex-plugin/plugin.json +1 -1
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/cli.py +3 -1
- package/src/installer.py +188 -31
- package/src/mcp_server.py +1 -1
- package/src/proxy.py +44 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "4.
|
|
2
|
+
"version": "4.2.0",
|
|
3
3
|
"name": "tokensafe",
|
|
4
4
|
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
|
|
5
5
|
"author": {
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.2.0",
|
|
4
4
|
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous 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.
|
|
4
|
+
"version": "4.2.0",
|
|
5
5
|
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous 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.
|
|
4
|
+
"version": "4.2.0",
|
|
5
5
|
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
|
|
6
6
|
"logo": "https://tokensafe.dev/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 agent isn't getting dumber, your context is full of trash. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.
|
|
6
|
+
"version": "4.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": "4.
|
|
33
|
+
"version": "4.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": "4.
|
|
49
|
+
"version": "4.2.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
package/src/cli.py
CHANGED
|
@@ -432,7 +432,9 @@ def main(argv: Optional[List[str]] = None):
|
|
|
432
432
|
from src.license_manager import LicenseManager
|
|
433
433
|
tier, lic = LicenseManager.get_active_license()
|
|
434
434
|
if tier == "guest":
|
|
435
|
-
|
|
435
|
+
# NOTE: no function-local MetricsTracker import here — it would
|
|
436
|
+
# shadow the module-level import (L20) for the WHOLE main()
|
|
437
|
+
# and crash `tokensafe status` with UnboundLocalError.
|
|
436
438
|
quota = LicenseManager.check_quota(MetricsTracker())
|
|
437
439
|
saved = int(quota.get("monthly_saved", 0))
|
|
438
440
|
pct = min(100.0, (saved / 50_000) * 100) if 50_000 > 0 else 0.0
|
package/src/installer.py
CHANGED
|
@@ -13,6 +13,7 @@ Scans and automatically configures MCP integration for:
|
|
|
13
13
|
import os
|
|
14
14
|
import sys
|
|
15
15
|
import json
|
|
16
|
+
import hashlib
|
|
16
17
|
import shutil
|
|
17
18
|
import re
|
|
18
19
|
import shlex
|
|
@@ -381,6 +382,10 @@ class AgentInstaller:
|
|
|
381
382
|
_PLIST_LABEL = "dev.tokensafe.proxy"
|
|
382
383
|
_SERVICE_NAME = "tokensafe-proxy"
|
|
383
384
|
_WIRING_BACKUP = "proxy_wiring_backup.json"
|
|
385
|
+
# ZCode desktop provider registry (separate from the CLI's ~/.zcode/cli/config.json
|
|
386
|
+
# which only holds mcp/plugins): model providers live in the v2 config.
|
|
387
|
+
ZCODE_V2_CONFIG = os.path.join(HOME, ".zcode", "v2", "config.json")
|
|
388
|
+
_ZCODE_CLONE_SUFFIX = "-tokensafe"
|
|
384
389
|
|
|
385
390
|
@classmethod
|
|
386
391
|
def proxy_health(cls, timeout: float = 1.5) -> bool:
|
|
@@ -464,6 +469,148 @@ class AgentInstaller:
|
|
|
464
469
|
cls._atomic_write_json(config_file, data)
|
|
465
470
|
return True, "Claude Code unwired (previous base URL restored)"
|
|
466
471
|
|
|
472
|
+
# ---- Multi-agent proxy wiring (one daemon, per-key upstream routes) ----
|
|
473
|
+
|
|
474
|
+
@staticmethod
|
|
475
|
+
def _proxy_routes_path() -> str:
|
|
476
|
+
try:
|
|
477
|
+
from src.paths import resolve_data_dir
|
|
478
|
+
return os.path.join(resolve_data_dir(), "proxy_routes.json")
|
|
479
|
+
except Exception:
|
|
480
|
+
return os.path.join(HOME, ".tokensafe", "data", "proxy_routes.json")
|
|
481
|
+
|
|
482
|
+
@classmethod
|
|
483
|
+
def _register_proxy_route(cls, label: str, upstream_url: str, api_key: str) -> bool:
|
|
484
|
+
"""Registers a key-fingerprint -> upstream route so the proxy forwards
|
|
485
|
+
this agent's traffic to the provider the key belongs to. Only the key
|
|
486
|
+
FINGERPRINT is stored — the key itself never touches the routes file."""
|
|
487
|
+
if not api_key or not upstream_url:
|
|
488
|
+
return False
|
|
489
|
+
try:
|
|
490
|
+
fp = hashlib.sha256(api_key.strip().encode("utf-8")).hexdigest()[:16]
|
|
491
|
+
path = cls._proxy_routes_path()
|
|
492
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
493
|
+
routes: Dict[str, Any] = {}
|
|
494
|
+
if os.path.exists(path):
|
|
495
|
+
try:
|
|
496
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
497
|
+
routes = json.load(f)
|
|
498
|
+
except Exception:
|
|
499
|
+
routes = {}
|
|
500
|
+
if not isinstance(routes, dict):
|
|
501
|
+
routes = {}
|
|
502
|
+
routes[fp] = {"upstream_url": upstream_url, "label": label, "added_at": int(time.time())}
|
|
503
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
504
|
+
json.dump(routes, f, indent=2)
|
|
505
|
+
return True
|
|
506
|
+
except Exception:
|
|
507
|
+
return False
|
|
508
|
+
|
|
509
|
+
@classmethod
|
|
510
|
+
def _wire_zcode_provider(cls) -> Tuple[bool, str]:
|
|
511
|
+
"""Points the ZCode desktop app at the local proxy by ADDING a clone of the
|
|
512
|
+
currently enabled provider entry (baseURL swapped, apiKey kept). The original
|
|
513
|
+
entry is only disabled, never mutated — rollback removes the clone and
|
|
514
|
+
re-enables the original. Requires an app restart to take effect."""
|
|
515
|
+
if not cls.proxy_health():
|
|
516
|
+
return (False, "proxy is not running on 127.0.0.1:8765 — start it first")
|
|
517
|
+
if not os.path.isfile(cls.ZCODE_V2_CONFIG):
|
|
518
|
+
return (False, f"{cls.ZCODE_V2_CONFIG} not found — ZCode desktop provider registry missing")
|
|
519
|
+
data, err = cls._load_json_with_backup(cls.ZCODE_V2_CONFIG)
|
|
520
|
+
if err or not isinstance(data, dict):
|
|
521
|
+
return (False, err or f"Failed to parse {cls.ZCODE_V2_CONFIG}")
|
|
522
|
+
providers = data.get("provider")
|
|
523
|
+
if not isinstance(providers, dict):
|
|
524
|
+
return (False, "no provider entries in the ZCode v2 config")
|
|
525
|
+
|
|
526
|
+
# Fast path: a proxy clone already exists. Re-assert its flags (app updates
|
|
527
|
+
# may re-enable the original entry), but respect a deliberate provider
|
|
528
|
+
# switch (user enabled a different provider while the clone was disabled).
|
|
529
|
+
existing_clone_key = next(
|
|
530
|
+
(k for k, v in providers.items() if isinstance(v, dict) and k.endswith(cls._ZCODE_CLONE_SUFFIX)),
|
|
531
|
+
None,
|
|
532
|
+
)
|
|
533
|
+
if existing_clone_key:
|
|
534
|
+
clone = providers[existing_clone_key]
|
|
535
|
+
base_ok = str((clone.get("options") or {}).get("baseURL", "")).rstrip("/") == cls.PROXY_BASE_URL
|
|
536
|
+
origin = providers.get(existing_clone_key[: -len(cls._ZCODE_CLONE_SUFFIX)])
|
|
537
|
+
other_enabled = any(
|
|
538
|
+
k
|
|
539
|
+
for k, v in providers.items()
|
|
540
|
+
if isinstance(v, dict)
|
|
541
|
+
and v.get("enabled") is True
|
|
542
|
+
and k != existing_clone_key
|
|
543
|
+
and not k.endswith(cls._ZCODE_CLONE_SUFFIX)
|
|
544
|
+
)
|
|
545
|
+
if base_ok and clone.get("enabled") is True and isinstance(origin, dict) and origin.get("enabled") is not True and not other_enabled:
|
|
546
|
+
return (True, "ZCode already wired to the local proxy (provider clone present)")
|
|
547
|
+
# Drift after an app update OR deliberate switch — drop the clone and
|
|
548
|
+
# re-derive the wiring from whatever the user has enabled now.
|
|
549
|
+
del providers[existing_clone_key]
|
|
550
|
+
|
|
551
|
+
enabled_key = next(
|
|
552
|
+
(
|
|
553
|
+
k
|
|
554
|
+
for k, v in providers.items()
|
|
555
|
+
if isinstance(v, dict) and v.get("enabled") is True and not k.endswith(cls._ZCODE_CLONE_SUFFIX)
|
|
556
|
+
),
|
|
557
|
+
None,
|
|
558
|
+
)
|
|
559
|
+
if not enabled_key:
|
|
560
|
+
return (False, "no enabled provider entry found in the ZCode v2 config")
|
|
561
|
+
src = providers[enabled_key]
|
|
562
|
+
opts = src.get("options") if isinstance(src.get("options"), dict) else {}
|
|
563
|
+
api_key = str(opts.get("apiKey") or "")
|
|
564
|
+
base_url = str(opts.get("baseURL") or "").rstrip("/")
|
|
565
|
+
if not api_key or not base_url:
|
|
566
|
+
return (False, f"enabled provider '{enabled_key}' lacks apiKey/baseURL")
|
|
567
|
+
clone_key = f"{enabled_key}{cls._ZCODE_CLONE_SUFFIX}"
|
|
568
|
+
# Anthropic-kind mirrors need the full messages endpoint on the route.
|
|
569
|
+
upstream = base_url
|
|
570
|
+
if str(src.get("kind") or "").lower() == "anthropic" and "/anthropic" in upstream and not upstream.endswith("/v1/messages"):
|
|
571
|
+
upstream = f"{upstream}/v1/messages"
|
|
572
|
+
route_ok = cls._register_proxy_route(f"zcode:{enabled_key}", upstream, api_key)
|
|
573
|
+
clone = json.loads(json.dumps(src))
|
|
574
|
+
clone["enabled"] = True
|
|
575
|
+
clone["name"] = f"{src.get('name') or enabled_key} — TokenSafe Proxy"
|
|
576
|
+
if not isinstance(clone.get("options"), dict):
|
|
577
|
+
clone["options"] = {}
|
|
578
|
+
clone["options"]["baseURL"] = cls.PROXY_BASE_URL
|
|
579
|
+
providers[clone_key] = clone
|
|
580
|
+
src["enabled"] = False
|
|
581
|
+
cls._atomic_write_json(cls.ZCODE_V2_CONFIG, data)
|
|
582
|
+
msg = (
|
|
583
|
+
f"ZCode wired: provider clone '{clone_key}' -> {cls.PROXY_BASE_URL} "
|
|
584
|
+
f"(original '{enabled_key}' disabled; rollback: tokensafe proxy off; "
|
|
585
|
+
f"restart the ZCode app to pick up the new provider)"
|
|
586
|
+
)
|
|
587
|
+
if not route_ok:
|
|
588
|
+
msg += " [WARN: upstream route registration failed — proxy will use its default upstream]"
|
|
589
|
+
return (True, msg)
|
|
590
|
+
|
|
591
|
+
@classmethod
|
|
592
|
+
def _unwire_zcode_provider(cls) -> Tuple[bool, str]:
|
|
593
|
+
"""Removes the TokenSafe provider clone and re-enables the original entry."""
|
|
594
|
+
if not os.path.isfile(cls.ZCODE_V2_CONFIG):
|
|
595
|
+
return (True, "ZCode v2 config not found — nothing to unwire")
|
|
596
|
+
data, err = cls._load_json_with_backup(cls.ZCODE_V2_CONFIG)
|
|
597
|
+
if err or not isinstance(data, dict):
|
|
598
|
+
return (False, err or f"Failed to parse {cls.ZCODE_V2_CONFIG}")
|
|
599
|
+
providers = data.get("provider")
|
|
600
|
+
if not isinstance(providers, dict):
|
|
601
|
+
return (True, "ZCode not wired (no provider entries)")
|
|
602
|
+
clone_keys = [k for k, v in providers.items() if isinstance(v, dict) and k.endswith(cls._ZCODE_CLONE_SUFFIX)]
|
|
603
|
+
if not clone_keys:
|
|
604
|
+
return (True, "ZCode not wired (no provider clone present)")
|
|
605
|
+
for ck in clone_keys:
|
|
606
|
+
origin_key = ck[: -len(cls._ZCODE_CLONE_SUFFIX)]
|
|
607
|
+
del providers[ck]
|
|
608
|
+
origin = providers.get(origin_key)
|
|
609
|
+
if isinstance(origin, dict):
|
|
610
|
+
origin["enabled"] = True
|
|
611
|
+
cls._atomic_write_json(cls.ZCODE_V2_CONFIG, data)
|
|
612
|
+
return (True, "ZCode unwired: clone removed, original provider re-enabled (restart the app)")
|
|
613
|
+
|
|
467
614
|
@classmethod
|
|
468
615
|
def install_proxy_daemon(cls) -> Tuple[bool, str]:
|
|
469
616
|
"""Keeps `tokensafe proxy` running: launchd (macOS) / systemd user unit (Linux)."""
|
|
@@ -564,11 +711,14 @@ WantedBy=default.target
|
|
|
564
711
|
if report["health"]:
|
|
565
712
|
w_ok, w_msg = cls.wire_proxy_config()
|
|
566
713
|
report["wiring"] = {"ok": w_ok, "message": w_msg}
|
|
714
|
+
z_ok, z_msg = cls._wire_zcode_provider()
|
|
715
|
+
report["wiring_zcode"] = {"ok": z_ok, "message": z_msg}
|
|
567
716
|
else:
|
|
568
717
|
report["wiring"] = {"ok": False, "message": "proxy not reachable; agents NOT rewired"}
|
|
569
718
|
report["manual_steps"] = [
|
|
570
719
|
"Cursor: Settings → Models → add OpenAI-compatible model with base URL http://127.0.0.1:8765/v1",
|
|
571
720
|
"Cline/Aider: set OpenAI-compatible base URL to http://127.0.0.1:8765/v1",
|
|
721
|
+
"Codex: add a model_providers entry in ~/.codex/config.toml with base_url http://127.0.0.1:8765/v1",
|
|
572
722
|
]
|
|
573
723
|
return report
|
|
574
724
|
|
|
@@ -577,6 +727,8 @@ WantedBy=default.target
|
|
|
577
727
|
report: Dict[str, Any] = {}
|
|
578
728
|
u_ok, u_msg = cls.unwire_proxy_config()
|
|
579
729
|
report["unwired"] = {"ok": u_ok, "message": u_msg}
|
|
730
|
+
z_ok, z_msg = cls._unwire_zcode_provider()
|
|
731
|
+
report["unwired_zcode"] = {"ok": z_ok, "message": z_msg}
|
|
580
732
|
r_ok, r_msg = cls.remove_proxy_daemon()
|
|
581
733
|
report["daemon"] = {"ok": r_ok, "message": r_msg}
|
|
582
734
|
return report
|
|
@@ -610,38 +762,32 @@ WantedBy=default.target
|
|
|
610
762
|
}
|
|
611
763
|
|
|
612
764
|
@classmethod
|
|
613
|
-
def
|
|
614
|
-
"""
|
|
615
|
-
|
|
616
|
-
|
|
765
|
+
def _ensure_proxy_default(cls, context: str = "install", fresh_bin: Optional[str] = None) -> None:
|
|
766
|
+
"""Ultimate default-on proxy assertion for install/update flows: TokenSafe
|
|
767
|
+
is the primary LLM route for every wire-able agent. Daemon is installed and
|
|
768
|
+
agents are wired WITHOUT asking (the old interactive prompt is retired).
|
|
769
|
+
Emergency brake: TOKENSAFE_PROXY_DISABLED=1 leaves everything untouched.
|
|
770
|
+
Fail-open: a proxy problem never breaks install/update itself."""
|
|
617
771
|
try:
|
|
618
|
-
if
|
|
619
|
-
|
|
620
|
-
if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes"):
|
|
621
|
-
return
|
|
622
|
-
if "unittest" in sys.modules and not os.environ.get("TOKENSAFE_TEST_PROMPT"):
|
|
772
|
+
if os.environ.get("TOKENSAFE_PROXY_DISABLED", "").strip().lower() in ("1", "true", "yes"):
|
|
773
|
+
print(f" {DIM}ℹ TokenSafe proxy left off (TOKENSAFE_PROXY_DISABLED is set). Enable anytime: tokensafe proxy on{RESET}")
|
|
623
774
|
return
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
print(f" Manual: {step}")
|
|
639
|
-
print(f" Rollback: {BOLD}tokensafe proxy off{RESET}")
|
|
640
|
-
except (EOFError, KeyboardInterrupt):
|
|
641
|
-
print()
|
|
642
|
-
return
|
|
775
|
+
if fresh_bin:
|
|
776
|
+
# Re-assert via the freshly upgraded binary so the daemon plist
|
|
777
|
+
# points at the new engine path, not this (old) process.
|
|
778
|
+
subprocess.run(
|
|
779
|
+
[fresh_bin, "proxy", "on"],
|
|
780
|
+
env=cls._npm_subprocess_env(fresh_bin), capture_output=True, text=True, timeout=30,
|
|
781
|
+
)
|
|
782
|
+
else:
|
|
783
|
+
cls.proxy_on()
|
|
784
|
+
if cls.proxy_health(timeout=3.0):
|
|
785
|
+
print(f" {GREEN}✔{RESET} TokenSafe proxy daemon active — Claude Code / ZCode routed through the local optimizer.")
|
|
786
|
+
print(f" {DIM}Rollback: tokensafe proxy off{RESET}")
|
|
787
|
+
else:
|
|
788
|
+
print(f" {YELLOW}⚠{RESET} TokenSafe proxy did not answer — run {BOLD}tokensafe proxy on{RESET} to retry.")
|
|
643
789
|
except Exception:
|
|
644
|
-
|
|
790
|
+
pass # fail-open: a proxy problem never breaks install/update
|
|
645
791
|
|
|
646
792
|
@classmethod
|
|
647
793
|
def maybe_prompt_account_login(cls, context: str = "install") -> None:
|
|
@@ -1319,7 +1465,7 @@ WantedBy=default.target
|
|
|
1319
1465
|
print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
|
|
1320
1466
|
print(" Restart your IDE / Agent to start saving tokens automatically.\n")
|
|
1321
1467
|
cls.maybe_prompt_account_login(context="install")
|
|
1322
|
-
cls.
|
|
1468
|
+
cls._ensure_proxy_default("install")
|
|
1323
1469
|
|
|
1324
1470
|
@staticmethod
|
|
1325
1471
|
def _is_tokensafe_mcp_command(cmd: str) -> bool:
|
|
@@ -1661,12 +1807,23 @@ WantedBy=default.target
|
|
|
1661
1807
|
print(f" {GREEN}✔{RESET} Restarted {restarted_count} running TokenSafe MCP daemon(s).")
|
|
1662
1808
|
print(f" {CYAN}ℹ{RESET} Antigravity/Cursor/Claude Code reconnect automatically; reload MCP in Claude Desktop/VS Code if disconnected.")
|
|
1663
1809
|
|
|
1810
|
+
# 7. Proxy re-assertion (ultimate, default-on): TokenSafe is the default LLM
|
|
1811
|
+
# route for every wire-able agent. Agent/app updates are known to rewrite
|
|
1812
|
+
# their own configs and drop third-party routing, so after every update we
|
|
1813
|
+
# reinstall the daemon with the FRESH engine binary and re-claim the wiring.
|
|
1814
|
+
ensure_bin = None
|
|
1815
|
+
for npm_bin in upgraded_npm_bins:
|
|
1816
|
+
cand_bin = os.path.join(os.path.dirname(npm_bin), "tokensafe.cmd" if os.name == "nt" else "tokensafe")
|
|
1817
|
+
if os.path.isfile(cand_bin) and os.access(cand_bin, os.X_OK):
|
|
1818
|
+
ensure_bin = cand_bin
|
|
1819
|
+
break
|
|
1820
|
+
cls._ensure_proxy_default("update", fresh_bin=ensure_bin)
|
|
1821
|
+
|
|
1664
1822
|
print(f"\n{BOLD}{GREEN}✅ Self-update complete!{RESET}")
|
|
1665
1823
|
print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
|
|
1666
1824
|
print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
|
|
1667
1825
|
print(f" {CYAN}ℹ{RESET} If your terminal still shows the old version, open a new window or run {BOLD}hash -r{RESET}.")
|
|
1668
1826
|
cls.maybe_prompt_account_login(context="update")
|
|
1669
|
-
cls.maybe_prompt_proxy_enable(context="update")
|
|
1670
1827
|
|
|
1671
1828
|
def main():
|
|
1672
1829
|
args = sys.argv[1:]
|
package/src/mcp_server.py
CHANGED
package/src/proxy.py
CHANGED
|
@@ -971,7 +971,13 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
971
971
|
|
|
972
972
|
# 4. Resolve Multi-Provider Upstream & API Key (needed before provider-aware cache breakpoints)
|
|
973
973
|
auth_header = self.headers.get("Authorization", "")
|
|
974
|
-
|
|
974
|
+
incoming_key = auth_header[7:].strip() if auth_header.lower().startswith("bearer ") else ""
|
|
975
|
+
if not incoming_key:
|
|
976
|
+
try:
|
|
977
|
+
incoming_key = self.headers.get("x-api-key", "") or ""
|
|
978
|
+
except Exception:
|
|
979
|
+
incoming_key = ""
|
|
980
|
+
custom_url = _apply_route_override(incoming_key, os.environ.get("TOKENSAFE_UPSTREAM_URL", ""))
|
|
975
981
|
|
|
976
982
|
data_dir = resolve_data_dir()
|
|
977
983
|
conf_keys = {}
|
|
@@ -1221,6 +1227,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
1221
1227
|
url = (upstream_url or "").lower()
|
|
1222
1228
|
if "anthropic.com" in url:
|
|
1223
1229
|
return "anthropic"
|
|
1230
|
+
# Anthropic-compatible mirrors (e.g. Z.ai /api/anthropic[/v1/messages]
|
|
1231
|
+
# coding-plan endpoint): same wire dialect, client x-api-key is forwarded as-is.
|
|
1232
|
+
if "/anthropic" in url:
|
|
1233
|
+
return "anthropic"
|
|
1224
1234
|
if "openai.com" in url:
|
|
1225
1235
|
return "openai"
|
|
1226
1236
|
if "googleapis.com" in url or "generativelanguage" in url:
|
|
@@ -1255,6 +1265,39 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
1255
1265
|
return custom_url, (gemini_key or generic_upstream_key)
|
|
1256
1266
|
return custom_url, (deepseek_key or generic_upstream_key or openai_key)
|
|
1257
1267
|
|
|
1268
|
+
def _key_fingerprint(api_key: str) -> str:
|
|
1269
|
+
"""Stable fingerprint of a client API key (never store the key itself)."""
|
|
1270
|
+
import hashlib
|
|
1271
|
+
return hashlib.sha256((api_key or "").strip().encode("utf-8")).hexdigest()[:16]
|
|
1272
|
+
|
|
1273
|
+
|
|
1274
|
+
def _load_proxy_routes() -> Dict[str, Any]:
|
|
1275
|
+
"""Per-agent upstream route table written by the installer
|
|
1276
|
+
(fingerprint -> {upstream_url, label}). Read per request so routes
|
|
1277
|
+
added by `tokensafe proxy on` are picked up without a daemon restart."""
|
|
1278
|
+
try:
|
|
1279
|
+
path = os.path.join(resolve_data_dir(), "proxy_routes.json")
|
|
1280
|
+
if os.path.exists(path):
|
|
1281
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
1282
|
+
data = json.load(f)
|
|
1283
|
+
if isinstance(data, dict):
|
|
1284
|
+
return {str(k): v for k, v in data.items() if isinstance(v, dict)}
|
|
1285
|
+
except Exception:
|
|
1286
|
+
pass
|
|
1287
|
+
return {}
|
|
1288
|
+
|
|
1289
|
+
|
|
1290
|
+
def _apply_route_override(incoming_key: str, custom_url: str) -> str:
|
|
1291
|
+
"""Returns the upstream URL for this client key: installer-registered route
|
|
1292
|
+
first (one proxy serves several agents with different providers), then the
|
|
1293
|
+
TOKENSAFE_UPSTREAM_URL env, then the default provider resolution."""
|
|
1294
|
+
if incoming_key:
|
|
1295
|
+
route = _load_proxy_routes().get(_key_fingerprint(incoming_key))
|
|
1296
|
+
if isinstance(route, dict) and route.get("upstream_url"):
|
|
1297
|
+
return str(route["upstream_url"])
|
|
1298
|
+
return custom_url
|
|
1299
|
+
|
|
1300
|
+
|
|
1258
1301
|
def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
|
|
1259
1302
|
# Auto-initialize Knowledge Graph & API Surface on startup
|
|
1260
1303
|
hubs_summary = "active"
|
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.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.2.0"
|
|
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.
|
|
20
|
+
CURRENT_VERSION = "4.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
|