tokensafe 2.6.1 → 2.7.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 (45) hide show
  1. package/bin/tokensafe +1 -1
  2. package/extensions/cursor-tokensafe/extension.js +21 -8
  3. package/hooks/claude_code_hook.py +13 -5
  4. package/hooks/cursor_hook.py +7 -4
  5. package/hooks/post_tool_use.py +24 -6
  6. package/hooks/pre_invocation.py +40 -27
  7. package/hooks/pre_tool_use.py +85 -83
  8. package/hooks/session_start.py +8 -4
  9. package/hooks/stop_hook.py +7 -4
  10. package/package.json +1 -1
  11. package/plugin.json +1 -1
  12. package/server.json +3 -3
  13. package/src/agent_firewall.py +38 -21
  14. package/src/cache_normalizer.py +39 -10
  15. package/src/cli.py +144 -91
  16. package/src/command_sanitizer.py +248 -136
  17. package/src/compactor.py +55 -25
  18. package/src/dashboard.py +17 -10
  19. package/src/deepseek_distiller.py +26 -17
  20. package/src/dependency_prefetcher.py +66 -41
  21. package/src/diff_slicer.py +23 -17
  22. package/src/distiller.py +45 -17
  23. package/src/distiller_cache.py +74 -47
  24. package/src/environment_auditor.py +34 -12
  25. package/src/governor.py +83 -26
  26. package/src/graph_engine.py +653 -140
  27. package/src/guard.py +316 -132
  28. package/src/history_compactor.py +57 -26
  29. package/src/installer.py +174 -131
  30. package/src/license_manager.py +12 -9
  31. package/src/loop_detector.py +68 -29
  32. package/src/mcp_server.py +200 -60
  33. package/src/metrics.py +141 -54
  34. package/src/paths.py +32 -6
  35. package/src/proxy.py +121 -52
  36. package/src/scoped_search.py +18 -6
  37. package/src/secret_redactor.py +78 -59
  38. package/src/skeletonizer.py +68 -13
  39. package/src/slicer.py +25 -7
  40. package/src/team_cache.py +10 -3
  41. package/src/telemetry_sync.py +110 -39
  42. package/src/tokenizer.py +24 -13
  43. package/src/treesitter_backend.py +539 -0
  44. package/src/version_checker.py +67 -32
  45. package/src/weekly_digest.py +6 -3
@@ -37,8 +37,8 @@ class SecretRedactor:
37
37
  ),
38
38
  (
39
39
  "aws_secret_key",
40
- re.compile(r"(?i)(aws_secret_access_key|aws_secret_key)\s*([:=])\s*['\"]?([A-Za-z0-9/+=]{40})['\"]?"),
41
- r'\1\2"[REDACTED_AWS_SECRET_KEY]"'
40
+ re.compile(r"""(?i)(['"]?(?:aws_secret_access_key|aws_secret_key)['"]?\s*[:=]\s*)(['"]?)([A-Za-z0-9/+=]{40})\2"""),
41
+ r'\1"[REDACTED_AWS_SECRET_KEY]"'
42
42
  ),
43
43
 
44
44
  # JWT Tokens (Header.Payload.Signature format)
@@ -51,7 +51,7 @@ class SecretRedactor:
51
51
  # Database Connection Strings with Passwords
52
52
  (
53
53
  "db_connection_url",
54
- re.compile(r"(?i)\b((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss):\/\/)([^:\s\"'/]+):([^\s\"'/]+)(@)([\w\.\-]+(?::\d+)?(?:/[^\s\"')]*)?)"),
54
+ re.compile(r"(?i)\b((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss):\/\/)([^:\s\"'/@]+):([^\s\"'@]+)(@)([\w\.\-]+(?::\d+)?(?:/[^\s\"')]*)?)"),
55
55
  r"\1\2:[REDACTED_DB_PWD]\4\5"
56
56
  ),
57
57
 
@@ -63,7 +63,7 @@ class SecretRedactor:
63
63
  ),
64
64
  (
65
65
  "openai_legacy_key",
66
- re.compile(r"\bsk-[a-zA-Z0-9]{32,}\b"),
66
+ re.compile(r"\bsk-(?:[A-Za-z0-9]{20}T3BlbkFJ[A-Za-z0-9]{20}|[a-zA-Z0-9]{48,})\b"),
67
67
  "sk-MOCK_OPENAI_KEY_ANCHOR"
68
68
  ),
69
69
  (
@@ -75,8 +75,8 @@ class SecretRedactor:
75
75
  # VCS & Platform Tokens
76
76
  (
77
77
  "github_token",
78
- re.compile(r"\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b"),
79
- r"\1_MOCK_GITHUB_TOKEN_ANCHOR"
78
+ re.compile(r"\b((?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}|github_pat_[A-Za-z0-9_]{22,})\b"),
79
+ "ghp_MOCK_GITHUB_TOKEN_ANCHOR"
80
80
  ),
81
81
  (
82
82
  "slack_token",
@@ -84,14 +84,59 @@ class SecretRedactor:
84
84
  "xoxb-MOCK_SLACK_TOKEN_ANCHOR"
85
85
  ),
86
86
 
87
- # Private Keys (RSA / DSA / EC / OPENSSH)
87
+ # Private Keys (RSA / DSA / EC / OPENSSH / ENCRYPTED) — idempotent against our anchor
88
88
  (
89
89
  "private_key",
90
- re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----[\s\S]+?-----END (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----"),
91
- "-----BEGIN PRIVATE KEY-----\n[REDACTED_PRIVATE_KEY_MOCK_ANCHOR]\n-----END PRIVATE KEY-----"
90
+ re.compile(
91
+ r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRI"
92
+ r"VATE KEY-----(?!\s*\[REDACTED_PRIVATE_KEY_MOCK_ANCHOR\])[\s\S]+?"
93
+ r"-----END (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRI"
94
+ r"VATE KEY-----"
95
+ ),
96
+ "-----BEGIN PRI" "VATE KEY-----\n[REDACTED_PRIVATE_KEY_MOCK_ANCHOR]\n-----END PRI" "VATE KEY-----"
92
97
  ),
93
98
  ]
94
99
 
100
+ _TEST_FILE_RE = re.compile(
101
+ r"(?:^|/)(?:__tests__|__mocks__|tests?|specs?|mocks?|fixtures?)(?:/|$)"
102
+ r"|(?:^|/)(?:test_[^/]+|mock_[^/]+|[^/]+_test\.[^/]+|[^/]+_spec\.[^/]+|[^/]+\.test\.[^/]+|[^/]+\.spec\.[^/]+|conftest\.py)$",
103
+ re.IGNORECASE,
104
+ )
105
+ _SAFE_PH_RE = re.compile(
106
+ r"(?:^|[_\-\s./:])(?:mock|test|dummy|placeholder|changeme|example|your|fake|sample|none|null|undefined|redacted|localhost|127\.0\.0\.1|0\.0\.0\.0)(?:$|[_\-\s./:])",
107
+ re.IGNORECASE,
108
+ )
109
+ _SECRET_VAR_RE = re.compile(
110
+ r"(?:^|_)(?:API_KEY|ACCESS_KEY|SECRET_KEY|PRIVATE_KEY|SIGNING_KEY|ENCRYPTION_KEY|MASTER_KEY|JWT_KEY|CLIENT_SECRET|WEBHOOK_SECRET|SECRET|TOKEN|PASSWORD|PASSWD|PWD|CREDENTIAL|CREDENTIALS|AUTH_TOKEN|AUTH_SECRET|PRIV_KEY)(?:$|_)",
111
+ re.IGNORECASE,
112
+ )
113
+ _NON_SECRET_VAR_RE = re.compile(
114
+ r"(?:PUBLIC|PUBKEY|PUB_KEY|_PUB\b|PUB_HEX|PRIVACY|AUTHOR|BYPASS|CACHE_KEY|SORT_KEY|STORAGE_KEY|LOCAL_STORAGE_KEY)",
115
+ re.IGNORECASE,
116
+ )
117
+ _ENV_PY_CALL_RE = re.compile(
118
+ r"""os\.(?:environ\.get|getenv)\s*\(\s*['"]([^'"]+)['"]\s*(?:,\s*(?:default\s*=\s*)?['"]([^'"]+)['"]\s*\)|\)\s*or\s*['"]([^'"]+)['"])""",
119
+ re.IGNORECASE,
120
+ )
121
+ _ENV_JS_RE = re.compile(
122
+ r"""process\.env(?:\.([A-Za-z0-9_]+)|\[\s*['"]([A-Za-z0-9_]+)['"]\s*\])\s*(?:\|\||\?\?)\s*['"`]([^'"`\n]+)['"`]""",
123
+ re.IGNORECASE,
124
+ )
125
+ _HEX_PRIV_RE = re.compile(
126
+ r"""(?:^|[\s;])(?:DEFAULT_)?(?:ED25519_|SECP256K1_|RSA_)?(?:PRIV|PRIVATE)_(?:KEY|HEX)\s*=\s*(?:os\.(?:environ\.get|getenv)\([^)]*\)\s*or\s*)?['"]([0-9a-fA-F]{64})['"]""",
127
+ re.MULTILINE,
128
+ )
129
+ _LIVE_CHECKS = (
130
+ (re.compile(r"\b(?:sk|rk)_live_[0-9a-zA-Z]{24,}\b"), "Detected live Stripe secret key hardcoded in code"),
131
+ (re.compile(r"\bwhsec_[0-9a-zA-Z]{32,}\b"), "Detected Stripe webhook signing secret hardcoded in code"),
132
+ (re.compile(r"\b(?:AKIA|ASIA|AROA)[A-Z0-9]{16}\b"), "Detected live AWS access key ID hardcoded in code"),
133
+ (re.compile(r"\bsk-proj-[A-Za-z0-9_-]{40,}\b"), "Detected live OpenAI project API key hardcoded in code"),
134
+ (re.compile(r"\bsk-(?:[A-Za-z0-9]{20}T3BlbkFJ[A-Za-z0-9]{20}|[a-zA-Z0-9]{48,})\b"), "Detected live OpenAI legacy API key hardcoded in code"),
135
+ (re.compile(r"\bsk-ant-[A-Za-z0-9_-]{40,}\b"), "Detected live Anthropic API key hardcoded in code"),
136
+ (re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36}\b|\bgithub_pat_[A-Za-z0-9_]{22,}\b"), "Detected GitHub personal access token hardcoded in code"),
137
+ (re.compile(r"\bxox[baprs]-[0-9a-zA-Z-]{24,}\b"), "Detected Slack API token hardcoded in code"),
138
+ )
139
+
95
140
  @classmethod
96
141
  def redact_text(cls, text: str) -> Tuple[str, int, List[str]]:
97
142
  """
@@ -106,11 +151,10 @@ class SecretRedactor:
106
151
  detected_types: List[str] = []
107
152
 
108
153
  for name, pattern, repl in cls.PATTERNS:
109
- matches = list(pattern.finditer(redacted))
110
- if matches:
111
- total_redacted += len(matches)
154
+ redacted, n_subs = pattern.subn(repl, redacted)
155
+ if n_subs > 0:
156
+ total_redacted += n_subs
112
157
  detected_types.append(name)
113
- redacted = pattern.sub(repl, redacted)
114
158
 
115
159
  return redacted, total_redacted, detected_types
116
160
 
@@ -145,24 +189,20 @@ class SecretRedactor:
145
189
  if not val or len(val.strip()) == 0:
146
190
  return True
147
191
  v = val.strip().lower()
148
- if any(w in v for w in cls.SAFE_PLACEHOLDERS):
192
+ if v in cls.SAFE_PLACEHOLDERS or cls._SAFE_PH_RE.search(v):
149
193
  return True
150
194
  # Check all identical characters (e.g. "00000000000000000000000000000000...")
151
195
  if len(set(v)) <= 2:
152
196
  return True
153
- # Short non-secret strings (less than 16 chars)
154
- if len(v) < 16 and not any(v.startswith(prefix) for prefix in ("sk_", "whsec_", "ghp_", "ts_sec_", "xoxb-")):
155
- return True
156
197
  return False
157
198
 
158
199
  @classmethod
159
200
  def _is_secret_var_name(cls, name: str) -> bool:
160
- """Checks if variable name represents a sensitive credential while ignoring public keys."""
201
+ """Checks if variable name represents a sensitive credential while ignoring public/non-secret keys."""
161
202
  n = name.upper()
162
- if any(pub in n for pub in ("PUBLIC", "PUBKEY", "PUB_KEY", "_PUB", "PUB_HEX")):
203
+ if cls._NON_SECRET_VAR_RE.search(n):
163
204
  return False
164
- secret_markers = ("KEY", "SECRET", "TOKEN", "PASS", "AUTH", "CREDENTIAL", "PRIV")
165
- return any(m in n for m in secret_markers)
205
+ return bool(cls._SECRET_VAR_RE.search(n))
166
206
 
167
207
  @classmethod
168
208
  def check_secret_fallback(cls, code_snippet: str, file_path: str = "") -> Tuple[bool, Optional[str]]:
@@ -174,54 +214,33 @@ class SecretRedactor:
174
214
  if not code_snippet or not isinstance(code_snippet, str):
175
215
  return False, None
176
216
 
177
- is_test = bool(file_path and any(p in file_path.lower() for p in ("test", "mock", "fixture")))
178
-
179
- # 1. Live provider keys (Stripe live, AWS, OpenAI, Anthropic, GitHub) anywhere
180
- if re.search(r"\b(?:sk|rk)_live_[0-9a-zA-Z]{24,}\b", code_snippet):
181
- return True, "Detected live Stripe secret key hardcoded in code"
182
- if re.search(r"\bwhsec_[0-9a-zA-Z]{32,}\b", code_snippet):
183
- return True, "Detected Stripe webhook signing secret hardcoded in code"
184
- if re.search(r"\b(?:AKIA|ASIA|AROA)[A-Z0-9]{16}\b", code_snippet):
185
- return True, "Detected live AWS access key ID hardcoded in code"
186
- if re.search(r"\bsk-proj-[A-Za-z0-9_-]{40,}\b", code_snippet):
187
- return True, "Detected live OpenAI project API key hardcoded in code"
188
- if re.search(r"\bsk-ant-[A-Za-z0-9_-]{40,}\b", code_snippet):
189
- return True, "Detected live Anthropic API key hardcoded in code"
190
- if re.search(r"\b(?:ghp|gho|ghs|ghr)_[A-Za-z0-9]{36}\b", code_snippet):
191
- return True, "Detected GitHub personal access token hardcoded in code"
192
- if re.search(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----", code_snippet):
217
+ is_test = bool(file_path and cls._TEST_FILE_RE.search(file_path.replace("\\", "/")))
218
+
219
+ # 1. Live provider keys (Stripe, AWS, OpenAI, Anthropic, GitHub, Slack) anywhere
220
+ for pat, err_msg in cls._LIVE_CHECKS:
221
+ if pat.search(code_snippet):
222
+ return True, err_msg
223
+ if re.search(r"-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----", code_snippet):
193
224
  if not is_test:
194
225
  return True, "Detected raw PEM private key block hardcoded in non-test source code"
195
226
 
196
- # 2. Python environment variable fallback patterns: os.environ.get("...KEY|SECRET...", "val")
197
- env_py_matches = re.finditer(
198
- r"""os\.(?:environ\.get|getenv)\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"]([^'"]+)['"]\s*\)""",
199
- code_snippet,
200
- re.IGNORECASE
201
- )
202
- for m in env_py_matches:
203
- var_name, fallback_val = m.group(1), m.group(2)
204
- if cls._is_secret_var_name(var_name) and not cls._is_safe_placeholder(fallback_val):
227
+ # 2. Python environment variable fallback patterns: os.environ.get("...", "val") or os.getenv(...) or "val"
228
+ for m in cls._ENV_PY_CALL_RE.finditer(code_snippet):
229
+ var_name = m.group(1)
230
+ fallback_val = m.group(2) if m.group(2) is not None else m.group(3)
231
+ if fallback_val is not None and cls._is_secret_var_name(var_name) and not cls._is_safe_placeholder(fallback_val):
205
232
  return True, f"Dangerous hardcoded fallback for sensitive environment variable '{var_name}'"
206
233
 
207
- # 3. JS/TS: process.env.XYZ_KEY || "val" or ?? "val"
208
- env_js_matches = re.finditer(
209
- r"""process\.env\.([A-Za-z0-9_]+)\s*(?:\|\||\?\?)\s*['"]([^'"]+)['"]""",
210
- code_snippet,
211
- re.IGNORECASE
212
- )
213
- for m in env_js_matches:
214
- var_name, fallback_val = m.group(1), m.group(2)
234
+ # 3. JS/TS: process.env.XYZ_KEY || "val" or process.env["XYZ_KEY"] ?? "val"
235
+ for m in cls._ENV_JS_RE.finditer(code_snippet):
236
+ var_name = m.group(1) or m.group(2) or ""
237
+ fallback_val = m.group(3)
215
238
  if cls._is_secret_var_name(var_name) and not cls._is_safe_placeholder(fallback_val):
216
239
  return True, f"Dangerous hardcoded fallback for sensitive environment variable 'process.env.{var_name}'"
217
240
 
218
241
  # 4. Raw 64-character hexadecimal private key assignments in non-test code
219
242
  if not is_test:
220
- hex_priv_match = re.search(
221
- r"""(?:^|[\s;])(?:DEFAULT_)?(?:ED25519_|SECP256K1_|RSA_)?(?:PRIV|PRIVATE)_(?:KEY|HEX)\s*=\s*(?:os\.(?:environ\.get|getenv)\([^)]*\)\s*or\s*)?['"]([0-9a-fA-F]{64})['"]""",
222
- code_snippet,
223
- re.MULTILINE
224
- )
243
+ hex_priv_match = cls._HEX_PRIV_RE.search(code_snippet)
225
244
  if hex_priv_match:
226
245
  val = hex_priv_match.group(1)
227
246
  if not cls._is_safe_placeholder(val):
@@ -21,14 +21,14 @@ CONTROL_KEYWORDS = {
21
21
  'return', 'throw', 'yield', 'await', 'import', 'export', 'record'
22
22
  }
23
23
 
24
- # 1. Standard function declarations (JS/TS/PHP/Swift/Kotlin)
24
+ # 1. Standard function declarations (JS/TS/PHP/Kotlin)
25
25
  FN_DECL_REGEX = re.compile(
26
- r'^(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function\s*\*?|fun)\s+([a-zA-Z0-9_$]+)?\s*(?:<[^>]+>)?\s*\('
26
+ r'^(?:export\s+)?(?:default\s+)?(?:(?:public|private|protected|internal|open|override|suspend|final|abstract|static|inline|tailrec|operator|infix|external)\s+)*(?:async\s+)?(?:function\s*\*?|fun)\s+([a-zA-Z0-9_$]+)?\s*(?:<[^>]+>)?\s*\('
27
27
  )
28
28
 
29
- # 2. Go func: func Foo(...) or func (r *Recv) Foo(...)
29
+ # 2. Go / Swift func: func Foo(...) or func (r *Recv) Foo(...) or public mutating func Foo(...)
30
30
  GO_FN_REGEX = re.compile(
31
- r'^func\s+(?:\([^)]+\)\s+)?([a-zA-Z0-9_]+)\s*(?:\[[^\]]+\])?\s*\('
31
+ r'^(?:(?:@[a-zA-Z0-9_]+(?:\([^)]*\))?\s+)*(?:public|private|fileprivate|internal|open|override|static|class|mutating|nonmutating|final)\s+)*func\s+(?:\([^)]+\)\s+)?([a-zA-Z0-9_]+)\s*(?:\[[^\]]+\]|<[^>]+>)?\s*\('
32
32
  )
33
33
 
34
34
  # 3. Rust fn: fn foo(...) or pub async fn foo(...)
@@ -66,12 +66,19 @@ ARROW_MULTILINE_START = re.compile(
66
66
 
67
67
  # 5. Method definition (Java, C#, C++, TS, PHP)
68
68
  METHOD_REGEX = re.compile(
69
- r'^(?:(?:public|private|protected|static|final|native|synchronized|abstract|async|override|virtual|inline|explicit|const|get|set)\s+)*'
69
+ r'^(?:(?:public|private|protected|internal|open|static|final|native|synchronized|abstract|async|override|virtual|inline|explicit|const|get|set|suspend|mutating)\s+)*'
70
70
  r'(?:[a-zA-Z0-9_<>\[\],.?*&:]+\s+)*'
71
71
  r'([a-zA-Z0-9_$:~]+)\s*(?:<[^>]+>)?\s*\([^)]*\)\s*'
72
72
  r'(?:const\s+|override\s+|final\s+|noexcept\s+|throws\s+[^{]+|->\s*[^{]+|:\s*[^{]+)*\{'
73
73
  )
74
74
 
75
+ # 5b. Multi-line / Allman-style method header (no '{' on first line; requires at least one modifier/type or trailing '(')
76
+ METHOD_MULTILINE_REGEX = re.compile(
77
+ r'^(?:(?:public|private|protected|internal|open|static|final|native|synchronized|abstract|async|override|virtual|inline|explicit|const|get|set|suspend|mutating)\s+)*'
78
+ r'(?:[a-zA-Z0-9_<>\[\],.?*&:]+\s+)+'
79
+ r'([a-zA-Z0-9_$:~]+)\s*(?:<[^>]+>)?\s*\([^;]*$'
80
+ )
81
+
75
82
  class BraceLexer:
76
83
  """Accurate tokenizer tracking multi-line comments and string literals for brace counting."""
77
84
  def __init__(self):
@@ -246,9 +253,17 @@ class Skeletonizer:
246
253
  return cls._collapse_import_lines(res, ext) if (collapse_imports and keep_symbols) else res
247
254
  elif ext in (
248
255
  ".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs",
249
- ".go", ".java", ".rs", ".cpp", ".cc", ".cxx", ".c", ".h", ".hpp", ".cs", ".php", ".kt", ".swift"
256
+ ".go", ".java", ".rs", ".cpp", ".cc", ".cxx", ".c", ".h", ".hpp",
257
+ ".cs", ".php", ".kt", ".kts", ".swift",
250
258
  ):
251
- res = cls._skeletonize_braces(code, ext, keep_symbols=keep_symbols)
259
+ res = None
260
+ try:
261
+ from src.treesitter_backend import TreeSitterBackend
262
+ res = TreeSitterBackend.skeletonize_braces(code, ext, keep_symbols=keep_symbols)
263
+ except Exception:
264
+ res = None
265
+ if res is None:
266
+ res = cls._skeletonize_braces(code, ext, keep_symbols=keep_symbols)
252
267
  return cls._collapse_import_lines(res, ext) if (collapse_imports and keep_symbols) else res
253
268
  elif ext in (".css", ".scss", ".sass", ".less"):
254
269
  return cls._skeletonize_css(code, ext, keep_symbols=keep_symbols)
@@ -265,12 +280,20 @@ class Skeletonizer:
265
280
  first_line = doc_val.strip().split("\n")[0].strip()
266
281
  tree.body[0].value.value = f"{first_line} ..."
267
282
 
268
- for node in ast.walk(tree):
269
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
270
- if keep_symbols is not None and node.name in keep_symbols:
271
- continue
272
- # Fold inert functions to pure ellipsis without verbose docstrings
273
- node.body = [ast.Expr(value=ast.Constant(value=Ellipsis))]
283
+ def _fold_py_node(node: ast.AST, class_name: Optional[str] = None):
284
+ for child in ast.iter_child_nodes(node):
285
+ if isinstance(child, ast.ClassDef):
286
+ _fold_py_node(child, class_name=child.name)
287
+ elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
288
+ qual_name = f"{class_name}.{child.name}" if class_name else child.name
289
+ if keep_symbols is not None and (child.name in keep_symbols or qual_name in keep_symbols):
290
+ _fold_py_node(child, class_name=class_name)
291
+ continue
292
+ child.body = [ast.Expr(value=ast.Constant(value=Ellipsis))]
293
+ else:
294
+ _fold_py_node(child, class_name=class_name)
295
+
296
+ _fold_py_node(tree)
274
297
  return ast.unparse(tree)
275
298
  except Exception:
276
299
  return code
@@ -325,6 +348,14 @@ class Skeletonizer:
325
348
  if clean_name not in CONTROL_KEYWORDS:
326
349
  return (clean_name, "method")
327
350
 
351
+ if not line_clean.endswith(";"):
352
+ m = METHOD_MULTILINE_REGEX.match(line_clean)
353
+ if m:
354
+ name = m.group(1)
355
+ clean_name = name.split("::")[-1]
356
+ if clean_name not in CONTROL_KEYWORDS and clean_name not in ("new", "delete", "sizeof"):
357
+ return (clean_name, "method_multiline")
358
+
328
359
  return None
329
360
 
330
361
  @classmethod
@@ -489,6 +520,15 @@ class Skeletonizer:
489
520
  pending_name = None
490
521
  pending_kind = None
491
522
  continue
523
+ elif len(pending_header_lines) > 25:
524
+ out.extend(pending_header_lines)
525
+ for phl in pending_header_lines:
526
+ op, cl = lexer.count_braces(phl)
527
+ current_depth += op - cl
528
+ pending_header_lines = []
529
+ pending_name = None
530
+ pending_kind = None
531
+ continue
492
532
  else:
493
533
  continue
494
534
 
@@ -535,11 +575,20 @@ class Skeletonizer:
535
575
  in_folding = True
536
576
  continue
537
577
 
578
+ if kind in ('fn_decl', 'go_func', 'rust_fn', 'method_multiline') and not raw_line.rstrip().endswith(";"):
579
+ pending_header_lines = [raw_line]
580
+ pending_name = name
581
+ pending_kind = 'fn_multiline'
582
+ continue
583
+
538
584
  # 4. Normal line
539
585
  out.append(raw_line)
540
586
  open_b, close_b = lexer.count_braces(count_src)
541
587
  current_depth += open_b - close_b
542
588
 
589
+ if pending_header_lines:
590
+ out.extend(pending_header_lines)
591
+
543
592
  return "\n".join(out)
544
593
 
545
594
  @classmethod
@@ -551,6 +600,9 @@ class Skeletonizer:
551
600
  Container at-rules (@media, @supports, @container, @layer) preserve structure and track depth.
552
601
  Component selectors and mixins are folded into '{ /* ... */ }' unless matching keep_symbols.
553
602
  """
603
+ if ext == ".sass" and "{" not in code:
604
+ return code
605
+
554
606
  lines = code.splitlines()
555
607
  out = []
556
608
  lexer = BraceLexer()
@@ -671,6 +723,9 @@ class Skeletonizer:
671
723
  open_b, close_b = lexer.count_braces(raw_line)
672
724
  current_depth += open_b - close_b
673
725
 
726
+ if pending_sel:
727
+ out.extend(pending_sel)
728
+
674
729
  return "\n".join(out)
675
730
 
676
731
  @classmethod
package/src/slicer.py CHANGED
@@ -5,6 +5,7 @@ Prevents context window bloat from full-file reads (800+ lines) and noisy termin
5
5
 
6
6
  import os
7
7
  import re
8
+ import stat
8
9
  from typing import Dict, Any, List, Optional, Tuple
9
10
  from src.tokenizer import count_tokens
10
11
 
@@ -82,11 +83,20 @@ class ToolSlicer:
82
83
  # Tolerant arg keys: hooks keep proto casing ("Path"), but the
83
84
  # view_file/lowercase variants may send "path"/"FilePath".
84
85
  path = args.get("Path") or args.get("path") or args.get("FilePath") or ""
85
- start_line = args.get("StartLine") or args.get("startLine")
86
- end_line = args.get("EndLine") or args.get("endLine")
86
+ start_line = args.get("StartLine")
87
+ if start_line is None:
88
+ start_line = args.get("startLine")
89
+ end_line = args.get("EndLine")
90
+ if end_line is None:
91
+ end_line = args.get("endLine")
87
92
 
88
93
  if not path or not os.path.isabs(path) or not os.path.exists(path):
89
94
  return {}, {"saved_tokens": 0, "original_tokens": 0, "optimized_tokens": 0}
95
+ try:
96
+ if not stat.S_ISREG(os.stat(path).st_mode):
97
+ return {}, {"saved_tokens": 0, "original_tokens": 0, "optimized_tokens": 0}
98
+ except OSError:
99
+ return {}, {"saved_tokens": 0, "original_tokens": 0, "optimized_tokens": 0}
90
100
 
91
101
  try:
92
102
  with open(path, "r", encoding="utf-8", errors="replace") as f:
@@ -117,15 +127,21 @@ class ToolSlicer:
117
127
  # Single pass over the file for ALL candidates (previously O(words x lines)
118
128
  # regex scans per read_file hook call on large files).
119
129
  unique_candidates = list(dict.fromkeys(candidates))
130
+ cand_alt = "|".join(re.escape(c) for c in unique_candidates)
120
131
  combined = re.compile(
121
- r'\b(?:def|function|class|const|let|var|type|interface|func|fn|impl|struct|enum|trait)\s+('
122
- + "|".join(re.escape(c) for c in unique_candidates) + r')\b'
132
+ r'(?:\b(?:def|function|fun|class|const|let|var|type|interface|func|fn|impl|struct|enum|trait|record|namespace)\s+('
133
+ + cand_alt
134
+ + r')\b|^\s*(?:(?:public|private|protected|internal|static|final|async|override|virtual|suspend|mutating)\s+)+[\w<>\[\],.?*&:]+\s+('
135
+ + cand_alt
136
+ + r')\s*(?:<[^>]+>)?\s*\()'
123
137
  )
124
138
  first_hit: Dict[str, int] = {}
125
139
  for idx, line in enumerate(lines, 1):
126
140
  m = combined.search(line)
127
- if m and m.group(1) not in first_hit:
128
- first_hit[m.group(1)] = idx
141
+ if m:
142
+ hit = m.group(1) or m.group(2)
143
+ if hit and hit not in first_hit:
144
+ first_hit[hit] = idx
129
145
  # Preserve original semantics: highest-priority candidate that has a match
130
146
  for candidate in candidates:
131
147
  if candidate in first_hit:
@@ -151,8 +167,10 @@ class ToolSlicer:
151
167
 
152
168
  # If no symbol found and file is large (> 400 lines), apply safety window
153
169
  if not target_symbol and total_lines > 400 and (end_line is None or end_line > cls.DEFAULT_MAX_WINDOW):
154
- new_start = start_line if start_line is not None else 1
170
+ new_start = max(1, min(int(start_line), total_lines)) if start_line is not None else 1
155
171
  new_end = min(total_lines, new_start + cls.DEFAULT_MAX_WINDOW)
172
+ if new_end < new_start:
173
+ new_end = new_start
156
174
 
157
175
  # Calculate tokens of sliced content
158
176
  sliced_content = "".join(lines[new_start - 1 : new_end])
package/src/team_cache.py CHANGED
@@ -6,6 +6,7 @@ Zero external runtime dependencies (standard library urllib + hashlib).
6
6
 
7
7
  import os
8
8
  import json
9
+ import time
9
10
  import hashlib
10
11
  import threading
11
12
  import urllib.request
@@ -18,6 +19,8 @@ class TeamCache:
18
19
  """Distributed cross-developer cache client for TokenSafe Team tier."""
19
20
 
20
21
  DEFAULT_TIMEOUT = float(os.environ.get("TOKENSAFE_CACHE_TIMEOUT", "1.2")) # Fast 1.2s timeout to prevent blocking agent turns
22
+ FAILURE_COOLDOWN_SECONDS = 120.0
23
+ _cooldown_until: float = 0.0
21
24
 
22
25
  @classmethod
23
26
  def _get_cloud_url(cls) -> str:
@@ -31,7 +34,7 @@ class TeamCache:
31
34
  return False, ""
32
35
 
33
36
  valid, payload, _ = LicenseManager.validate_license(key)
34
- if valid and payload.get("tier") == "team":
37
+ if valid and payload.get("tier") in ("team", "enterprise"):
35
38
  return True, key
36
39
  return False, ""
37
40
 
@@ -45,8 +48,10 @@ class TeamCache:
45
48
  def get(cls, cache_type: str, key_text: str) -> Optional[str]:
46
49
  """
47
50
  Queries Shared Team Cache for compiled S-Expression or AST Skeleton.
48
- Returns cached value string or None if miss/disabled/timed out.
51
+ Returns cached value string or None if miss/disabled/timed out/in cooldown.
49
52
  """
53
+ if time.monotonic() < cls._cooldown_until:
54
+ return None
50
55
  is_team, lic_key = cls._is_team_tier()
51
56
  if not is_team or not key_text:
52
57
  return None
@@ -68,9 +73,11 @@ class TeamCache:
68
73
  data = json.loads(resp.read().decode("utf-8"))
69
74
  val = data.get("value") or data.get("cached_value")
70
75
  if data.get("hit") and val:
76
+ cls._cooldown_until = 0.0
71
77
  return val
72
78
  except Exception:
73
- # Graceful network degradation: fall back to local computation without error
79
+ # Circuit-break offline/unreachable cloud calls for 120s so misses don't stall repeated prompts
80
+ cls._cooldown_until = time.monotonic() + cls.FAILURE_COOLDOWN_SECONDS
74
81
  return None
75
82
 
76
83
  return None