tokensafe 2.7.3 → 2.8.0

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.
@@ -0,0 +1,302 @@
1
+ """Schema-aware slicer for heavy declarative files that break AST code tooling.
2
+
3
+ Opening a 5,000-line OpenAPI spec, Prisma schema, GraphQL SDL or SQL migration
4
+ dump costs 20k-50k tokens; generic AST skeletonization does not apply to them.
5
+ SchemaSlicer returns a compact overview when no target is given, and a targeted
6
+ slice (the requested entry + 1-hop references) when one is:
7
+
8
+ - OpenAPI/Swagger (JSON + YAML): one path + its $ref schema closure, or one schema.
9
+ - Prisma: one model block + 1-hop relation targets.
10
+ - GraphQL SDL: one type block + 1-hop field types.
11
+ - SQL: DDL statements only (CREATE TABLE/INDEX/ALTER/TYPE) — INSERT/UPDATE
12
+ history is dropped; a target table filters further.
13
+
14
+ Standard library only. `target` semantics follow the `symbol` argument of
15
+ smart_read_file so agents use one familiar entry point.
16
+ """
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ from typing import Any, Dict, List, Optional, Tuple
22
+
23
+ _MAX_REF_CHAIN = 15
24
+ _MAX_SQL_BYTES = 4 * 1024 * 1024
25
+
26
+
27
+ class SchemaSlicer:
28
+ """Detects schema files and produces targeted, token-cheap slices."""
29
+
30
+ @classmethod
31
+ def detect(cls, path: str) -> Optional[str]:
32
+ """Returns the schema kind for `path` (openapi|prisma|graphql|sql) or None."""
33
+ ext = os.path.splitext(path)[1].lower()
34
+ if ext == ".prisma":
35
+ return "prisma"
36
+ if ext in (".graphql", ".gql"):
37
+ return "graphql"
38
+ if ext == ".sql":
39
+ return "sql"
40
+ if ext == ".json":
41
+ try:
42
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
43
+ head = f.read(4096)
44
+ return "openapi" if re.search(r'"(?:openapi|swagger|paths)"\s*:', head) else None
45
+ except Exception:
46
+ return None
47
+ if ext in (".yaml", ".yml"):
48
+ try:
49
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
50
+ head = f.read(4096)
51
+ return "openapi" if re.search(r"^\s*(openapi|swagger)\s*:", head, re.MULTILINE) else None
52
+ except Exception:
53
+ return None
54
+ return None
55
+
56
+ @classmethod
57
+ def slice_file(cls, path: str, target: str = "") -> Tuple[str, Dict[str, Any]]:
58
+ """Returns (sliced_text, info). Empty `target` yields a compact overview."""
59
+ kind = cls.detect(path)
60
+ if kind == "openapi":
61
+ return cls._slice_openapi(path, target.strip())
62
+ if kind == "prisma":
63
+ return cls._slice_prisma(path, target.strip())
64
+ if kind == "graphql":
65
+ return cls._slice_graphql(path, target.strip())
66
+ if kind == "sql":
67
+ return cls._slice_sql(path, target.strip())
68
+ return "", {"kind": None}
69
+
70
+ # ------------------------------------------------------------------ OpenAPI
71
+
72
+ @classmethod
73
+ def _slice_openapi(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
74
+ ext = os.path.splitext(path)[1].lower()
75
+ if ext in (".yaml", ".yml"):
76
+ return cls._slice_openapi_yaml(path, target)
77
+ try:
78
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
79
+ spec = json.load(f)
80
+ except Exception as e:
81
+ return f"[TokenSafe SchemaSlicer] Cannot parse OpenAPI JSON: {e}", {"kind": "openapi", "error": True}
82
+
83
+ def schema_pool() -> Dict[str, Any]:
84
+ comps = spec.get("components") or {}
85
+ return (comps.get("schemas") or {}) or (spec.get("definitions") or {})
86
+
87
+ def resolve_refs(node: Any, pool: Dict[str, Any], acc: Dict[str, Any], depth: int = 0) -> None:
88
+ if depth > _MAX_REF_CHAIN or len(acc) >= _MAX_REF_CHAIN:
89
+ return
90
+ if isinstance(node, dict):
91
+ ref = node.get("$ref")
92
+ if isinstance(ref, str) and ref.startswith("#/"):
93
+ name = ref.rsplit("/", 1)[-1]
94
+ if name not in acc and name in pool:
95
+ acc[name] = pool[name]
96
+ resolve_refs(pool[name], pool, acc, depth + 1)
97
+ for v in node.values():
98
+ resolve_refs(v, pool, acc, depth + 1)
99
+ elif isinstance(node, list):
100
+ for v in node:
101
+ resolve_refs(v, pool, acc, depth + 1)
102
+
103
+ if target.startswith("/"):
104
+ item = (spec.get("paths") or {}).get(target)
105
+ if item is None:
106
+ return cls._openapi_overview(spec, missing=target)
107
+ pool = schema_pool()
108
+ acc: Dict[str, Any] = {}
109
+ resolve_refs(item, pool, acc)
110
+ out = [f"# OpenAPI path: {target}", json.dumps({target: item}, indent=2, ensure_ascii=False)]
111
+ if acc:
112
+ out.append("\n# Referenced schemas ($ref closure)")
113
+ out.append(json.dumps(acc, indent=2, ensure_ascii=False))
114
+ return "\n".join(out), {"kind": "openapi", "mode": "path", "refs": list(acc)}
115
+ if target:
116
+ pool = schema_pool()
117
+ if target in pool:
118
+ acc: Dict[str, Any] = {}
119
+ resolve_refs(pool[target], pool, acc)
120
+ body = {"name": target, **(pool[target] if isinstance(pool[target], dict) else {"schema": pool[target]})}
121
+ out = [f"# OpenAPI schema: {target}", json.dumps(body, indent=2, ensure_ascii=False)]
122
+ others = {k: v for k, v in acc.items() if k != target}
123
+ if others:
124
+ out.append("\n# Referenced schemas ($ref closure)")
125
+ out.append(json.dumps(others, indent=2, ensure_ascii=False))
126
+ return "\n".join(out), {"kind": "openapi", "mode": "schema", "refs": list(others)}
127
+ # Try a method-scoped path: "/users get" or "/users:get"
128
+ parts = re.split(r"[\s:]+", target, maxsplit=1)
129
+ if len(parts) == 2 and parts[0].startswith("/") and parts[1].lower() in ("get", "post", "put", "patch", "delete", "options", "head"):
130
+ item = (spec.get("paths") or {}).get(parts[0]) or {}
131
+ op = item.get(parts[1].lower())
132
+ if op is not None:
133
+ pool = schema_pool()
134
+ acc: Dict[str, Any] = {}
135
+ resolve_refs(op, pool, acc)
136
+ out = [f"# OpenAPI operation: {parts[1].upper()} {parts[0]}", json.dumps({parts[1].lower(): op}, indent=2, ensure_ascii=False)]
137
+ if acc:
138
+ out.append("\n# Referenced schemas ($ref closure)")
139
+ out.append(json.dumps(acc, indent=2, ensure_ascii=False))
140
+ return "\n".join(out), {"kind": "openapi", "mode": "operation", "refs": list(acc)}
141
+ return cls._openapi_overview(spec, missing=target)
142
+ return cls._openapi_overview(spec)
143
+
144
+ @classmethod
145
+ def _openapi_overview(cls, spec: Dict[str, Any], missing: str = "") -> Tuple[str, Dict[str, Any]]:
146
+ lines = [f"# OpenAPI {spec.get('openapi') or spec.get('swagger') or ''} — overview"]
147
+ if missing:
148
+ lines.append(f"# (target '{missing}' not found — showing the spec index)")
149
+ paths = spec.get("paths") or {}
150
+ lines.append(f"\n## Paths ({len(paths)})")
151
+ for p, item in list(paths.items())[:120]:
152
+ methods = [m.upper() for m in (item or {}) if m in ("get", "post", "put", "patch", "delete", "options", "head")]
153
+ lines.append(f" {'/'.join(methods) or '-'} {p}")
154
+ pool = (spec.get("components") or {}).get("schemas") or spec.get("definitions") or {}
155
+ names = list(pool.keys())
156
+ lines.append(f"\n## Schemas ({len(names)})")
157
+ lines.append(" " + ", ".join(names[:150]))
158
+ lines.append("\nSlice a specific entry: symbol='/users/{id}' (path), '/users get' (operation) or 'User' (schema).")
159
+ return "\n".join(lines), {"kind": "openapi", "mode": "overview"}
160
+
161
+ @classmethod
162
+ def _slice_openapi_yaml(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
163
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
164
+ lines = f.readlines()
165
+ # Top-level paths block: lines matching " /path:" under "paths:"
166
+ in_paths = False
167
+ blocks: Dict[str, List[str]] = {}
168
+ current: Optional[str] = None
169
+ for ln in lines:
170
+ if re.match(r"^paths\s*:", ln):
171
+ in_paths = True
172
+ continue
173
+ if in_paths:
174
+ if re.match(r"^[A-Za-z_#-]", ln): # next top-level key ends paths
175
+ in_paths = False
176
+ current = None
177
+ else:
178
+ m = re.match(r"^ (\s*/[^\s:]+)\s*:", ln)
179
+ if m:
180
+ current = m.group(1)
181
+ blocks[current] = [ln]
182
+ elif current:
183
+ blocks[current].append(ln)
184
+ if not target:
185
+ lines_out = [f"# OpenAPI (YAML) — overview", "", "## Paths"]
186
+ for p in list(blocks)[:120]:
187
+ lines_out.append(f" {p.rstrip(':')}")
188
+ lines_out.append("\nSlice a specific path: symbol='/users/{id}'.")
189
+ return "\n".join(lines_out), {"kind": "openapi", "mode": "overview"}
190
+ norm = target if target.startswith("/") else "/" + target
191
+ blk = blocks.get(norm) or blocks.get(target.rstrip(":"))
192
+ if not blk:
193
+ return "\n".join([f"# target '{target}' not found", "## Paths"] + [f" {p.rstrip(':')}" for p in list(blocks)[:120]]), {"kind": "openapi", "mode": "missing"}
194
+ return f"# OpenAPI path: {norm}\n" + "".join(blk), {"kind": "openapi", "mode": "path"}
195
+
196
+ # ------------------------------------------------------------------ Prisma
197
+
198
+ @classmethod
199
+ def _slice_prisma(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
200
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
201
+ src = f.read()
202
+ block_re = re.compile(r"^(model|enum|type)\s+(\w+)\s*\{(.*?)^\}", re.MULTILINE | re.DOTALL)
203
+ blocks: Dict[str, Tuple[str, str]] = {}
204
+ order: List[str] = []
205
+ for m in block_re.finditer(src):
206
+ name = m.group(2)
207
+ blocks[name] = (m.group(1), m.group(0))
208
+ order.append(name)
209
+ if not target:
210
+ lines = [f"# Prisma schema — overview ({len(blocks)} definitions)", ""]
211
+ for name in order[:150]:
212
+ kind_name, body = blocks[name]
213
+ fields = len(re.findall(r"^\s{2,}\w+", body, re.MULTILINE))
214
+ lines.append(f" {kind_name} {name} ({fields} fields)")
215
+ lines.append("\nSlice a model: symbol='User'.")
216
+ return "\n".join(lines), {"kind": "prisma", "mode": "overview"}
217
+ if target not in blocks:
218
+ return f"# target '{target}' not found. Definitions: {', '.join(order[:100])}", {"kind": "prisma", "mode": "missing"}
219
+ kind_name, body = blocks[target]
220
+ out = [f"# Prisma {kind_name} {target}", body]
221
+ # 1-hop: capitalized field types that are themselves defined blocks
222
+ refs = set()
223
+ for fm in re.finditer(r"^\s{2,}\w+\??\s+([A-Z]\w*)(?:\[\])?(?:\s|$)", body, re.MULTILINE):
224
+ if fm.group(1) in blocks and fm.group(1) != target:
225
+ refs.add(fm.group(1))
226
+ if refs:
227
+ out.append("\n# 1-hop related definitions")
228
+ for r in sorted(refs):
229
+ out.append(blocks[r][1])
230
+ return "\n".join(out), {"kind": "prisma", "mode": "model", "refs": sorted(refs)}
231
+
232
+ # ------------------------------------------------------------------ GraphQL
233
+
234
+ @classmethod
235
+ def _slice_graphql(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
236
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
237
+ src = f.read()
238
+ src = re.sub(r'"""[\s\S]*?"""', '""', src) # drop block descriptions for overview scanning
239
+ block_re = re.compile(r"^(type|input|interface|enum)\s+(\w+)([^{}]*?)\{(.*?)\}", re.MULTILINE | re.DOTALL)
240
+ blocks: Dict[str, Tuple[str, str]] = {}
241
+ order: List[str] = []
242
+ for m in block_re.finditer(src):
243
+ name = m.group(2)
244
+ blocks[name] = (m.group(1), m.group(0))
245
+ order.append(name)
246
+ for m in re.finditer(r"^(scalar|union)\s+(\w+)([^\n]*)", src, re.MULTILINE):
247
+ name = m.group(2)
248
+ if name not in blocks:
249
+ blocks[name] = (m.group(1), m.group(0).strip())
250
+ order.append(name)
251
+ if not target:
252
+ lines = [f"# GraphQL SDL — overview ({len(blocks)} definitions)", ""]
253
+ for name in order[:150]:
254
+ kind_name, _ = blocks[name]
255
+ lines.append(f" {kind_name} {name}")
256
+ lines.append("\nSlice a type: symbol='User'.")
257
+ return "\n".join(lines), {"kind": "graphql", "mode": "overview"}
258
+ if target not in blocks:
259
+ return f"# target '{target}' not found. Definitions: {', '.join(order[:100])}", {"kind": "graphql", "mode": "missing"}
260
+ kind_name, body = blocks[target]
261
+ out = [f"# GraphQL {kind_name} {target}", body]
262
+ refs = set()
263
+ for fm in re.finditer(r":\s*\[?([A-Z]\w*)[!\]]*(?:\s|$)", body):
264
+ if fm.group(1) in blocks and fm.group(1) != target:
265
+ refs.add(fm.group(1))
266
+ if refs:
267
+ out.append("\n# 1-hop related types")
268
+ for r in sorted(refs):
269
+ out.append(blocks[r][1])
270
+ return "\n".join(out), {"kind": "graphql", "mode": "type", "refs": sorted(refs)}
271
+
272
+ # ------------------------------------------------------------------ SQL
273
+
274
+ _SQL_DDL_RE = re.compile(
275
+ r"^\s*(CREATE\s+(?:UNIQUE\s+)?(?:TABLE|INDEX|MATERIALIZED\s+VIEW|VIEW|TYPE|SCHEMA)|ALTER\s+TABLE)\b",
276
+ re.IGNORECASE,
277
+ )
278
+
279
+ @classmethod
280
+ def _slice_sql(cls, path: str, target: str) -> Tuple[str, Dict[str, Any]]:
281
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
282
+ src = f.read(_MAX_SQL_BYTES)
283
+ # Split into statements on ';' (string-literal safe enough for DDL scans:
284
+ # quoted ';' inside INSERT values never appears in DDL we keep).
285
+ statements = [s.strip() for s in src.split(";") if s.strip()]
286
+ ddl = [s for s in statements if cls._SQL_DDL_RE.match(s)]
287
+ if not target:
288
+ tables = []
289
+ for s in ddl:
290
+ m = re.search(r"CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[\"'`]?([\w.]+)[\"'`]?", s, re.IGNORECASE)
291
+ if m:
292
+ tables.append(m.group(1))
293
+ lines = [f"# SQL DDL skeleton — {len(ddl)} DDL statements, {len(tables)} tables (DML history omitted)", ""]
294
+ for t in tables[:150]:
295
+ lines.append(f" {t}")
296
+ lines.append("\nSlice a table: symbol='users'.")
297
+ return "\n".join(lines), {"kind": "sql", "mode": "overview", "tables": tables}
298
+ t_lower = target.lower().lstrip('"\'`')
299
+ matched = [s for s in ddl if re.search(r"[\"'`]?[\w.]*" + re.escape(t_lower) + r"[\"`]?", s, re.IGNORECASE)]
300
+ if not matched:
301
+ return f"# target '{target}' not found among {len(ddl)} DDL statements", {"kind": "sql", "mode": "missing"}
302
+ return ";\n\n".join(matched) + ";", {"kind": "sql", "mode": "ddl", "statements": len(matched)}
@@ -228,7 +228,7 @@ class TelemetrySync:
228
228
  current_last_id = last_id
229
229
  headers = {
230
230
  "Content-Type": "application/json",
231
- "User-Agent": "TokenSafe-Sync/2.7.3"
231
+ "User-Agent": "TokenSafe-Sync/2.8.0"
232
232
  }
233
233
  if active_key:
234
234
  headers["Authorization"] = f"Bearer {active_key}"
@@ -35,6 +35,7 @@ _LANGUAGE_SPECS: Dict[str, Tuple[str, str]] = {
35
35
  ".kt": ("tree_sitter_kotlin", "language"),
36
36
  ".kts": ("tree_sitter_kotlin", "language"),
37
37
  ".swift": ("tree_sitter_swift", "language"),
38
+ ".rb": ("tree_sitter_ruby", "language"),
38
39
  }
39
40
 
40
41
  _CONTAINER_NODE_TYPES = {
@@ -56,6 +57,9 @@ _CONTAINER_NODE_TYPES = {
56
57
  "extension_declaration",
57
58
  "namespace_definition",
58
59
  "namespace_declaration",
60
+ # Ruby: keyword-named container nodes
61
+ "class",
62
+ "module",
59
63
  }
60
64
 
61
65
  _FUNC_NODE_TYPES = {
@@ -74,6 +78,9 @@ _FUNC_NODE_TYPES = {
74
78
  "deinit_declaration",
75
79
  "secondary_constructor",
76
80
  "anonymous_function",
81
+ # Ruby: keyword-named function nodes
82
+ "method",
83
+ "singleton_method",
77
84
  }
78
85
 
79
86
  _IMPORT_NODE_TYPES = {
@@ -107,6 +114,7 @@ _SKIP_CALL_NAMES = {
107
114
  "dict", "set", "tuple", "div", "span", "button", "input", "label",
108
115
  "form", "svg", "path", "true", "false", "null", "undefined", "None",
109
116
  "True", "False",
117
+ "require_relative",
110
118
  }
111
119
 
112
120
 
@@ -177,7 +185,7 @@ class TreeSitterBackend:
177
185
  return None
178
186
  if node.type in (
179
187
  "identifier", "type_identifier", "field_identifier",
180
- "property_identifier", "simple_identifier", "name",
188
+ "property_identifier", "simple_identifier", "name", "constant",
181
189
  ):
182
190
  return cls._node_text(node, code_bytes)
183
191
  if node.type == "qualified_identifier":
@@ -194,7 +202,7 @@ class TreeSitterBackend:
194
202
  for child in node.children:
195
203
  if child.type in (
196
204
  "identifier", "type_identifier", "field_identifier",
197
- "property_identifier", "simple_identifier", "name",
205
+ "property_identifier", "simple_identifier", "name", "constant",
198
206
  "function_declarator", "qualified_identifier",
199
207
  ):
200
208
  res = cls._find_identifier_in_declarator(child, code_bytes)
@@ -250,7 +258,7 @@ class TreeSitterBackend:
250
258
  for child in node.children:
251
259
  if child.type in (
252
260
  "identifier", "type_identifier", "field_identifier",
253
- "property_identifier", "simple_identifier", "name",
261
+ "property_identifier", "simple_identifier", "name", "constant",
254
262
  ):
255
263
  return cls._node_text(child, code_bytes)
256
264
  return None
@@ -278,6 +286,12 @@ class TreeSitterBackend:
278
286
  name_n = node.child_by_field_name("name")
279
287
  if name_n is not None:
280
288
  return cls._node_text(name_n, code_bytes)
289
+ if node.type == "call":
290
+ # Ruby `call` nodes: the callee lives in the 'method' field when the
291
+ # grammar exposes it; otherwise the children[0] fallback below applies.
292
+ m_n = node.child_by_field_name("method")
293
+ if m_n is not None:
294
+ return cls._node_text(m_n, code_bytes).strip()
281
295
 
282
296
  fn_node = node.child_by_field_name("function") or node.child_by_field_name("name")
283
297
  if fn_node is None and node.children:
@@ -330,6 +344,10 @@ class TreeSitterBackend:
330
344
  m = re.search(r'[<"]([^>"]+)[>"]', raw)
331
345
  if m:
332
346
  mods.append(m.group(1))
347
+ elif ext == ".rb":
348
+ m = re.match(r"^(?:require|require_relative)\s+['\"]([^'\"]+)['\"]", raw)
349
+ if m:
350
+ mods.append(m.group(1))
333
351
  else:
334
352
  # Rust use, Java/Kotlin import, C# using, PHP use, Swift import
335
353
  cleaned = re.sub(r"^(?:pub\s+)?(?:use|import|using|namespace)\s+", "", raw)
@@ -360,7 +378,13 @@ class TreeSitterBackend:
360
378
  def walk(node: Any, container_stack: List[str], current_fn_key: Optional[str]):
361
379
  ntype = node.type
362
380
 
363
- if ntype in _IMPORT_NODE_TYPES:
381
+ # Ruby `require`/`require_relative` are call nodes: divert them to the
382
+ # import branch so file->file edges can be resolved from them.
383
+ is_ruby_require = (
384
+ ext == ".rb" and ntype == "call"
385
+ and cls._node_text(node, code_bytes).lstrip().startswith(("require", "require_relative"))
386
+ )
387
+ if ntype in _IMPORT_NODE_TYPES or is_ruby_require:
364
388
  mods, syms = cls._extract_imports_from_node(node, code_bytes, ext)
365
389
  imports.extend(mods)
366
390
  imported_symbols.extend(syms)
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "2.7.3"
20
+ CURRENT_VERSION = "2.8.0"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage
@@ -1,141 +0,0 @@
1
- """
2
- DeepSeek-Flash Intent Distiller: Translates complex, conversational developer requests
3
- into ultra-dense Token-Optimized Communication Protocol (TOCP) S-Expressions.
4
- Uses native standard-library urllib with strict timeout and zero dependencies.
5
- """
6
-
7
- import os
8
- import json
9
- import re
10
- import urllib.request
11
- import urllib.error
12
- from typing import Optional, Dict, Any
13
- from src.distiller_cache import DistillationCache
14
- from src.license_manager import LicenseManager
15
- from src.paths import resolve_data_dir
16
-
17
- class DeepSeekDistiller:
18
- """Uses DeepSeek-Flash as a high-density semantic compiler for prompts."""
19
-
20
- DEFAULT_URL = "https://api.deepseek.com/chat/completions"
21
- DEFAULT_MODEL = "deepseek-flash"
22
- DEFAULT_TIMEOUT = 2.5
23
-
24
- SYSTEM_PROMPT = """You are a multilingual semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
25
- (ACTION [filepath] [symbol] [[traits...]] ["minimal_intent"])
26
-
27
- Available ACTIONS: REFACTOR, DEBUG, CREATE, OPTIMIZE, EXPLAIN, AUDIT, TEST, RUN.
28
-
29
- Examples:
30
- Input: "Could you please rewrite the get_balance function in wallet.ts, add redis caching to it and make it async?"
31
- Output: (REFACTOR wallet.ts get_balance [async redis] "add caching and async")
32
-
33
- Input: "In auth.controller.ts during Google login, if user has no avatar the promise hangs for 30s and throws 504"
34
- Output: (DEBUG auth.controller.ts [oauth google timeout_504 missing_avatar] "fix 30s hang on no avatar")
35
-
36
- Input: "Por favor arregla la función validate_token en auth.py para que verifique jwt y devuelva boolean"
37
- Output: (DEBUG auth.py validate_token [jwt] "verify jwt and return boolean")
38
-
39
- Rules:
40
- 1. Output ONLY the S-Expression starting with ( and ending with ).
41
- 2. No markdown code blocks, no preamble, no explanations.
42
- 3. Keep minimal_intent ultra-compact (under 10 words, English preferred for BPE token economy). Total response MUST be under 50 tokens."""
43
-
44
- @classmethod
45
- def _get_config(cls) -> Dict[str, Any]:
46
- """Loads API key and configuration from environment or config.json."""
47
- config = {
48
- "api_key": os.environ.get("DEEPSEEK_API_KEY", "").strip(),
49
- "model": cls.DEFAULT_MODEL,
50
- "timeout": cls.DEFAULT_TIMEOUT,
51
- "enabled": True
52
- }
53
-
54
- config_path = os.path.join(resolve_data_dir(), "config.json")
55
- if os.path.exists(config_path):
56
- try:
57
- with open(config_path, "r", encoding="utf-8") as f:
58
- file_conf = json.load(f)
59
- if isinstance(file_conf, dict):
60
- if not config["api_key"] and file_conf.get("deepseek_api_key"):
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))
74
- except Exception:
75
- pass
76
-
77
- return config
78
-
79
- @classmethod
80
- def distill(cls, raw_text: str) -> Optional[str]:
81
- """
82
- Sends raw text to DeepSeek-V3 to compile into an S-Expression.
83
- Returns distilled S-Expression or None if unavailable/timed out.
84
- Requires active TokenSafe Solo or Team subscription.
85
- """
86
- tier, _ = LicenseManager.get_active_license()
87
- if tier == "free":
88
- return None
89
-
90
- # In standard SaaS mode, delegate to UniversalDistiller's Managed Cloud Distillation
91
- if os.environ.get("TOKENSAFE_SELF_HOSTED", "").lower() not in ("1", "true", "yes"):
92
- from src.distiller import UniversalDistiller
93
- return UniversalDistiller.distill(raw_text)
94
-
95
- conf = cls._get_config()
96
- if not conf["enabled"] or not conf["api_key"] or not raw_text or len(raw_text.strip()) < 10:
97
- return None
98
-
99
- # Check distillation cache before remote roundtrips
100
- cached = DistillationCache.get(raw_text)
101
- if cached:
102
- return cached
103
-
104
- payload = {
105
- "model": conf["model"],
106
- "messages": [
107
- {"role": "system", "content": cls.SYSTEM_PROMPT},
108
- {"role": "user", "content": raw_text.strip()}
109
- ],
110
- "temperature": 0.0,
111
- "max_tokens": conf.get("max_tokens", 60),
112
- "effort": "low"
113
- }
114
-
115
- req = urllib.request.Request(
116
- cls.DEFAULT_URL,
117
- data=json.dumps(payload).encode("utf-8"),
118
- headers={
119
- "Authorization": f"Bearer {conf['api_key']}",
120
- "Content-Type": "application/json",
121
- "User-Agent": "TokenSafe/1.0",
122
- }
123
- )
124
-
125
- try:
126
- with urllib.request.urlopen(req, timeout=conf["timeout"]) as resp:
127
- if resp.status == 200:
128
- data = json.loads(resp.read().decode("utf-8"))
129
- choices = data.get("choices", [])
130
- if choices:
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
137
- except Exception:
138
- # Network issue, timeout, or rate limit: fallback gracefully
139
- return None
140
-
141
- return None