tokensafe 4.16.2 → 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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/README.md +8 -3
- package/bin/agy-tokens +1 -1
- package/bin/tokensafe +1 -1
- package/bin/tokensafe-acp.js +1 -1
- package/bin/tokensafe-mcp +1 -1
- package/bin/tokensafe.js +1 -1
- package/hooks/claude_code_hook.py +49 -45
- package/hooks/cursor_hook.py +8 -8
- package/hooks/kimi_hook.py +23 -23
- package/hooks/post_tool_use.py +6 -6
- package/hooks/pre_invocation.py +21 -17
- package/hooks/pre_tool_use.py +27 -27
- package/hooks/session_start.py +17 -17
- package/hooks/stop_hook.py +3 -3
- package/hooks/zcode_hook.py +2 -2
- package/kimi.plugin.json +2 -2
- package/mcp_config.json +1 -1
- package/package.json +5 -4
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/__init__.py +9 -5
- package/src/cli.py +11 -2429
- package/src/mcp_server.py +11 -5024
- package/src/proxy.py +11 -1803
- package/tokensafe/__init__.py +6 -0
- package/{src → tokensafe}/acp/__init__.py +2 -2
- package/{src → tokensafe}/acp/server.py +5 -5
- package/{src → tokensafe}/adapter_core.py +42 -17
- package/{src → tokensafe}/agent/__init__.py +1 -1
- package/{src → tokensafe}/agent/context.py +4 -4
- package/{src → tokensafe}/agent/loop.py +4 -4
- package/{src → tokensafe}/agent/providers.py +2 -2
- package/{src → tokensafe}/agent/tools.py +2 -2
- package/{src → tokensafe}/agent_firewall.py +68 -9
- package/{src → tokensafe}/angular_cli.py +4 -4
- package/{src → tokensafe}/auto_inject.py +37 -5
- package/{src → tokensafe}/batch_editor.py +185 -28
- package/tokensafe/batch_search.py +1191 -0
- package/{src → tokensafe}/bench/go_target.py +1 -1
- package/{src → tokensafe}/bench/mechanics.py +1 -1
- package/{src → tokensafe}/bench/react_target.py +1 -1
- package/{src → tokensafe}/bench/runner.py +4 -4
- package/{src → tokensafe}/benchmark.py +12 -12
- package/{src → tokensafe}/benchmark_real.py +18 -18
- package/{src → tokensafe}/build_parsers.py +3 -3
- package/{src → tokensafe}/bundle_probe.py +1 -1
- package/{src → tokensafe}/burn_monitor.py +3 -3
- package/{src → tokensafe}/cache_normalizer.py +1 -1
- package/tokensafe/cli.py +2490 -0
- package/{src → tokensafe}/command_sanitizer.py +94 -26
- package/{src → tokensafe}/compaction_recovery.py +5 -5
- package/{src → tokensafe}/compactor.py +148 -95
- package/{src → tokensafe}/context_index.py +194 -28
- package/{src → tokensafe}/cross_stack.py +2 -2
- package/{src → tokensafe}/dashboard.py +3 -3
- package/{src → tokensafe}/delegation.py +4 -4
- package/{src → tokensafe}/dependency_prefetcher.py +1 -1
- package/{src → tokensafe}/diff_slicer.py +2 -2
- package/{src → tokensafe}/distiller.py +7 -7
- package/{src → tokensafe}/distiller_cache.py +3 -3
- package/{src → tokensafe}/egress_counter.py +1 -1
- package/{src → tokensafe}/environment_auditor.py +7 -7
- package/{src → tokensafe}/file_state.py +2 -2
- package/{src → tokensafe}/format_invariants.py +1 -1
- package/tokensafe/format_parsers/__init__.py +20 -0
- package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
- package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
- package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
- package/{src → tokensafe}/format_parsers/json_log.py +1 -1
- package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
- package/{src → tokensafe}/format_parsers/tabular.py +1 -1
- package/{src → tokensafe}/fts_index.py +20 -11
- package/{src → tokensafe}/governor.py +143 -31
- package/{src → tokensafe}/graph_engine.py +769 -126
- package/{src → tokensafe}/guard.py +80 -25
- package/{src → tokensafe}/history_compactor.py +407 -133
- package/{src → tokensafe}/i18n_catalog.py +39 -14
- package/{src → tokensafe}/image_downscale.py +1 -1
- package/tokensafe/ingress_staging.py +384 -0
- package/{src → tokensafe}/installer.py +118 -61
- package/{src → tokensafe}/license_manager.py +9 -67
- package/{src → tokensafe}/live_relay.py +2 -2
- package/{src → tokensafe}/loop_detector.py +2 -2
- package/{src → tokensafe}/mcp_config_manager.py +2 -2
- package/{src → tokensafe}/mcp_proxy.py +4 -4
- package/tokensafe/mcp_server.py +5664 -0
- package/{src → tokensafe}/metrics.py +56 -21
- package/{src → tokensafe}/mistakes.py +4 -4
- package/{src → tokensafe}/oumv_brief.py +21 -3
- package/{src → tokensafe}/oumv_gateway.py +146 -49
- package/{src → tokensafe}/oumv_policy.py +1 -1
- package/{src → tokensafe}/paths.py +1 -1
- package/{src → tokensafe}/project_memory.py +4 -4
- package/tokensafe/proxy.py +2075 -0
- package/{src → tokensafe}/quality_score.py +4 -4
- package/tokensafe/read_baseline.py +192 -0
- package/tokensafe/repo_compute.py +332 -0
- package/{src → tokensafe}/result_ledger.py +19 -19
- package/{src → tokensafe}/retrofit.py +6 -6
- package/{src → tokensafe}/savings.py +3 -3
- package/tokensafe/schema_slicer.py +1087 -0
- package/{src → tokensafe}/scoped_search.py +144 -6
- package/{src → tokensafe}/secret_redactor.py +22 -0
- package/{src → tokensafe}/session_brief.py +8 -8
- package/{src → tokensafe}/skeletonizer.py +89 -26
- package/{src → tokensafe}/slicer.py +3 -2
- package/{src → tokensafe}/snapshot.py +1 -1
- package/{src → tokensafe}/stash.py +1 -1
- package/{src → tokensafe}/statusline.py +1 -1
- package/{src → tokensafe}/superseded.py +22 -4
- package/{src → tokensafe}/team_cache.py +3 -3
- package/{src → tokensafe}/telemetry_sync.py +63 -11
- package/{src → tokensafe}/test_parsers.py +3 -3
- package/{src → tokensafe}/thinking_fold.py +3 -3
- package/{src → tokensafe}/tokenizer.py +37 -1
- package/{src → tokensafe}/tool_pruner.py +3 -3
- package/{src → tokensafe}/transcript_analyzer.py +1 -1
- package/{src → tokensafe}/transcript_recall.py +8 -8
- package/{src → tokensafe}/type_slicer.py +3 -3
- package/{src → tokensafe}/usage_ledger.py +4 -4
- package/{src → tokensafe}/version_checker.py +6 -6
- package/{src → tokensafe}/web_reader.py +86 -8
- package/{src → tokensafe}/workspace_roots.py +2 -2
- package/src/batch_search.py +0 -589
- package/src/format_parsers/__init__.py +0 -20
- package/src/schema_slicer.py +0 -578
- /package/{src → tokensafe}/agent/pricing.py +0 -0
- /package/{src → tokensafe}/atomic_io.py +0 -0
- /package/{src → tokensafe}/backend_release.py +0 -0
- /package/{src → tokensafe}/bench/__init__.py +0 -0
- /package/{src → tokensafe}/bench/driver.py +0 -0
- /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
- /package/{src → tokensafe}/bench_scenarios.json +0 -0
- /package/{src → tokensafe}/competitors.py +0 -0
- /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
- /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
- /package/{src → tokensafe}/globmatch.py +0 -0
- /package/{src → tokensafe}/host_capabilities.py +0 -0
- /package/{src → tokensafe}/json_repair.py +0 -0
- /package/{src → tokensafe}/route_index.py +0 -0
- /package/{src → tokensafe}/scaffold.py +0 -0
- /package/{src → tokensafe}/session_context.py +0 -0
- /package/{src → tokensafe}/ssl_context.py +0 -0
- /package/{src → tokensafe}/stdio_io.py +0 -0
- /package/{src → tokensafe}/syntax_guard.py +0 -0
- /package/{src → tokensafe}/toml_mcp_config.py +0 -0
- /package/{src → tokensafe}/treesitter_backend.py +0 -0
- /package/{src → tokensafe}/win_paths.py +0 -0
|
@@ -18,8 +18,8 @@ import shlex
|
|
|
18
18
|
import fnmatch
|
|
19
19
|
import subprocess
|
|
20
20
|
from typing import Tuple, Optional, Dict, Any, List, NamedTuple
|
|
21
|
-
from
|
|
22
|
-
from
|
|
21
|
+
from tokensafe.secret_redactor import SecretRedactor
|
|
22
|
+
from tokensafe.command_sanitizer import CommandSanitizer
|
|
23
23
|
|
|
24
24
|
_TOKENSAFE_SRC_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
25
25
|
|
|
@@ -42,7 +42,8 @@ _EXFIL_FILE = rf"(?:[\w./~-]*/)?{_EXFIL_SENSITIVE_PATH}"
|
|
|
42
42
|
_EXFIL_NET = r"(?:sudo\s+)?(?:curl|wget|nc|ncat|netcat)"
|
|
43
43
|
|
|
44
44
|
_EXFIL_PATTERNS = (
|
|
45
|
-
|
|
45
|
+
# `--json @f` and `--data-urlencode @f` / `name@f` upload a file just like -d @f.
|
|
46
|
+
rf"\b{_EXFIL_NET}\b[^;|&\n]*(?:--data(?:-binary|-raw|-urlencode)?|--json|--post-file|-d|-T|--upload-file)(?:[=\s]+)['\"]?(?:[\w.-]*@)?['\"]?{_EXFIL_FILE}",
|
|
46
47
|
rf"\b{_EXFIL_NET}\b[^;|&\n]*(?:-F|--form)\s+[^=\s]*=@['\"]?{_EXFIL_FILE}",
|
|
47
48
|
rf"\b{_EXFIL_NET}\b[^;|&\n]*<\s*['\"]?{_EXFIL_FILE}",
|
|
48
49
|
rf"\bcat\s+['\"]?{_EXFIL_FILE}['\"]?\s*\|\s*{_EXFIL_NET}\b",
|
|
@@ -288,10 +289,18 @@ class TokenSafeGuard:
|
|
|
288
289
|
@classmethod
|
|
289
290
|
def _stage_cmd_tokens(cls, stage: str) -> Tuple[str, List[str]]:
|
|
290
291
|
tokens = cls._tokenize_stage(stage)
|
|
292
|
+
# Subshell/group wrappers: `(rm -rf /)` tokenizes to `(rm` … `/)`, which
|
|
293
|
+
# hid the command name and its target from every check.
|
|
294
|
+
tokens = [t.lstrip("({") if i == 0 or t.startswith(("(", "{")) else t for i, t in enumerate(tokens)]
|
|
295
|
+
if tokens:
|
|
296
|
+
last = tokens[-1]
|
|
297
|
+
if last.endswith((")", "}")) and "(" not in last and "{" not in last and "$" not in last:
|
|
298
|
+
tokens[-1] = last.rstrip(")}")
|
|
299
|
+
tokens = [t for t in tokens if t not in ("", "(", ")", "{", "}", "!")]
|
|
291
300
|
i = 0
|
|
292
301
|
while i < len(tokens):
|
|
293
302
|
tok = tokens[i]
|
|
294
|
-
if tok in ("sudo", "env", "command", "time", "nohup"):
|
|
303
|
+
if tok in ("sudo", "env", "command", "time", "nohup", "exec", "builtin"):
|
|
295
304
|
i += 1
|
|
296
305
|
continue
|
|
297
306
|
if "=" in tok and not tok.startswith("-") and tok.split("=", 1)[0].replace("_", "").isalnum():
|
|
@@ -302,6 +311,10 @@ class TokenSafeGuard:
|
|
|
302
311
|
return "", []
|
|
303
312
|
return os.path.basename(tokens[i]), tokens[i + 1 :]
|
|
304
313
|
|
|
314
|
+
@classmethod
|
|
315
|
+
def _mentions_code_ext(cls, text: str) -> bool:
|
|
316
|
+
return any(re.search(re.escape(ext) + r"(?![\w])", text) for ext in cls.CODE_EXTENSIONS)
|
|
317
|
+
|
|
305
318
|
@classmethod
|
|
306
319
|
def _is_sensitive_filename(cls, path_arg: str) -> bool:
|
|
307
320
|
base = os.path.basename(path_arg.rstrip("/\\"))
|
|
@@ -430,8 +443,14 @@ class TokenSafeGuard:
|
|
|
430
443
|
)
|
|
431
444
|
if has_rf:
|
|
432
445
|
for tgt in targets:
|
|
446
|
+
tgt = tgt.rstrip(";").strip("'\"")
|
|
433
447
|
norm_tgt = tgt.rstrip("/") if tgt != "/" else "/"
|
|
434
|
-
|
|
448
|
+
# Root, home (in any spelling) or cwd/parent, optionally with a
|
|
449
|
+
# trailing `/*` or `/.*` glob: `rm -rf $HOME/*` slipped through.
|
|
450
|
+
home_or_root = re.fullmatch(
|
|
451
|
+
r"(?:/|~|\$HOME|\$\{HOME\}|\.{1,2})(?:/(?:\.?\*)?)?|/?\*|\.?\*", tgt
|
|
452
|
+
)
|
|
453
|
+
if tgt in _DANGEROUS_RM_TARGETS or home_or_root or norm_tgt in ("/", "~", "$HOME", "${HOME}", ".", "..", "*"):
|
|
435
454
|
return GuardResult(
|
|
436
455
|
blocked=True,
|
|
437
456
|
check_name="DESTRUCTIVE_RM",
|
|
@@ -560,11 +579,21 @@ class TokenSafeGuard:
|
|
|
560
579
|
# keys, credential bundles) pulls live secrets into the model context —
|
|
561
580
|
# and off the machine — even without any exfil pipe. Example files are exempt.
|
|
562
581
|
def _is_secret_file_read(path: str) -> bool:
|
|
563
|
-
|
|
582
|
+
clean = path.strip("'\"").replace("\\", "/")
|
|
583
|
+
base = os.path.basename(clean).lower()
|
|
564
584
|
if not base:
|
|
565
585
|
return False
|
|
566
586
|
if "example" in base or "sample" in base or "template" in base:
|
|
567
587
|
return False
|
|
588
|
+
# Per-user credential stores (cloud CLIs, package registries, netrc).
|
|
589
|
+
parent = os.path.basename(os.path.dirname(clean)).lower()
|
|
590
|
+
if base in (".npmrc", ".pypirc", ".netrc", ".pgpass", ".git-credentials"):
|
|
591
|
+
return True
|
|
592
|
+
if (parent, base) in (
|
|
593
|
+
(".aws", "credentials"), (".docker", "config.json"), (".kube", "config"),
|
|
594
|
+
("gcloud", "application_default_credentials.json"),
|
|
595
|
+
):
|
|
596
|
+
return True
|
|
568
597
|
if base == ".env" or base.startswith(".env."):
|
|
569
598
|
return True
|
|
570
599
|
if base.endswith((".pem", ".key", ".p12", ".pfx", ".keystore")):
|
|
@@ -668,7 +697,7 @@ class TokenSafeGuard:
|
|
|
668
697
|
if not cls._oumv_curl_guard_enabled():
|
|
669
698
|
return None
|
|
670
699
|
try:
|
|
671
|
-
from
|
|
700
|
+
from tokensafe.oumv_gateway import OUMVGateway
|
|
672
701
|
live_ports = OUMVGateway.get_live_ports(cwd)
|
|
673
702
|
except Exception:
|
|
674
703
|
live_ports = []
|
|
@@ -714,8 +743,7 @@ class TokenSafeGuard:
|
|
|
714
743
|
path_args = positionals
|
|
715
744
|
|
|
716
745
|
for p in path_args:
|
|
717
|
-
|
|
718
|
-
if any(low_p.endswith(ext) or ext in low_p for ext in cls.CODE_EXTENSIONS):
|
|
746
|
+
if cls._mentions_code_ext(p.lower()):
|
|
719
747
|
return True
|
|
720
748
|
segs = [s for s in re.split(r"[/\\]", p.strip("\"'")) if s]
|
|
721
749
|
if any(s in cls.CODE_DIRS for s in segs):
|
|
@@ -756,7 +784,9 @@ class TokenSafeGuard:
|
|
|
756
784
|
|
|
757
785
|
if cmd_tok in ("grep", "egrep", "rg", "ripgrep") or is_git_grep:
|
|
758
786
|
effective_args = cmd_args[cmd_args.index("grep") + 1:] if is_git_grep else cmd_args
|
|
759
|
-
|
|
787
|
+
# Whole extension only: a substring test took `.js` in
|
|
788
|
+
# `package.json`, `.c` in `.cfg` and `.h` in `.html` for code.
|
|
789
|
+
has_code_ext = cls._mentions_code_ext(sub_cmd)
|
|
760
790
|
has_code_dir = cls._has_code_target_in_args("grep" if is_git_grep else cmd_tok, effective_args)
|
|
761
791
|
is_recursive_grep = (cmd_tok in ("grep", "egrep") or is_git_grep) and any(
|
|
762
792
|
(a.startswith("-") and not a.startswith("--") and ("r" in a or "R" in a)) or a == "--recursive"
|
|
@@ -775,7 +805,9 @@ class TokenSafeGuard:
|
|
|
775
805
|
)
|
|
776
806
|
|
|
777
807
|
elif cmd_tok == "find":
|
|
778
|
-
|
|
808
|
+
# Whole extension only: a substring test took `.js` in
|
|
809
|
+
# `package.json`, `.c` in `.cfg` and `.h` in `.html` for code.
|
|
810
|
+
has_code_ext = cls._mentions_code_ext(sub_cmd)
|
|
779
811
|
has_code_dir = cls._has_code_target_in_args(cmd_tok, cmd_args) or bool(cls._CODE_DIR_RE.search(sub_cmd))
|
|
780
812
|
is_root_file_crawl = any(a in (".", "./") for a in cmd_args[:2]) and ("-type" in cmd_args and "f" in cmd_args)
|
|
781
813
|
if has_code_ext or has_code_dir or is_root_file_crawl:
|
|
@@ -791,7 +823,8 @@ class TokenSafeGuard:
|
|
|
791
823
|
def _find_unignored_sensitive_file(cls, target_dir: str) -> Optional[str]:
|
|
792
824
|
"""
|
|
793
825
|
Returns the repo-relative path of the first unignored sensitive file, or None.
|
|
794
|
-
Prefers
|
|
826
|
+
Prefers git itself: `ls-files -o` for untracked files, then `status` on
|
|
827
|
+
tracked sensitive paths only (skipping deleted 'D' entries).
|
|
795
828
|
"""
|
|
796
829
|
def _is_sensitive_name(name: str) -> bool:
|
|
797
830
|
low = name.lower()
|
|
@@ -800,22 +833,44 @@ class TokenSafeGuard:
|
|
|
800
833
|
return name in cls.SENSITIVE_GIT_FILES or (name.startswith(".env") and not any(low.endswith(suf) for suf in cls._TEMPLATE_EXAMPLES))
|
|
801
834
|
|
|
802
835
|
# 1. Fast & exact: ask git itself (only lists non-ignored files).
|
|
803
|
-
|
|
836
|
+
# `git status -uall` refreshed the whole index and diffed every
|
|
837
|
+
# tracked file on each `git add -A`. The same answer needs much less:
|
|
838
|
+
# untracked, non-ignored files come from `ls-files -o` (no content
|
|
839
|
+
# diff), and tracked files are filtered by name from the index first,
|
|
840
|
+
# so `git status` only runs on the few sensitive paths, if any.
|
|
841
|
+
def _git(args: List[str]) -> Optional[str]:
|
|
804
842
|
res = subprocess.run(
|
|
805
|
-
["git", "-C", target_dir,
|
|
843
|
+
["git", "-C", target_dir, *args],
|
|
806
844
|
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5
|
|
807
845
|
)
|
|
808
|
-
if res.returncode == 0
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
846
|
+
return res.stdout if res.returncode == 0 else None
|
|
847
|
+
|
|
848
|
+
try:
|
|
849
|
+
untracked = _git(["ls-files", "-z", "--others", "--exclude-standard", "--", ":/"])
|
|
850
|
+
if untracked is not None:
|
|
851
|
+
for candidate in untracked.split("\0"):
|
|
852
|
+
if candidate and _is_sensitive_name(os.path.basename(candidate)):
|
|
853
|
+
return candidate
|
|
854
|
+
tracked = _git(["ls-files", "-z", "--cached", "--", ":/"])
|
|
855
|
+
if tracked is not None:
|
|
856
|
+
suspects = sorted({
|
|
857
|
+
c for c in tracked.split("\0")
|
|
858
|
+
if c and _is_sensitive_name(os.path.basename(c))
|
|
859
|
+
})
|
|
860
|
+
if not suspects:
|
|
861
|
+
return None
|
|
862
|
+
status = _git(["status", "--porcelain", "--", *suspects])
|
|
863
|
+
if status is not None:
|
|
864
|
+
for line in status.splitlines():
|
|
865
|
+
if len(line) >= 2 and line[:2] in (" D", "D ", "DD"):
|
|
866
|
+
continue
|
|
867
|
+
path_part = line[3:].strip() if len(line) > 3 else ""
|
|
868
|
+
if path_part.startswith('"') and path_part.endswith('"'):
|
|
869
|
+
path_part = path_part[1:-1]
|
|
870
|
+
for candidate in (seg.strip() for seg in path_part.split("->")):
|
|
871
|
+
if candidate and _is_sensitive_name(os.path.basename(candidate)):
|
|
872
|
+
return candidate
|
|
873
|
+
return None
|
|
819
874
|
except Exception:
|
|
820
875
|
pass
|
|
821
876
|
|