tokensafe 3.2.0 → 4.0.1

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 (41) hide show
  1. package/README.md +60 -28
  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 +2 -2
  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 +234 -2
  16. package/src/command_sanitizer.py +2 -0
  17. package/src/competitors.py +179 -0
  18. package/src/environment_auditor.py +110 -1
  19. package/src/format_parsers/__init__.py +20 -0
  20. package/src/format_parsers/ansi.py +41 -0
  21. package/src/format_parsers/compiler_errors.py +159 -0
  22. package/src/format_parsers/docker_k8s.py +95 -0
  23. package/src/format_parsers/json_log.py +89 -0
  24. package/src/format_parsers/lockfiles.py +157 -0
  25. package/src/format_parsers/tabular.py +175 -0
  26. package/src/fts_index.py +296 -0
  27. package/src/graph_engine.py +395 -48
  28. package/src/image_downscale.py +228 -0
  29. package/src/loop_detector.py +5 -0
  30. package/src/mcp_config_manager.py +197 -0
  31. package/src/mcp_proxy.py +154 -0
  32. package/src/mcp_server.py +215 -1
  33. package/src/mistakes.py +203 -0
  34. package/src/result_ledger.py +8 -1
  35. package/src/scoped_search.py +32 -0
  36. package/src/stash.py +199 -0
  37. package/src/superseded.py +220 -0
  38. package/src/telemetry_sync.py +1 -1
  39. package/src/test_parsers.py +271 -0
  40. package/src/version_checker.py +1 -1
  41. package/src/web_reader.py +202 -0
@@ -0,0 +1,89 @@
1
+ """
2
+ TokenSafe Structured JSON & NDJSON Log Reducer (v3.3.0).
3
+
4
+ Filters high-volume JSON log streams (Winston, Bunyan, Zap, Logstash, Docker JSON logs):
5
+ - Summarizes total log events by severity level (INFO, WARN, ERROR, DEBUG)
6
+ - Drops noisy repetitive DEBUG/INFO lines while preserving all ERROR and WARN events
7
+ - Stashes raw log stream into TokenSafe reversible stash with a hash anchor.
8
+ """
9
+
10
+ import json
11
+ from typing import Tuple, Dict, Any, List
12
+ from src.stash import stash_block
13
+
14
+
15
+ class JSONLogReducer:
16
+ """Parses and compresses structured NDJSON log streams."""
17
+
18
+ @classmethod
19
+ def is_ndjson_log(cls, content: str) -> bool:
20
+ lines = [ln.strip() for ln in content.splitlines() if ln.strip()]
21
+ if len(lines) < 10:
22
+ return False
23
+ # Check first 3 lines
24
+ valid_json = 0
25
+ for ln in lines[:3]:
26
+ if ln.startswith("{") and ln.endswith("}"):
27
+ try:
28
+ obj = json.loads(ln)
29
+ if isinstance(obj, dict) and any(k in obj for k in ("level", "msg", "message", "timestamp", "time")):
30
+ valid_json += 1
31
+ except Exception:
32
+ pass
33
+ return valid_json >= 2
34
+
35
+ @classmethod
36
+ def reduce(cls, content: str) -> Tuple[str, bool]:
37
+ """Reduces JSON log stream down to error/warn events and count summary."""
38
+ lines = [ln.strip() for ln in content.splitlines() if ln.strip()]
39
+ if len(lines) < 15:
40
+ return content, False
41
+
42
+ counts = {"DEBUG": 0, "INFO": 0, "WARN": 0, "ERROR": 0, "OTHER": 0}
43
+ important_logs = []
44
+
45
+ for ln in lines:
46
+ try:
47
+ obj = json.loads(ln)
48
+ if not isinstance(obj, dict):
49
+ continue
50
+ lvl = str(obj.get("level") or obj.get("severity") or "OTHER").upper()
51
+ if "ERR" in lvl or lvl in ("50", "FATAL"):
52
+ counts["ERROR"] += 1
53
+ important_logs.append((lvl, obj))
54
+ elif "WARN" in lvl or lvl == "40":
55
+ counts["WARN"] += 1
56
+ important_logs.append((lvl, obj))
57
+ elif "INFO" in lvl or lvl == "30":
58
+ counts["INFO"] += 1
59
+ elif "DEBUG" in lvl or lvl == "20" or lvl == "10":
60
+ counts["DEBUG"] += 1
61
+ else:
62
+ counts["OTHER"] += 1
63
+ except Exception:
64
+ pass
65
+
66
+ total_parsed = sum(counts.values())
67
+ if total_parsed < 10:
68
+ return content, False
69
+
70
+ hash8, marker = stash_block(content, source="json_logs")
71
+ counts_str = ", ".join(f"{k}: {v}" for k, v in counts.items() if v > 0)
72
+ out = [
73
+ f"# [TokenSafe JSON Logs: {total_parsed} events ({counts_str})]",
74
+ ""
75
+ ]
76
+
77
+ if important_logs:
78
+ out.append(f"## Errors & Warnings ({len(important_logs)} events):")
79
+ for lvl, obj in important_logs[:20]:
80
+ msg = obj.get("msg") or obj.get("message") or str(obj)
81
+ ts = obj.get("time") or obj.get("timestamp") or ""
82
+ ts_str = f"[{ts}] " if ts else ""
83
+ out.append(f" ✗ {ts_str}{lvl}: {msg}")
84
+ else:
85
+ out.append("✓ No errors or warnings found in log stream.")
86
+
87
+ out.append("")
88
+ out.append(marker)
89
+ return "\n".join(out), True
@@ -0,0 +1,157 @@
1
+ """
2
+ TokenSafe Lockfile Parser & Reducer (v3.3.0).
3
+
4
+ Reduces bloated lockfiles (package-lock.json, Cargo.lock, poetry.lock, pnpm-lock.yaml)
5
+ from 10,000+ lines of integrity hashes and URLs down to a compact dependency bill:
6
+ - Direct packages and exact resolved versions
7
+ - Dependency count summary
8
+ - Reversible hash anchor pointing to the full raw file in TokenSafe stash.
9
+ """
10
+
11
+ import json
12
+ import re
13
+ from typing import Tuple, Dict, Any, List, Optional
14
+ from src.stash import stash_block
15
+
16
+
17
+ class LockfileReducer:
18
+ """Extracts compact dependency information from verbose lockfiles."""
19
+
20
+ @classmethod
21
+ def is_lockfile(cls, filename_or_path: str) -> bool:
22
+ name = filename_or_path.lower().split("/")[-1].split("\\")[-1]
23
+ return name in (
24
+ "package-lock.json",
25
+ "pnpm-lock.yaml",
26
+ "yarn.lock",
27
+ "cargo.lock",
28
+ "poetry.lock",
29
+ "gemfile.lock",
30
+ "composer.lock",
31
+ "go.sum",
32
+ )
33
+
34
+ @classmethod
35
+ def reduce(cls, content: str, filename: str = "package-lock.json") -> Tuple[str, bool]:
36
+ """Reduces lockfile content to a clean summary. Returns (compacted_text, was_compacted)."""
37
+ lines = content.splitlines()
38
+ if len(lines) < 30:
39
+ return content, False
40
+
41
+ fname = filename.lower().split("/")[-1].split("\\")[-1]
42
+
43
+ if fname == "package-lock.json":
44
+ return cls._reduce_npm_lock(content)
45
+ elif fname == "cargo.lock":
46
+ return cls._reduce_cargo_lock(content)
47
+ elif fname == "poetry.lock":
48
+ return cls._reduce_poetry_lock(content)
49
+
50
+ return cls._generic_reduce(content, fname)
51
+
52
+ @classmethod
53
+ def _reduce_npm_lock(cls, content: str) -> Tuple[str, bool]:
54
+ try:
55
+ data = json.loads(content)
56
+ except Exception:
57
+ return cls._generic_reduce(content, "package-lock.json")
58
+
59
+ name = data.get("name") or "project"
60
+ lock_version = data.get("lockfileVersion", 1)
61
+ packages = data.get("packages", {})
62
+ dependencies = data.get("dependencies", {})
63
+
64
+ direct_deps = {}
65
+ total_count = 0
66
+
67
+ # Lockfile v2/v3
68
+ if packages and isinstance(packages, dict):
69
+ root_pkg = packages.get("") or {}
70
+ root_deps = {**root_pkg.get("dependencies", {}), **root_pkg.get("devDependencies", {})}
71
+ total_count = len(packages) - 1
72
+ for dep_name, expected_ver in sorted(root_deps.items()):
73
+ target_key = f"node_modules/{dep_name}"
74
+ resolved_ver = packages.get(target_key, {}).get("version") or expected_ver
75
+ direct_deps[dep_name] = resolved_ver
76
+ elif dependencies and isinstance(dependencies, dict):
77
+ # Lockfile v1
78
+ total_count = len(dependencies)
79
+ for dep_name, info in sorted(dependencies.items()):
80
+ if isinstance(info, dict):
81
+ direct_deps[dep_name] = info.get("version", "*")
82
+
83
+ lines = [
84
+ f"# [TokenSafe Lockfile Summary: package-lock.json (v{lock_version})]",
85
+ f"Project: {name} | Total installed packages: {total_count}",
86
+ "",
87
+ "## Direct Dependencies:"
88
+ ]
89
+ for dname, dver in direct_deps.items():
90
+ lines.append(f" - {dname}: {dver}")
91
+
92
+ hash8, marker = stash_block(content, source="lockfile:npm")
93
+ lines.append("")
94
+ lines.append(marker)
95
+ return "\n".join(lines), True
96
+
97
+ @classmethod
98
+ def _reduce_cargo_lock(cls, content: str) -> Tuple[str, bool]:
99
+ # Cargo.lock format: [[package]] name = "..." version = "..."
100
+ pkg_pattern = re.compile(r'\[\[package\]\]\s+name\s*=\s*"([^"]+)"\s+version\s*=\s*"([^"]+)"')
101
+ matches = pkg_pattern.findall(content)
102
+ if not matches:
103
+ return cls._generic_reduce(content, "Cargo.lock")
104
+
105
+ lines = [
106
+ f"# [TokenSafe Lockfile Summary: Cargo.lock]",
107
+ f"Total resolved crates: {len(matches)}",
108
+ "",
109
+ "## Crates:"
110
+ ]
111
+ # Show top 40 unique packages
112
+ seen = set()
113
+ for name, ver in sorted(matches):
114
+ if name not in seen:
115
+ seen.add(name)
116
+ lines.append(f" - {name}: {ver}")
117
+
118
+ hash8, marker = stash_block(content, source="lockfile:cargo")
119
+ lines.append("")
120
+ lines.append(marker)
121
+ return "\n".join(lines), True
122
+
123
+ @classmethod
124
+ def _reduce_poetry_lock(cls, content: str) -> Tuple[str, bool]:
125
+ pkg_pattern = re.compile(r'\[\[package\]\]\s+name\s*=\s*"([^"]+)"\s+version\s*=\s*"([^"]+)"')
126
+ matches = pkg_pattern.findall(content)
127
+ if not matches:
128
+ return cls._generic_reduce(content, "poetry.lock")
129
+
130
+ lines = [
131
+ f"# [TokenSafe Lockfile Summary: poetry.lock]",
132
+ f"Total resolved Python packages: {len(matches)}",
133
+ "",
134
+ "## Packages:"
135
+ ]
136
+ for name, ver in sorted(matches):
137
+ lines.append(f" - {name}: {ver}")
138
+
139
+ hash8, marker = stash_block(content, source="lockfile:poetry")
140
+ lines.append("")
141
+ lines.append(marker)
142
+ return "\n".join(lines), True
143
+
144
+ @classmethod
145
+ def _generic_reduce(cls, content: str, fname: str) -> Tuple[str, bool]:
146
+ lines = content.splitlines()
147
+ head = lines[:20]
148
+ tail = lines[-10:]
149
+ omitted = len(lines) - 30
150
+ hash8, marker = stash_block(content, source=f"lockfile:{fname}")
151
+ out = (
152
+ head +
153
+ [f"\n... [{omitted} lines of lockfile metadata omitted by TokenSafe] ...\n"] +
154
+ tail +
155
+ ["", marker]
156
+ )
157
+ return "\n".join(out), True
@@ -0,0 +1,175 @@
1
+ """
2
+ TokenSafe Tabular & Data Dump Reducer (v3.3.0).
3
+
4
+ Compacts large structured data files:
5
+ - CSV / TSV files: outputs column schema, types, and top 10 sample rows (-95% tokens)
6
+ - SQL dumps: preserves schema (CREATE/ALTER TABLE) while folding repetitive INSERT batches
7
+ - HAR (HTTP Archive) files: summarizes network requests (method, URL, status, size) without multi-MB payloads
8
+ All folded content is stashed in TokenSafe reversible stash.
9
+ """
10
+
11
+ import csv
12
+ import io
13
+ import json
14
+ import re
15
+ from typing import Tuple, Dict, Any, List, Optional
16
+ from src.stash import stash_block
17
+
18
+
19
+ class TabularReducer:
20
+ """Reduces CSV, TSV, SQL dump, and HAR data blobs."""
21
+
22
+ @classmethod
23
+ def is_tabular_or_dump(cls, filename: str) -> bool:
24
+ fn = filename.lower()
25
+ return fn.endswith((".csv", ".tsv", ".sql", ".har"))
26
+
27
+ @classmethod
28
+ def reduce_csv(cls, content: str, delimiter: Optional[str] = None) -> Tuple[str, bool]:
29
+ """Reduces CSV/TSV content to a compact schema + sample rows."""
30
+ lines = content.splitlines()
31
+ if len(lines) < 25:
32
+ return content, False
33
+
34
+ # Detect delimiter if not given
35
+ sample = "\n".join(lines[:10])
36
+ if delimiter is None:
37
+ if "\t" in lines[0] and lines[0].count("\t") > lines[0].count(","):
38
+ delimiter = "\t"
39
+ elif ";" in lines[0] and lines[0].count(";") > lines[0].count(","):
40
+ delimiter = ";"
41
+ else:
42
+ delimiter = ","
43
+
44
+ try:
45
+ reader = csv.reader(io.StringIO(content), delimiter=delimiter)
46
+ all_rows = []
47
+ for idx, row in enumerate(reader):
48
+ all_rows.append(row)
49
+ if idx > 50000:
50
+ break
51
+ except Exception:
52
+ return content, False
53
+
54
+ total_rows = len(all_rows)
55
+ if total_rows < 25:
56
+ return content, False
57
+
58
+ header = all_rows[0]
59
+ sample_rows = all_rows[1:11]
60
+
61
+ # Infer column types from sample
62
+ col_types = []
63
+ for col_idx in range(len(header)):
64
+ vals = [r[col_idx] for r in sample_rows if col_idx < len(r) and r[col_idx].strip()]
65
+ inferred = "string"
66
+ if vals:
67
+ if all(v.isdigit() for v in vals):
68
+ inferred = "int"
69
+ elif all(re.match(r"^-?\d+(?:\.\d+)?$", v) for v in vals):
70
+ inferred = "float"
71
+ elif all(v.lower() in ("true", "false", "0", "1") for v in vals):
72
+ inferred = "bool"
73
+ elif all("-" in v and len(v) in (10, 19, 20, 24) for v in vals):
74
+ inferred = "date/time"
75
+ col_types.append(inferred)
76
+
77
+ hash8, marker = stash_block(content, source="tabular:csv")
78
+ out = [
79
+ f"# [TokenSafe CSV Summary: {total_rows - 1} rows × {len(header)} columns]",
80
+ f"Columns: {', '.join(f'`{h}` ({t})' for h, t in zip(header, col_types))}",
81
+ "",
82
+ "## Sample Data (first 10 rows):",
83
+ "| " + " | ".join(header) + " |",
84
+ "| " + " | ".join(["---"] * len(header)) + " |"
85
+ ]
86
+ for row in sample_rows:
87
+ # Pad row if short
88
+ padded = row + [""] * (len(header) - len(row))
89
+ clean_cells = [c.replace("\n", " ").replace("|", "\\|")[:40] for c in padded[:len(header)]]
90
+ out.append("| " + " | ".join(clean_cells) + " |")
91
+
92
+ out.append("")
93
+ out.append(f"... [{total_rows - 11} rows omitted by TokenSafe] ...")
94
+ out.append("")
95
+ out.append(marker)
96
+ return "\n".join(out), True
97
+
98
+ @classmethod
99
+ def reduce_sql_dump(cls, content: str) -> Tuple[str, bool]:
100
+ """Folds repetitive INSERT INTO statements while preserving DDL schemas."""
101
+ lines = content.splitlines()
102
+ if len(lines) < 30 or "INSERT INTO" not in content.upper():
103
+ return content, False
104
+
105
+ kept_lines = []
106
+ insert_counts: Dict[str, int] = {}
107
+ insert_pattern = re.compile(r"^\s*INSERT\s+INTO\s+[`\"']?([a-zA-Z0-9_.-]+)[`\"']?", re.IGNORECASE)
108
+
109
+ for ln in lines:
110
+ m = insert_pattern.match(ln)
111
+ if m:
112
+ tbl = m.group(1)
113
+ insert_counts[tbl] = insert_counts.get(tbl, 0) + 1
114
+ else:
115
+ kept_lines.append(ln)
116
+
117
+ total_inserts = sum(insert_counts.values())
118
+ if total_inserts < 15:
119
+ return content, False
120
+
121
+ hash8, marker = stash_block(content, source="sql_dump")
122
+ out = [
123
+ f"-- [TokenSafe SQL Dump Summary: {len(kept_lines)} DDL/meta lines | {total_inserts} INSERT statements folded]",
124
+ "-- INSERT batches omitted per table:"
125
+ ]
126
+ for tbl, cnt in insert_counts.items():
127
+ out.append(f"-- • `{tbl}`: {cnt} rows folded")
128
+ out.append(f"-- {marker}")
129
+ out.append("")
130
+ out.extend(kept_lines[:200]) # keep schema DDL
131
+ if len(kept_lines) > 200:
132
+ out.append(f"\n-- ... [{len(kept_lines) - 200} DDL lines omitted] ...")
133
+ return "\n".join(out), True
134
+
135
+ @classmethod
136
+ def reduce_har(cls, content: str) -> Tuple[str, bool]:
137
+ """Summarizes HTTP Archive JSON down to request URLs and HTTP statuses."""
138
+ try:
139
+ data = json.loads(content)
140
+ except Exception:
141
+ return content, False
142
+
143
+ log = data.get("log")
144
+ if not isinstance(log, dict) or "entries" not in log:
145
+ return content, False
146
+
147
+ entries = log.get("entries", [])
148
+ if len(entries) < 5:
149
+ return content, False
150
+
151
+ summary_rows = []
152
+ for e in entries:
153
+ req = e.get("request", {})
154
+ resp = e.get("response", {})
155
+ method = req.get("method", "GET")
156
+ url = req.get("url", "")
157
+ status = resp.get("status", 0)
158
+ body_size = resp.get("bodySize", 0)
159
+ time_ms = int(e.get("time", 0))
160
+
161
+ # Strip query params if too long
162
+ clean_url = url.split("?")[0] if len(url) > 80 else url
163
+ summary_rows.append(f"- `[{method}]` {status} | {body_size} B | {time_ms}ms | {clean_url}")
164
+
165
+ hash8, marker = stash_block(content, source="har_archive")
166
+ out = [
167
+ f"# [TokenSafe HAR Archive Summary: {len(entries)} HTTP transactions]",
168
+ "",
169
+ *summary_rows[:60],
170
+ ]
171
+ if len(summary_rows) > 60:
172
+ out.append(f"... [{len(summary_rows) - 60} requests omitted] ...")
173
+ out.append("")
174
+ out.append(marker)
175
+ return "\n".join(out), True