tokensafe 4.16.3 → 5.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 (151) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +1 -1
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2487
  26. package/src/mcp_server.py +11 -5437
  27. package/src/proxy.py +11 -1834
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +21 -18
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +51 -10
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +729 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/{src → tokensafe}/ingress_staging.py +9 -9
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5664 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/{src → tokensafe}/read_baseline.py +1 -1
  100. package/{src → tokensafe}/repo_compute.py +1 -1
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -23,7 +23,7 @@ import time
23
23
  from pathlib import Path
24
24
  from typing import Any, Dict, List, Optional, Tuple
25
25
 
26
- from src.bench import tokensafe_mcp
26
+ from tokensafe.bench import tokensafe_mcp
27
27
 
28
28
  REPO_ROOT = Path(__file__).resolve().parents[3]
29
29
  GO_ROOT = REPO_ROOT / "tokensafe-backend" / "go"
@@ -21,7 +21,7 @@ import time
21
21
  from pathlib import Path
22
22
  from typing import Any, Dict, List, Optional
23
23
 
24
- from src.bench import go_target, react_target
24
+ from tokensafe.bench import go_target, react_target
25
25
 
26
26
 
27
27
  def _ms(fn, repeats: int) -> Dict[str, float]:
@@ -21,7 +21,7 @@ import time
21
21
  from pathlib import Path
22
22
  from typing import Any, Dict, List, Optional, Tuple
23
23
 
24
- from src.bench import tokensafe_mcp
24
+ from tokensafe.bench import tokensafe_mcp
25
25
 
26
26
  REPO_ROOT = Path(__file__).resolve().parents[3]
27
27
  AGENT_DOM = REPO_ROOT / "agent-dom"
@@ -9,8 +9,8 @@ import time
9
9
  from pathlib import Path
10
10
  from typing import Any, Dict, List, Optional
11
11
 
12
- from src.bench import go_target, react_target
13
- from src.bench.driver import BudgetExceeded, DeepSeekClient, run_agent
12
+ from tokensafe.bench import go_target, react_target
13
+ from tokensafe.bench.driver import BudgetExceeded, DeepSeekClient, run_agent
14
14
 
15
15
 
16
16
  def run_one(
@@ -94,7 +94,7 @@ def _matrix_report(
94
94
 
95
95
 
96
96
  def checkpoint_path(files: int = 0) -> Path:
97
- from src.paths import resolve_data_dir
97
+ from tokensafe.paths import resolve_data_dir
98
98
 
99
99
  label = f"go-{files}f" if files else "go"
100
100
  return Path(resolve_data_dir()) / "bench" / f"{label}-checkpoint.json"
@@ -421,7 +421,7 @@ def render_markdown(report: Dict[str, Any]) -> str:
421
421
 
422
422
 
423
423
  def write_artifacts(report: Dict[str, Any], out_dir: Optional[Path] = None) -> Dict[str, str]:
424
- from src.paths import resolve_data_dir
424
+ from tokensafe.paths import resolve_data_dir
425
425
 
426
426
  base = Path(out_dir) if out_dir else Path(resolve_data_dir()) / "bench"
427
427
  base.mkdir(parents=True, exist_ok=True)
@@ -10,18 +10,18 @@ import json
10
10
  import time
11
11
  import tempfile
12
12
  from typing import Dict, List, Any, Optional
13
- from src.tokenizer import count_tokens
14
- from src.compactor import PromptCompactor
15
- from src.command_sanitizer import CommandSanitizer
16
- from src.slicer import ToolSlicer
17
- from src.skeletonizer import Skeletonizer
18
- from src.dependency_prefetcher import DependencyPrefetcher
19
- from src.graph_engine import CodeGraph
20
- from src.metrics import MetricsTracker
21
- from src.agent_firewall import AgentFirewall
22
- from src.distiller_cache import DistillationCache
23
- from src.cache_normalizer import PromptCacheNormalizer
24
- from src.governor import ContextGovernor
13
+ from tokensafe.tokenizer import count_tokens
14
+ from tokensafe.compactor import PromptCompactor
15
+ from tokensafe.command_sanitizer import CommandSanitizer
16
+ from tokensafe.slicer import ToolSlicer
17
+ from tokensafe.skeletonizer import Skeletonizer
18
+ from tokensafe.dependency_prefetcher import DependencyPrefetcher
19
+ from tokensafe.graph_engine import CodeGraph
20
+ from tokensafe.metrics import MetricsTracker
21
+ from tokensafe.agent_firewall import AgentFirewall
22
+ from tokensafe.distiller_cache import DistillationCache
23
+ from tokensafe.cache_normalizer import PromptCacheNormalizer
24
+ from tokensafe.governor import ContextGovernor
25
25
 
26
26
  # ANSI Colors
27
27
  RESET = "\033[0m"
@@ -1,7 +1,7 @@
1
1
  """
2
2
  Real-Repo Benchmark: measured token reduction on live open-source repositories.
3
3
 
4
- Methodology (pre-registered in src/bench_scenarios.json — committed BEFORE runs):
4
+ Methodology (pre-registered in tokensafe/bench_scenarios.json — committed BEFORE runs):
5
5
  - Every token count is measured with the calibrated BPE tokenizer on real
6
6
  repository bytes; nothing is assumed or hardcoded.
7
7
  - Baseline = what an unassisted agent sends upstream (full file reads, raw
@@ -25,11 +25,11 @@ import sys
25
25
  import time
26
26
  from typing import Any, Dict, List, Optional
27
27
 
28
- from src.tokenizer import count_tokens
29
- from src.skeletonizer import Skeletonizer
30
- from src.command_sanitizer import CommandSanitizer
31
- from src.diff_slicer import DiffSlicer
32
- from src.paths import resolve_data_dir
28
+ from tokensafe.tokenizer import count_tokens
29
+ from tokensafe.skeletonizer import Skeletonizer
30
+ from tokensafe.command_sanitizer import CommandSanitizer
31
+ from tokensafe.diff_slicer import DiffSlicer
32
+ from tokensafe.paths import resolve_data_dir
33
33
 
34
34
  _DEF_KEYWORD_RE = re.compile(r"\b(function|func|fn|def|class|struct|interface|trait|impl|type|module)\b")
35
35
 
@@ -276,7 +276,7 @@ class RealRepoBenchmark:
276
276
  """Top graph-hub files × their largest symbol — the reads an agent
277
277
  actually performs first in an unfamiliar repo. Uses the language-agnostic
278
278
  graph (works for any supported language, not just Python)."""
279
- from src.graph_engine import GraphEngine
279
+ from tokensafe.graph_engine import GraphEngine
280
280
  graph = GraphEngine.get_instance(root)
281
281
  out: List[Any] = []
282
282
  for node in graph.get_god_nodes(top_n=10):
@@ -412,7 +412,7 @@ class RealRepoBenchmark:
412
412
 
413
413
  # -- scenario 4: architecture discovery --------------------------------
414
414
  def _hub_files(self, root: str, limit: int = 5) -> List[str]:
415
- from src.graph_engine import GraphEngine
415
+ from tokensafe.graph_engine import GraphEngine
416
416
  graph = GraphEngine.get_instance(root)
417
417
  out = []
418
418
  for n in graph.get_god_nodes(top_n=limit):
@@ -422,7 +422,7 @@ class RealRepoBenchmark:
422
422
  return out
423
423
 
424
424
  def _architecture_map(self, root: str) -> str:
425
- from src.graph_engine import GraphEngine
425
+ from tokensafe.graph_engine import GraphEngine
426
426
  graph = GraphEngine.get_instance(root)
427
427
  lines = [f"Architecture: {len(graph.symbols)} symbols in {len(graph.file_symbols)} files"]
428
428
  for n in graph.get_god_nodes(top_n=7):
@@ -568,7 +568,7 @@ class RealRepoBenchmark:
568
568
  for f in hub_files:
569
569
  with open(os.path.join(root, f), "r", encoding="utf-8", errors="replace") as fh:
570
570
  baseline += count_tokens(fh.read())
571
- from src.graph_engine import GraphEngine
571
+ from tokensafe.graph_engine import GraphEngine
572
572
  graph = GraphEngine.get_instance(root)
573
573
  surface_text = graph.generate_api_surface()
574
574
  if not surface_text:
@@ -586,9 +586,9 @@ class RealRepoBenchmark:
586
586
  growing conversation. Byte-identical prefixes between consecutive turns are
587
587
  cache-hit tokens (billed at the 0.1x cached rate); the PromptCacheNormalizer
588
588
  must keep those prefixes byte-identical or the gate fails."""
589
- from src.graph_engine import GraphEngine
590
- from src.cache_normalizer import PromptCacheNormalizer
591
- from src.benchmark import _extract_canonical_units, _longest_prefix_tokens, _cached_tokens
589
+ from tokensafe.graph_engine import GraphEngine
590
+ from tokensafe.cache_normalizer import PromptCacheNormalizer
591
+ from tokensafe.benchmark import _extract_canonical_units, _longest_prefix_tokens, _cached_tokens
592
592
 
593
593
  hub_files = self._hub_files(root, limit=10)
594
594
  if len(hub_files) < 5:
@@ -676,7 +676,7 @@ class RealRepoBenchmark:
676
676
 
677
677
  # -- scenario 10: secret guard --------------------------------------------
678
678
  def measure_secret_guard(self, root: str) -> Dict[str, Any]:
679
- from src.guard import TokenSafeGuard
679
+ from tokensafe.guard import TokenSafeGuard
680
680
  env_content = self.reg.get("secret_guard", {}).get("env_content", "")
681
681
  if not env_content:
682
682
  return {"status": "skipped", "reason": "no secret_guard template"}
@@ -743,7 +743,7 @@ class RealRepoBenchmark:
743
743
 
744
744
  # -- scenario 12: prompt compaction (TOCP) --------------------------------
745
745
  def measure_prompt_compaction(self, root: str, sr: Dict[str, Any]) -> Dict[str, Any]:
746
- from src.compactor import PromptCompactor
746
+ from tokensafe.compactor import PromptCompactor
747
747
  template = self.reg.get("prompt_compaction", {}).get("template", "")
748
748
  if not template:
749
749
  return {"status": "skipped", "reason": "no prompt template"}
@@ -762,7 +762,7 @@ class RealRepoBenchmark:
762
762
 
763
763
  # -- scenario 13: Tree-sitter AST polyglot (13 languages) ----------------
764
764
  def measure_treesitter_polyglot(self, root: str, repo: Dict[str, Any]) -> Dict[str, Any]:
765
- from src.treesitter_backend import TreeSitterBackend
765
+ from tokensafe.treesitter_backend import TreeSitterBackend
766
766
  if not TreeSitterBackend.is_available():
767
767
  return {"status": "skipped", "reason": "Tree-sitter parser unavailable"}
768
768
  target_file = None
@@ -802,7 +802,7 @@ class RealRepoBenchmark:
802
802
 
803
803
  # -- scenario 14: Reversible Hash Stashing (#hash + expand_ref) ----------
804
804
  def measure_hash_stash_expand(self, root: str) -> Dict[str, Any]:
805
- from src.stash import stash_block, expand_ref
805
+ from tokensafe.stash import stash_block, expand_ref
806
806
  sample_log = (
807
807
  "=== TEST SUITE EXECUTION LOG ===\n"
808
808
  "Running 420 unit tests across 18 test modules...\n"
@@ -826,7 +826,7 @@ class RealRepoBenchmark:
826
826
 
827
827
  # -- scenario 15: Context Tax & Ghost Token Audit (tokensafe doctor) ------
828
828
  def measure_context_tax_audit(self, root: str) -> Dict[str, Any]:
829
- from src.environment_auditor import EnvironmentAuditor
829
+ from tokensafe.environment_auditor import EnvironmentAuditor
830
830
  report = EnvironmentAuditor.audit(root)
831
831
  total_static = report.get("total_static_tokens_per_turn", 13425)
832
832
  ghost_tokens = report.get("ghost_tokens", {}).get("ghost_tokens_per_turn", 4342)
@@ -22,8 +22,8 @@ Specialized compactor for:
22
22
  import os
23
23
  import re
24
24
  from typing import Dict, Any, List, Optional, Tuple
25
- from src.stash import stash_block
26
- from src.format_parsers.ansi import strip_ansi
25
+ from tokensafe.stash import stash_block
26
+ from tokensafe.format_parsers.ansi import strip_ansi
27
27
 
28
28
  # Patterns for build detection
29
29
  _VITE_START_RE = re.compile(r"\bvite\s+v?[\d.]+\s+building\s+for\s+production\b", re.IGNORECASE)
@@ -168,7 +168,7 @@ class BuildOutputParser:
168
168
  # If the build failure contains TypeScript compiler error cascades (e.g. vue-tsc, vite build type error),
169
169
  # compact using CompilerErrorCompactor to save massive token cascades.
170
170
  try:
171
- from src.format_parsers.compiler_errors import CompilerErrorCompactor
171
+ from tokensafe.format_parsers.compiler_errors import CompilerErrorCompactor
172
172
  if CompilerErrorCompactor.is_tsc_output(result or cleaned):
173
173
  compacted_tsc, was_tsc = CompilerErrorCompactor.compact_tsc(result or cleaned)
174
174
  if was_tsc:
@@ -12,7 +12,7 @@ import time
12
12
  from typing import Any, Dict, List, Optional
13
13
  from urllib.parse import urljoin, urlparse
14
14
 
15
- from src.web_reader import WebReader
15
+ from tokensafe.web_reader import WebReader
16
16
 
17
17
  _MAX_CHUNKS = 20
18
18
  _DEFAULT_TIMEOUT_MS = 6000
@@ -18,7 +18,7 @@ import re
18
18
  import time
19
19
  from typing import Any, Dict, List, Optional, Tuple
20
20
 
21
- from src.tokenizer import count_tokens
21
+ from tokensafe.tokenizer import count_tokens
22
22
 
23
23
  # (M_input, M_cache, M_output) per 10,000 tokens (Z.ai) or relative cost ratio.
24
24
  _MODEL_MULTIPLIERS: List[Tuple[str, Tuple[float, float, float]]] = [
@@ -462,7 +462,7 @@ def _output_budget_for(agent: str) -> int:
462
462
  except ValueError:
463
463
  pass
464
464
  try:
465
- from src.paths import resolve_data_dir
465
+ from tokensafe.paths import resolve_data_dir
466
466
 
467
467
  path = os.path.join(resolve_data_dir(), "output_budget.json")
468
468
  with open(path, "r", encoding="utf-8") as f:
@@ -622,7 +622,7 @@ def evaluate_burn_warnings(
622
622
 
623
623
  def _dedup_state_path() -> str:
624
624
  try:
625
- from src.paths import resolve_data_dir
625
+ from tokensafe.paths import resolve_data_dir
626
626
  return os.path.join(resolve_data_dir(), "burn_alerts_state.json")
627
627
  except Exception:
628
628
  return os.path.join(os.path.expanduser("~"), ".tokensafe", "data", "burn_alerts_state.json")
@@ -9,7 +9,7 @@ import re
9
9
  import json
10
10
  import hashlib
11
11
  from typing import Dict, List, Any, Tuple, Optional
12
- from src.tokenizer import count_tokens
12
+ from tokensafe.tokenizer import count_tokens
13
13
 
14
14
 
15
15
  def _canonicalize_json(obj: Any) -> Any: