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
package/src/dashboard.py CHANGED
@@ -6,6 +6,7 @@ Provides colorful CLI reports, Markdown exports, and rich modern HTML widgets.
6
6
  import sys
7
7
  import os
8
8
  import json
9
+ import html as html_lib
9
10
  from datetime import datetime
10
11
  from typing import Dict, Any, List
11
12
 
@@ -129,7 +130,8 @@ class Dashboard:
129
130
  ev_type = ev["event_type"]
130
131
  saved = ev["saved_tokens"]
131
132
  pct_ev = ev["reduction_pct"]
132
- details = ev.get("details", {})
133
+ raw_details = ev.get("details")
134
+ details = raw_details if isinstance(raw_details, dict) else {}
133
135
  detail_desc = details.get("action", "") or details.get("target_file", "") or ""
134
136
  if detail_desc:
135
137
  detail_desc = f"({detail_desc})"
@@ -140,7 +142,7 @@ class Dashboard:
140
142
  out.append(f"{DIM}Run `tokensafe html` to view interactive browser dashboard.{RESET}")
141
143
 
142
144
  if VersionChecker:
143
- banner = VersionChecker.get_banner()
145
+ banner = VersionChecker.get_banner(cache_only=True)
144
146
  if banner:
145
147
  out.append(banner)
146
148
  else:
@@ -187,7 +189,8 @@ class Dashboard:
187
189
  md.append("| :--- | :--- | :--- | :--- | :--- |")
188
190
  for ev in recent:
189
191
  t_str = ev["timestamp"].split("T")[1][:8] if "T" in ev["timestamp"] else ev["timestamp"]
190
- details = ev.get("details", {})
192
+ raw_details = ev.get("details")
193
+ details = raw_details if isinstance(raw_details, dict) else {}
191
194
  scope = details.get("target_file") or details.get("action") or "General"
192
195
  md.append(f"| `{t_str}` | `{ev['event_type']}` | `{scope}` | {ev['original_tokens']} ➔ {ev['optimized_tokens']} | **+{ev['saved_tokens']:,} (-{ev['reduction_pct']}%)** |")
193
196
 
@@ -207,7 +210,7 @@ class Dashboard:
207
210
 
208
211
  breakdown_rows = ""
209
212
  for source, data in summary.get("breakdown", {}).items():
210
- s_name = EVENT_NAMES.get(source, source)
213
+ s_name = html_lib.escape(str(EVENT_NAMES.get(source, source)))
211
214
  s_pct = round((data['saved'] / total_saved * 100.0), 1) if total_saved > 0 else 0
212
215
  breakdown_rows += f"""
213
216
  <div class="source-card">
@@ -227,13 +230,15 @@ class Dashboard:
227
230
 
228
231
  recent_rows = ""
229
232
  for ev in recent:
230
- t_str = ev["timestamp"].split("T")[1][:8] if "T" in ev["timestamp"] else ev["timestamp"]
231
- details = ev.get("details", {})
232
- scope = details.get("target_file") or details.get("action") or ev["event_type"]
233
+ t_str = html_lib.escape(str(ev["timestamp"].split("T")[1][:8] if "T" in ev["timestamp"] else ev["timestamp"]))
234
+ raw_details = ev.get("details")
235
+ details = raw_details if isinstance(raw_details, dict) else {}
236
+ scope = html_lib.escape(str(details.get("target_file") or details.get("action") or ev["event_type"]))
237
+ ev_type_esc = html_lib.escape(str(ev['event_type']))
233
238
  recent_rows += f"""
234
239
  <tr>
235
240
  <td><span class="badge time">{t_str}</span></td>
236
- <td><span class="badge type">{ev['event_type']}</span></td>
241
+ <td><span class="badge type">{ev_type_esc}</span></td>
237
242
  <td class="scope-cell">{scope}</td>
238
243
  <td class="tokens-cell">{ev['original_tokens']:,} ➔ {ev['optimized_tokens']:,}</td>
239
244
  <td class="saved-cell">+{ev['saved_tokens']:,} (-{ev['reduction_pct']}%)</td>
@@ -254,12 +259,14 @@ class Dashboard:
254
259
  </div>
255
260
  """
256
261
  else:
262
+ email_esc = html_lib.escape(str(payload.get('email', '')))
263
+ tier_esc = html_lib.escape(str(tier.upper()))
257
264
  banner_html = f"""
258
265
  <div style="background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 12px; padding: 14px 18px; margin-bottom: 24px; display: flex; justify-content: space-between; align-items: center; font-size: 13px;">
259
266
  <div>
260
- <strong style="color: #10b981;">⚡ License Active:</strong> TokenSafe {tier.upper()} Plan (Unlimited Tokens).
267
+ <strong style="color: #10b981;">⚡ License Active:</strong> TokenSafe {tier_esc} Plan (Unlimited Tokens).
261
268
  </div>
262
- <span style="color: #9ca3af; font-size: 12px;">{payload.get('email', '')}</span>
269
+ <span style="color: #9ca3af; font-size: 12px;">{email_esc}</span>
263
270
  </div>
264
271
  """
265
272
 
@@ -12,6 +12,7 @@ import urllib.error
12
12
  from typing import Optional, Dict, Any
13
13
  from src.distiller_cache import DistillationCache
14
14
  from src.license_manager import LicenseManager
15
+ from src.paths import resolve_data_dir
15
16
 
16
17
  class DeepSeekDistiller:
17
18
  """Uses DeepSeek-Flash as a high-density semantic compiler for prompts."""
@@ -42,27 +43,34 @@ Rules:
42
43
 
43
44
  @classmethod
44
45
  def _get_config(cls) -> Dict[str, Any]:
45
- """Loads API key and configuration from environment or data/config.json."""
46
+ """Loads API key and configuration from environment or config.json."""
46
47
  config = {
47
- "api_key": os.environ.get("DEEPSEEK_API_KEY", ""),
48
+ "api_key": os.environ.get("DEEPSEEK_API_KEY", "").strip(),
48
49
  "model": cls.DEFAULT_MODEL,
49
50
  "timeout": cls.DEFAULT_TIMEOUT,
50
51
  "enabled": True
51
52
  }
52
53
 
53
- # Check data/config.json relative to project root
54
- base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
55
- config_path = os.path.join(base_dir, "data", "config.json")
54
+ config_path = os.path.join(resolve_data_dir(), "config.json")
56
55
  if os.path.exists(config_path):
57
56
  try:
58
57
  with open(config_path, "r", encoding="utf-8") as f:
59
58
  file_conf = json.load(f)
59
+ if isinstance(file_conf, dict):
60
60
  if not config["api_key"] and file_conf.get("deepseek_api_key"):
61
- config["api_key"] = file_conf["deepseek_api_key"]
62
- config["model"] = file_conf.get("deepseek_model", config["model"])
63
- config["timeout"] = file_conf.get("deepseek_timeout", config["timeout"])
64
- config["max_tokens"] = int(file_conf.get("distill_max_tokens", 60))
65
- config["enabled"] = file_conf.get("enable_deepseek_tier", True)
61
+ config["api_key"] = str(file_conf["deepseek_api_key"]).strip()
62
+ config["model"] = str(file_conf.get("deepseek_model") or config["model"])
63
+ try:
64
+ raw_to = file_conf.get("deepseek_timeout")
65
+ config["timeout"] = float(raw_to if raw_to is not None else config["timeout"])
66
+ except (TypeError, ValueError):
67
+ pass
68
+ try:
69
+ raw_mt = file_conf.get("distill_max_tokens")
70
+ config["max_tokens"] = int(raw_mt if raw_mt is not None else 60)
71
+ except (TypeError, ValueError):
72
+ config["max_tokens"] = 60
73
+ config["enabled"] = bool(file_conf.get("enable_deepseek_tier", True))
66
74
  except Exception:
67
75
  pass
68
76
 
@@ -109,7 +117,8 @@ Rules:
109
117
  data=json.dumps(payload).encode("utf-8"),
110
118
  headers={
111
119
  "Authorization": f"Bearer {conf['api_key']}",
112
- "Content-Type": "application/json"
120
+ "Content-Type": "application/json",
121
+ "User-Agent": "TokenSafe/1.0",
113
122
  }
114
123
  )
115
124
 
@@ -119,12 +128,12 @@ Rules:
119
128
  data = json.loads(resp.read().decode("utf-8"))
120
129
  choices = data.get("choices", [])
121
130
  if choices:
122
- content = choices[0].get("message", {}).get("content", "").strip()
123
- # Clean backticks if any
124
- content = re.sub(r"^```[a-zA-Z]*\n?|```$", "", content).strip()
125
- if content.startswith("(") and content.endswith(")"):
126
- DistillationCache.set(raw_text, content, provider="deepseek")
127
- return content
131
+ from src.distiller import UniversalDistiller
132
+ raw_msg = choices[0].get("message", {}).get("content", "")
133
+ clean = UniversalDistiller._sanitize_s_expression(raw_msg)
134
+ if clean:
135
+ DistillationCache.set(raw_text, clean, provider="deepseek")
136
+ return clean
128
137
  except Exception:
129
138
  # Network issue, timeout, or rate limit: fallback gracefully
130
139
  return None
@@ -36,7 +36,7 @@ class DependencyPrefetcher:
36
36
 
37
37
  if ext == ".py":
38
38
  imported_symbols = cls._parse_python_imports(content, file_dir)
39
- elif ext in (".ts", ".js", ".tsx", ".jsx"):
39
+ elif ext in (".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs"):
40
40
  imported_symbols = cls._parse_ts_imports(content, file_dir)
41
41
 
42
42
  if not imported_symbols:
@@ -81,22 +81,31 @@ class DependencyPrefetcher:
81
81
  symbols = [alias.name for alias in node.names]
82
82
 
83
83
  dep_path = None
84
+ mod_rel = os.path.join(*module.split(".")) if module else ""
84
85
  if level > 0:
85
- # Relative import
86
- rel_levels = ".." * (level - 1)
87
- target_dir = os.path.abspath(os.path.join(current_dir, rel_levels))
88
- candidate = os.path.join(target_dir, f"{module}.py") if module else None
89
- if candidate and os.path.exists(candidate):
90
- dep_path = candidate
91
- elif not module:
92
- candidate = os.path.join(target_dir, "__init__.py")
93
- if os.path.exists(candidate):
94
- dep_path = candidate
95
- else:
96
- # Check if local file in same directory
97
- candidate = os.path.join(current_dir, f"{module}.py")
98
- if os.path.exists(candidate):
99
- dep_path = candidate
86
+ # Relative import: level=1 -> '.', level=2 -> '..', level=3 -> '../..'
87
+ parents = [".."] * (level - 1)
88
+ target_dir = os.path.abspath(os.path.join(current_dir, *parents)) if parents else current_dir
89
+ if mod_rel:
90
+ for cand in (
91
+ os.path.join(target_dir, f"{mod_rel}.py"),
92
+ os.path.join(target_dir, mod_rel, "__init__.py"),
93
+ ):
94
+ if os.path.exists(cand):
95
+ dep_path = cand
96
+ break
97
+ else:
98
+ cand = os.path.join(target_dir, "__init__.py")
99
+ if os.path.exists(cand):
100
+ dep_path = cand
101
+ elif mod_rel:
102
+ for cand in (
103
+ os.path.join(current_dir, f"{mod_rel}.py"),
104
+ os.path.join(current_dir, mod_rel, "__init__.py"),
105
+ ):
106
+ if os.path.exists(cand):
107
+ dep_path = cand
108
+ break
100
109
 
101
110
  if dep_path and os.path.exists(dep_path):
102
111
  results.append({"path": dep_path, "symbols": symbols})
@@ -126,14 +135,16 @@ class DependencyPrefetcher:
126
135
  elif default_import:
127
136
  symbols = [default_import.strip()]
128
137
 
129
- # Resolve target file path (check .ts, .tsx, .js, /index.ts)
138
+ # Resolve target file path (handles already-extensioned ESM imports like './foo.js' -> './foo.ts')
130
139
  base_target = os.path.normpath(os.path.join(current_dir, rel_path))
131
- resolved = None
132
- for ext in (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"):
133
- candidate = f"{base_target}{ext}" if not ext.startswith("/") else f"{base_target}{ext}"
134
- if os.path.exists(candidate):
135
- resolved = candidate
136
- break
140
+ base_no_js = re.sub(r"\.(?:mjs|cjs|jsx|js)$", "", base_target)
141
+ candidates: List[str] = []
142
+ if os.path.isfile(base_target):
143
+ candidates.append(base_target)
144
+ for root_cand in dict.fromkeys((base_target, base_no_js)):
145
+ for ext in (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", "/index.ts", "/index.tsx", "/index.js", "/index.mjs"):
146
+ candidates.append(f"{root_cand}{ext}")
147
+ resolved = next((c for c in candidates if os.path.isfile(c)), None)
137
148
 
138
149
  if resolved and symbols:
139
150
  results.append({"path": resolved, "symbols": symbols})
@@ -169,25 +180,39 @@ class DependencyPrefetcher:
169
180
  except Exception:
170
181
  pass
171
182
  else:
172
- # TS/JS interface/class/type/function extraction
183
+ # TS/JS interface/class/type/function extraction (brace-depth safe)
173
184
  for sym in symbols:
174
- pattern = re.compile(
175
- rf"""(?:export\s+)?(interface|type|class)\s+{re.escape(sym)}\b\s*\{{([^}}]*)\}}""",
176
- re.DOTALL
177
- )
178
- m = pattern.search(code)
179
- if m:
180
- kind = m.group(1)
181
- body = m.group(2).strip()
182
- body_clean = re.sub(r"\s+", " ", body)
183
- extracted.append(f"{kind} {sym} {{ {body_clean} }}")
185
+ decl_re = re.compile(rf"(?:export\s+(?:default\s+)?)?(?:declare\s+)?(interface|type|class|enum)\s+{re.escape(sym)}\b[^{{;]*")
186
+ dm = decl_re.search(code)
187
+ if dm:
188
+ kind = dm.group(1)
189
+ rest = code[dm.end():]
190
+ if rest.lstrip().startswith("{"):
191
+ brace_idx = code.find("{", dm.end())
192
+ depth = 0
193
+ end_idx = brace_idx
194
+ for idx in range(brace_idx, min(len(code), brace_idx + 2000)):
195
+ ch = code[idx]
196
+ if ch == "{":
197
+ depth += 1
198
+ elif ch == "}":
199
+ depth -= 1
200
+ if depth == 0:
201
+ end_idx = idx
202
+ break
203
+ body_clean = re.sub(r"\s+", " ", code[brace_idx + 1 : end_idx].strip())
204
+ if len(body_clean) > 120:
205
+ body_clean = body_clean[:117] + "..."
206
+ extracted.append(f"{kind} {sym} {{ {body_clean} }}")
207
+ continue
208
+ fn_pattern = re.compile(rf"""(?:export\s+(?:default\s+)?)?(?:async\s+)?(function|const|let)\s+{re.escape(sym)}\b[^\n;]*""", re.MULTILINE)
209
+ fm = fn_pattern.search(code)
210
+ if fm:
211
+ sig = fm.group(0).replace("export default ", "").replace("export ", "").strip()
212
+ sig = sig.rstrip("{").strip()
213
+ sig = re.sub(r"\s+", " ", sig)
214
+ extracted.append(sig)
184
215
  else:
185
- fn_pattern = re.compile(rf"""(?:export\s+)?(function|const)\s+{re.escape(sym)}\b[^{{;]*""", re.MULTILINE)
186
- fm = fn_pattern.search(code)
187
- if fm:
188
- sig = re.sub(r"\s+", " ", fm.group(0).replace("export ", "").strip())
189
- extracted.append(sig)
190
- else:
191
- extracted.append(sym)
216
+ extracted.append(sym)
192
217
 
193
218
  return "; ".join(extracted) if extracted else ", ".join(symbols)
@@ -34,6 +34,7 @@ class DiffSlicer:
34
34
  return raw_diff, 0, 0
35
35
 
36
36
  orig_tokens = count_tokens(raw_diff)
37
+ max_context_lines = max(0, int(max_context_lines))
37
38
  lines = raw_diff.splitlines()
38
39
  output_lines: List[str] = []
39
40
 
@@ -49,21 +50,23 @@ class DiffSlicer:
49
50
  output_lines.extend(context_run)
50
51
  else:
51
52
  if is_trailing:
52
- # Keep first N lines of trailing context
53
- output_lines.extend(context_run[:limit])
53
+ # Keep first N lines of trailing context (0 when limit == 0)
54
+ if limit > 0:
55
+ output_lines.extend(context_run[:limit])
54
56
  output_lines.append(f" ... ({len(context_run) - limit} context lines omitted)")
55
57
  else:
56
- # Keep last N lines of leading context
58
+ # Keep last N lines of leading context (0 when limit == 0)
57
59
  output_lines.append(f" ... ({len(context_run) - limit} context lines omitted)")
58
- output_lines.extend(context_run[-limit:])
60
+ if limit > 0:
61
+ output_lines.extend(context_run[-limit:])
59
62
  context_run = []
60
63
 
61
64
  for line in lines:
62
65
  # File header detection
63
66
  if line.startswith("diff --git "):
64
67
  flush_context(max_context_lines, is_trailing=True)
65
- parts = line.split(" ")
66
- current_file = parts[-1] if len(parts) > 2 else ""
68
+ m_file = re.match(r'^diff --git\s+"?(?:a/)?(.+?)"?\s+"?(?:b/)?(.+?)"?\s*$', line)
69
+ current_file = m_file.group(2) if m_file else (line.split(" ")[-1].strip('"'))
67
70
  # Check if ignored file pattern or extension
68
71
  skip_current_file = any(pat in current_file for pat in cls.IGNORED_DIFF_PATTERNS) or current_file.endswith((".lock", ".lockb", ".sum", ".map", ".png", ".jpg", ".svg"))
69
72
  if skip_current_file:
@@ -106,15 +109,10 @@ class DiffSlicer:
106
109
  def optimize_git_diff_command(cls, cmd: str) -> Tuple[Optional[str], int, str]:
107
110
  """
108
111
  Rewrites git diff commands to enforce 2-line unified diffs and ignore lockfiles.
109
- Per-stage: excludes are appended to each `git diff` stage itself, never
110
- to the tail of a compound command (which would leak pathspecs into an
111
- unrelated trailing command like `npm test`).
112
+ Per-stage: -U2 and excludes apply cleanly per git diff stage.
112
113
  """
113
114
  clean_cmd = cmd.strip()
114
- if not re.search(r"\bgit\s+diff\b", clean_cmd):
115
- return None, 0, ""
116
-
117
- if "--unified=" in clean_cmd or "-U" in clean_cmd:
115
+ if not re.search(r"\bgit\s+(?:-C\s+\S+\s+)?diff\b", clean_cmd):
118
116
  return None, 0, ""
119
117
 
120
118
  from src.command_sanitizer import CommandSanitizer
@@ -122,11 +120,19 @@ class DiffSlicer:
122
120
  lockfile_excludes = " ':!*lock*' ':!*.min.*' ':!*.map'"
123
121
  changed = False
124
122
  for i, (op, stage) in enumerate(pairs):
125
- if not re.search(r"\bgit\s+diff\b", stage):
123
+ if not re.search(r"^(?:[A-Za-z_]\w*=\S*\s+)*(?:sudo\s+|env\s+)?git(?:\s+-C\s+\S+)?\s+diff\b", stage):
124
+ continue
125
+ if ":!" in stage or re.search(r"(?:^|\s)(?:--unified=\d+|-U\d*)\b", stage):
126
126
  continue
127
- if ":!" in stage:
128
- continue # caller already manages pathspec excludes
129
- pairs[i] = (op, stage.replace("git diff", "git diff -U2", 1) + lockfile_excludes)
127
+ new_stage = re.sub(r"\bdiff\b", "diff -U2", stage, count=1)
128
+ if "-- " not in stage and not stage.rstrip().endswith("--"):
129
+ toks = CommandSanitizer._split_tokens_safe(stage)
130
+ diff_pos = toks.index("diff") if "diff" in toks else 1
131
+ sub_args = toks[diff_pos + 1 :]
132
+ has_path = any(not a.startswith("-") and not CommandSanitizer._GIT_REF_RE.match(a) for a in sub_args)
133
+ if not has_path:
134
+ new_stage += lockfile_excludes
135
+ pairs[i] = (op, new_stage)
130
136
  changed = True
131
137
 
132
138
  if not changed:
package/src/distiller.py CHANGED
@@ -14,6 +14,7 @@ import urllib.error
14
14
  from typing import Optional, Dict, Any, Tuple
15
15
  from src.distiller_cache import DistillationCache
16
16
  from src.license_manager import LicenseManager
17
+ from src.paths import resolve_data_dir
17
18
 
18
19
  class UniversalDistiller:
19
20
  """Multi-provider semantic intent compiler supporting DeepSeek, OpenAI, and Google Gemini."""
@@ -26,9 +27,7 @@ class UniversalDistiller:
26
27
 
27
28
  @classmethod
28
29
  def _failure_state_path(cls) -> str:
29
- base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30
- data_dir = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(base_dir, "data"))
31
- return os.path.join(data_dir, "distill_failure_state.json")
30
+ return os.path.join(resolve_data_dir(), "distill_failure_state.json")
32
31
 
33
32
  @classmethod
34
33
  def _cooldown_active(cls) -> bool:
@@ -150,12 +149,13 @@ Rules:
150
149
  }
151
150
 
152
151
  config_file_data = {}
153
- base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
154
- config_path = os.path.join(base_dir, "data", "config.json")
152
+ config_path = os.path.join(resolve_data_dir(), "config.json")
155
153
  if os.path.exists(config_path):
156
154
  try:
157
155
  with open(config_path, "r", encoding="utf-8") as f:
158
- config_file_data = json.load(f)
156
+ loaded_cfg = json.load(f)
157
+ if isinstance(loaded_cfg, dict):
158
+ config_file_data = loaded_cfg
159
159
  except Exception:
160
160
  pass
161
161
 
@@ -165,12 +165,20 @@ Rules:
165
165
  for key, p_info in cls.PROVIDERS.items():
166
166
  api_key = os.environ.get(p_info["env_key"], "").strip()
167
167
  if not api_key and p_info["config_key"] in config_file_data:
168
- api_key = str(config_file_data[p_info["config_key"]]).strip()
168
+ api_key = str(config_file_data[p_info["config_key"]] or "").strip()
169
169
 
170
170
  if api_key:
171
- model = config_file_data.get(f"{key}_model", p_info["default_model"])
172
- timeout = float(config_file_data.get(f"{key}_timeout", cls.DEFAULT_TIMEOUT))
173
- max_tokens = int(config_file_data.get("distill_max_tokens", 60))
171
+ model = str(config_file_data.get(f"{key}_model") or p_info["default_model"])
172
+ try:
173
+ raw_to = config_file_data.get(f"{key}_timeout")
174
+ timeout = float(raw_to if raw_to is not None else cls.DEFAULT_TIMEOUT)
175
+ except (TypeError, ValueError):
176
+ timeout = cls.DEFAULT_TIMEOUT
177
+ try:
178
+ raw_mt = config_file_data.get("distill_max_tokens")
179
+ max_tokens = int(raw_mt if raw_mt is not None else 60)
180
+ except (TypeError, ValueError):
181
+ max_tokens = 60
174
182
  available[key] = {
175
183
  "provider": key,
176
184
  "name": p_info["name"],
@@ -231,8 +239,7 @@ Rules:
231
239
  # Determine order
232
240
  pref = preferred_provider
233
241
  if not pref:
234
- base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
235
- config_path = os.path.join(base_dir, "data", "config.json")
242
+ config_path = os.path.join(resolve_data_dir(), "config.json")
236
243
  if os.path.exists(config_path):
237
244
  try:
238
245
  with open(config_path, "r", encoding="utf-8") as f:
@@ -345,10 +352,31 @@ Rules:
345
352
  lines = content.splitlines()
346
353
  content = " ".join([l for l in lines if not l.startswith("```")]).strip()
347
354
 
348
- # Extract parenthesized S-Expression
349
- match = re.search(r"\([A-Z]+[^\)]*\)", content)
350
- if match:
351
- return match.group(0).strip()
352
- elif content.startswith("(") and content.endswith(")"):
355
+ # Balanced quote-aware extraction so parens inside "intent foo(x)" don't truncate
356
+ m_start = re.search(r"\([A-Z]+(?:\s|\))", content)
357
+ if m_start:
358
+ start = m_start.start()
359
+ depth = 0
360
+ in_quote = False
361
+ i = start
362
+ while i < len(content):
363
+ ch = content[i]
364
+ if in_quote:
365
+ if ch == "\\" and i + 1 < len(content):
366
+ i += 2
367
+ continue
368
+ if ch == '"':
369
+ in_quote = False
370
+ else:
371
+ if ch == '"':
372
+ in_quote = True
373
+ elif ch == "(":
374
+ depth += 1
375
+ elif ch == ")":
376
+ depth -= 1
377
+ if depth == 0:
378
+ return content[start : i + 1].strip()
379
+ i += 1
380
+ if content.startswith("(") and content.endswith(")"):
353
381
  return content
354
382
  return None