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
@@ -17,8 +17,8 @@ import uuid
17
17
  import threading
18
18
  from typing import Dict, Any, Tuple, Optional, List
19
19
 
20
- from src.paths import resolve_data_dir
21
- from src.ssl_context import shared_ssl_context
20
+ from tokensafe.paths import resolve_data_dir
21
+ from tokensafe.ssl_context import shared_ssl_context
22
22
 
23
23
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24
24
  DATA_DIR = resolve_data_dir()
@@ -317,64 +317,10 @@ class LicenseManager:
317
317
  sig = hmac.new(hmac_key.encode("utf-8"), payload_bytes, hashlib.sha256).hexdigest()[:32]
318
318
  return f"TS1.{payload_b64}.{sig}"
319
319
 
320
- @classmethod
321
- def _disk_cache_path(cls) -> str:
322
- try:
323
- return os.path.join(resolve_data_dir(), "license_state.json")
324
- except Exception:
325
- return ""
326
-
327
320
  @staticmethod
328
321
  def _cache_slot(cache_key: str) -> str:
329
322
  return hashlib.sha256(cache_key.encode("utf-8")).hexdigest()[:16]
330
323
 
331
- @classmethod
332
- def _disk_cache_get(cls, cache_key: str) -> Optional[Dict[str, Any]]:
333
- """Cross-process verified-license cache (hooks are short-lived processes)."""
334
- path = cls._disk_cache_path()
335
- if not path:
336
- return None
337
- try:
338
- with open(path, "r", encoding="utf-8") as fh:
339
- data = json.load(fh)
340
- entry = (data.get("entries") or {}).get(cls._cache_slot(cache_key))
341
- if not isinstance(entry, dict) or float(entry.get("expires", 0)) <= time.time():
342
- return None
343
- payload = entry.get("payload")
344
- return dict(payload) if isinstance(payload, dict) else None
345
- except Exception:
346
- return None
347
-
348
- @classmethod
349
- def _disk_cache_put(cls, cache_key: str, payload: Dict[str, Any], expires: float) -> None:
350
- path = cls._disk_cache_path()
351
- if not path:
352
- return
353
- try:
354
- data: Dict[str, Any] = {}
355
- try:
356
- with open(path, "r", encoding="utf-8") as fh:
357
- loaded = json.load(fh)
358
- if isinstance(loaded, dict):
359
- data = loaded
360
- except Exception:
361
- data = {}
362
- entries = data.get("entries") if isinstance(data.get("entries"), dict) else {}
363
- now = time.time()
364
- alive = {
365
- key: value
366
- for key, value in entries.items()
367
- if isinstance(value, dict) and float(value.get("expires", 0)) > now
368
- }
369
- alive[cls._cache_slot(cache_key)] = {"payload": payload, "expires": expires}
370
- payload_out = {"version": 1, "entries": dict(list(alive.items())[-8:])}
371
- tmp = f"{path}.tmp.{os.getpid()}"
372
- with open(tmp, "w", encoding="utf-8") as fh:
373
- json.dump(payload_out, fh)
374
- os.replace(tmp, path)
375
- except Exception:
376
- pass
377
-
378
324
  # --- Quota aggregate cache -------------------------------------------
379
325
  # check_quota() runs on every hook invocation and reads a 30-day SQL
380
326
  # aggregate plus the sidecar ledger. The aggregate is cached for a few
@@ -521,8 +467,12 @@ class LicenseManager:
521
467
 
522
468
  license_key = license_key.strip()
523
469
 
524
- # Fast path: recently verified signature (avoids ~0.6s pure-Python Ed25519
525
- # verification on every hook invocation when the 'cryptography' package is absent)
470
+ # Fast path: a signature this process already verified. There is no
471
+ # cross-process cache on purpose: a JSON file in the user-writable data
472
+ # dir was trusted without re-checking the signature, so writing one entry
473
+ # turned any `TS2.<payload>.<junk>` key into a valid license. With the
474
+ # required `cryptography` package a fresh check costs ~9 ms of import plus
475
+ # ~0.2 ms of verification per hook process.
526
476
  now = time.time()
527
477
  effective_pub = public_key or DEFAULT_ED25519_PUBLIC_KEY
528
478
  cache_key = f"{effective_pub}|{int(bool(allow_legacy_ts1))}|{license_key}"
@@ -531,12 +481,6 @@ class LicenseManager:
531
481
  if cached and now < cached[1]:
532
482
  return True, dict(cached[0]), "License is active and valid (cached)"
533
483
 
534
- # Same fast path across processes: every hook is a fresh interpreter,
535
- # so the in-process memo above never survives to the next tool call.
536
- disk_cached = cls._disk_cache_get(cache_key)
537
- if disk_cached is not None:
538
- return True, disk_cached, "License is active and valid (disk cache)"
539
-
540
484
  parts = license_key.split(".")
541
485
  if len(parts) != 3 or parts[0] not in ("TS1", "TS2"):
542
486
  return False, {}, "Invalid license key format (must start with TS2. or TS1.)"
@@ -609,8 +553,6 @@ class LicenseManager:
609
553
  cls._VALIDATION_CACHE.pop(oldest, None)
610
554
  cls._VALIDATION_CACHE[cache_key] = (payload, now + ttl)
611
555
 
612
- cls._disk_cache_put(cache_key, payload, now + ttl)
613
-
614
556
  return True, payload, "License is active and valid"
615
557
 
616
558
  @classmethod
@@ -911,7 +853,7 @@ class LicenseManager:
911
853
  # For guest / free tier, calculate monthly saved tokens
912
854
  if tracker is None:
913
855
  try:
914
- from src.metrics import MetricsTracker
856
+ from tokensafe.metrics import MetricsTracker
915
857
  tracker = MetricsTracker()
916
858
  except Exception:
917
859
  tracker = None
@@ -15,8 +15,8 @@ import urllib.request
15
15
  from collections import deque
16
16
  from typing import Dict
17
17
 
18
- from src.license_manager import LicenseManager
19
- from src.ssl_context import shared_ssl_context
18
+ from tokensafe.license_manager import LicenseManager
19
+ from tokensafe.ssl_context import shared_ssl_context
20
20
 
21
21
  _MACHINE_HASH = ""
22
22
 
@@ -10,7 +10,7 @@ import hashlib
10
10
  from contextlib import contextmanager
11
11
  from typing import Dict, Any, Tuple
12
12
 
13
- from src.paths import resolve_data_dir
13
+ from tokensafe.paths import resolve_data_dir
14
14
 
15
15
  class LoopDetector:
16
16
  """Tracks tool invocation signatures to detect hallucination loops."""
@@ -160,7 +160,7 @@ class LoopDetector:
160
160
  f"parameters {repeats} times in a row. Pausing loop to prevent token drain."
161
161
  )
162
162
  try:
163
- from src.mistakes import MistakesLedger
163
+ from tokensafe.mistakes import MistakesLedger
164
164
  MistakesLedger.record_from_loop(tool_name, args, repeats)
165
165
  except Exception:
166
166
  pass
@@ -7,7 +7,7 @@ Cline/Roo) to route them through `tokensafe mcp-proxy`. Preserves original comma
7
7
  & arguments under `_tokensafe_orig` for 100% reversible unwrapping.
8
8
 
9
9
  Codex CLI stores its servers in `~/.codex/config.toml`, so it goes through
10
- `src/toml_mcp_config.py`: a splice editor that touches only the two keys it must
10
+ `tokensafe/toml_mcp_config.py`: a splice editor that touches only the two keys it must
11
11
  and keeps the original definition in a `# tokensafe:orig {json}` comment inside
12
12
  the table. Hand-written comments, ordering and other tables stay byte-identical.
13
13
  """
@@ -18,7 +18,7 @@ import json
18
18
  import shutil
19
19
  from typing import Dict, Any, List, Optional, Sequence, Tuple
20
20
 
21
- from src import toml_mcp_config as toml_mcp
21
+ from tokensafe import toml_mcp_config as toml_mcp
22
22
 
23
23
  HOME = os.path.expanduser("~")
24
24
 
@@ -17,8 +17,8 @@ import subprocess
17
17
  import threading
18
18
  from typing import Dict, Any, Optional, List, Tuple
19
19
 
20
- from src.stash import stash_block
21
- from src.stdio_io import ensure_utf8_stdio
20
+ from tokensafe.stash import stash_block
21
+ from tokensafe.stdio_io import ensure_utf8_stdio
22
22
 
23
23
  ensure_utf8_stdio()
24
24
 
@@ -56,7 +56,7 @@ def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
56
56
  Strictly enforces MAX_UNFOLDED_BYTES (8800 bytes) to prevent disk spills."""
57
57
  if not text:
58
58
  return text, False
59
- from src.format_parsers.ansi import strip_ansi
59
+ from tokensafe.format_parsers.ansi import strip_ansi
60
60
  text = strip_ansi(text)
61
61
  raw_bytes = len(text.encode("utf-8"))
62
62
  lines = text.splitlines()
@@ -67,7 +67,7 @@ def fold_tool_text(text: str, tool_name: str = "mcp_tool") -> Tuple[str, bool]:
67
67
  # A string catalog (i18n messages) is 100% payload: head/tail keeps the
68
68
  # boilerplate and drops the middle, while a digest says what is inside.
69
69
  try:
70
- from src.format_parsers.i18n_strings import StringCatalogReducer, sniff
70
+ from tokensafe.format_parsers.i18n_strings import StringCatalogReducer, sniff
71
71
  if sniff(text):
72
72
  digest, was_reduced = StringCatalogReducer.reduce(text, "catalog.ts")
73
73
  if was_reduced: