tokensafe 4.2.5 → 4.2.7
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/bin/tokensafe.js +1 -0
- package/hooks/session_start.py +18 -0
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +1 -1
- package/server.json +4 -4
- package/skills/token-optimizer/SKILL.md +2 -2
- package/src/adapter_core.py +1 -1
- package/src/cli.py +26 -0
- package/src/installer.py +618 -1
- package/src/mcp_server.py +1 -1
- package/src/proxy.py +19 -5
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/bin/tokensafe.js
CHANGED
|
@@ -136,6 +136,7 @@ Commands:
|
|
|
136
136
|
tokensafe license Show current license status and active tier
|
|
137
137
|
tokensafe update One-click self-update for npm, pip & all AI agent rules
|
|
138
138
|
tokensafe install Interactive installer for Cursor, Antigravity, Claude, etc.
|
|
139
|
+
tokensafe uninstall Uninstall TokenSafe from AI agents, unwire proxy & clean rules
|
|
139
140
|
tokensafe --help Show this help screen
|
|
140
141
|
`);
|
|
141
142
|
process.exit(0);
|
package/hooks/session_start.py
CHANGED
|
@@ -71,6 +71,24 @@ def main():
|
|
|
71
71
|
{"systemMessage": {"systemMessage": PROTOCOL_DIRECTIVES, "metadata": {}}}
|
|
72
72
|
]
|
|
73
73
|
|
|
74
|
+
try:
|
|
75
|
+
from src.graph_engine import GraphEngine
|
|
76
|
+
graph = GraphEngine.get_instance(workspace_root)
|
|
77
|
+
banner = graph.format_topology_banner()
|
|
78
|
+
if banner:
|
|
79
|
+
inject_steps.append({
|
|
80
|
+
"systemMessage": {
|
|
81
|
+
"systemMessage": (
|
|
82
|
+
f"{banner}\n"
|
|
83
|
+
"⚡ Core God Nodes and dependency hubs mapped above. "
|
|
84
|
+
"Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
|
|
85
|
+
),
|
|
86
|
+
"metadata": {},
|
|
87
|
+
}
|
|
88
|
+
})
|
|
89
|
+
except Exception:
|
|
90
|
+
pass
|
|
91
|
+
|
|
74
92
|
try:
|
|
75
93
|
tracker = MetricsTracker()
|
|
76
94
|
quota = LicenseManager.check_quota(tracker)
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.2.
|
|
3
|
+
"version": "4.2.7",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.2.
|
|
4
|
+
"version": "4.2.7",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.2.
|
|
4
|
+
"version": "4.2.7",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"logo": "https://tokensafe.dev/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/rules/AGENTS.md
CHANGED
|
@@ -32,7 +32,7 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
32
32
|
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `"src/service.ts"` or absolute) and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview). Lockfiles (`package-lock.json`, `Cargo.lock`) and tabular data (`.csv`, `.tsv`, `.sql`, `.har`) auto-reduce to compact schemas with reversible hash anchors.
|
|
33
33
|
3. **Reversible Hash Stashing (`expand_ref`)**: Whenever TokenSafe folds a long command output, test log, file, or MCP payload, it tags it with an 8-character hash `[TokenSafe folded: #a1b2c3d4 ...]`. If full raw content is ever needed, ALWAYS call `tokensafe:expand_ref(hash="a1b2c3d4")` or run `tokensafe expand-ref a1b2c3d4` to retrieve the exact original bytes without re-running.
|
|
34
34
|
4. **Web & Documentation Reading (`read_web_page`)**: To read web pages, documentation, or API references, ALWAYS call `tokensafe:read_web_page(url)` or run `tokensafe web <url>` instead of raw HTML fetches — it strips scripts, styles, navbars, and cookie banners (-80-95% tokens).
|
|
35
|
-
5. **Architecture
|
|
35
|
+
5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path=".")` to locate God Nodes and dependency topology in < 250 tokens before reading individual files or searching (`project_path` defaults to active workspace).
|
|
36
36
|
6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path=".")` to get all exported classes, types, and interfaces in a single markdown map without crawling files.
|
|
37
37
|
7. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
|
|
38
38
|
8. **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). Supports relative subfolders (`path="src"`).
|
package/server.json
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
|
-
"description": "Your AI agent is smart enough to code all day.
|
|
6
|
-
"version": "4.2.
|
|
5
|
+
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
+
"version": "4.2.7",
|
|
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.2.
|
|
33
|
+
"version": "4.2.7",
|
|
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.2.
|
|
49
|
+
"version": "4.2.7",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -31,8 +31,8 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
31
31
|
- **Schema Auto-Slicing**: OpenAPI/Swagger, Prisma, GraphQL and SQL files bypass AST skeletonization. Pass the spec path (`/users/{id}`), Prisma model, GraphQL type, or SQL table as `symbol` for a targeted slice with 1-hop references; an empty `symbol` returns a compact overview (paths/models/types/tables index) instead of a 20k-50k token dump.
|
|
32
32
|
- **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -98% tokens).
|
|
33
33
|
|
|
34
|
-
3. **ARCHITECTURE
|
|
35
|
-
-
|
|
34
|
+
3. **MANDATORY ARCHITECTURE GRAPH & GOD NODES FIRST (`get_architecture_graph`)**:
|
|
35
|
+
- For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path=".")` (`project_path` defaults to active workspace) before diving into individual files or running searches.
|
|
36
36
|
- **Result**: Returns top architectural God Nodes, dependency hubs, and centrality rankings in < 250 tokens without file crawling.
|
|
37
37
|
|
|
38
38
|
4. **API SURFACE INSPECTION (`get_api_surface`)**:
|
package/src/adapter_core.py
CHANGED
|
@@ -38,7 +38,7 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
38
38
|
"• Zero-Fluff Egress: Omit conversational filler, courtesy preambles, and wrap-ups. Format responses in dense, technical prose.\n"
|
|
39
39
|
"• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.\n"
|
|
40
40
|
"• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
|
|
41
|
-
"•
|
|
41
|
+
"• Mandatory Architecture Graph & God Nodes: For any codebase navigation, feature design, or multi-component investigation, ALWAYS inspect God Nodes via 'tokensafe:get_architecture_graph(project_path)' first before diving into individual files.\n"
|
|
42
42
|
"• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
|
|
43
43
|
"• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check context headroom and Quality Score (Grade S-F).\n"
|
|
44
44
|
"• When context_budget reports warning/critical or Grade C/F: call 'tokensafe:compact_conversation(transcript_path=...)' to fold history before continuing.\n"
|
package/src/cli.py
CHANGED
|
@@ -115,6 +115,7 @@ def _print_help():
|
|
|
115
115
|
print(" vacuum Reclaim SQLite disk space")
|
|
116
116
|
print(" reset Reset all local token metrics")
|
|
117
117
|
print(" install | setup [--all] Configure detected agent environments")
|
|
118
|
+
print(" uninstall [--all | --project] Remove TokenSafe from agent environments & unwire proxy")
|
|
118
119
|
print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
|
|
119
120
|
print(" check-update Check for a newer published version")
|
|
120
121
|
print(" activate / license License activation and status")
|
|
@@ -416,6 +417,31 @@ def main(argv: Optional[List[str]] = None):
|
|
|
416
417
|
else:
|
|
417
418
|
AgentInstaller.run_interactive()
|
|
418
419
|
|
|
420
|
+
elif command in ("uninstall", "unistall", "remove", "unlink-all"):
|
|
421
|
+
from src.installer import AgentInstaller
|
|
422
|
+
purge = "--purge" in args
|
|
423
|
+
if "--all" in args or "-a" in args or "-y" in args or "--auto" in args:
|
|
424
|
+
print("\n\033[1m\033[36m⚡ TOKENSAFE UNIVERSAL MULTI-AGENT UNINSTALLER (--all) ⚡\033[0m\n")
|
|
425
|
+
res = AgentInstaller.uninstall_all(force=True, purge=purge)
|
|
426
|
+
print("Uninstalled AI agent configurations:")
|
|
427
|
+
for k, r in res["agents"].items():
|
|
428
|
+
status = "\033[32m✔\033[0m" if r["success"] else "\033[33m–\033[0m"
|
|
429
|
+
print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
|
|
430
|
+
if res.get("project_rules"):
|
|
431
|
+
print(f"\n\033[32m✔ Project rules cleaned from: {', '.join(res['project_rules'])}\033[0m")
|
|
432
|
+
if res.get("proxy"):
|
|
433
|
+
print(f" \033[32m✔\033[0m Proxy daemon stopped and routing restored")
|
|
434
|
+
if purge:
|
|
435
|
+
print(f" \033[32m✔\033[0m Local data directory purged (~/.tokensafe)")
|
|
436
|
+
print("\n\033[32m✔ TokenSafe uninstallation complete.\033[0m\n")
|
|
437
|
+
elif "--project" in args:
|
|
438
|
+
res = AgentInstaller.uninstall_project(os.getcwd())
|
|
439
|
+
cleaned = res.get("cleaned_rules", [])
|
|
440
|
+
msg = f"TokenSafe rules cleaned from project: {', '.join(cleaned)}" if cleaned else "No TokenSafe rules found in project workspace"
|
|
441
|
+
print(f"\n\033[32m✔ {msg}\033[0m\n")
|
|
442
|
+
else:
|
|
443
|
+
AgentInstaller.run_interactive_uninstall()
|
|
444
|
+
|
|
419
445
|
elif command in ("update", "upgrade"):
|
|
420
446
|
from src.installer import AgentInstaller
|
|
421
447
|
AgentInstaller.self_update()
|
package/src/installer.py
CHANGED
|
@@ -51,7 +51,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
51
51
|
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `'src/service.ts'` or absolute) and `symbol`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).\n"
|
|
52
52
|
"3. **Repeat Read Deduplication**: Never repeatedly re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`); pass `force_full=true` only if context was compacted or you are a fresh subagent.\n"
|
|
53
53
|
"4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler, courtesy preambles, and sign-offs. Provide concise bullet prose. Never reprint full unmodified files or lengthy boilerplate; link to file line ranges (`file.ts#L10-L25`) and output surgical diffs.\n"
|
|
54
|
-
"5. **Architecture
|
|
54
|
+
"5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path='.')` to inspect project God Nodes and key dependency hubs in < 250 tokens before reading individual files or searching.\n"
|
|
55
55
|
"6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path='.')` to get all exported classes, types, and interfaces in a single markdown map without crawling files.\n"
|
|
56
56
|
"7. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path='.', depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path='src'`).\n"
|
|
57
57
|
"8. **Command Sanitization, Build Compaction & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `git push` --no-progress, `git commit` hook protection, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`, and build/typecheck commands like `npm run build`, `vite build`, `next build`, `cargo build`, `tsc`, `tsc --noEmit`, `npm run typecheck`, `npx eslint`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, `go test`) via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 1-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest`/`bun` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
|
|
@@ -424,6 +424,195 @@ class AgentInstaller:
|
|
|
424
424
|
cls._atomic_write_json(config_file, data)
|
|
425
425
|
return True, "guards registered (shell + junk-read + prompt pipeline)"
|
|
426
426
|
|
|
427
|
+
@classmethod
|
|
428
|
+
def uninstall_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
429
|
+
"""Removes TokenSafe lifecycle hooks from agents that support them."""
|
|
430
|
+
if agent_key not in ("claude_code", "cursor", "kimi", "zcode"):
|
|
431
|
+
return True, ""
|
|
432
|
+
|
|
433
|
+
if agent_key == "kimi":
|
|
434
|
+
config_file = os.path.join(HOME, ".kimi-code", "config.toml")
|
|
435
|
+
if not os.path.exists(config_file):
|
|
436
|
+
return True, "Kimi Code config.toml not found"
|
|
437
|
+
try:
|
|
438
|
+
shutil.copy2(config_file, f"{config_file}.backup")
|
|
439
|
+
except Exception:
|
|
440
|
+
pass
|
|
441
|
+
try:
|
|
442
|
+
with open(config_file, "r", encoding="utf-8") as f:
|
|
443
|
+
content = f.read()
|
|
444
|
+
except Exception:
|
|
445
|
+
return False, f"Could not read {config_file}"
|
|
446
|
+
|
|
447
|
+
sections = re.split(r'(?m)^(?=\[\[hooks\]\])', content)
|
|
448
|
+
keep = []
|
|
449
|
+
removed = False
|
|
450
|
+
for s in sections:
|
|
451
|
+
if "kimi_hook.py" in s:
|
|
452
|
+
removed = True
|
|
453
|
+
continue
|
|
454
|
+
keep.append(s)
|
|
455
|
+
|
|
456
|
+
new_content = "".join(keep)
|
|
457
|
+
new_content = re.sub(r'(?m)^[ \t]*#[ \t]*TokenSafe[^\n]*\n?', '', new_content)
|
|
458
|
+
cleaned = new_content.strip()
|
|
459
|
+
if not cleaned:
|
|
460
|
+
try:
|
|
461
|
+
os.remove(config_file)
|
|
462
|
+
return True, "Removed hooks from ~/.kimi-code/config.toml (file removed)"
|
|
463
|
+
except Exception:
|
|
464
|
+
pass
|
|
465
|
+
|
|
466
|
+
with open(config_file, "w", encoding="utf-8") as f:
|
|
467
|
+
f.write(cleaned + "\n" if cleaned else "")
|
|
468
|
+
return True, "Removed TokenSafe hooks from ~/.kimi-code/config.toml" if removed else "No TokenSafe hooks in config.toml"
|
|
469
|
+
|
|
470
|
+
if agent_key == "claude_code":
|
|
471
|
+
config_file = os.path.join(HOME, ".claude", "settings.json")
|
|
472
|
+
if not os.path.exists(config_file):
|
|
473
|
+
return True, "Claude Code settings.json not found"
|
|
474
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
475
|
+
if err or data is None:
|
|
476
|
+
return False, err or f"Failed to parse {config_file}"
|
|
477
|
+
hooks = data.get("hooks")
|
|
478
|
+
if not isinstance(hooks, dict):
|
|
479
|
+
return True, "No hooks in Claude Code settings.json"
|
|
480
|
+
|
|
481
|
+
changed = False
|
|
482
|
+
for event_name in list(hooks.keys()):
|
|
483
|
+
entries = hooks.get(event_name)
|
|
484
|
+
if not isinstance(entries, list):
|
|
485
|
+
continue
|
|
486
|
+
new_entries = []
|
|
487
|
+
for entry in entries:
|
|
488
|
+
if isinstance(entry, dict) and isinstance(entry.get("hooks"), list):
|
|
489
|
+
remaining = [
|
|
490
|
+
h for h in entry["hooks"]
|
|
491
|
+
if not (isinstance(h, dict) and "claude_code_hook.py" in str(h.get("command", "")))
|
|
492
|
+
]
|
|
493
|
+
if len(remaining) != len(entry["hooks"]):
|
|
494
|
+
changed = True
|
|
495
|
+
if remaining:
|
|
496
|
+
entry["hooks"] = remaining
|
|
497
|
+
new_entries.append(entry)
|
|
498
|
+
else:
|
|
499
|
+
new_entries.append(entry)
|
|
500
|
+
if new_entries:
|
|
501
|
+
hooks[event_name] = new_entries
|
|
502
|
+
else:
|
|
503
|
+
hooks.pop(event_name, None)
|
|
504
|
+
changed = True
|
|
505
|
+
|
|
506
|
+
if changed:
|
|
507
|
+
if not hooks:
|
|
508
|
+
data.pop("hooks", None)
|
|
509
|
+
else:
|
|
510
|
+
data["hooks"] = hooks
|
|
511
|
+
cls._atomic_write_json(config_file, data)
|
|
512
|
+
return True, "Removed TokenSafe hooks from Claude Code settings.json"
|
|
513
|
+
return True, "No TokenSafe hooks found in Claude Code settings.json"
|
|
514
|
+
|
|
515
|
+
if agent_key == "zcode":
|
|
516
|
+
config_file = os.path.join(HOME, ".zcode", "cli", "config.json")
|
|
517
|
+
if not os.path.exists(config_file):
|
|
518
|
+
return True, "ZCode config.json not found"
|
|
519
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
520
|
+
if err or data is None:
|
|
521
|
+
return False, err or f"Failed to parse {config_file}"
|
|
522
|
+
hooks_block = data.get("hooks")
|
|
523
|
+
if not isinstance(hooks_block, dict):
|
|
524
|
+
return True, "No hooks in ZCode config.json"
|
|
525
|
+
events = hooks_block.get("events")
|
|
526
|
+
if not isinstance(events, dict):
|
|
527
|
+
return True, "No events in ZCode hooks"
|
|
528
|
+
|
|
529
|
+
tokensafe_scripts = ("session_start.py", "pre_invocation.py", "pre_tool_use.py", "post_tool_use.py", "stop_hook.py")
|
|
530
|
+
changed = False
|
|
531
|
+
for event_name in list(events.keys()):
|
|
532
|
+
entries = events.get(event_name)
|
|
533
|
+
if not isinstance(entries, list):
|
|
534
|
+
continue
|
|
535
|
+
new_entries = []
|
|
536
|
+
for entry in entries:
|
|
537
|
+
if isinstance(entry, dict) and isinstance(entry.get("hooks"), list):
|
|
538
|
+
remaining = []
|
|
539
|
+
for h in entry["hooks"]:
|
|
540
|
+
args = h.get("args") if isinstance(h, dict) else []
|
|
541
|
+
is_ts = False
|
|
542
|
+
if isinstance(args, list):
|
|
543
|
+
for a in args:
|
|
544
|
+
if isinstance(a, str) and (any(a.endswith(s) for s in tokensafe_scripts) or "tokensafe" in a):
|
|
545
|
+
is_ts = True
|
|
546
|
+
break
|
|
547
|
+
if not is_ts:
|
|
548
|
+
remaining.append(h)
|
|
549
|
+
else:
|
|
550
|
+
changed = True
|
|
551
|
+
if remaining:
|
|
552
|
+
entry["hooks"] = remaining
|
|
553
|
+
new_entries.append(entry)
|
|
554
|
+
else:
|
|
555
|
+
new_entries.append(entry)
|
|
556
|
+
if new_entries:
|
|
557
|
+
events[event_name] = new_entries
|
|
558
|
+
else:
|
|
559
|
+
events.pop(event_name, None)
|
|
560
|
+
changed = True
|
|
561
|
+
|
|
562
|
+
if changed:
|
|
563
|
+
if not events:
|
|
564
|
+
hooks_block.pop("events", None)
|
|
565
|
+
if list(hooks_block.keys()) == ["enabled"]:
|
|
566
|
+
data.pop("hooks", None)
|
|
567
|
+
else:
|
|
568
|
+
data["hooks"] = hooks_block
|
|
569
|
+
else:
|
|
570
|
+
hooks_block["events"] = events
|
|
571
|
+
data["hooks"] = hooks_block
|
|
572
|
+
cls._atomic_write_json(config_file, data)
|
|
573
|
+
return True, "Removed TokenSafe hooks from ZCode config.json"
|
|
574
|
+
return True, "No TokenSafe hooks found in ZCode config.json"
|
|
575
|
+
|
|
576
|
+
# cursor
|
|
577
|
+
config_file = os.path.join(HOME, ".cursor", "hooks.json")
|
|
578
|
+
if not os.path.exists(config_file):
|
|
579
|
+
return True, "Cursor hooks.json not found"
|
|
580
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
581
|
+
if err or data is None:
|
|
582
|
+
return False, err or f"Failed to parse {config_file}"
|
|
583
|
+
hooks = data.get("hooks")
|
|
584
|
+
if not isinstance(hooks, dict):
|
|
585
|
+
return True, "No hooks in Cursor hooks.json"
|
|
586
|
+
|
|
587
|
+
changed = False
|
|
588
|
+
for event_name in list(hooks.keys()):
|
|
589
|
+
entries = hooks.get(event_name)
|
|
590
|
+
if not isinstance(entries, list):
|
|
591
|
+
continue
|
|
592
|
+
new_entries = [
|
|
593
|
+
e for e in entries
|
|
594
|
+
if not (isinstance(e, dict) and "cursor_hook.py" in str(e.get("command", "")))
|
|
595
|
+
]
|
|
596
|
+
if len(new_entries) != len(entries):
|
|
597
|
+
changed = True
|
|
598
|
+
if new_entries:
|
|
599
|
+
hooks[event_name] = new_entries
|
|
600
|
+
else:
|
|
601
|
+
hooks.pop(event_name, None)
|
|
602
|
+
changed = True
|
|
603
|
+
|
|
604
|
+
if changed:
|
|
605
|
+
if not hooks:
|
|
606
|
+
try:
|
|
607
|
+
os.remove(config_file)
|
|
608
|
+
except Exception:
|
|
609
|
+
cls._atomic_write_json(config_file, {})
|
|
610
|
+
else:
|
|
611
|
+
data["hooks"] = hooks
|
|
612
|
+
cls._atomic_write_json(config_file, data)
|
|
613
|
+
return True, "Removed TokenSafe guards from Cursor hooks.json"
|
|
614
|
+
return True, "No TokenSafe guards found in Cursor hooks.json"
|
|
615
|
+
|
|
427
616
|
# ------------------------------------------------------------------
|
|
428
617
|
# Proxy auto-wiring (v3.0.0): daemon + per-agent base URL override with
|
|
429
618
|
# one-command rollback. Only agents that CAN be wired programmatically
|
|
@@ -1266,6 +1455,185 @@ WantedBy=default.target
|
|
|
1266
1455
|
|
|
1267
1456
|
return False, "Unsupported type"
|
|
1268
1457
|
|
|
1458
|
+
@staticmethod
|
|
1459
|
+
def _remove_path_safely(target_path: Optional[str]) -> bool:
|
|
1460
|
+
"""Safely removes a file, symlink, or directory. Returns True if removed."""
|
|
1461
|
+
if not target_path:
|
|
1462
|
+
return False
|
|
1463
|
+
if os.path.islink(target_path) or os.path.isfile(target_path):
|
|
1464
|
+
try:
|
|
1465
|
+
os.unlink(target_path)
|
|
1466
|
+
return True
|
|
1467
|
+
except Exception:
|
|
1468
|
+
return False
|
|
1469
|
+
elif os.path.isdir(target_path):
|
|
1470
|
+
try:
|
|
1471
|
+
shutil.rmtree(target_path)
|
|
1472
|
+
return True
|
|
1473
|
+
except Exception:
|
|
1474
|
+
return False
|
|
1475
|
+
return False
|
|
1476
|
+
|
|
1477
|
+
@classmethod
|
|
1478
|
+
def uninstall_mcp_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
1479
|
+
"""Removes TokenSafe MCP server, skills, rules, and plugins from the target agent."""
|
|
1480
|
+
info = AGENTS_REGISTRY.get(agent_key)
|
|
1481
|
+
if not info:
|
|
1482
|
+
return False, f"Unknown agent: {agent_key}"
|
|
1483
|
+
|
|
1484
|
+
if info["type"] == "plugin":
|
|
1485
|
+
target = info["target_path"]
|
|
1486
|
+
legacy = info.get("legacy_path")
|
|
1487
|
+
r1 = cls._remove_path_safely(target)
|
|
1488
|
+
r2 = False
|
|
1489
|
+
if legacy and os.path.islink(legacy):
|
|
1490
|
+
r2 = cls._remove_path_safely(legacy)
|
|
1491
|
+
r3 = cls._remove_user_level_tokensafe_mcp()
|
|
1492
|
+
if r1 or r2 or r3:
|
|
1493
|
+
return True, f"Removed TokenSafe plugin from Antigravity ({target})"
|
|
1494
|
+
return True, "TokenSafe plugin not found in Antigravity"
|
|
1495
|
+
|
|
1496
|
+
elif info["type"] == "cursor_env":
|
|
1497
|
+
config_file = info["config_path"]
|
|
1498
|
+
if os.path.exists(config_file):
|
|
1499
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
1500
|
+
if not err and data and isinstance(data.get("mcpServers"), dict):
|
|
1501
|
+
if "tokensafe" in data["mcpServers"]:
|
|
1502
|
+
data["mcpServers"].pop("tokensafe")
|
|
1503
|
+
cls._atomic_write_json(config_file, data)
|
|
1504
|
+
|
|
1505
|
+
cls._remove_path_safely(info.get("skills_path"))
|
|
1506
|
+
cls._remove_path_safely(info.get("extension_path"))
|
|
1507
|
+
cls._remove_path_safely(info.get("rules_path"))
|
|
1508
|
+
cls._remove_global_rule(os.path.join(HOME, ".cursorrules"))
|
|
1509
|
+
return True, "Removed MCP, Extension & Rules for Cursor"
|
|
1510
|
+
|
|
1511
|
+
elif info["type"] == "mcp_json":
|
|
1512
|
+
config_file = info["config_path"]
|
|
1513
|
+
if os.path.exists(config_file):
|
|
1514
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
1515
|
+
if not err and data and isinstance(data.get("mcpServers"), dict):
|
|
1516
|
+
if "tokensafe" in data["mcpServers"]:
|
|
1517
|
+
data["mcpServers"].pop("tokensafe")
|
|
1518
|
+
cls._atomic_write_json(config_file, data)
|
|
1519
|
+
|
|
1520
|
+
if "skills_path" in info:
|
|
1521
|
+
cls._remove_path_safely(info["skills_path"])
|
|
1522
|
+
|
|
1523
|
+
if "rules_path" in info:
|
|
1524
|
+
if info["rules_path"].endswith("Rule_TokenSafe.md"):
|
|
1525
|
+
cls._remove_path_safely(info["rules_path"])
|
|
1526
|
+
else:
|
|
1527
|
+
cls._remove_global_rule(info["rules_path"])
|
|
1528
|
+
|
|
1529
|
+
return True, f"Removed MCP & Rules from {config_file}"
|
|
1530
|
+
|
|
1531
|
+
elif info["type"] == "codex_toml":
|
|
1532
|
+
config_file = info["config_path"]
|
|
1533
|
+
if os.path.exists(config_file):
|
|
1534
|
+
try:
|
|
1535
|
+
with open(config_file, "r", encoding="utf-8") as f:
|
|
1536
|
+
content = f.read()
|
|
1537
|
+
if re.search(r'(?m)^\[mcp_servers\.tokensafe\]\s*$', content):
|
|
1538
|
+
shutil.copy2(config_file, f"{config_file}.backup")
|
|
1539
|
+
pattern = re.compile(r'(?ms)^\[mcp_servers\.tokensafe\]\s*\n(?:(?!^\[).)*')
|
|
1540
|
+
content = pattern.sub("", content)
|
|
1541
|
+
with open(config_file, "w", encoding="utf-8") as f:
|
|
1542
|
+
f.write(content.strip() + "\n" if content.strip() else "")
|
|
1543
|
+
except Exception:
|
|
1544
|
+
pass
|
|
1545
|
+
|
|
1546
|
+
if "skills_path" in info:
|
|
1547
|
+
cls._remove_path_safely(info["skills_path"])
|
|
1548
|
+
|
|
1549
|
+
if "plugin_path" in info:
|
|
1550
|
+
cls._remove_path_safely(info["plugin_path"])
|
|
1551
|
+
|
|
1552
|
+
if "agents_md_path" in info:
|
|
1553
|
+
cls._remove_global_rule(info["agents_md_path"])
|
|
1554
|
+
|
|
1555
|
+
return True, f"Removed MCP, Plugin, Skill & AGENTS.md for Codex ({config_file})"
|
|
1556
|
+
|
|
1557
|
+
elif info["type"] == "claude_md":
|
|
1558
|
+
if "config_path" in info and os.path.exists(info["config_path"]):
|
|
1559
|
+
config_file = info["config_path"]
|
|
1560
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
1561
|
+
if not err and data and isinstance(data.get("mcpServers"), dict):
|
|
1562
|
+
if "tokensafe" in data["mcpServers"]:
|
|
1563
|
+
data["mcpServers"].pop("tokensafe")
|
|
1564
|
+
cls._atomic_write_json(config_file, data)
|
|
1565
|
+
|
|
1566
|
+
if "agents_md_path" in info:
|
|
1567
|
+
cls._remove_global_rule(info["agents_md_path"])
|
|
1568
|
+
|
|
1569
|
+
if "skills_path" in info:
|
|
1570
|
+
cls._remove_path_safely(info["skills_path"])
|
|
1571
|
+
|
|
1572
|
+
return True, f"Removed MCP, Rule & Skill for Claude Code ({info.get('agents_md_path')})"
|
|
1573
|
+
|
|
1574
|
+
elif info["type"] == "copilot_json":
|
|
1575
|
+
config_file = info["config_path"]
|
|
1576
|
+
if os.path.exists(config_file):
|
|
1577
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
1578
|
+
if not err and data and isinstance(data.get("mcpServers"), dict):
|
|
1579
|
+
if "tokensafe" in data["mcpServers"]:
|
|
1580
|
+
data["mcpServers"].pop("tokensafe")
|
|
1581
|
+
cls._atomic_write_json(config_file, data)
|
|
1582
|
+
return True, f"Removed MCP for GitHub Copilot in {config_file}"
|
|
1583
|
+
|
|
1584
|
+
elif info["type"] == "zcode_json":
|
|
1585
|
+
config_file = info["config_path"]
|
|
1586
|
+
if os.path.exists(config_file):
|
|
1587
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
1588
|
+
if not err and data:
|
|
1589
|
+
mcp = data.get("mcp")
|
|
1590
|
+
if isinstance(mcp, dict) and isinstance(mcp.get("servers"), dict):
|
|
1591
|
+
if "tokensafe" in mcp["servers"]:
|
|
1592
|
+
mcp["servers"].pop("tokensafe")
|
|
1593
|
+
cls._atomic_write_json(config_file, data)
|
|
1594
|
+
|
|
1595
|
+
if "skills_path" in info:
|
|
1596
|
+
cls._remove_path_safely(info["skills_path"])
|
|
1597
|
+
|
|
1598
|
+
if "plugin_path" in info:
|
|
1599
|
+
cls._remove_path_safely(info["plugin_path"])
|
|
1600
|
+
|
|
1601
|
+
if "agents_md_path" in info:
|
|
1602
|
+
cls._remove_global_rule(info["agents_md_path"])
|
|
1603
|
+
|
|
1604
|
+
return True, f"Removed MCP, Plugin, Skill & AGENTS.md for Z.ai Code ({config_file})"
|
|
1605
|
+
|
|
1606
|
+
elif info["type"] == "kimi_plugin":
|
|
1607
|
+
mcp_file = info.get("config_path")
|
|
1608
|
+
if mcp_file and os.path.exists(mcp_file):
|
|
1609
|
+
data, err = cls._load_json_with_backup(mcp_file)
|
|
1610
|
+
if not err and data and isinstance(data.get("mcpServers"), dict):
|
|
1611
|
+
if "tokensafe" in data["mcpServers"]:
|
|
1612
|
+
data["mcpServers"].pop("tokensafe")
|
|
1613
|
+
cls._atomic_write_json(mcp_file, data)
|
|
1614
|
+
|
|
1615
|
+
managed_plugin_path = info.get("managed_plugin_path")
|
|
1616
|
+
if managed_plugin_path:
|
|
1617
|
+
cls._remove_path_safely(managed_plugin_path)
|
|
1618
|
+
|
|
1619
|
+
installed_json = info.get("installed_json_path")
|
|
1620
|
+
if installed_json and os.path.exists(installed_json):
|
|
1621
|
+
inst_data, err = cls._load_json_with_backup(installed_json)
|
|
1622
|
+
if not err and inst_data and isinstance(inst_data.get("plugins"), list):
|
|
1623
|
+
inst_data["plugins"] = [
|
|
1624
|
+
p for p in inst_data["plugins"]
|
|
1625
|
+
if not (isinstance(p, dict) and p.get("id") == "tokensafe")
|
|
1626
|
+
]
|
|
1627
|
+
cls._atomic_write_json(installed_json, inst_data)
|
|
1628
|
+
|
|
1629
|
+
if "skills_path" in info:
|
|
1630
|
+
cls._remove_path_safely(info["skills_path"])
|
|
1631
|
+
|
|
1632
|
+
if "agents_md_path" in info:
|
|
1633
|
+
cls._remove_global_rule(info["agents_md_path"])
|
|
1634
|
+
|
|
1635
|
+
return True, "Removed MCP, Plugin, Skill & AGENTS.md for Kimi Code"
|
|
1636
|
+
|
|
1269
1637
|
@staticmethod
|
|
1270
1638
|
def _remove_user_level_tokensafe_mcp() -> bool:
|
|
1271
1639
|
"""Removes the tokensafe MCP entry from Antigravity's user-level
|
|
@@ -1353,6 +1721,43 @@ WantedBy=default.target
|
|
|
1353
1721
|
with open(file_path, "w", encoding="utf-8") as f:
|
|
1354
1722
|
f.write(new_content)
|
|
1355
1723
|
|
|
1724
|
+
@classmethod
|
|
1725
|
+
def _remove_global_rule(cls, file_path: Optional[str], tag: str = "tokensafe") -> bool:
|
|
1726
|
+
"""Removes a delimited rule block from a markdown instruction file.
|
|
1727
|
+
Returns True if a rule block was found and stripped."""
|
|
1728
|
+
if not file_path or not os.path.exists(file_path):
|
|
1729
|
+
return False
|
|
1730
|
+
try:
|
|
1731
|
+
with open(file_path, "r", encoding="utf-8") as f:
|
|
1732
|
+
content = f.read()
|
|
1733
|
+
except Exception:
|
|
1734
|
+
return False
|
|
1735
|
+
|
|
1736
|
+
start_tag = f"<!-- {tag} -->"
|
|
1737
|
+
end_tag = f"<!-- /{tag} -->"
|
|
1738
|
+
pattern = re.compile(rf"[ \t]*{re.escape(start_tag)}.*?{re.escape(end_tag)}[ \t]*\n?", re.DOTALL)
|
|
1739
|
+
if not re.search(pattern, content) and start_tag not in content:
|
|
1740
|
+
return False
|
|
1741
|
+
|
|
1742
|
+
new_content = pattern.sub("", content)
|
|
1743
|
+
if start_tag in new_content:
|
|
1744
|
+
new_content = re.sub(rf"[ \t]*{re.escape(start_tag)}.*", "", new_content)
|
|
1745
|
+
|
|
1746
|
+
cleaned = new_content.strip()
|
|
1747
|
+
if not cleaned:
|
|
1748
|
+
try:
|
|
1749
|
+
os.remove(file_path)
|
|
1750
|
+
return True
|
|
1751
|
+
except Exception:
|
|
1752
|
+
pass
|
|
1753
|
+
|
|
1754
|
+
try:
|
|
1755
|
+
with open(file_path, "w", encoding="utf-8") as f:
|
|
1756
|
+
f.write(cleaned + "\n" if cleaned else "")
|
|
1757
|
+
return True
|
|
1758
|
+
except Exception:
|
|
1759
|
+
return False
|
|
1760
|
+
|
|
1356
1761
|
@classmethod
|
|
1357
1762
|
def _symlink_skill(cls, target_path: str):
|
|
1358
1763
|
"""Symlinks the TokenSafe skill into the target agent's skills directory."""
|
|
@@ -1557,6 +1962,218 @@ WantedBy=default.target
|
|
|
1557
1962
|
cls.maybe_prompt_account_login(context="install")
|
|
1558
1963
|
cls._ensure_proxy_default("install")
|
|
1559
1964
|
|
|
1965
|
+
@classmethod
|
|
1966
|
+
def uninstall_project(cls, project_dir: Optional[str] = None) -> Dict[str, Any]:
|
|
1967
|
+
"""Removes TokenSafe rules, project MCP configs, and .gitignore references from a project workspace."""
|
|
1968
|
+
if not project_dir:
|
|
1969
|
+
project_dir = os.getcwd()
|
|
1970
|
+
project_dir = os.path.abspath(project_dir)
|
|
1971
|
+
|
|
1972
|
+
rule_files = [
|
|
1973
|
+
os.path.join(project_dir, "AGENTS.md"),
|
|
1974
|
+
os.path.join(project_dir, "CLAUDE.md"),
|
|
1975
|
+
os.path.join(project_dir, ".cursorrules"),
|
|
1976
|
+
os.path.join(project_dir, ".windsurfrules"),
|
|
1977
|
+
os.path.join(project_dir, ".clinerules"),
|
|
1978
|
+
os.path.join(project_dir, ".github", "copilot-instructions.md"),
|
|
1979
|
+
]
|
|
1980
|
+
cleaned = []
|
|
1981
|
+
for rf in rule_files:
|
|
1982
|
+
try:
|
|
1983
|
+
if cls._remove_global_rule(rf):
|
|
1984
|
+
cleaned.append(os.path.relpath(rf, project_dir))
|
|
1985
|
+
except Exception:
|
|
1986
|
+
pass
|
|
1987
|
+
|
|
1988
|
+
# Remove .cursor/rules/tokensafe.mdc if present
|
|
1989
|
+
cursor_mdc = os.path.join(project_dir, ".cursor", "rules", "tokensafe.mdc")
|
|
1990
|
+
if cls._remove_path_safely(cursor_mdc):
|
|
1991
|
+
cleaned.append(".cursor/rules/tokensafe.mdc")
|
|
1992
|
+
|
|
1993
|
+
# Clean project-local .cursor/mcp.json
|
|
1994
|
+
cursor_mcp = os.path.join(project_dir, ".cursor", "mcp.json")
|
|
1995
|
+
if os.path.exists(cursor_mcp):
|
|
1996
|
+
try:
|
|
1997
|
+
data, err = cls._load_json_with_backup(cursor_mcp)
|
|
1998
|
+
if not err and data and isinstance(data.get("mcpServers"), dict):
|
|
1999
|
+
if "tokensafe" in data["mcpServers"]:
|
|
2000
|
+
data["mcpServers"].pop("tokensafe")
|
|
2001
|
+
if not data["mcpServers"] and list(data.keys()) == ["mcpServers"]:
|
|
2002
|
+
os.remove(cursor_mcp)
|
|
2003
|
+
else:
|
|
2004
|
+
cls._atomic_write_json(cursor_mcp, data)
|
|
2005
|
+
cleaned.append(".cursor/mcp.json")
|
|
2006
|
+
except Exception:
|
|
2007
|
+
pass
|
|
2008
|
+
|
|
2009
|
+
# Clean .agents/plugins.json
|
|
2010
|
+
agents_plugins = os.path.join(project_dir, ".agents", "plugins.json")
|
|
2011
|
+
if os.path.exists(agents_plugins):
|
|
2012
|
+
try:
|
|
2013
|
+
data, err = cls._load_json_with_backup(agents_plugins)
|
|
2014
|
+
if not err and data and isinstance(data.get("entries"), list):
|
|
2015
|
+
original_len = len(data["entries"])
|
|
2016
|
+
data["entries"] = [
|
|
2017
|
+
e for e in data["entries"]
|
|
2018
|
+
if not (isinstance(e, dict) and "tokensafe" in str(e.get("path", "")))
|
|
2019
|
+
]
|
|
2020
|
+
if len(data["entries"]) != original_len:
|
|
2021
|
+
if not data["entries"] and list(data.keys()) == ["entries"]:
|
|
2022
|
+
os.remove(agents_plugins)
|
|
2023
|
+
else:
|
|
2024
|
+
cls._write_file_safely(agents_plugins, json.dumps(data, indent=2))
|
|
2025
|
+
cleaned.append(".agents/plugins.json")
|
|
2026
|
+
except Exception:
|
|
2027
|
+
pass
|
|
2028
|
+
|
|
2029
|
+
# Clean .gitignore
|
|
2030
|
+
root_gitignore = os.path.join(project_dir, ".gitignore")
|
|
2031
|
+
if os.path.isfile(root_gitignore):
|
|
2032
|
+
try:
|
|
2033
|
+
with open(root_gitignore, "r", encoding="utf-8") as f:
|
|
2034
|
+
lines = f.readlines()
|
|
2035
|
+
new_lines = [
|
|
2036
|
+
line for line in lines
|
|
2037
|
+
if not line.strip().startswith(".tokensafe")
|
|
2038
|
+
and not ("TokenSafe" in line and ("runtime" in line or "metric" in line or "cache" in line))
|
|
2039
|
+
]
|
|
2040
|
+
if len(new_lines) != len(lines):
|
|
2041
|
+
with open(root_gitignore, "w", encoding="utf-8") as f:
|
|
2042
|
+
f.writelines(new_lines)
|
|
2043
|
+
cleaned.append(".gitignore")
|
|
2044
|
+
except Exception:
|
|
2045
|
+
pass
|
|
2046
|
+
|
|
2047
|
+
return {
|
|
2048
|
+
"success": True,
|
|
2049
|
+
"project_dir": project_dir,
|
|
2050
|
+
"cleaned_rules": cleaned
|
|
2051
|
+
}
|
|
2052
|
+
|
|
2053
|
+
@classmethod
|
|
2054
|
+
def uninstall_all(cls, force: bool = False, purge: bool = False) -> Dict[str, Any]:
|
|
2055
|
+
"""Uninstalls TokenSafe from all detected AI agents, unwires proxy, and optionally purges data."""
|
|
2056
|
+
proxy_report = cls.proxy_off()
|
|
2057
|
+
|
|
2058
|
+
agents = cls.detect_available_agents()
|
|
2059
|
+
results = {}
|
|
2060
|
+
for key, info in agents.items():
|
|
2061
|
+
if info["installed"] or force:
|
|
2062
|
+
m_ok, m_msg = cls.uninstall_mcp_config(key)
|
|
2063
|
+
h_ok, h_msg = cls.uninstall_hooks_config(key)
|
|
2064
|
+
status_ok = m_ok or h_ok
|
|
2065
|
+
msgs = [m for m in (m_msg, h_msg) if m]
|
|
2066
|
+
results[key] = {
|
|
2067
|
+
"name": info["name"],
|
|
2068
|
+
"success": status_ok,
|
|
2069
|
+
"message": "; ".join(msgs) if msgs else "Cleaned"
|
|
2070
|
+
}
|
|
2071
|
+
|
|
2072
|
+
cls.restart_mcp_daemons()
|
|
2073
|
+
proj_report = cls.uninstall_project(os.getcwd())
|
|
2074
|
+
|
|
2075
|
+
purged = False
|
|
2076
|
+
if purge:
|
|
2077
|
+
try:
|
|
2078
|
+
from src.paths import resolve_data_dir
|
|
2079
|
+
d_dir = resolve_data_dir()
|
|
2080
|
+
if os.path.isdir(d_dir):
|
|
2081
|
+
shutil.rmtree(d_dir, ignore_errors=True)
|
|
2082
|
+
ts_home = os.path.join(HOME, ".tokensafe")
|
|
2083
|
+
if os.path.isdir(ts_home):
|
|
2084
|
+
shutil.rmtree(ts_home, ignore_errors=True)
|
|
2085
|
+
purged = True
|
|
2086
|
+
except Exception:
|
|
2087
|
+
pass
|
|
2088
|
+
|
|
2089
|
+
return {
|
|
2090
|
+
"agents": results,
|
|
2091
|
+
"project_rules": proj_report.get("cleaned_rules", []),
|
|
2092
|
+
"proxy": proxy_report,
|
|
2093
|
+
"purged": purged
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
@classmethod
|
|
2097
|
+
def run_interactive_uninstall(cls):
|
|
2098
|
+
"""Interactive terminal UI asking developer which agents to disconnect and unwire."""
|
|
2099
|
+
agents = cls.detect_available_agents()
|
|
2100
|
+
|
|
2101
|
+
print("\n\033[1m\033[36m╔════════════════════════════════════════════════════════════════════╗\033[0m")
|
|
2102
|
+
print("\033[1m\033[36m║ ⚡ TOKENSAFE UNIVERSAL MCP & AGENT UNINSTALLER ⚡ ║\033[0m")
|
|
2103
|
+
print("\033[1m\033[36m╚════════════════════════════════════════════════════════════════════╝\033[0m\n")
|
|
2104
|
+
print("Detected AI developer environments on your machine:\n")
|
|
2105
|
+
|
|
2106
|
+
keys = list(agents.keys())
|
|
2107
|
+
selected = {}
|
|
2108
|
+
|
|
2109
|
+
for idx, key in enumerate(keys, 1):
|
|
2110
|
+
info = agents[key]
|
|
2111
|
+
tag = "\033[32m[Detected]\033[0m" if info["installed"] else "\033[2m[Not Found]\033[0m"
|
|
2112
|
+
selected[key] = info["installed"]
|
|
2113
|
+
mark = "[\033[32m✓\033[0m]" if selected[key] else "[ ]"
|
|
2114
|
+
print(f" {idx}. {mark} {info['name']:<28} {tag}")
|
|
2115
|
+
|
|
2116
|
+
print("\n\033[2mEnter numbers to toggle (e.g., 2,3), 'A' for all, or press Enter to uninstall selected:\033[0m")
|
|
2117
|
+
try:
|
|
2118
|
+
choice = input("> ").strip().lower()
|
|
2119
|
+
except (EOFError, KeyboardInterrupt):
|
|
2120
|
+
print("\nAborted.")
|
|
2121
|
+
return
|
|
2122
|
+
|
|
2123
|
+
if choice == "a":
|
|
2124
|
+
for k in selected:
|
|
2125
|
+
selected[k] = True
|
|
2126
|
+
elif choice:
|
|
2127
|
+
for num in choice.replace(",", " ").split():
|
|
2128
|
+
if num.isdigit() and 1 <= int(num) <= len(keys):
|
|
2129
|
+
k = keys[int(num) - 1]
|
|
2130
|
+
selected[k] = not selected[k]
|
|
2131
|
+
|
|
2132
|
+
try:
|
|
2133
|
+
purge_ans = input("\nAlso purge local metrics database and cache (~/.tokensafe)? [y/N]: ").strip().lower()
|
|
2134
|
+
purge = purge_ans in ("y", "yes")
|
|
2135
|
+
except (EOFError, KeyboardInterrupt):
|
|
2136
|
+
purge = False
|
|
2137
|
+
|
|
2138
|
+
print("\nUninstalling TokenSafe configurations...\n")
|
|
2139
|
+
p_rep = cls.proxy_off()
|
|
2140
|
+
if p_rep.get("unwired", {}).get("ok"):
|
|
2141
|
+
print(f" \033[32m✔\033[0m Proxy daemon & wiring unwound")
|
|
2142
|
+
|
|
2143
|
+
uninstalled_count = 0
|
|
2144
|
+
for key, is_sel in selected.items():
|
|
2145
|
+
if is_sel:
|
|
2146
|
+
name = agents[key]["name"]
|
|
2147
|
+
m_ok, m_msg = cls.uninstall_mcp_config(key)
|
|
2148
|
+
h_ok, h_msg = cls.uninstall_hooks_config(key)
|
|
2149
|
+
if m_ok or h_ok:
|
|
2150
|
+
msg = f"{m_msg}; {h_msg}" if (m_msg and h_msg) else (m_msg or h_msg)
|
|
2151
|
+
print(f" \033[32m✔\033[0m \033[1m{name}\033[0m: {msg}")
|
|
2152
|
+
uninstalled_count += 1
|
|
2153
|
+
else:
|
|
2154
|
+
print(f" \033[33m–\033[0m \033[1m{name}\033[0m: Nothing to remove")
|
|
2155
|
+
|
|
2156
|
+
cls.restart_mcp_daemons()
|
|
2157
|
+
proj_rep = cls.uninstall_project(os.getcwd())
|
|
2158
|
+
if proj_rep.get("cleaned_rules"):
|
|
2159
|
+
print(f"\n\033[32m✔ Cleaned project rules from: {', '.join(proj_rep['cleaned_rules'])}\033[0m")
|
|
2160
|
+
|
|
2161
|
+
if purge:
|
|
2162
|
+
try:
|
|
2163
|
+
from src.paths import resolve_data_dir
|
|
2164
|
+
d_dir = resolve_data_dir()
|
|
2165
|
+
if os.path.isdir(d_dir):
|
|
2166
|
+
shutil.rmtree(d_dir, ignore_errors=True)
|
|
2167
|
+
ts_home = os.path.join(HOME, ".tokensafe")
|
|
2168
|
+
if os.path.isdir(ts_home):
|
|
2169
|
+
shutil.rmtree(ts_home, ignore_errors=True)
|
|
2170
|
+
print(" \033[32m✔\033[0m Local data directory purged (~/.tokensafe)")
|
|
2171
|
+
except Exception:
|
|
2172
|
+
pass
|
|
2173
|
+
|
|
2174
|
+
print(f"\n\033[32m\033[1m✅ TokenSafe uninstalled from {uninstalled_count} agent(s)!\033[0m")
|
|
2175
|
+
print(" To completely remove the CLI, run:\n npm uninstall -g @tokensafe/cli (or pip uninstall tokensafe)\n")
|
|
2176
|
+
|
|
1560
2177
|
@staticmethod
|
|
1561
2178
|
def _is_tokensafe_mcp_command(cmd: str) -> bool:
|
|
1562
2179
|
"""Returns True if a process command line represents a running TokenSafe MCP server daemon."""
|
package/src/mcp_server.py
CHANGED
package/src/proxy.py
CHANGED
|
@@ -902,11 +902,16 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
902
902
|
else:
|
|
903
903
|
err_body = {"error": message}
|
|
904
904
|
err_bytes = json.dumps(err_body).encode("utf-8")
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
905
|
+
# Client may have already hung up (BrokenPipeError in the traceback log
|
|
906
|
+
# used to bury the real cause under a full socketserver dump).
|
|
907
|
+
try:
|
|
908
|
+
self.send_response(status_code)
|
|
909
|
+
self.send_header("Content-Type", "application/json")
|
|
910
|
+
self.send_header("Content-Length", str(len(err_bytes)))
|
|
911
|
+
self.end_headers()
|
|
912
|
+
self.wfile.write(err_bytes)
|
|
913
|
+
except (BrokenPipeError, ConnectionResetError):
|
|
914
|
+
self.close_connection = True
|
|
910
915
|
|
|
911
916
|
def handle_chat_completions(self):
|
|
912
917
|
try:
|
|
@@ -1347,6 +1352,15 @@ def run_proxy(port: int = DEFAULT_PORT, host: str = DEFAULT_HOST):
|
|
|
1347
1352
|
daemon_threads = True
|
|
1348
1353
|
allow_reuse_address = True
|
|
1349
1354
|
|
|
1355
|
+
def handle_error(self, request, client_address):
|
|
1356
|
+
# Client hangups (agent cancelled a request mid-stream) are routine
|
|
1357
|
+
# here — keep them out of proxy.log, surface everything else.
|
|
1358
|
+
import sys as _sys
|
|
1359
|
+
exc = _sys.exc_info()[1]
|
|
1360
|
+
if isinstance(exc, (BrokenPipeError, ConnectionResetError, TimeoutError)):
|
|
1361
|
+
return
|
|
1362
|
+
super().handle_error(request, client_address)
|
|
1363
|
+
|
|
1350
1364
|
httpd = _TokenSafeThreadingServer(server_address, TokenSafeProxyHandler)
|
|
1351
1365
|
display_host = "localhost" if host in ("0.0.0.0", "", "127.0.0.1") else host
|
|
1352
1366
|
print(f"\n⚡ TokenSafe Local AI Proxy running on: http://{display_host}:{port} (bound to {host})")
|
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.2.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.2.7"
|
|
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.2.
|
|
20
|
+
CURRENT_VERSION = "4.2.7"
|
|
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
|