tokensafe 1.4.9 → 1.4.11

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "1.4.9",
3
+ "version": "1.4.11",
4
4
  "description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
5
5
  "main": "bin/tokensafe.js",
6
6
  "bin": {
package/plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.4.9",
4
+ "version": "1.4.11",
5
5
  "description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
@@ -49,7 +49,8 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
49
49
  | MCP Tool | Description | Efficiency Impact |
50
50
  |---|---|---|
51
51
  | `tokensafe:smart_read_file` | Graph-guided AST reader with target `symbol` body retention and 1-hop dependency inlining. | **-85% to -92%** token reduction |
52
- | `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase. | **-90% to -95%** vs raw grep/find |
52
+ | `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path`, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
53
+ | `tokensafe:list_dir` | Token-efficient directory tree without lockfiles, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces `ls -la`. | **-90%** vs verbose `ls` |
53
54
  | `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
54
55
  | `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
55
56
  | `tokensafe:sanitize_command` | Intercepts shell commands to strip lockfiles, cap unbounded git logs, and quiet test tracebacks. | Saves **10k-50k tokens** per run |
@@ -81,11 +82,25 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
81
82
  "ToolName": "scoped_search",
82
83
  "Arguments": {
83
84
  "query": "HARDCODED_VERSION",
85
+ "path": "/Users/.../projects/my-app/src",
84
86
  "scope": "code"
85
87
  }
86
88
  }
87
89
  ```
88
- *Locates exact occurrences with file and line references in < 100 tokens, without running raw terminal grep.*
90
+ *Locates exact occurrences with file and line references in < 100 tokens. Always pass explicit `path` or `project_path` (auto-guarded against system roots with 4s safety timeout).*
91
+
92
+ ### 2b. Directory Navigation Workflow (`list_dir`)
93
+ ```json
94
+ {
95
+ "ServerName": "tokensafe",
96
+ "ToolName": "list_dir",
97
+ "Arguments": {
98
+ "path": "/Users/.../projects/my-app/src",
99
+ "depth": 2
100
+ }
101
+ }
102
+ ```
103
+ *Renders a clean directory tree without permissions, timestamps, lockfiles, or heavy directories (`node_modules`, `.git`, `dist`).*
89
104
 
90
105
  ### 3. Targeted Symbol Inspection Workflow
91
106
  ```json
package/src/mcp_server.py CHANGED
@@ -6,6 +6,7 @@ Exposes tools for smart file reading, dependency prefetching, prompt compression
6
6
 
7
7
  import sys
8
8
  import os
9
+ import time
9
10
  import json
10
11
  import traceback
11
12
  import fnmatch
@@ -32,7 +33,7 @@ from src.scoped_search import ScopedSearch
32
33
 
33
34
  SERVER_INFO = {
34
35
  "name": "tokensafe-mcp",
35
- "version": "1.4.9"
36
+ "version": "1.4.11"
36
37
  }
37
38
 
38
39
  TOOLS = [
@@ -153,6 +154,10 @@ TOOLS = [
153
154
  "enum": ["code", "config", "all"],
154
155
  "description": "Scope of search: 'code' (source files only), 'config' (json, toml, yaml), or 'all' (default: 'all')"
155
156
  },
157
+ "path": {
158
+ "type": "string",
159
+ "description": "Directory or project path to search (alias for project_path)"
160
+ },
156
161
  "project_path": {
157
162
  "type": "string",
158
163
  "description": "Optional root directory path (defaults to current project)"
@@ -191,7 +196,8 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
191
196
  IGNORE_DIRS = {
192
197
  'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
193
198
  '__pycache__', '.turbo', '.vite', '.output', '.bunny', 'data',
194
- '.venv', 'venv', '.cache', '.idea', '.vscode'
199
+ '.venv', 'venv', '.cache', '.idea', '.vscode',
200
+ 'Library', 'Applications', 'Movies', 'Music', 'Pictures'
195
201
  }
196
202
  IGNORE_FILES = {
197
203
  '*.lock', '*.lockb', '*.map', '.DS_Store', 'Thumbs.db', 'package-lock.json',
@@ -209,11 +215,14 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
209
215
  base_name = os.path.basename(os.path.abspath(dir_path)) or dir_path
210
216
  lines = [f"📁 **{base_name}/** (max depth: {max_depth})"]
211
217
  entries_count = 0
218
+ start_time = time.monotonic()
212
219
 
213
220
  def _traverse(curr_dir: str, prefix: str, current_depth: int):
214
221
  nonlocal entries_count
215
222
  if current_depth > max_depth or entries_count >= max_entries:
216
223
  return
224
+ if time.monotonic() - start_time > 3.0:
225
+ return
217
226
 
218
227
  try:
219
228
  items = sorted(os.listdir(curr_dir))
@@ -569,7 +578,11 @@ def handle_tool_call(name: str, args: dict) -> dict:
569
578
 
570
579
  # Resolve path relative to current working directory or absolute
571
580
  abs_path = os.path.abspath(path)
581
+ system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
572
582
  depth = min(4, max(1, int(args.get("depth", 2))))
583
+ if abs_path in system_roots:
584
+ # Do not walk entire home dir or filesystem root deeply
585
+ depth = 1
573
586
  max_entries = min(150, max(10, int(args.get("max_entries", 80))))
574
587
 
575
588
  tree_output = build_dir_tree(abs_path, max_depth=depth, max_entries=max_entries)
@@ -591,8 +604,20 @@ def handle_tool_call(name: str, args: dict) -> dict:
591
604
  return {"isError": True, "content": [{"type": "text", "text": "Error: 'query' argument is required for scoped_search."}]}
592
605
 
593
606
  scope = args.get("scope", "all")
594
- p_path = args.get("project_path", "")
595
- target_path = os.path.abspath(p_path) if p_path else os.getcwd()
607
+ raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
608
+ if raw_path:
609
+ target_path = os.path.abspath(raw_path)
610
+ if os.path.isfile(target_path):
611
+ target_path = os.path.dirname(target_path)
612
+ else:
613
+ resolved_path, err = _resolve_project_root(args)
614
+ if err or not resolved_path:
615
+ return {
616
+ "isError": True,
617
+ "content": [{"type": "text", "text": err or "Error: Invalid or unspecified project_path."}]
618
+ }
619
+ target_path = resolved_path
620
+
596
621
  max_res = args.get("max_results", 25)
597
622
  c_sens = bool(args.get("case_sensitive", False))
598
623
  u_regex = bool(args.get("use_regex", False))
@@ -606,6 +631,9 @@ def handle_tool_call(name: str, args: dict) -> dict:
606
631
  use_regex=u_regex
607
632
  )
608
633
  md_text = res["markdown"]
634
+ if not res.get("success", True):
635
+ return {"isError": True, "content": [{"type": "text", "text": md_text}]}
636
+
609
637
  res_tokens = count_tokens(md_text)
610
638
  est_orig = max(1500, res_tokens * 8)
611
639
  tracker.record_event(
@@ -6,12 +6,15 @@ Replaces uncontrolled grep/find commands with bounded, clean, token-efficient re
6
6
  import os
7
7
  import re
8
8
  import fnmatch
9
+ import time
9
10
  from typing import Dict, List, Optional, Any, Tuple
10
11
 
11
12
  IGNORED_DIRS = {
12
- ".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
13
+ ".git", ".hg", ".svn", "node_modules", ".venv", "venv", "__pycache__", "dist", "build",
13
14
  ".next", ".turbo", ".idea", ".vscode", "coverage", ".pytest_cache",
14
- ".mypy_cache", ".gemini", ".system_generated", "data", "tokensafe.egg-info"
15
+ ".mypy_cache", ".gemini", ".system_generated", "data", "tokensafe.egg-info",
16
+ "Library", "Applications", "Pictures", "Movies", "Music", "Downloads",
17
+ ".cache", ".npm", ".bun", ".rustup", ".cargo", ".local", ".output", ".vite"
15
18
  }
16
19
 
17
20
  IGNORED_EXTENSIONS = {
@@ -90,6 +93,16 @@ class ScopedSearch:
90
93
  }
91
94
 
92
95
  root_dir = os.path.abspath(project_path or os.getcwd())
96
+ system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
97
+ if root_dir in system_roots:
98
+ return {
99
+ "success": False,
100
+ "error": f"Refusing to search system root or home directory ({root_dir}). Please provide an explicit project directory.",
101
+ "matches": [],
102
+ "total_matches": 0,
103
+ "markdown": f"Search aborted: '{root_dir}' is a system root. Please specify an explicit project directory path."
104
+ }
105
+
93
106
  if not os.path.isdir(root_dir):
94
107
  return {
95
108
  "success": False,
@@ -122,8 +135,18 @@ class ScopedSearch:
122
135
  matches: List[Dict[str, Any]] = []
123
136
  total_scanned_files = 0
124
137
  hit_files = set()
138
+ start_time = time.monotonic()
139
+ timeout_seconds = 4.0
140
+ max_scanned_files = 2500
141
+ timed_out = False
125
142
 
126
143
  for dirpath, dirnames, filenames in os.walk(root_dir):
144
+ if time.monotonic() - start_time > timeout_seconds:
145
+ timed_out = True
146
+ break
147
+ if total_scanned_files >= max_scanned_files:
148
+ break
149
+
127
150
  # Prune ignored directories in-place
128
151
  dirnames[:] = [
129
152
  d for d in dirnames
@@ -131,6 +154,11 @@ class ScopedSearch:
131
154
  ]
132
155
 
133
156
  for fname in filenames:
157
+ if time.monotonic() - start_time > timeout_seconds:
158
+ timed_out = True
159
+ break
160
+ if total_scanned_files >= max_scanned_files:
161
+ break
134
162
  full_path = os.path.join(dirpath, fname)
135
163
  rel_path = os.path.relpath(full_path, root_dir).replace("\\", "/")
136
164
 
@@ -184,6 +212,10 @@ class ScopedSearch:
184
212
 
185
213
  if len(matches) >= max_results:
186
214
  lines.append(f"_Results capped at {max_results} matches._")
215
+ elif timed_out:
216
+ lines.append(f"_Search bounded at {timeout_seconds}s safety limit ({total_scanned_files} files scanned). Narrow 'project_path' for exhaustive scan._")
217
+ elif total_scanned_files >= max_scanned_files:
218
+ lines.append(f"_Scan bounded at {max_scanned_files} files limit. Narrow 'project_path' if needed._")
187
219
 
188
220
  return {
189
221
  "success": True,
@@ -192,6 +224,7 @@ class ScopedSearch:
192
224
  "total_matches": len(matches),
193
225
  "files_matched": len(hit_files),
194
226
  "scanned_files": total_scanned_files,
227
+ "timed_out": timed_out,
195
228
  "matches": matches,
196
229
  "markdown": "\n".join(lines)
197
230
  }
package/src/team_cache.py CHANGED
@@ -17,7 +17,7 @@ from src.license_manager import LicenseManager
17
17
  class TeamCache:
18
18
  """Distributed cross-developer cache client for TokenSafe Team tier."""
19
19
 
20
- DEFAULT_TIMEOUT = 0.4 # Strict 400ms timeout to prevent blocking agent turns
20
+ DEFAULT_TIMEOUT = float(os.environ.get("TOKENSAFE_CACHE_TIMEOUT", "1.2")) # Fast 1.2s timeout to prevent blocking agent turns
21
21
 
22
22
  @classmethod
23
23
  def _get_cloud_url(cls) -> str:
@@ -144,7 +144,7 @@ class TeamCache:
144
144
  headers={"Authorization": f"Bearer {lic_key}", "User-Agent": "TokenSafe-TeamCache/1.0"}
145
145
  )
146
146
  try:
147
- with urllib.request.urlopen(req, timeout=1.0) as resp:
147
+ with urllib.request.urlopen(req, timeout=max(2.5, cls.DEFAULT_TIMEOUT)) as resp:
148
148
  if resp.status == 200:
149
149
  res = json.loads(resp.read().decode("utf-8"))
150
150
  res["active"] = True
@@ -236,7 +236,7 @@ class TelemetrySync:
236
236
  total_sent = 0
237
237
  headers = {
238
238
  "Content-Type": "application/json",
239
- "User-Agent": "TokenSafe-Sync/1.4.9"
239
+ "User-Agent": "TokenSafe-Sync/1.4.11"
240
240
  }
241
241
  if active_key:
242
242
  headers["Authorization"] = f"Bearer {active_key}"
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "1.4.9"
19
+ CURRENT_VERSION = "1.4.11"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
 
22
22
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))