tokensafe 4.1.13 → 4.2.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/.codex-plugin/plugin.json +1 -1
- package/hooks.json +7 -0
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/installer.py +253 -32
- package/src/mcp_server.py +42 -3
- package/src/proxy.py +52 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "4.1
|
|
2
|
+
"version": "4.2.1",
|
|
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/hooks.json
CHANGED
|
@@ -15,6 +15,13 @@
|
|
|
15
15
|
"timeout": 10
|
|
16
16
|
}
|
|
17
17
|
],
|
|
18
|
+
"UserPromptSubmit": [
|
|
19
|
+
{
|
|
20
|
+
"type": "command",
|
|
21
|
+
"command": "python3 hooks/pre_invocation.py",
|
|
22
|
+
"timeout": 10
|
|
23
|
+
}
|
|
24
|
+
],
|
|
18
25
|
"PreToolUse": [
|
|
19
26
|
{
|
|
20
27
|
"matcher": "read_file|view_file|run_command|write_file|edit_file",
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.1
|
|
3
|
+
"version": "4.2.1",
|
|
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.1
|
|
4
|
+
"version": "4.2.1",
|
|
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.1
|
|
4
|
+
"version": "4.2.1",
|
|
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.1
|
|
6
|
+
"version": "4.2.1",
|
|
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.1
|
|
33
|
+
"version": "4.2.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": "4.1
|
|
49
|
+
"version": "4.2.1",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
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
|
|
@@ -227,7 +228,7 @@ class AgentInstaller:
|
|
|
227
228
|
Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
|
|
228
229
|
if agent_key == "codex":
|
|
229
230
|
return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
|
|
230
|
-
if agent_key not in ("claude_code", "cursor", "kimi"):
|
|
231
|
+
if agent_key not in ("claude_code", "cursor", "kimi", "zcode"):
|
|
231
232
|
return False, "hooks not applicable for this agent"
|
|
232
233
|
|
|
233
234
|
claude_cmd = cls._tokensafe_hook_command("claude_code_hook.py")
|
|
@@ -330,6 +331,66 @@ class AgentInstaller:
|
|
|
330
331
|
cls._atomic_write_json(config_file, data)
|
|
331
332
|
return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write + PostToolUse stdout compact)"
|
|
332
333
|
|
|
334
|
+
if agent_key == "zcode":
|
|
335
|
+
config_file = os.path.join(HOME, ".zcode", "cli", "config.json")
|
|
336
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
337
|
+
if err or data is None:
|
|
338
|
+
return False, err or f"Failed to parse {config_file}"
|
|
339
|
+
# ZCode configuration-file hooks are disabled by default and only run
|
|
340
|
+
# with enabled=true. The bundled hook scripts already speak the ZCode
|
|
341
|
+
# contract (injectSteps/systemMessage outputs + decision/reason), so
|
|
342
|
+
# registration is pure plumbing — no adapter shim needed.
|
|
343
|
+
hooks_block = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
|
|
344
|
+
hooks_block["enabled"] = True
|
|
345
|
+
events = hooks_block.get("events") if isinstance(hooks_block.get("events"), dict) else {}
|
|
346
|
+
|
|
347
|
+
def _zcode_entry(script_name: str) -> dict:
|
|
348
|
+
return {"hooks": [{
|
|
349
|
+
"type": "process",
|
|
350
|
+
"command": PYTHON_BIN,
|
|
351
|
+
"args": [os.path.join(PROJECT_ROOT, "hooks", script_name)],
|
|
352
|
+
"timeoutMs": 10000,
|
|
353
|
+
}]}
|
|
354
|
+
|
|
355
|
+
def _sync_zcode_event(event_name: str, script_name: str) -> bool:
|
|
356
|
+
entry = _zcode_entry(script_name)
|
|
357
|
+
expected = os.path.join(PROJECT_ROOT, "hooks", script_name)
|
|
358
|
+
entries = events.get(event_name)
|
|
359
|
+
if not isinstance(entries, list):
|
|
360
|
+
events[event_name] = [entry]
|
|
361
|
+
return True
|
|
362
|
+
seen = False
|
|
363
|
+
dirty = False
|
|
364
|
+
for e in entries:
|
|
365
|
+
if isinstance(e, dict) and isinstance(e.get("hooks"), list):
|
|
366
|
+
for h in e["hooks"]:
|
|
367
|
+
args = h.get("args") if isinstance(h, dict) else None
|
|
368
|
+
if not isinstance(args, list):
|
|
369
|
+
continue
|
|
370
|
+
if any(isinstance(a, str) and a.endswith(script_name) for a in args):
|
|
371
|
+
seen = True
|
|
372
|
+
if args[-1] != expected:
|
|
373
|
+
args[-1] = expected
|
|
374
|
+
dirty = True
|
|
375
|
+
if not seen:
|
|
376
|
+
entries.append(entry)
|
|
377
|
+
dirty = True
|
|
378
|
+
return dirty
|
|
379
|
+
|
|
380
|
+
changed = any([
|
|
381
|
+
_sync_zcode_event("SessionStart", "session_start.py"),
|
|
382
|
+
_sync_zcode_event("UserPromptSubmit", "pre_invocation.py"),
|
|
383
|
+
_sync_zcode_event("PreToolUse", "pre_tool_use.py"),
|
|
384
|
+
_sync_zcode_event("PostToolUse", "post_tool_use.py"),
|
|
385
|
+
_sync_zcode_event("Stop", "stop_hook.py"),
|
|
386
|
+
])
|
|
387
|
+
if changed:
|
|
388
|
+
hooks_block["events"] = events
|
|
389
|
+
data["hooks"] = hooks_block
|
|
390
|
+
cls._atomic_write_json(config_file, data)
|
|
391
|
+
return True, "ZCode hooks registered in ~/.zcode/cli/config.json (SessionStart + UserPromptSubmit + PreToolUse guard + PostToolUse compact + Stop) — restart the app to take effect"
|
|
392
|
+
return True, "TokenSafe ZCode hooks already registered"
|
|
393
|
+
|
|
333
394
|
# cursor
|
|
334
395
|
config_file = os.path.join(HOME, ".cursor", "hooks.json")
|
|
335
396
|
os.makedirs(os.path.dirname(config_file), exist_ok=True)
|
|
@@ -381,6 +442,10 @@ class AgentInstaller:
|
|
|
381
442
|
_PLIST_LABEL = "dev.tokensafe.proxy"
|
|
382
443
|
_SERVICE_NAME = "tokensafe-proxy"
|
|
383
444
|
_WIRING_BACKUP = "proxy_wiring_backup.json"
|
|
445
|
+
# ZCode desktop provider registry (separate from the CLI's ~/.zcode/cli/config.json
|
|
446
|
+
# which only holds mcp/plugins): model providers live in the v2 config.
|
|
447
|
+
ZCODE_V2_CONFIG = os.path.join(HOME, ".zcode", "v2", "config.json")
|
|
448
|
+
_ZCODE_CLONE_SUFFIX = "-tokensafe"
|
|
384
449
|
|
|
385
450
|
@classmethod
|
|
386
451
|
def proxy_health(cls, timeout: float = 1.5) -> bool:
|
|
@@ -464,6 +529,152 @@ class AgentInstaller:
|
|
|
464
529
|
cls._atomic_write_json(config_file, data)
|
|
465
530
|
return True, "Claude Code unwired (previous base URL restored)"
|
|
466
531
|
|
|
532
|
+
# ---- Multi-agent proxy wiring (one daemon, per-key upstream routes) ----
|
|
533
|
+
|
|
534
|
+
@staticmethod
|
|
535
|
+
def _proxy_routes_path() -> str:
|
|
536
|
+
try:
|
|
537
|
+
from src.paths import resolve_data_dir
|
|
538
|
+
return os.path.join(resolve_data_dir(), "proxy_routes.json")
|
|
539
|
+
except Exception:
|
|
540
|
+
return os.path.join(HOME, ".tokensafe", "data", "proxy_routes.json")
|
|
541
|
+
|
|
542
|
+
@classmethod
|
|
543
|
+
def _register_proxy_route(cls, label: str, upstream_url: str, api_key: str) -> bool:
|
|
544
|
+
"""Registers a key-fingerprint -> upstream route so the proxy forwards
|
|
545
|
+
this agent's traffic to the provider the key belongs to. Only the key
|
|
546
|
+
FINGERPRINT is stored — the key itself never touches the routes file."""
|
|
547
|
+
if not api_key or not upstream_url:
|
|
548
|
+
return False
|
|
549
|
+
try:
|
|
550
|
+
fp = hashlib.sha256(api_key.strip().encode("utf-8")).hexdigest()[:16]
|
|
551
|
+
path = cls._proxy_routes_path()
|
|
552
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
553
|
+
routes: Dict[str, Any] = {}
|
|
554
|
+
if os.path.exists(path):
|
|
555
|
+
try:
|
|
556
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
557
|
+
routes = json.load(f)
|
|
558
|
+
except Exception:
|
|
559
|
+
routes = {}
|
|
560
|
+
if not isinstance(routes, dict):
|
|
561
|
+
routes = {}
|
|
562
|
+
routes[fp] = {"upstream_url": upstream_url, "label": label, "added_at": int(time.time())}
|
|
563
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
564
|
+
json.dump(routes, f, indent=2)
|
|
565
|
+
return True
|
|
566
|
+
except Exception as e:
|
|
567
|
+
try:
|
|
568
|
+
sys.stderr.write(f"[TokenSafe] WARN: proxy route registration failed ({label}): {e}\n")
|
|
569
|
+
except Exception:
|
|
570
|
+
pass
|
|
571
|
+
return False
|
|
572
|
+
|
|
573
|
+
@classmethod
|
|
574
|
+
def _wire_zcode_provider(cls) -> Tuple[bool, str]:
|
|
575
|
+
"""Points the ZCode desktop app at the local proxy by ADDING a clone of the
|
|
576
|
+
currently enabled provider entry (baseURL swapped, apiKey kept). The original
|
|
577
|
+
entry is only disabled, never mutated — rollback removes the clone and
|
|
578
|
+
re-enables the original. Requires an app restart to take effect."""
|
|
579
|
+
if not cls.proxy_health():
|
|
580
|
+
return (False, "proxy is not running on 127.0.0.1:8765 — start it first")
|
|
581
|
+
if not os.path.isfile(cls.ZCODE_V2_CONFIG):
|
|
582
|
+
return (False, f"{cls.ZCODE_V2_CONFIG} not found — ZCode desktop provider registry missing")
|
|
583
|
+
data, err = cls._load_json_with_backup(cls.ZCODE_V2_CONFIG)
|
|
584
|
+
if err or not isinstance(data, dict):
|
|
585
|
+
return (False, err or f"Failed to parse {cls.ZCODE_V2_CONFIG}")
|
|
586
|
+
providers = data.get("provider")
|
|
587
|
+
if not isinstance(providers, dict):
|
|
588
|
+
return (False, "no provider entries in the ZCode v2 config")
|
|
589
|
+
|
|
590
|
+
# Fast path: a proxy clone already exists. Re-assert its flags (app updates
|
|
591
|
+
# may re-enable the original entry), but respect a deliberate provider
|
|
592
|
+
# switch (user enabled a different provider while the clone was disabled).
|
|
593
|
+
existing_clone_key = next(
|
|
594
|
+
(k for k, v in providers.items() if isinstance(v, dict) and k.endswith(cls._ZCODE_CLONE_SUFFIX)),
|
|
595
|
+
None,
|
|
596
|
+
)
|
|
597
|
+
if existing_clone_key:
|
|
598
|
+
clone = providers[existing_clone_key]
|
|
599
|
+
base_ok = str((clone.get("options") or {}).get("baseURL", "")).rstrip("/") == cls.PROXY_BASE_URL
|
|
600
|
+
origin = providers.get(existing_clone_key[: -len(cls._ZCODE_CLONE_SUFFIX)])
|
|
601
|
+
other_enabled = any(
|
|
602
|
+
k
|
|
603
|
+
for k, v in providers.items()
|
|
604
|
+
if isinstance(v, dict)
|
|
605
|
+
and v.get("enabled") is True
|
|
606
|
+
and k != existing_clone_key
|
|
607
|
+
and not k.endswith(cls._ZCODE_CLONE_SUFFIX)
|
|
608
|
+
)
|
|
609
|
+
if base_ok and clone.get("enabled") is True and isinstance(origin, dict) and origin.get("enabled") is not True and not other_enabled:
|
|
610
|
+
return (True, "ZCode already wired to the local proxy (provider clone present)")
|
|
611
|
+
# Drift after an app update OR deliberate switch — drop the clone and
|
|
612
|
+
# re-derive the wiring from whatever the user has enabled now.
|
|
613
|
+
del providers[existing_clone_key]
|
|
614
|
+
|
|
615
|
+
enabled_key = next(
|
|
616
|
+
(
|
|
617
|
+
k
|
|
618
|
+
for k, v in providers.items()
|
|
619
|
+
if isinstance(v, dict) and v.get("enabled") is True and not k.endswith(cls._ZCODE_CLONE_SUFFIX)
|
|
620
|
+
),
|
|
621
|
+
None,
|
|
622
|
+
)
|
|
623
|
+
if not enabled_key:
|
|
624
|
+
return (False, "no enabled provider entry found in the ZCode v2 config")
|
|
625
|
+
src = providers[enabled_key]
|
|
626
|
+
opts = src.get("options") if isinstance(src.get("options"), dict) else {}
|
|
627
|
+
api_key = str(opts.get("apiKey") or "")
|
|
628
|
+
base_url = str(opts.get("baseURL") or "").rstrip("/")
|
|
629
|
+
if not api_key or not base_url:
|
|
630
|
+
return (False, f"enabled provider '{enabled_key}' lacks apiKey/baseURL")
|
|
631
|
+
clone_key = f"{enabled_key}{cls._ZCODE_CLONE_SUFFIX}"
|
|
632
|
+
# Anthropic-kind mirrors need the full messages endpoint on the route.
|
|
633
|
+
upstream = base_url
|
|
634
|
+
if str(src.get("kind") or "").lower() == "anthropic" and "/anthropic" in upstream and not upstream.endswith("/v1/messages"):
|
|
635
|
+
upstream = f"{upstream}/v1/messages"
|
|
636
|
+
route_ok = cls._register_proxy_route(f"zcode:{enabled_key}", upstream, api_key)
|
|
637
|
+
clone = json.loads(json.dumps(src))
|
|
638
|
+
clone["enabled"] = True
|
|
639
|
+
clone["name"] = f"{src.get('name') or enabled_key} — TokenSafe Proxy"
|
|
640
|
+
if not isinstance(clone.get("options"), dict):
|
|
641
|
+
clone["options"] = {}
|
|
642
|
+
clone["options"]["baseURL"] = cls.PROXY_BASE_URL
|
|
643
|
+
providers[clone_key] = clone
|
|
644
|
+
src["enabled"] = False
|
|
645
|
+
cls._atomic_write_json(cls.ZCODE_V2_CONFIG, data)
|
|
646
|
+
msg = (
|
|
647
|
+
f"ZCode wired: provider clone '{clone_key}' -> {cls.PROXY_BASE_URL} "
|
|
648
|
+
f"(original '{enabled_key}' disabled; rollback: tokensafe proxy off; "
|
|
649
|
+
f"restart the ZCode app to pick up the new provider)"
|
|
650
|
+
)
|
|
651
|
+
if not route_ok:
|
|
652
|
+
msg += " [WARN: upstream route registration failed — proxy will use its default upstream]"
|
|
653
|
+
return (True, msg)
|
|
654
|
+
|
|
655
|
+
@classmethod
|
|
656
|
+
def _unwire_zcode_provider(cls) -> Tuple[bool, str]:
|
|
657
|
+
"""Removes the TokenSafe provider clone and re-enables the original entry."""
|
|
658
|
+
if not os.path.isfile(cls.ZCODE_V2_CONFIG):
|
|
659
|
+
return (True, "ZCode v2 config not found — nothing to unwire")
|
|
660
|
+
data, err = cls._load_json_with_backup(cls.ZCODE_V2_CONFIG)
|
|
661
|
+
if err or not isinstance(data, dict):
|
|
662
|
+
return (False, err or f"Failed to parse {cls.ZCODE_V2_CONFIG}")
|
|
663
|
+
providers = data.get("provider")
|
|
664
|
+
if not isinstance(providers, dict):
|
|
665
|
+
return (True, "ZCode not wired (no provider entries)")
|
|
666
|
+
clone_keys = [k for k, v in providers.items() if isinstance(v, dict) and k.endswith(cls._ZCODE_CLONE_SUFFIX)]
|
|
667
|
+
if not clone_keys:
|
|
668
|
+
return (True, "ZCode not wired (no provider clone present)")
|
|
669
|
+
for ck in clone_keys:
|
|
670
|
+
origin_key = ck[: -len(cls._ZCODE_CLONE_SUFFIX)]
|
|
671
|
+
del providers[ck]
|
|
672
|
+
origin = providers.get(origin_key)
|
|
673
|
+
if isinstance(origin, dict):
|
|
674
|
+
origin["enabled"] = True
|
|
675
|
+
cls._atomic_write_json(cls.ZCODE_V2_CONFIG, data)
|
|
676
|
+
return (True, "ZCode unwired: clone removed, original provider re-enabled (restart the app)")
|
|
677
|
+
|
|
467
678
|
@classmethod
|
|
468
679
|
def install_proxy_daemon(cls) -> Tuple[bool, str]:
|
|
469
680
|
"""Keeps `tokensafe proxy` running: launchd (macOS) / systemd user unit (Linux)."""
|
|
@@ -564,11 +775,14 @@ WantedBy=default.target
|
|
|
564
775
|
if report["health"]:
|
|
565
776
|
w_ok, w_msg = cls.wire_proxy_config()
|
|
566
777
|
report["wiring"] = {"ok": w_ok, "message": w_msg}
|
|
778
|
+
z_ok, z_msg = cls._wire_zcode_provider()
|
|
779
|
+
report["wiring_zcode"] = {"ok": z_ok, "message": z_msg}
|
|
567
780
|
else:
|
|
568
781
|
report["wiring"] = {"ok": False, "message": "proxy not reachable; agents NOT rewired"}
|
|
569
782
|
report["manual_steps"] = [
|
|
570
783
|
"Cursor: Settings → Models → add OpenAI-compatible model with base URL http://127.0.0.1:8765/v1",
|
|
571
784
|
"Cline/Aider: set OpenAI-compatible base URL to http://127.0.0.1:8765/v1",
|
|
785
|
+
"Codex: add a model_providers entry in ~/.codex/config.toml with base_url http://127.0.0.1:8765/v1",
|
|
572
786
|
]
|
|
573
787
|
return report
|
|
574
788
|
|
|
@@ -577,6 +791,8 @@ WantedBy=default.target
|
|
|
577
791
|
report: Dict[str, Any] = {}
|
|
578
792
|
u_ok, u_msg = cls.unwire_proxy_config()
|
|
579
793
|
report["unwired"] = {"ok": u_ok, "message": u_msg}
|
|
794
|
+
z_ok, z_msg = cls._unwire_zcode_provider()
|
|
795
|
+
report["unwired_zcode"] = {"ok": z_ok, "message": z_msg}
|
|
580
796
|
r_ok, r_msg = cls.remove_proxy_daemon()
|
|
581
797
|
report["daemon"] = {"ok": r_ok, "message": r_msg}
|
|
582
798
|
return report
|
|
@@ -610,38 +826,32 @@ WantedBy=default.target
|
|
|
610
826
|
}
|
|
611
827
|
|
|
612
828
|
@classmethod
|
|
613
|
-
def
|
|
614
|
-
"""
|
|
615
|
-
|
|
616
|
-
|
|
829
|
+
def _ensure_proxy_default(cls, context: str = "install", fresh_bin: Optional[str] = None) -> None:
|
|
830
|
+
"""Ultimate default-on proxy assertion for install/update flows: TokenSafe
|
|
831
|
+
is the primary LLM route for every wire-able agent. Daemon is installed and
|
|
832
|
+
agents are wired WITHOUT asking (the old interactive prompt is retired).
|
|
833
|
+
Emergency brake: TOKENSAFE_PROXY_DISABLED=1 leaves everything untouched.
|
|
834
|
+
Fail-open: a proxy problem never breaks install/update itself."""
|
|
617
835
|
try:
|
|
618
|
-
if
|
|
619
|
-
|
|
620
|
-
if os.environ.get("TOKENSAFE_NONINTERACTIVE", "").strip() in ("1", "true", "yes"):
|
|
836
|
+
if os.environ.get("TOKENSAFE_PROXY_DISABLED", "").strip().lower() in ("1", "true", "yes"):
|
|
837
|
+
print(f" {DIM}ℹ TokenSafe proxy left off (TOKENSAFE_PROXY_DISABLED is set). Enable anytime: tokensafe proxy on{RESET}")
|
|
621
838
|
return
|
|
622
|
-
if
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
print(f" Wiring: {'✔ ' + w['message'] if w['ok'] else '✖ ' + w['message']}")
|
|
637
|
-
for step in report.get("manual_steps") or []:
|
|
638
|
-
print(f" Manual: {step}")
|
|
639
|
-
print(f" Rollback: {BOLD}tokensafe proxy off{RESET}")
|
|
640
|
-
except (EOFError, KeyboardInterrupt):
|
|
641
|
-
print()
|
|
642
|
-
return
|
|
839
|
+
if fresh_bin:
|
|
840
|
+
# Re-assert via the freshly upgraded binary so the daemon plist
|
|
841
|
+
# points at the new engine path, not this (old) process.
|
|
842
|
+
subprocess.run(
|
|
843
|
+
[fresh_bin, "proxy", "on"],
|
|
844
|
+
env=cls._npm_subprocess_env(fresh_bin), capture_output=True, text=True, timeout=30,
|
|
845
|
+
)
|
|
846
|
+
else:
|
|
847
|
+
cls.proxy_on()
|
|
848
|
+
if cls.proxy_health(timeout=3.0):
|
|
849
|
+
print(f" {GREEN}✔{RESET} TokenSafe proxy daemon active — Claude Code / ZCode routed through the local optimizer.")
|
|
850
|
+
print(f" {DIM}Rollback: tokensafe proxy off{RESET}")
|
|
851
|
+
else:
|
|
852
|
+
print(f" {YELLOW}⚠{RESET} TokenSafe proxy did not answer — run {BOLD}tokensafe proxy on{RESET} to retry.")
|
|
643
853
|
except Exception:
|
|
644
|
-
|
|
854
|
+
pass # fail-open: a proxy problem never breaks install/update
|
|
645
855
|
|
|
646
856
|
@classmethod
|
|
647
857
|
def maybe_prompt_account_login(cls, context: str = "install") -> None:
|
|
@@ -1319,7 +1529,7 @@ WantedBy=default.target
|
|
|
1319
1529
|
print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
|
|
1320
1530
|
print(" Restart your IDE / Agent to start saving tokens automatically.\n")
|
|
1321
1531
|
cls.maybe_prompt_account_login(context="install")
|
|
1322
|
-
cls.
|
|
1532
|
+
cls._ensure_proxy_default("install")
|
|
1323
1533
|
|
|
1324
1534
|
@staticmethod
|
|
1325
1535
|
def _is_tokensafe_mcp_command(cmd: str) -> bool:
|
|
@@ -1661,12 +1871,23 @@ WantedBy=default.target
|
|
|
1661
1871
|
print(f" {GREEN}✔{RESET} Restarted {restarted_count} running TokenSafe MCP daemon(s).")
|
|
1662
1872
|
print(f" {CYAN}ℹ{RESET} Antigravity/Cursor/Claude Code reconnect automatically; reload MCP in Claude Desktop/VS Code if disconnected.")
|
|
1663
1873
|
|
|
1874
|
+
# 7. Proxy re-assertion (ultimate, default-on): TokenSafe is the default LLM
|
|
1875
|
+
# route for every wire-able agent. Agent/app updates are known to rewrite
|
|
1876
|
+
# their own configs and drop third-party routing, so after every update we
|
|
1877
|
+
# reinstall the daemon with the FRESH engine binary and re-claim the wiring.
|
|
1878
|
+
ensure_bin = None
|
|
1879
|
+
for npm_bin in upgraded_npm_bins:
|
|
1880
|
+
cand_bin = os.path.join(os.path.dirname(npm_bin), "tokensafe.cmd" if os.name == "nt" else "tokensafe")
|
|
1881
|
+
if os.path.isfile(cand_bin) and os.access(cand_bin, os.X_OK):
|
|
1882
|
+
ensure_bin = cand_bin
|
|
1883
|
+
break
|
|
1884
|
+
cls._ensure_proxy_default("update", fresh_bin=ensure_bin)
|
|
1885
|
+
|
|
1664
1886
|
print(f"\n{BOLD}{GREEN}✅ Self-update complete!{RESET}")
|
|
1665
1887
|
print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
|
|
1666
1888
|
print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
|
|
1667
1889
|
print(f" {CYAN}ℹ{RESET} If your terminal still shows the old version, open a new window or run {BOLD}hash -r{RESET}.")
|
|
1668
1890
|
cls.maybe_prompt_account_login(context="update")
|
|
1669
|
-
cls.maybe_prompt_proxy_enable(context="update")
|
|
1670
1891
|
|
|
1671
1892
|
def main():
|
|
1672
1893
|
args = sys.argv[1:]
|
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.1
|
|
45
|
+
"version": "4.2.1"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -1864,6 +1864,45 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1864
1864
|
return _fallback_error(name, f"unknown tool '{name}'")
|
|
1865
1865
|
|
|
1866
1866
|
|
|
1867
|
+
def _redact_result_secrets(result):
|
|
1868
|
+
"""Egress guard at the MCP boundary: strips recognized secret patterns from
|
|
1869
|
+
tool results BEFORE they enter any agent's context. Covers every MCP-connected
|
|
1870
|
+
agent (CC, Cursor, Cline, Windsurf, Copilot, Kimi, Codex, Antigravity, ZCode)
|
|
1871
|
+
even when the proxy is not on the path. Same redactor the proxy pipeline uses.
|
|
1872
|
+
Fail-open: any internal problem returns the result untouched."""
|
|
1873
|
+
try:
|
|
1874
|
+
if result is None:
|
|
1875
|
+
return result
|
|
1876
|
+
from src.secret_redactor import SecretRedactor
|
|
1877
|
+
except Exception:
|
|
1878
|
+
return result
|
|
1879
|
+
total = 0
|
|
1880
|
+
|
|
1881
|
+
def _walk(node):
|
|
1882
|
+
nonlocal total
|
|
1883
|
+
if isinstance(node, str):
|
|
1884
|
+
red, n, _ = SecretRedactor.redact_text(node)
|
|
1885
|
+
if n:
|
|
1886
|
+
total += n
|
|
1887
|
+
return red
|
|
1888
|
+
if isinstance(node, dict):
|
|
1889
|
+
return {k: _walk(v) for k, v in node.items()}
|
|
1890
|
+
if isinstance(node, list):
|
|
1891
|
+
return [_walk(v) for v in node]
|
|
1892
|
+
return node
|
|
1893
|
+
|
|
1894
|
+
try:
|
|
1895
|
+
redacted = _walk(result)
|
|
1896
|
+
except Exception:
|
|
1897
|
+
return result
|
|
1898
|
+
if total:
|
|
1899
|
+
try:
|
|
1900
|
+
sys.stderr.write(f"[TokenSafe] MCP egress redaction: {total} secret occurrence(s) stripped from tool result\n")
|
|
1901
|
+
except Exception:
|
|
1902
|
+
pass
|
|
1903
|
+
return redacted
|
|
1904
|
+
|
|
1905
|
+
|
|
1867
1906
|
def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
|
|
1868
1907
|
"""Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
|
|
1869
1908
|
box = {"result": None, "error": None}
|
|
@@ -1977,9 +2016,9 @@ def run_mcp_server():
|
|
|
1977
2016
|
from src.json_repair import parse_tool_arguments
|
|
1978
2017
|
tool_args = parse_tool_arguments(raw_tool_args) or {}
|
|
1979
2018
|
try:
|
|
1980
|
-
response["result"] = _execute_with_timeout(tool_name, tool_args)
|
|
2019
|
+
response["result"] = _redact_result_secrets(_execute_with_timeout(tool_name, tool_args))
|
|
1981
2020
|
except Exception as e:
|
|
1982
|
-
response["result"] = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
|
|
2021
|
+
response["result"] = _redact_result_secrets(_fallback_error(tool_name, f"{type(e).__name__}: {str(e)}"))
|
|
1983
2022
|
finally:
|
|
1984
2023
|
try:
|
|
1985
2024
|
from src.telemetry_sync import TelemetrySync
|
package/src/proxy.py
CHANGED
|
@@ -834,6 +834,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
834
834
|
try:
|
|
835
835
|
openai_payload = _translate_anthropic_payload_to_openai(payload)
|
|
836
836
|
except Exception as e:
|
|
837
|
+
try:
|
|
838
|
+
sys.stderr.write(f"[TokenSafe][debug] translate fail body[:800]={json.dumps(payload)[:800]}\n")
|
|
839
|
+
except Exception:
|
|
840
|
+
pass
|
|
837
841
|
self._send_json_error(400, f"Failed to translate Anthropic payload: {e}")
|
|
838
842
|
return False
|
|
839
843
|
self._client_shape = "anthropic"
|
|
@@ -879,6 +883,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
879
883
|
return self.rfile.read(content_len)
|
|
880
884
|
|
|
881
885
|
def _send_json_error(self, status_code: int, message: str):
|
|
886
|
+
try:
|
|
887
|
+
sys.stderr.write(f"[TokenSafe] {self.command} {self.path} -> {status_code}: {message}\n")
|
|
888
|
+
except Exception:
|
|
889
|
+
pass
|
|
882
890
|
err_bytes = json.dumps({"error": message}).encode("utf-8")
|
|
883
891
|
self.send_response(status_code)
|
|
884
892
|
self.send_header("Content-Type", "application/json")
|
|
@@ -971,7 +979,13 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
971
979
|
|
|
972
980
|
# 4. Resolve Multi-Provider Upstream & API Key (needed before provider-aware cache breakpoints)
|
|
973
981
|
auth_header = self.headers.get("Authorization", "")
|
|
974
|
-
|
|
982
|
+
incoming_key = auth_header[7:].strip() if auth_header.lower().startswith("bearer ") else ""
|
|
983
|
+
if not incoming_key:
|
|
984
|
+
try:
|
|
985
|
+
incoming_key = self.headers.get("x-api-key", "") or ""
|
|
986
|
+
except Exception:
|
|
987
|
+
incoming_key = ""
|
|
988
|
+
custom_url = _apply_route_override(incoming_key, os.environ.get("TOKENSAFE_UPSTREAM_URL", ""))
|
|
975
989
|
|
|
976
990
|
data_dir = resolve_data_dir()
|
|
977
991
|
conf_keys = {}
|
|
@@ -1221,6 +1235,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
1221
1235
|
url = (upstream_url or "").lower()
|
|
1222
1236
|
if "anthropic.com" in url:
|
|
1223
1237
|
return "anthropic"
|
|
1238
|
+
# Anthropic-compatible mirrors (e.g. Z.ai /api/anthropic[/v1/messages]
|
|
1239
|
+
# coding-plan endpoint): same wire dialect, client x-api-key is forwarded as-is.
|
|
1240
|
+
if "/anthropic" in url:
|
|
1241
|
+
return "anthropic"
|
|
1224
1242
|
if "openai.com" in url:
|
|
1225
1243
|
return "openai"
|
|
1226
1244
|
if "googleapis.com" in url or "generativelanguage" in url:
|
|
@@ -1255,6 +1273,39 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
1255
1273
|
return custom_url, (gemini_key or generic_upstream_key)
|
|
1256
1274
|
return custom_url, (deepseek_key or generic_upstream_key or openai_key)
|
|
1257
1275
|
|
|
1276
|
+
def _key_fingerprint(api_key: str) -> str:
|
|
1277
|
+
"""Stable fingerprint of a client API key (never store the key itself)."""
|
|
1278
|
+
import hashlib
|
|
1279
|
+
return hashlib.sha256((api_key or "").strip().encode("utf-8")).hexdigest()[:16]
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
def _load_proxy_routes() -> Dict[str, Any]:
|
|
1283
|
+
"""Per-agent upstream route table written by the installer
|
|
1284
|
+
(fingerprint -> {upstream_url, label}). Read per request so routes
|
|
1285
|
+
added by `tokensafe proxy on` are picked up without a daemon restart."""
|
|
1286
|
+
try:
|
|
1287
|
+
path = os.path.join(resolve_data_dir(), "proxy_routes.json")
|
|
1288
|
+
if os.path.exists(path):
|
|
1289
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
1290
|
+
data = json.load(f)
|
|
1291
|
+
if isinstance(data, dict):
|
|
1292
|
+
return {str(k): v for k, v in data.items() if isinstance(v, dict)}
|
|
1293
|
+
except Exception:
|
|
1294
|
+
pass
|
|
1295
|
+
return {}
|
|
1296
|
+
|
|
1297
|
+
|
|
1298
|
+
def _apply_route_override(incoming_key: str, custom_url: str) -> str:
|
|
1299
|
+
"""Returns the upstream URL for this client key: installer-registered route
|
|
1300
|
+
first (one proxy serves several agents with different providers), then the
|
|
1301
|
+
TOKENSAFE_UPSTREAM_URL env, then the default provider resolution."""
|
|
1302
|
+
if incoming_key:
|
|
1303
|
+
route = _load_proxy_routes().get(_key_fingerprint(incoming_key))
|
|
1304
|
+
if isinstance(route, dict) and route.get("upstream_url"):
|
|
1305
|
+
return str(route["upstream_url"])
|
|
1306
|
+
return custom_url
|
|
1307
|
+
|
|
1308
|
+
|
|
1258
1309
|
def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
|
|
1259
1310
|
# Auto-initialize Knowledge Graph & API Surface on startup
|
|
1260
1311
|
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.1
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.2.1"
|
|
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.1
|
|
20
|
+
CURRENT_VERSION = "4.2.1"
|
|
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
|