tokensafe 4.2.4 → 4.2.6
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 +2 -2
- package/README.md +3 -3
- package/bin/tokensafe.js +1 -0
- package/kimi.plugin.json +2 -2
- package/package.json +2 -2
- package/plugin.json +2 -2
- package/rules/AGENTS.md +1 -1
- package/server.json +4 -4
- package/skills/token-optimizer/SKILL.md +3 -1
- package/skills/token-optimizer/references/guard-checks.md +1 -0
- package/src/adapter_core.py +1 -0
- package/src/cli.py +26 -0
- package/src/guard.py +31 -0
- package/src/installer.py +617 -0
- package/src/mcp_server.py +2 -2
- package/src/proxy.py +19 -5
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "4.2.
|
|
2
|
+
"version": "4.2.6",
|
|
3
3
|
"name": "tokensafe",
|
|
4
|
-
"description": "Your
|
|
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
|
"author": {
|
|
6
6
|
"name": "TokenSafe",
|
|
7
7
|
"url": "https://tokensafe.dev"
|
package/README.md
CHANGED
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
<!-- mcp-name: dev.tokensafe/tokensafe -->
|
|
7
7
|
|
|
8
8
|
<p align="center">
|
|
9
|
-
<b>Your
|
|
10
|
-
|
|
11
|
-
TokenSafe
|
|
9
|
+
<b>Your AI agent is smart enough to code all day. Now it actually can.</b><br>
|
|
10
|
+
Stop letting bloated file reads, noisy test dumps, and broken prompt caches drain your limits by lunch.<br>
|
|
11
|
+
TokenSafe runs locally, filtering context down to what the model actually touches while keeping secrets out of git.<br>
|
|
12
12
|
Works with <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Kimi Code, and ChatGPT</b>.
|
|
13
13
|
</p>
|
|
14
14
|
|
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/kimi.plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.2.
|
|
4
|
-
"description": "Your
|
|
3
|
+
"version": "4.2.6",
|
|
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",
|
|
7
7
|
"logo": "https://tokensafe.dev/logo.png",
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.2.
|
|
5
|
-
"description": "Your
|
|
4
|
+
"version": "4.2.6",
|
|
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": {
|
|
8
8
|
"tokensafe": "bin/tokensafe.js"
|
package/plugin.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.2.
|
|
5
|
-
"description": "Your
|
|
4
|
+
"version": "4.2.6",
|
|
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",
|
|
8
8
|
"author": {
|
package/rules/AGENTS.md
CHANGED
|
@@ -21,7 +21,7 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
21
21
|
|
|
22
22
|
### 2. Zero-Fluff Output Directives (Egress Optimization)
|
|
23
23
|
1. **No Conversational Filler**: Never include courtesy greetings or sign-offs (e.g., "Certainly!", "Sure, I can help", "Let me know if you need anything else").
|
|
24
|
-
2. **Surgical Code Edits**: Prefer `edit_file` with concise `Target` and `Replacement` over `write_file` on large existing files.
|
|
24
|
+
2. **Surgical Code Edits & Zero In-Place Stream Editing**: Prefer `edit_file` with concise `Target` and `Replacement` over `write_file` on large existing files. NEVER run terminal stream editors (`sed -i`, `perl -i`, `awk -i`) to edit or delete source code — blind numeric ranges cause line-drift and silent code loss (hard-blocked by TokenSafe Guard). NEVER suppress errors (`2>/dev/null`) on file modifications.
|
|
25
25
|
3. **Diff-Centric Responses**: Never reprint entire unmodified files or long boilerplate blocks. Reference file lines instead (e.g., `wallet.ts#L42-L50`).
|
|
26
26
|
4. **Dense Formatting**: Use compact bullet points and direct technical prose.
|
|
27
27
|
5. **Repeat Read Deduplication**: Never re-read unchanged files or symbols in the same session. Reuse the skeleton or pointer reference (`// [TokenSafe: Pointer Hit ...]`) returned earlier; only pass `force_full=true` if your context was compacted or you are a fresh subagent.
|
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 agent
|
|
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.6",
|
|
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.6",
|
|
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.6",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -42,8 +42,10 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
42
42
|
- NEVER run `ls -la` or `ls -l` in terminal.
|
|
43
43
|
- Call `tokensafe:list_dir(path=".", depth=2)` for clean directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
|
|
44
44
|
|
|
45
|
-
6. **SURGICAL FILE EDITS (`edit_file`)**:
|
|
45
|
+
6. **SURGICAL FILE EDITS (`edit_file`) & IN-PLACE STREAM MUTATION GUARD (`sed -i` HARD-BLOCKED)**:
|
|
46
46
|
- On existing files with >= 40 lines, wholesale rewrites via `write_file` are blocked by **Output Guard**. Always use `edit_file` with precise `Target` and `Replacement` blocks.
|
|
47
|
+
- Strictly NEVER run `sed -i`, `perl -i`, `awk -i`, or terminal stream editors on source files (`.ts`, `.tsx`, `.py`, `.js`, etc.) or with numeric line ranges (`'10,20d'`). Blind numeric editing causes line-drift and catastrophic accidental code deletion. These commands are hard-blocked by **TokenSafe Guard** (`decision: deny`).
|
|
48
|
+
- NEVER suppress errors with `2>/dev/null` or `&>/dev/null` on file modifications or build commands; failures must fail fast and loud.
|
|
47
49
|
|
|
48
50
|
7. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
|
|
49
51
|
- Never provide real private keys, API secrets, or credentials as fallback values in `os.environ.get()` or `process.env`. Real credentials must exist strictly in environment variables.
|
|
@@ -10,6 +10,7 @@ TokenSafe Guard automatically intercepts dangerous operations in `PreToolUse`:
|
|
|
10
10
|
| **SQL_INJECTION** | Unsafe f-string / template string interpolation in queries | **Blocked** (`decision: deny`), enforces parameterized queries |
|
|
11
11
|
| **GIT_SECRET_STAGING** | `git add .env` or blanket staging with unignored secrets | **Blocked** (`decision: deny`), prevents staging credentials |
|
|
12
12
|
| **DESTRUCTIVE_RM** | `rm -rf /`, `rm -rf ~`, `rm -rf *` | **Blocked** (`decision: deny`), prevents catastrophic deletion |
|
|
13
|
+
| **INPLACE_STREAM_EDIT** | `sed -i`, `perl -i`, `awk -i` on source code or with numeric line ranges (`'10,20d'`) | **Blocked** (`decision: deny`), prevents line-drift and code loss; directs to `edit_file` |
|
|
13
14
|
| **DATA_EXFILTRATION** | Piping `.env` or private keys to `curl`/`wget` | **Blocked** (`decision: deny`), prevents secret leakage |
|
|
14
15
|
| **PACKAGE_TYPOSQUAT** | Installing known typosquatted packages | **Warning** injected into turn context |
|
|
15
16
|
| **INFINITE_STREAM** (adapters) | Never-terminating commands: `tail -f`, `watch`, `docker attach`, `docker/kubectl logs -f`, `vitest` (watch by default — use `vitest run`), `jest`/`vitest --watch` | **Asked** (`decision: ask`) — intentional runs proceed via confirmation |
|
package/src/adapter_core.py
CHANGED
|
@@ -42,6 +42,7 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
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"
|
|
45
|
+
"• Prohibited File Edits: NEVER use 'sed -i', 'perl -i', or stream editors to modify source files; ALWAYS use 'edit_file' with exact string targets. NEVER suppress errors with '2>/dev/null'.\n"
|
|
45
46
|
"• Prefer 'edit_file' over 'write_file' for existing files."
|
|
46
47
|
)
|
|
47
48
|
|
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/guard.py
CHANGED
|
@@ -9,6 +9,7 @@ Protects local workspaces and repository integrity by intercepting dangerous ope
|
|
|
9
9
|
6. Destructive Shell Command & Unbounded Deletion Prevention (rm -rf /)
|
|
10
10
|
7. Network Data Exfiltration Prevention (piping secrets to curl/wget)
|
|
11
11
|
8. Package Typosquatting & Hallucination Early Warning
|
|
12
|
+
9. In-Place Stream Editing & Blind Line Deletion Prevention (sed -i, perl -i, awk -i inplace)
|
|
12
13
|
"""
|
|
13
14
|
|
|
14
15
|
import os
|
|
@@ -316,6 +317,36 @@ class TokenSafeGuard:
|
|
|
316
317
|
)
|
|
317
318
|
)
|
|
318
319
|
|
|
320
|
+
# 1b. In-Place Stream Editing & Blind Line Mutation Prevention (sed -i, perl -i, awk -i inplace)
|
|
321
|
+
_NUMERIC_RANGE_RE = re.compile(r"""['"]?\s*\d+\s*(?:,\s*\d+)?\s*[ds]\b""")
|
|
322
|
+
for stage in stages:
|
|
323
|
+
cmd_tok, cmd_args = cls._stage_cmd_tokens(stage)
|
|
324
|
+
if cmd_tok in ("sed", "perl", "awk", "gawk"):
|
|
325
|
+
has_inplace = False
|
|
326
|
+
if cmd_tok == "sed":
|
|
327
|
+
has_inplace = any(a == "-i" or a.startswith("-i") or a == "--in-place" or a.startswith("--in-place=") for a in cmd_args)
|
|
328
|
+
elif cmd_tok == "perl":
|
|
329
|
+
has_inplace = any(a == "-i" or a.startswith("-i") or (a.startswith("-") and not a.startswith("--") and "i" in a) for a in cmd_args)
|
|
330
|
+
elif cmd_tok in ("awk", "gawk"):
|
|
331
|
+
has_inplace = any(a in ("inplace", "--include=inplace") or a.startswith("-i") for a in cmd_args)
|
|
332
|
+
|
|
333
|
+
has_code_target = cls._has_code_target_in_args(cmd_tok, cmd_args)
|
|
334
|
+
has_numeric_range = bool(_NUMERIC_RANGE_RE.search(stage))
|
|
335
|
+
|
|
336
|
+
if (has_inplace and (has_code_target or has_numeric_range)) or (has_numeric_range and has_code_target):
|
|
337
|
+
reason = (
|
|
338
|
+
f"In-place stream editing of source files blocked: '{stage}'. "
|
|
339
|
+
f"Modifying code with sed/perl/awk or blind line ranges causes line-drift and catastrophic code deletion. "
|
|
340
|
+
f"Use the structured 'edit_file' tool with exact target matching instead."
|
|
341
|
+
)
|
|
342
|
+
if "2>/dev/null" in stage or "&>/dev/null" in stage:
|
|
343
|
+
reason += " Stderr suppression ('2>/dev/null') was also detected, which hides execution failures."
|
|
344
|
+
return GuardResult(
|
|
345
|
+
blocked=True,
|
|
346
|
+
check_name="INPLACE_STREAM_EDIT",
|
|
347
|
+
reason=reason
|
|
348
|
+
)
|
|
349
|
+
|
|
319
350
|
# 2. Git Staging Protection for Sensitive Files (.env, private keys)
|
|
320
351
|
for stage in stages:
|
|
321
352
|
cmd_tok, cmd_args = cls._stage_cmd_tokens(stage)
|
package/src/installer.py
CHANGED
|
@@ -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
|
@@ -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.2.
|
|
45
|
+
"version": "4.2.6"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -217,7 +217,7 @@ TOOLS = [
|
|
|
217
217
|
},
|
|
218
218
|
{
|
|
219
219
|
"name": "guard_inspect",
|
|
220
|
-
"description": "Pre-flight security & hygiene audit for commands or code snippets. Detects secret leaks, SQL injection, TLS bypass (incl. git-level), CORS wildcard, destructive commands, raw grep, and never-terminating streams (tail -f, watch, docker attach).",
|
|
220
|
+
"description": "Pre-flight security & hygiene audit for commands or code snippets. Detects secret leaks, SQL injection, TLS bypass (incl. git-level), CORS wildcard, destructive commands, raw grep, in-place stream editing (sed -i, perl -i), and never-terminating streams (tail -f, watch, docker attach).",
|
|
221
221
|
"inputSchema": {
|
|
222
222
|
"type": "object",
|
|
223
223
|
"properties": {
|
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.6"
|
|
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.6"
|
|
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
|