tokensafe 3.1.5 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +79 -58
  2. package/bin/tokensafe.js +25 -9
  3. package/hooks/claude_code_hook.py +7 -0
  4. package/hooks/pre_tool_use.py +24 -0
  5. package/hooks/session_start.py +8 -0
  6. package/package.json +3 -3
  7. package/plugin.json +1 -1
  8. package/rules/AGENTS.md +13 -7
  9. package/server.json +3 -3
  10. package/skills/token-optimizer/SKILL.md +7 -2
  11. package/skills/token-optimizer/references/cli-reference.md +11 -1
  12. package/skills/token-optimizer/references/mcp-tools.md +44 -2
  13. package/src/bench_scenarios.json +376 -0
  14. package/src/cache_normalizer.py +21 -0
  15. package/src/cli.py +425 -4
  16. package/src/command_sanitizer.py +2 -0
  17. package/src/compactor.py +1 -1
  18. package/src/competitors.py +179 -0
  19. package/src/environment_auditor.py +110 -1
  20. package/src/format_parsers/__init__.py +20 -0
  21. package/src/format_parsers/ansi.py +41 -0
  22. package/src/format_parsers/compiler_errors.py +159 -0
  23. package/src/format_parsers/docker_k8s.py +95 -0
  24. package/src/format_parsers/json_log.py +89 -0
  25. package/src/format_parsers/lockfiles.py +157 -0
  26. package/src/format_parsers/tabular.py +175 -0
  27. package/src/fts_index.py +296 -0
  28. package/src/graph_engine.py +395 -48
  29. package/src/image_downscale.py +228 -0
  30. package/src/installer.py +47 -1
  31. package/src/license_manager.py +103 -7
  32. package/src/loop_detector.py +5 -0
  33. package/src/mcp_config_manager.py +197 -0
  34. package/src/mcp_proxy.py +154 -0
  35. package/src/mcp_server.py +215 -1
  36. package/src/mistakes.py +203 -0
  37. package/src/result_ledger.py +8 -1
  38. package/src/scoped_search.py +32 -0
  39. package/src/stash.py +199 -0
  40. package/src/superseded.py +220 -0
  41. package/src/telemetry_sync.py +14 -1
  42. package/src/test_parsers.py +271 -0
  43. package/src/version_checker.py +1 -1
  44. package/src/web_reader.py +202 -0
package/src/cli.py CHANGED
@@ -10,6 +10,7 @@ Used by:
10
10
  import sys
11
11
  import os
12
12
  import subprocess
13
+ from typing import Optional, List, Dict, Any
13
14
 
14
15
  SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
15
16
  PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
@@ -104,7 +105,10 @@ def _print_help():
104
105
  print(" test <prompt> Preview TOCP S-expression prompt compaction")
105
106
  print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
106
107
  print(" guard <command> Pre-flight safety check for a shell command")
107
- print(" doctor Audit MCP tool overhead and token tax")
108
+ print(" expand-ref <hash> Restore folded tool/command/file result by its 8-char hash")
109
+ print(" wrap <command> Run command with compact output folding (e.g. tests/logs)")
110
+ print(" web <url> Fetch web page/docs and print clean compact Markdown")
111
+ print(" doctor [--cleanup] Audit MCP tool overhead and detect competitor conflicts")
108
112
  print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
109
113
  print(" prune [--days N | --max N] Compact metrics database (roll old events)")
110
114
  print(" vacuum Reclaim SQLite disk space")
@@ -113,13 +117,15 @@ def _print_help():
113
117
  print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
114
118
  print(" check-update Check for a newer published version")
115
119
  print(" activate / license License activation and status")
120
+ print(" login / auth Authorize this device via browser login")
121
+ print(" logout / unlink Unlink this device and remove local license")
116
122
  print(" sync Sync telemetry with the cloud backend")
117
123
  print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
118
124
  print(" --version Print version and exit")
119
125
 
120
126
 
121
- def main():
122
- args = sys.argv[1:]
127
+ def main(argv: Optional[List[str]] = None):
128
+ args = sys.argv[1:] if argv is None else list(argv)
123
129
  command = args[0] if args else "stats"
124
130
 
125
131
  if command in ("--help", "-h", "help"):
@@ -212,7 +218,7 @@ def main():
212
218
  pass
213
219
  print(dashboard.render_terminal())
214
220
 
215
- elif command in ("html", "web"):
221
+ elif command in ("html", "dashboard-html"):
216
222
  from src.paths import resolve_data_dir
217
223
  tracker = MetricsTracker()
218
224
  dashboard = Dashboard(tracker)
@@ -465,6 +471,36 @@ def main():
465
471
  print(f"\n\033[32m✔ MCP server '{target}' re-enabled successfully.\033[0m\n")
466
472
  else:
467
473
  print(f"\n\033[31m✖ Server '{target}' not found in disabled servers.\033[0m\n")
474
+ elif subcmd in ("wrap", "proxy-wrap"):
475
+ from src.mcp_config_manager import MCPConfigManager
476
+ target = args[2].strip() if len(args) > 2 else "--all"
477
+ if target in ("--all", "-a", "all"):
478
+ count = MCPConfigManager.wrap_all()
479
+ print(f"\n\033[32m✔ Wrapped {count} third-party MCP server(s) behind tokensafe mcp-proxy.\033[0m\n")
480
+ else:
481
+ servers = MCPConfigManager.list_servers()
482
+ matched = [s for s in servers if s["server_name"] == target]
483
+ if not matched:
484
+ print(f"\n\033[31m✖ Server '{target}' not found in active agent MCP configs.\033[0m\n")
485
+ else:
486
+ for s in matched:
487
+ MCPConfigManager.wrap_server(s["config_path"], s["server_name"])
488
+ print(f"\n\033[32m✔ Server '{target}' wrapped behind tokensafe mcp-proxy.\033[0m\n")
489
+ elif subcmd in ("unwrap", "restore"):
490
+ from src.mcp_config_manager import MCPConfigManager
491
+ target = args[2].strip() if len(args) > 2 else "--all"
492
+ if target in ("--all", "-a", "all"):
493
+ count = MCPConfigManager.unwrap_all()
494
+ print(f"\n\033[32m✔ Unwrapped {count} MCP server(s) back to direct execution.\033[0m\n")
495
+ else:
496
+ servers = MCPConfigManager.list_servers()
497
+ matched = [s for s in servers if s["server_name"] == target]
498
+ if not matched:
499
+ print(f"\n\033[31m✖ Server '{target}' not found in active agent MCP configs.\033[0m\n")
500
+ else:
501
+ for s in matched:
502
+ MCPConfigManager.unwrap_server(s["config_path"], s["server_name"])
503
+ print(f"\n\033[32m✔ Server '{target}' restored to original command.\033[0m\n")
468
504
  elif subcmd in ("list", "ls", "status"):
469
505
  from src.environment_auditor import EnvironmentAuditor
470
506
  print(EnvironmentAuditor.format_cli_report())
@@ -472,10 +508,94 @@ def main():
472
508
  from src.mcp_server import run_mcp_server
473
509
  run_mcp_server()
474
510
 
511
+ elif command in ("mcp-proxy", "mcp_proxy"):
512
+ target_args = list(args[1:])
513
+ if target_args and target_args[0] == "--":
514
+ target_args.pop(0)
515
+ from src.mcp_proxy import run_proxy
516
+ run_proxy(target_args)
517
+
475
518
  elif command in ("doctor", "audit", "tax"):
476
519
  from src.environment_auditor import EnvironmentAuditor
477
520
  print(EnvironmentAuditor.format_cli_report())
478
521
 
522
+ from src.competitors import CompetitorAuditor
523
+ conflicts = CompetitorAuditor.audit()
524
+ if conflicts:
525
+ print("\n\033[1m\033[33m⚡ DETECTED CONFLICTING OR STALE TOOLS ⚡\033[0m")
526
+ for c in conflicts:
527
+ print(f" • \033[1m{c['name']}\033[0m [{c['class']}]: {c['description']}")
528
+ for tr in c['traces']:
529
+ loc = tr.get('path') or tr.get('file') or tr.get('config')
530
+ print(f" - {tr['kind']}: {loc}")
531
+ print("\n 💡 Tip: Run 'tokensafe doctor --cleanup' to remove conflicting orphan hooks/rules.\n")
532
+
533
+ if "--cleanup" in args:
534
+ for c in conflicts:
535
+ res = CompetitorAuditor.cleanup(c["id"])
536
+ print(f" \033[32m✔ Cleaned {c['name']}: {', '.join(res.get('removed', []))}\033[0m")
537
+
538
+ elif command in ("web", "fetch", "url"):
539
+ if len(args) < 2:
540
+ print("Usage: tokensafe web <url>")
541
+ sys.exit(1)
542
+ url = args[1].strip()
543
+ from src.web_reader import WebReader
544
+ md, ok, err = WebReader.fetch_url(url)
545
+ if not ok:
546
+ print(f"\033[31mError: {err}\033[0m")
547
+ sys.exit(1)
548
+ print(md)
549
+
550
+ elif command in ("search", "find", "fts"):
551
+ if len(args) < 2:
552
+ print("Usage: tokensafe search <query> [--limit 25] [--path <dir>]")
553
+ sys.exit(1)
554
+ query = args[1]
555
+ limit = 25
556
+ target_dir = os.getcwd()
557
+ if "--limit" in args:
558
+ idx = args.index("--limit")
559
+ if idx + 1 < len(args):
560
+ try:
561
+ limit = int(args[idx + 1])
562
+ except ValueError:
563
+ pass
564
+ if "--path" in args:
565
+ idx = args.index("--path")
566
+ if idx + 1 < len(args):
567
+ target_dir = os.path.abspath(args[idx + 1])
568
+
569
+ from src.fts_index import CodeFTSIndex
570
+ idx_engine = CodeFTSIndex(target_dir)
571
+ idx_engine.index_files()
572
+ results = idx_engine.search(query, limit=limit)
573
+ if not results:
574
+ print(f"No matches found for '{query}'.")
575
+ else:
576
+ print(f"\n\033[1m\033[36m⚡ SQLite FTS5 BM25 Search ({len(results)} matches for '{query}'):\033[0m\n")
577
+ for r in results:
578
+ print(f" \033[32m{r['file']}:{r['line']}\033[0m: {r['content']}")
579
+ print()
580
+
581
+ elif command in ("index", "fts-index"):
582
+ target_dir = os.getcwd()
583
+ if len(args) > 1 and not args[1].startswith("-"):
584
+ target_dir = os.path.abspath(args[1])
585
+ from src.fts_index import CodeFTSIndex
586
+ idx_engine = CodeFTSIndex(target_dir)
587
+ if "--clear" in args or "--reset" in args:
588
+ idx_engine.clear()
589
+ print(f"\033[32m✔ Cleared FTS index database for {target_dir}.\033[0m")
590
+ else:
591
+ stats = idx_engine.index_files()
592
+ print(f"\n\033[1m\033[36m⚡ SQLite FTS5 Full-Text Indexer ⚡\033[0m")
593
+ print(f" Scanned files: {stats['scanned_files']}")
594
+ print(f" Updated files: {stats['updated_files']}")
595
+ print(f" Indexed lines: {stats['indexed_lines']:,}")
596
+ print(f" Duration: {stats['duration_ms']:.2f} ms")
597
+ print(f" Index path: {idx_engine.db_path}\n")
598
+
479
599
  elif command in ("graph", "nodes"):
480
600
  from src.graph_engine import GraphEngine
481
601
  target_dir = args[1] if len(args) > 1 else os.getcwd()
@@ -515,6 +635,192 @@ def main():
515
635
  res = graph.graph_guided_skeletonize(file_path, target_symbol)
516
636
  print(res)
517
637
 
638
+ elif command in ("login", "auth", "connect"):
639
+ from src.license_manager import LicenseManager
640
+ import json
641
+ import time
642
+ import urllib.request
643
+ import webbrowser
644
+ import platform
645
+
646
+ cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
647
+ active_tier, active_lic = LicenseManager.get_active_license()
648
+ active_email = active_lic.get("email", "")
649
+
650
+ print("\n\033[1m\033[36m╔════════════════════════════════════════════════════════════════════╗\033[0m")
651
+ print("\033[1m\033[36m║ ⚡ TOKENSAFE ACCOUNT AUTHORIZATION ⚡ ║\033[0m")
652
+ print("\033[1m\033[36m╚════════════════════════════════════════════════════════════════════╝\033[0m\n")
653
+
654
+ if active_email and active_email != "community@tokensafe.dev":
655
+ print(f" Currently logged in as: \033[32m{active_email}\033[0m (Tier: {active_tier.upper()})")
656
+ if sys.stdin.isatty():
657
+ ans = input(" Do you want to re-authenticate or switch accounts? [y/N]: ").strip().lower()
658
+ if ans not in ("y", "yes"):
659
+ print(" Keeping current authorization.\n")
660
+ sys.exit(0)
661
+
662
+ # 1. Request device code
663
+ machine_fp = LicenseManager.get_machine_fingerprint()
664
+ payload = {
665
+ "machine_fp": machine_fp,
666
+ "platform": platform.system()[:32],
667
+ "arch": platform.machine()[:32],
668
+ "agent": str(LicenseManager.detect_agent())[:32],
669
+ "version": "",
670
+ "hostname": platform.node()[:64]
671
+ }
672
+ try:
673
+ req = urllib.request.Request(
674
+ f"{cloud_url}/api/auth/device/code",
675
+ data=json.dumps(payload).encode("utf-8"),
676
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Login"},
677
+ method="POST"
678
+ )
679
+ with urllib.request.urlopen(req, timeout=5.0) as resp:
680
+ init_data = json.loads(resp.read().decode("utf-8") or "{}")
681
+ except Exception as exc:
682
+ print(f"\033[31m✖ Could not connect to {cloud_url}: {exc}\033[0m")
683
+ print(" Check your internet connection and try again.\n")
684
+ sys.exit(1)
685
+
686
+ if not init_data.get("success"):
687
+ print(f"\033[31m✖ Authorization initiation failed: {init_data.get('error')}\033[0m\n")
688
+ sys.exit(1)
689
+
690
+ user_code = init_data["user_code"]
691
+ device_code = init_data["device_code"]
692
+ verif_url = init_data.get("verification_uri_complete") or f"{init_data['verification_uri']}?code={user_code}"
693
+ interval = init_data.get("interval", 3)
694
+
695
+ print(" To authorize this device and connect your account:")
696
+ print(f" 1. Confirm code: \033[1m\033[33m{user_code}\033[0m")
697
+ print(f" 2. In browser at: \033[36m{verif_url}\033[0m\n")
698
+
699
+ # Attempt to open browser automatically
700
+ try:
701
+ webbrowser.open(verif_url)
702
+ print(" \033[2m(Opened verification page in your default browser)\033[0m")
703
+ except Exception:
704
+ pass
705
+
706
+ print(" Waiting for authorization in browser (Ctrl+C to abort)...", end="", flush=True)
707
+
708
+ # 2. Polling loop
709
+ spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
710
+ spin_idx = 0
711
+ approved_data = None
712
+
713
+ try:
714
+ start_time = time.time()
715
+ while time.time() - start_time < 600:
716
+ time.sleep(interval)
717
+ spin_char = spinner[spin_idx % len(spinner)]
718
+ spin_idx += 1
719
+ print(f"\r {spin_char} Waiting for authorization in browser (Ctrl+C to abort)...", end="", flush=True)
720
+
721
+ try:
722
+ poll_req = urllib.request.Request(
723
+ f"{cloud_url}/api/auth/device/poll",
724
+ data=json.dumps({"device_code": device_code}).encode("utf-8"),
725
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Login"},
726
+ method="POST"
727
+ )
728
+ with urllib.request.urlopen(poll_req, timeout=4.0) as resp:
729
+ poll_data = json.loads(resp.read().decode("utf-8") or "{}")
730
+ except Exception:
731
+ continue
732
+
733
+ status = poll_data.get("status")
734
+ if status == "approved":
735
+ approved_data = poll_data
736
+ break
737
+ elif status == "quota_exhausted":
738
+ print(f"\n\n\033[31m✖ {poll_data.get('error')}\033[0m\n")
739
+ sys.exit(1)
740
+ elif status in ("expired", "denied"):
741
+ print(f"\n\n\033[31m✖ Authorization {status}.\033[0m\n")
742
+ sys.exit(1)
743
+
744
+ except KeyboardInterrupt:
745
+ print("\n\n\033[33m Authorization cancelled by user.\033[0m")
746
+ print(" Run 'tokensafe login' whenever you are ready.\n")
747
+ sys.exit(130)
748
+
749
+ if not approved_data:
750
+ print("\n\n\033[31m✖ Authorization timed out. Please try again.\033[0m\n")
751
+ sys.exit(1)
752
+
753
+ # 3. Save license and device token
754
+ lic_key = approved_data.get("license_key", "")
755
+ dev_tok = approved_data.get("device_token", "")
756
+ auth_email = approved_data.get("email", "")
757
+
758
+ ok, msg = LicenseManager.save_license(lic_key, device_token=dev_tok)
759
+ if ok:
760
+ valid, lic_meta, _ = LicenseManager.validate_license(lic_key)
761
+ detected_tier = (lic_meta.get("tier") or approved_data.get("tier") or "free").lower()
762
+ org_id = lic_meta.get("org")
763
+
764
+ print(f"\r\033[K \033[32m\033[1m✔ Successfully authenticated as {auth_email}!\033[0m")
765
+ if detected_tier == "solo":
766
+ print(" \033[32m✔ Solo Pro license activated (Unlimited tokens).\033[0m")
767
+ elif detected_tier in ("team", "enterprise"):
768
+ org_msg = f" [{org_id}]" if org_id else ""
769
+ print(f" \033[32m✔ Team license activated (Unlimited tokens, organization workspace{org_msg}).\033[0m")
770
+ else:
771
+ print(" \033[32m✔ Community Edition license activated (500,000 free tokens/month).\033[0m")
772
+ print(f" \033[36m✔ Web dashboard unlocked at: https://tokensafe.dev/dashboard\033[0m\n")
773
+
774
+ # Sync local token metrics
775
+ try:
776
+ from src.telemetry_sync import TelemetrySync
777
+ sync_res = TelemetrySync.sync(license_key=lic_key, timeout=3.0)
778
+ if sync_res.get("success") and sync_res.get("synced_events", 0) > 0:
779
+ print(f" \033[36m✔ Synced {sync_res['synced_events']:,} optimization events to your cloud dashboard.\033[0m\n")
780
+ except Exception:
781
+ pass
782
+ else:
783
+ print(f"\n\033[31m✖ Failed to save license: {msg}\033[0m\n")
784
+ sys.exit(1)
785
+
786
+ elif command in ("logout", "unlink", "disconnect"):
787
+ from src.license_manager import LicenseManager, LICENSE_FILE, GLOBAL_LICENSE_FILE
788
+ import json
789
+ import urllib.request
790
+
791
+ cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
792
+ machine_fp = LicenseManager.get_machine_fingerprint()
793
+ _, active_lic = LicenseManager.get_active_license()
794
+ active_email = active_lic.get("email", "")
795
+
796
+ # 1. Unlink on server to free up device slot
797
+ if active_email and machine_fp and active_email != "community@tokensafe.dev":
798
+ try:
799
+ req = urllib.request.Request(
800
+ f"{cloud_url}/api/auth/device/unlink",
801
+ data=json.dumps({"email": active_email, "machine_fp": machine_fp}).encode("utf-8"),
802
+ headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Logout"},
803
+ method="POST"
804
+ )
805
+ with urllib.request.urlopen(req, timeout=4.0):
806
+ pass
807
+ except Exception:
808
+ pass
809
+
810
+ # 2. Remove local license files
811
+ for p in (LICENSE_FILE, GLOBAL_LICENSE_FILE):
812
+ try:
813
+ if os.path.exists(p):
814
+ os.remove(p)
815
+ except Exception:
816
+ pass
817
+
818
+ print("\n\033[32m✔ Successfully unlinked this device and logged out.\033[0m")
819
+ if active_email and active_email != "community@tokensafe.dev":
820
+ print(f" Disconnected account: {active_email}")
821
+ print(" Your device slot has been freed.")
822
+ print(" Run \033[36mtokensafe login\033[0m anytime to connect again.\n")
823
+
518
824
  elif command == "activate":
519
825
  from src.license_manager import LicenseManager
520
826
  if len(args) < 2:
@@ -634,6 +940,40 @@ def main():
634
940
  print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
635
941
  print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
636
942
 
943
+ elif command == "wrap":
944
+ if len(args) < 2:
945
+ print("Usage: tokensafe wrap <command>")
946
+ sys.exit(1)
947
+ sub_cmd = " ".join(args[1:])
948
+ try:
949
+ proc = subprocess.run(sub_cmd, shell=True, capture_output=True, text=True)
950
+ raw = (proc.stdout or "") + (proc.stderr or "")
951
+ except Exception as e:
952
+ print(f"Error running command: {e}")
953
+ sys.exit(1)
954
+
955
+ from src.format_parsers.ansi import strip_ansi
956
+ from src.test_parsers import TestOutputParser
957
+ from src.stash import stash_block
958
+
959
+ raw = strip_ansi(raw)
960
+ compacted, was_test = TestOutputParser.compact(raw)
961
+ if was_test:
962
+ print(compacted)
963
+ sys.exit(proc.returncode)
964
+
965
+ lines = raw.splitlines()
966
+ if len(lines) > 40:
967
+ head = lines[:15]
968
+ tail = lines[-15:]
969
+ omitted = len(lines) - 30
970
+ _, marker = stash_block(raw, source="wrap")
971
+ folded = "\n".join(head + [f"... [{omitted} lines omitted by TokenSafe] ..."] + tail + [marker])
972
+ print(folded)
973
+ else:
974
+ print(raw)
975
+ sys.exit(proc.returncode)
976
+
637
977
  elif command in ("tests", "testsuite", "unittest"):
638
978
  tests_dir = os.path.join(PROJECT_ROOT, "tests")
639
979
  if not os.path.isdir(tests_dir):
@@ -773,6 +1113,87 @@ def main():
773
1113
  else:
774
1114
  print("Tip: Run with --send to dispatch email, or --email=<addr> to target specific team.\n")
775
1115
 
1116
+ elif command in ("expand-ref", "expand_ref", "expand"):
1117
+ if len(args) < 2:
1118
+ print("Usage: tokensafe expand-ref <hash8>")
1119
+ sys.exit(1)
1120
+ ref_hash = args[1].strip()
1121
+ from src.stash import retrieve_block
1122
+ content = retrieve_block(ref_hash)
1123
+ if content is None:
1124
+ print(f"\033[31mError: Stashed reference '{ref_hash}' not found or expired.\033[0m")
1125
+ sys.exit(1)
1126
+ print(content)
1127
+
1128
+ elif command in ("optimize-image", "image-opt", "image"):
1129
+ if len(args) < 2:
1130
+ print("Usage: tokensafe optimize-image <image_path> [--max-edge 1024]")
1131
+ sys.exit(1)
1132
+ img_path = args[1]
1133
+ max_edge = 1024
1134
+ if "--max-edge" in args:
1135
+ idx = args.index("--max-edge")
1136
+ if idx + 1 < len(args):
1137
+ try:
1138
+ max_edge = int(args[idx + 1])
1139
+ except ValueError:
1140
+ pass
1141
+ from src.image_downscale import ImageDownscaler
1142
+ res = ImageDownscaler.optimize(img_path, max_edge=max_edge)
1143
+ if not res.get("success"):
1144
+ print(f"\033[31mError: {res.get('error')}\033[0m")
1145
+ sys.exit(1)
1146
+ if res.get("was_downscaled"):
1147
+ print(f"\033[32m✔ Downscaled image using {res.get('engine')}:\033[0m {res['orig_dimensions']} ➔ {res['new_dimensions']}")
1148
+ print(f" Saved vision tokens: ~{res['saved_tokens']} tokens")
1149
+ print(f" Optimized image: {res['optimized_path']}")
1150
+ else:
1151
+ print(f"Image within bounds ({res.get('dimensions', 'N/A')} <= {max_edge}px). Using original file.")
1152
+
1153
+ elif command in ("prune-superseded", "prune_superseded"):
1154
+ if len(args) < 2:
1155
+ print("Usage: tokensafe prune-superseded <transcript_path>")
1156
+ sys.exit(1)
1157
+ t_path = args[1]
1158
+ from src.superseded import SupersededPruner
1159
+ res = SupersededPruner.prune_transcript(t_path)
1160
+ if not res.get("success"):
1161
+ print(f"\033[31mError: {res.get('error')}\033[0m")
1162
+ sys.exit(1)
1163
+ print(f"\033[32m✔ Pruned {res['pruned_count']} superseded tool read(s) from transcript.\033[0m")
1164
+ print(f" Saved context: ~{res['saved_tokens']} tokens")
1165
+
1166
+ elif command in ("mistakes", "deadends"):
1167
+ from src.mistakes import MistakesLedger
1168
+ sub = args[1] if len(args) > 1 else "list"
1169
+ if sub in ("clear", "reset"):
1170
+ c = MistakesLedger.clear_mistakes(os.getcwd())
1171
+ print(f"\033[32m✔ Cleared {c} mistake record(s).\033[0m")
1172
+ elif sub in ("record", "add"):
1173
+ reason = "Failed hypothesis"
1174
+ f_path = None
1175
+ if "--reason" in args:
1176
+ idx = args.index("--reason")
1177
+ if idx + 1 < len(args):
1178
+ reason = args[idx + 1]
1179
+ if "--file" in args:
1180
+ idx = args.index("--file")
1181
+ if idx + 1 < len(args):
1182
+ f_path = args[idx + 1]
1183
+ entry = MistakesLedger.record_revert(f_path or "project", reason, project_root=os.getcwd())
1184
+ print(f"\033[32m✔ Recorded mistake: {entry['summary']}\033[0m")
1185
+ else:
1186
+ entries = MistakesLedger.list_mistakes(project_root=os.getcwd())
1187
+ if not entries:
1188
+ print("No recorded dead-ends or reverts for this project.")
1189
+ else:
1190
+ print(f"\n\033[1m\033[36m⚡ TOKENSAFE ANTI-STUCK DEAD-ENDS LEDGER ({len(entries)}) ⚡\033[0m\n")
1191
+ for e in entries:
1192
+ print(f" • \033[1m{e.get('file') or 'project'}\033[0m: {e.get('summary')} [{e.get('source')}]")
1193
+ guard = MistakesLedger.get_guard_prompt(project_root=os.getcwd())
1194
+ if guard:
1195
+ print(f"\n\033[33mActive prompt guard:\033[0m\n{guard}\n")
1196
+
776
1197
  elif command == "reset":
777
1198
  confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
778
1199
  if confirm == "y":
@@ -719,6 +719,8 @@ class CommandSanitizer:
719
719
  raw, resolved_exit = cls._extract_tool_stdout(tool_response)
720
720
  if not raw or len(raw) < 400:
721
721
  return None
722
+ from src.format_parsers.ansi import strip_ansi
723
+ raw = strip_ansi(raw)
722
724
  if resolved_exit is None:
723
725
  # Unknown exit status: refuse to mute anything that looks like a failure,
724
726
  # but allow noise-only stripping (tracebacks stay intact) when it saves >=15%.
package/src/compactor.py CHANGED
@@ -267,7 +267,7 @@ class PromptCompactor:
267
267
  )
268
268
  FILE_REGEX = re.compile(
269
269
  r'(?:'
270
- r'(?:[\w\-\./\\@+()()][\w\-\./\\@+()() ]*[\/\\])?[\w\-\.+()()]+\.(?:' + "|".join(_FILE_EXTS) + r')\b'
270
+ r'(?:[\w\-\./\\@+()()][\w\-\./\\@+()() ]*[\/\\])?[\w\-\.+()()@]+\.(?:' + "|".join(_FILE_EXTS) + r')\b'
271
271
  r'|(?:\.env(?:\.[\w\-]+)?|\.gitignore|\.dockerignore|\.prettierrc[\w\.\-]*|\.eslintrc[\w\.\-]*|\.npmignore|\.npmrc|\.yarnrc)'
272
272
  r'|\b(?:Dockerfile(?:\.[\w\-]+)?|Makefile|Procfile|Gemfile|Vagrantfile|Containerfile)\b'
273
273
  r'|\b(?:README(?:\.md)?|LICENSE|CHANGELOG(?:\.md)?)\b'