tokensafe 4.4.9 → 4.5.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 (65) hide show
  1. package/.codex-plugin/plugin.json +1 -1
  2. package/bin/agy-tokens +10 -1
  3. package/bin/tokensafe.js +2 -1
  4. package/hooks/claude_code_hook.py +38 -126
  5. package/hooks/cursor_hook.py +45 -1
  6. package/hooks/kimi_hook.py +46 -90
  7. package/hooks/pre_invocation.py +23 -4
  8. package/hooks/pre_tool_use.py +40 -22
  9. package/hooks/session_start.py +44 -15
  10. package/hooks/zcode_hook.py +95 -0
  11. package/hooks.json +1 -1
  12. package/kimi.plugin.json +17 -1
  13. package/mcp_config.json +24 -1
  14. package/package.json +1 -1
  15. package/plugin.json +1 -1
  16. package/rules/AGENTS.md +24 -21
  17. package/server.json +3 -3
  18. package/skills/token-optimizer/SKILL.md +61 -76
  19. package/skills/token-optimizer/references/mcp-tools.md +32 -132
  20. package/src/adapter_core.py +231 -7
  21. package/src/batch_editor.py +403 -0
  22. package/src/batch_search.py +428 -0
  23. package/src/burn_monitor.py +581 -0
  24. package/src/cache_normalizer.py +2 -0
  25. package/src/cli.py +85 -4
  26. package/src/compactor.py +1 -1
  27. package/src/dashboard.py +17 -9
  28. package/src/diff_slicer.py +1 -1
  29. package/src/distiller.py +11 -1
  30. package/src/environment_auditor.py +30 -6
  31. package/src/format_parsers/ansi.py +1 -1
  32. package/src/format_parsers/lockfiles.py +22 -17
  33. package/src/format_parsers/tabular.py +6 -3
  34. package/src/fts_index.py +26 -20
  35. package/src/governor.py +2 -2
  36. package/src/graph_engine.py +232 -52
  37. package/src/guard.py +3 -3
  38. package/src/image_downscale.py +26 -0
  39. package/src/installer.py +61 -48
  40. package/src/license_manager.py +49 -16
  41. package/src/live_relay.py +9 -8
  42. package/src/mcp_proxy.py +13 -7
  43. package/src/mcp_server.py +758 -26
  44. package/src/metrics.py +10 -1
  45. package/src/mistakes.py +4 -2
  46. package/src/oumv_gateway.py +81 -7
  47. package/src/paths.py +4 -1
  48. package/src/proxy.py +302 -123
  49. package/src/result_ledger.py +39 -1
  50. package/src/schema_slicer.py +40 -18
  51. package/src/scoped_search.py +66 -23
  52. package/src/skeletonizer.py +22 -11
  53. package/src/slicer.py +6 -4
  54. package/src/snapshot.py +249 -0
  55. package/src/stash.py +37 -7
  56. package/src/superseded.py +42 -23
  57. package/src/syntax_guard.py +86 -0
  58. package/src/team_cache.py +3 -0
  59. package/src/telemetry_sync.py +66 -53
  60. package/src/thinking_fold.py +50 -12
  61. package/src/transcript_analyzer.py +483 -0
  62. package/src/treesitter_backend.py +2 -0
  63. package/src/type_slicer.py +60 -18
  64. package/src/version_checker.py +1 -1
  65. package/src/web_reader.py +55 -22
@@ -0,0 +1,428 @@
1
+ """
2
+ TokenSafe Batch Search Engine (v3.5.0).
3
+
4
+ Executes up to 20 heterogeneous code, path, and read-only git searches
5
+ concurrently in one MCP call, cutting round-trip LLM turns and avoiding
6
+ per-command remote safety evaluation overheads.
7
+
8
+ Supported query types:
9
+ - 'text': literal substring search.
10
+ - 'regex': regular expression pattern matching.
11
+ - 'glob': file name and path pattern matching.
12
+ - 'fuzzy': case-insensitive fuzzy path and symbol search.
13
+ - 'git': read-only git queries (status, diff, log, show, branch, rev-parse, ls-files).
14
+ """
15
+
16
+ import os
17
+ import re
18
+ import fnmatch
19
+ import shutil
20
+ import subprocess
21
+ from concurrent.futures import ThreadPoolExecutor, as_completed
22
+ from typing import Dict, Any, List, Optional, Tuple
23
+
24
+ from src.scoped_search import ScopedSearch, IGNORED_DIRS, IGNORED_EXTENSIONS, CODE_EXTENSIONS
25
+ from src.format_parsers.ansi import strip_ansi
26
+
27
+ MAX_BATCH_QUERIES = 20
28
+ MAX_OUTPUT_CHARS = 8000
29
+ DEFAULT_QUERY_RESULTS = 25
30
+
31
+ ALLOWED_GIT_COMMANDS = {
32
+ "status", "diff", "log", "show", "branch", "rev-parse",
33
+ "ls-files", "blame", "shortlog", "describe", "tag"
34
+ }
35
+
36
+ HARDENED_GIT_BASE_ARGS = [
37
+ "--no-optional-locks",
38
+ "-c", "core.fsmonitor=false",
39
+ "-c", "diff.external=",
40
+ "-c", "gpg.program=false",
41
+ "--no-pager"
42
+ ]
43
+
44
+
45
+ def _is_git_command_safe(args_str: str) -> Tuple[bool, str, List[str]]:
46
+ """Checks if git command is strictly read-only and returns tokens."""
47
+ tokens = [t for t in re.split(r"\s+", args_str.strip()) if t]
48
+ if not tokens:
49
+ return False, "Empty git command.", []
50
+ subcmd = tokens[0].lower()
51
+ if subcmd.startswith("git"):
52
+ tokens = tokens[1:]
53
+ if not tokens:
54
+ return False, "Empty git command.", []
55
+ subcmd = tokens[0].lower()
56
+
57
+ if subcmd not in ALLOWED_GIT_COMMANDS:
58
+ return False, f"Git subcommand '{subcmd}' is not in the read-only allowlist ({', '.join(sorted(ALLOWED_GIT_COMMANDS))}).", []
59
+
60
+ # Block destructive, config-overriding, or mutating flags
61
+ _BLOCKED_GIT_PREFIXES = ("-c", "-C", "--git-dir", "--work-tree", "--exec-path", "--output", "--ext-diff", "--exec")
62
+ _READ_ONLY_BRANCH_TAG_FLAGS = {
63
+ "-l", "--list", "-a", "--all", "-r", "--remotes", "-v", "-vv", "--verbose",
64
+ "--show-current", "--contains", "--no-contains", "--merged", "--no-merged",
65
+ "--sort", "--format", "--points-at", "--color", "--no-color", "--abbrev",
66
+ }
67
+ for idx, tok in enumerate(tokens[1:], start=1):
68
+ low_tok = tok.lower()
69
+ if tok in ("--delete", "-d", "-D", "-m", "-M", "--hard", "--reset", "--force", "-f", "--interactive", "-i"):
70
+ return False, f"Destructive flag '{tok}' is disallowed in batch_search.", []
71
+ if any(tok == p or tok.startswith(p + "=") for p in _BLOCKED_GIT_PREFIXES):
72
+ return False, f"Git flag '{tok}' is disallowed in batch_search.", []
73
+ if subcmd in ("branch", "tag") and not tok.startswith("-"):
74
+ prev = tokens[idx - 1]
75
+ if prev not in ("--contains", "--no-contains", "--merged", "--no-merged", "--sort", "--format", "--points-at", "-l", "--list"):
76
+ return False, f"Positional argument '{tok}' with git {subcmd} is disallowed (read-only flags only).", []
77
+ elif subcmd in ("branch", "tag") and tok.startswith("-") and tok.split("=", 1)[0] not in _READ_ONLY_BRANCH_TAG_FLAGS:
78
+ return False, f"Flag '{tok}' with git {subcmd} is not in read-only list.", []
79
+
80
+ return True, "", tokens
81
+
82
+
83
+ def _run_git_query(pattern: str, cwd: str, timeout_sec: int = 5) -> Dict[str, Any]:
84
+ """Runs a read-only git query."""
85
+ is_safe, err_msg, tokens = _is_git_command_safe(pattern)
86
+ if not is_safe:
87
+ return {"error": err_msg, "matches": [], "count": 0}
88
+
89
+ git_bin = shutil.which("git")
90
+ if not git_bin:
91
+ return {"error": "git executable not found in PATH", "matches": [], "count": 0}
92
+
93
+ cmd = [git_bin, *HARDENED_GIT_BASE_ARGS, *tokens]
94
+ env = os.environ.copy()
95
+ env["GIT_TERMINAL_PROMPT"] = "0"
96
+ env["GIT_PAGER"] = "cat"
97
+
98
+ try:
99
+ proc = subprocess.run(
100
+ cmd,
101
+ cwd=cwd,
102
+ stdout=subprocess.PIPE,
103
+ stderr=subprocess.PIPE,
104
+ text=True,
105
+ timeout=timeout_sec,
106
+ env=env
107
+ )
108
+ if proc.returncode != 0:
109
+ err = proc.stderr.strip() or f"git exited with code {proc.returncode}"
110
+ return {"error": err, "matches": [], "count": 0}
111
+
112
+ raw_out = strip_ansi(proc.stdout or "").strip()
113
+ lines = [l for l in raw_out.splitlines() if l.strip()]
114
+ return {"matches": lines[:50], "count": len(lines), "raw": "\n".join(lines[:50])}
115
+ except subprocess.TimeoutExpired:
116
+ return {"error": f"git query timed out after {timeout_sec}s", "matches": [], "count": 0}
117
+ except Exception as e:
118
+ return {"error": f"git execution error: {e}", "matches": [], "count": 0}
119
+
120
+
121
+ def _run_rg_query(
122
+ pattern: str,
123
+ cwd: str,
124
+ path_filter: Optional[str] = None,
125
+ is_regex: bool = False,
126
+ case_sensitive: bool = False,
127
+ file_type: Optional[str] = None,
128
+ glob_filter: Optional[str] = None,
129
+ max_results: int = 25
130
+ ) -> Optional[List[Dict[str, Any]]]:
131
+ """Attempts fast search via ripgrep if available."""
132
+ rg_bin = shutil.which("rg")
133
+ if not rg_bin:
134
+ return None
135
+
136
+ cmd = [rg_bin, "--no-heading", "--line-number", "--color=never", "--max-count", str(max_results)]
137
+ if not is_regex:
138
+ cmd.append("--fixed-strings")
139
+ if not case_sensitive:
140
+ cmd.append("--ignore-case")
141
+ else:
142
+ cmd.append("--case-sensitive")
143
+
144
+ if file_type:
145
+ cmd.extend(["--type", file_type])
146
+ if glob_filter:
147
+ cmd.extend(["--glob", glob_filter])
148
+
149
+ # Ignore default heavy folders
150
+ for d in ("node_modules", ".git", "dist", "build", ".venv", "__pycache__"):
151
+ cmd.extend(["--glob", f"!{d}/**"])
152
+
153
+ target_path = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
154
+ cmd.extend(["--", pattern, target_path])
155
+
156
+ try:
157
+ proc = subprocess.run(
158
+ cmd,
159
+ cwd=cwd,
160
+ stdout=subprocess.PIPE,
161
+ stderr=subprocess.PIPE,
162
+ text=True,
163
+ timeout=5
164
+ )
165
+ matches = []
166
+ _rg_line_re = re.compile(r"^(.*):(\d+):(.*)$")
167
+ for line in proc.stdout.splitlines():
168
+ if not line.strip():
169
+ continue
170
+ m_line = _rg_line_re.match(line)
171
+ if m_line:
172
+ raw_file, raw_lnum, raw_txt = m_line.groups()
173
+ f_path = os.path.relpath(raw_file, cwd)
174
+ try:
175
+ l_num = int(raw_lnum)
176
+ except ValueError:
177
+ l_num = 0
178
+ snippet = raw_txt.strip()[:180]
179
+ matches.append({"file": f_path, "line": l_num, "content": snippet})
180
+ if len(matches) >= max_results:
181
+ break
182
+ return matches
183
+ except Exception:
184
+ return None
185
+
186
+
187
+ def _run_python_text_search(
188
+ pattern: str,
189
+ cwd: str,
190
+ path_filter: Optional[str] = None,
191
+ is_regex: bool = False,
192
+ case_sensitive: bool = False,
193
+ scope: str = "all",
194
+ glob_filter: Optional[str] = None,
195
+ max_results: int = 25
196
+ ) -> List[Dict[str, Any]]:
197
+ """Pure Python search fallback."""
198
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
199
+ if not os.path.exists(search_root):
200
+ return []
201
+
202
+ regex = None
203
+ if is_regex:
204
+ flags = 0 if case_sensitive else re.IGNORECASE
205
+ try:
206
+ regex = re.compile(pattern, flags)
207
+ except re.error:
208
+ regex = None
209
+
210
+ matches = []
211
+ target_lower = pattern if case_sensitive else pattern.lower()
212
+
213
+ for root, dirs, files in os.walk(search_root):
214
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
215
+ for f in files:
216
+ ext = os.path.splitext(f)[1].lower()
217
+ if ext in IGNORED_EXTENSIONS:
218
+ continue
219
+ if scope == "code" and ext not in CODE_EXTENSIONS:
220
+ continue
221
+ full_path = os.path.join(root, f)
222
+ rel_p = os.path.relpath(full_path, cwd)
223
+ if glob_filter and not (fnmatch.fnmatch(f, glob_filter) or fnmatch.fnmatch(rel_p, glob_filter)):
224
+ continue
225
+
226
+ try:
227
+ with open(full_path, "r", encoding="utf-8", errors="replace") as fp:
228
+ for line_idx, line in enumerate(fp):
229
+ hit = False
230
+ if regex:
231
+ hit = bool(regex.search(line))
232
+ elif case_sensitive:
233
+ hit = pattern in line
234
+ else:
235
+ hit = target_lower in line.lower()
236
+
237
+ if hit:
238
+ matches.append({
239
+ "file": rel_p,
240
+ "line": line_idx + 1,
241
+ "content": line.strip()[:180]
242
+ })
243
+ if len(matches) >= max_results:
244
+ return matches
245
+ except Exception:
246
+ continue
247
+
248
+ return matches
249
+
250
+
251
+ def _run_glob_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 50) -> List[str]:
252
+ """Finds matching files by glob pattern."""
253
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
254
+ if not os.path.exists(search_root):
255
+ return []
256
+
257
+ results = []
258
+ for root, dirs, files in os.walk(search_root):
259
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
260
+ for f in files:
261
+ rel_p = os.path.relpath(os.path.join(root, f), cwd)
262
+ if fnmatch.fnmatch(rel_p, pattern) or fnmatch.fnmatch(f, pattern):
263
+ results.append(rel_p)
264
+ if len(results) >= max_results:
265
+ return results
266
+ return results
267
+
268
+
269
+ def _run_fuzzy_search(pattern: str, cwd: str, path_filter: Optional[str] = None, max_results: int = 30) -> List[str]:
270
+ """Case-insensitive fuzzy match across relative file paths."""
271
+ search_root = os.path.normpath(os.path.join(cwd, path_filter)) if path_filter else cwd
272
+ if not os.path.exists(search_root):
273
+ return []
274
+
275
+ pat_lower = pattern.lower().replace(" ", "")
276
+ results = []
277
+ for root, dirs, files in os.walk(search_root):
278
+ dirs[:] = [d for d in dirs if d not in IGNORED_DIRS and not d.startswith(".")]
279
+ for f in files:
280
+ rel_p = os.path.relpath(os.path.join(root, f), cwd)
281
+ name_lower = rel_p.lower()
282
+ # Subsequence match
283
+ it = iter(name_lower)
284
+ if all(ch in it for ch in pat_lower):
285
+ results.append(rel_p)
286
+ if len(results) >= max_results:
287
+ return results
288
+ return results
289
+
290
+
291
+ def _execute_single_query(query_dict: Dict[str, Any], cwd: str) -> Dict[str, Any]:
292
+ """Executes a single search query dict."""
293
+ pattern = str(query_dict.get("pattern") or query_dict.get("query") or "").strip()
294
+ q_type = str(query_dict.get("type") or "text").lower().strip()
295
+ path_filter = query_dict.get("path")
296
+ max_res = int(query_dict.get("max_results") or DEFAULT_QUERY_RESULTS)
297
+ case_sensitive = bool(query_dict.get("case_sensitive"))
298
+ output_mode = str(query_dict.get("output_mode") or "content").lower()
299
+ file_type = query_dict.get("file_type")
300
+ glob_filter = query_dict.get("glob")
301
+
302
+ if not pattern and q_type != "git":
303
+ return {"type": q_type, "pattern": pattern, "error": "Empty pattern.", "matches": [], "count": 0}
304
+
305
+ if q_type == "git":
306
+ res = _run_git_query(pattern, cwd)
307
+ return {"type": "git", "pattern": pattern, **res}
308
+
309
+ if q_type == "glob":
310
+ matched_paths = _run_glob_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
311
+ return {"type": "glob", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
312
+
313
+ if q_type == "fuzzy":
314
+ matched_paths = _run_fuzzy_search(pattern, cwd, path_filter=path_filter, max_results=max_res)
315
+ return {"type": "fuzzy", "pattern": pattern, "matches": matched_paths, "count": len(matched_paths)}
316
+
317
+ is_regex = (q_type == "regex")
318
+ # Try ripgrep first
319
+ rg_matches = _run_rg_query(
320
+ pattern=pattern,
321
+ cwd=cwd,
322
+ path_filter=path_filter,
323
+ is_regex=is_regex,
324
+ case_sensitive=case_sensitive,
325
+ file_type=file_type,
326
+ glob_filter=glob_filter,
327
+ max_results=max_res
328
+ )
329
+
330
+ matches = rg_matches if rg_matches is not None else _run_python_text_search(
331
+ pattern=pattern,
332
+ cwd=cwd,
333
+ path_filter=path_filter,
334
+ is_regex=is_regex,
335
+ case_sensitive=case_sensitive,
336
+ scope="all",
337
+ glob_filter=glob_filter,
338
+ max_results=max_res
339
+ )
340
+
341
+ if output_mode == "files_with_matches":
342
+ unique_files = list(dict.fromkeys(m["file"] for m in matches if isinstance(m, dict) and "file" in m))
343
+ return {"type": q_type, "pattern": pattern, "matches": unique_files, "count": len(unique_files)}
344
+ elif output_mode == "count":
345
+ return {"type": q_type, "pattern": pattern, "count": len(matches)}
346
+
347
+ return {"type": q_type, "pattern": pattern, "matches": matches, "count": len(matches)}
348
+
349
+
350
+ def execute_batch_search(
351
+ queries: List[Dict[str, Any]],
352
+ cwd: Optional[str] = None
353
+ ) -> Dict[str, Any]:
354
+ """
355
+ Executes up to 20 mixed search queries concurrently and returns a consolidated report.
356
+ """
357
+ if not isinstance(queries, list) or not queries:
358
+ return {
359
+ "success": False,
360
+ "error": "Queries must be a non-empty array of query specifications.",
361
+ "results": [],
362
+ "summary_md": "Error: queries array is empty."
363
+ }
364
+
365
+ if len(queries) > MAX_BATCH_QUERIES:
366
+ return {
367
+ "success": False,
368
+ "error": f"Batch search exceeds maximum of {MAX_BATCH_QUERIES} queries (got {len(queries)}).",
369
+ "results": [],
370
+ "summary_md": "Error: query count exceeds maximum."
371
+ }
372
+
373
+ base_dir = os.path.abspath(cwd or os.getcwd())
374
+ results: List[Dict[str, Any]] = [{} for _ in queries]
375
+
376
+ # Concurrent execution across queries
377
+ with ThreadPoolExecutor(max_workers=min(len(queries), 8)) as executor:
378
+ future_to_idx = {
379
+ executor.submit(_execute_single_query, q, base_dir): i
380
+ for i, q in enumerate(queries)
381
+ }
382
+ for future in as_completed(future_to_idx):
383
+ idx = future_to_idx[future]
384
+ try:
385
+ results[idx] = future.result()
386
+ except Exception as e:
387
+ results[idx] = {"error": str(e), "matches": [], "count": 0}
388
+
389
+ # Format into markdown summary
390
+ md_lines: List[str] = [f"## TokenSafe Batch Search Report ({len(queries)} queries)"]
391
+ for i, res in enumerate(results):
392
+ q_type = res.get("type", "search")
393
+ pattern = res.get("pattern", "")
394
+ count = res.get("count", 0)
395
+ err = res.get("error")
396
+
397
+ if err:
398
+ md_lines.append(f"\n### Q{i+1} [{q_type}] `{pattern}` — Error: {err}")
399
+ continue
400
+
401
+ md_lines.append(f"\n### Q{i+1} [{q_type}] `{pattern}` — {count} match(es)")
402
+ matches = res.get("matches") or []
403
+
404
+ if q_type == "git":
405
+ raw_git = res.get("raw")
406
+ if raw_git:
407
+ md_lines.append("```text\n" + raw_git[:1200] + "\n```")
408
+ elif not matches:
409
+ md_lines.append("*(clean / no output)*")
410
+ elif isinstance(matches, list):
411
+ for m in matches[:15]:
412
+ if isinstance(m, dict):
413
+ f_name = m.get("file", "")
414
+ l_num = m.get("line", "")
415
+ content = m.get("content", "")
416
+ md_lines.append(f"- `{f_name}:{l_num}`: {content}")
417
+ elif isinstance(m, str):
418
+ md_lines.append(f"- `{m}`")
419
+ if len(matches) > 15:
420
+ md_lines.append(f"- *(+{len(matches) - 15} more matches)*")
421
+
422
+ summary_md = "\n".join(md_lines)
423
+ return {
424
+ "success": True,
425
+ "query_count": len(queries),
426
+ "results": results,
427
+ "summary_md": summary_md
428
+ }