tokensafe 4.4.0 → 4.4.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.
- package/.codex-plugin/plugin.json +1 -1
- package/hooks/pre_invocation.py +3 -17
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/format_parsers/lockfiles.py +210 -48
- package/src/installer.py +4 -2
- package/src/mcp_server.py +13 -3
- package/src/mistakes.py +80 -9
- package/src/schema_slicer.py +43 -13
- package/src/team_cache.py +48 -1
- package/src/telemetry_sync.py +1 -1
- package/src/type_slicer.py +59 -17
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +26 -11
package/hooks/pre_invocation.py
CHANGED
|
@@ -74,6 +74,8 @@ def _handle(payload: dict) -> dict:
|
|
|
74
74
|
|
|
75
75
|
tracker = MetricsTracker()
|
|
76
76
|
inject_steps = []
|
|
77
|
+
workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
|
|
78
|
+
hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
|
|
77
79
|
|
|
78
80
|
# 0. Asynchronous telemetry sync (detached & throttled to 20s)
|
|
79
81
|
try:
|
|
@@ -138,7 +140,7 @@ def _handle(payload: dict) -> dict:
|
|
|
138
140
|
# 2.5 Proactive Anti-Stuck Guard (Inject recent failure lessons from MistakesLedger)
|
|
139
141
|
try:
|
|
140
142
|
from src.mistakes import MistakesLedger
|
|
141
|
-
active_guard = MistakesLedger.get_guard_prompt()
|
|
143
|
+
active_guard = MistakesLedger.get_guard_prompt(project_root=hook_cwd)
|
|
142
144
|
if active_guard:
|
|
143
145
|
inject_steps.append({
|
|
144
146
|
"systemMessage": {
|
|
@@ -283,22 +285,6 @@ def _handle(payload: dict) -> dict:
|
|
|
283
285
|
except Exception:
|
|
284
286
|
pass
|
|
285
287
|
|
|
286
|
-
# 6. Anti-Stuck Dead-Ends Guard Prompt
|
|
287
|
-
try:
|
|
288
|
-
from src.mistakes import MistakesLedger
|
|
289
|
-
workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
|
|
290
|
-
hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
|
|
291
|
-
mistake_guard = MistakesLedger.get_guard_prompt(project_root=hook_cwd)
|
|
292
|
-
if mistake_guard:
|
|
293
|
-
inject_steps.append({
|
|
294
|
-
"systemMessage": {
|
|
295
|
-
"systemMessage": mistake_guard,
|
|
296
|
-
"metadata": {"source": "anti_stuck_guard"}
|
|
297
|
-
}
|
|
298
|
-
})
|
|
299
|
-
except Exception:
|
|
300
|
-
pass
|
|
301
|
-
|
|
302
288
|
return {"injectSteps": inject_steps} if inject_steps else {}
|
|
303
289
|
|
|
304
290
|
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.4.
|
|
3
|
+
"version": "4.4.1",
|
|
4
4
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.4.
|
|
4
|
+
"version": "4.4.1",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.4.
|
|
4
|
+
"version": "4.4.1",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
|
|
6
6
|
"logo": "assets/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.4.
|
|
6
|
+
"version": "4.4.1",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"registryType": "npm",
|
|
24
24
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
25
25
|
"identifier": "tokensafe",
|
|
26
|
-
"version": "4.4.
|
|
26
|
+
"version": "4.4.1",
|
|
27
27
|
"runtimeHint": "npx",
|
|
28
28
|
"transport": {
|
|
29
29
|
"type": "stdio"
|
|
@@ -39,7 +39,7 @@
|
|
|
39
39
|
"registryType": "pypi",
|
|
40
40
|
"registryBaseUrl": "https://pypi.org",
|
|
41
41
|
"identifier": "tokensafe",
|
|
42
|
-
"version": "4.4.
|
|
42
|
+
"version": "4.4.1",
|
|
43
43
|
"runtimeHint": "uvx",
|
|
44
44
|
"transport": {
|
|
45
45
|
"type": "stdio"
|
|
@@ -27,6 +27,8 @@ class LockfileReducer:
|
|
|
27
27
|
name = filename_or_path.lower().split("/")[-1].split("\\")[-1]
|
|
28
28
|
return name in (
|
|
29
29
|
"package-lock.json",
|
|
30
|
+
"bun.lock",
|
|
31
|
+
"bun.lockb",
|
|
30
32
|
"pnpm-lock.yaml",
|
|
31
33
|
"yarn.lock",
|
|
32
34
|
"cargo.lock",
|
|
@@ -36,6 +38,24 @@ class LockfileReducer:
|
|
|
36
38
|
"go.sum",
|
|
37
39
|
)
|
|
38
40
|
|
|
41
|
+
@classmethod
|
|
42
|
+
def _load_jsonc(cls, text: str) -> Optional[Dict[str, Any]]:
|
|
43
|
+
"""Safely parses JSON or JSONC (JSON with comments and trailing commas)."""
|
|
44
|
+
if not text:
|
|
45
|
+
return None
|
|
46
|
+
try:
|
|
47
|
+
return json.loads(text)
|
|
48
|
+
except Exception:
|
|
49
|
+
pass
|
|
50
|
+
try:
|
|
51
|
+
# Strip whole-line comments // ... without corrupting base64 hashes inside strings
|
|
52
|
+
no_comments = re.sub(r'^\s*//.*$', '', text, flags=re.MULTILINE)
|
|
53
|
+
# Strip trailing commas before } or ]
|
|
54
|
+
cleaned = re.sub(r',(\s*[}\]])', r'\1', no_comments)
|
|
55
|
+
return json.loads(cleaned)
|
|
56
|
+
except Exception:
|
|
57
|
+
return None
|
|
58
|
+
|
|
39
59
|
@classmethod
|
|
40
60
|
def reduce(cls, content: str, filename: str = "package-lock.json") -> Tuple[str, bool]:
|
|
41
61
|
"""Reduces lockfile content to a clean summary. Returns (compacted_text, was_compacted)."""
|
|
@@ -47,6 +67,8 @@ class LockfileReducer:
|
|
|
47
67
|
|
|
48
68
|
if fname == "package-lock.json":
|
|
49
69
|
return cls._reduce_npm_lock(content)
|
|
70
|
+
elif fname in ("bun.lock", "bun.lockb"):
|
|
71
|
+
return cls._reduce_bun_lock(content, fname)
|
|
50
72
|
elif fname == "cargo.lock":
|
|
51
73
|
return cls._reduce_cargo_lock(content)
|
|
52
74
|
elif fname == "poetry.lock":
|
|
@@ -54,6 +76,44 @@ class LockfileReducer:
|
|
|
54
76
|
|
|
55
77
|
return cls._generic_reduce(content, fname)
|
|
56
78
|
|
|
79
|
+
@classmethod
|
|
80
|
+
def _reduce_bun_lock(cls, content: str, fname: str = "bun.lock") -> Tuple[str, bool]:
|
|
81
|
+
data = cls._load_jsonc(content)
|
|
82
|
+
if not data or not isinstance(data, dict):
|
|
83
|
+
return cls._generic_reduce(content, fname)
|
|
84
|
+
|
|
85
|
+
packages = data.get("packages", {})
|
|
86
|
+
workspaces = data.get("workspaces", {})
|
|
87
|
+
root_ws = workspaces.get("") if isinstance(workspaces, dict) else {}
|
|
88
|
+
root_deps = {}
|
|
89
|
+
if isinstance(root_ws, dict):
|
|
90
|
+
root_deps = {**root_ws.get("dependencies", {}), **root_ws.get("devDependencies", {})}
|
|
91
|
+
|
|
92
|
+
direct_deps = {}
|
|
93
|
+
total_count = len(packages) if isinstance(packages, dict) else 0
|
|
94
|
+
|
|
95
|
+
for dep_name, range_ver in sorted(root_deps.items()):
|
|
96
|
+
resolved_ver = range_ver
|
|
97
|
+
if isinstance(packages, dict) and dep_name in packages:
|
|
98
|
+
val = packages[dep_name]
|
|
99
|
+
if isinstance(val, list) and len(val) > 0 and isinstance(val[0], str):
|
|
100
|
+
resolved_ver = val[0].rsplit("@", 1)[1] if "@" in val[0] else val[0]
|
|
101
|
+
direct_deps[dep_name] = resolved_ver
|
|
102
|
+
|
|
103
|
+
lines = [
|
|
104
|
+
f"# [TokenSafe Lockfile Summary: {fname}]",
|
|
105
|
+
f"Total installed packages: {total_count}",
|
|
106
|
+
"",
|
|
107
|
+
"## Direct Dependencies:"
|
|
108
|
+
]
|
|
109
|
+
for dname, dver in sorted(direct_deps.items()):
|
|
110
|
+
lines.append(f" - {dname}: {dver}")
|
|
111
|
+
|
|
112
|
+
hash8, marker = stash_block(content, source="lockfile:bun")
|
|
113
|
+
lines.append("")
|
|
114
|
+
lines.append(marker)
|
|
115
|
+
return "\n".join(lines), True
|
|
116
|
+
|
|
57
117
|
@classmethod
|
|
58
118
|
def _reduce_npm_lock(cls, content: str) -> Tuple[str, bool]:
|
|
59
119
|
try:
|
|
@@ -163,7 +223,7 @@ class LockfileReducer:
|
|
|
163
223
|
|
|
164
224
|
@classmethod
|
|
165
225
|
def find_lockfile(cls, directory: Optional[str] = None, start_dir: Optional[str] = None) -> Optional[str]:
|
|
166
|
-
"""Locates the nearest lockfile in directory or parent directories up to git root."""
|
|
226
|
+
"""Locates the nearest lockfile in directory or parent directories up to git root, or downward in monorepos."""
|
|
167
227
|
target = directory or start_dir or os.getcwd()
|
|
168
228
|
start = os.path.abspath(target)
|
|
169
229
|
curr = start
|
|
@@ -171,6 +231,7 @@ class LockfileReducer:
|
|
|
171
231
|
"package-lock.json", "bun.lock", "bun.lockb",
|
|
172
232
|
"pnpm-lock.yaml", "yarn.lock", "Cargo.lock", "poetry.lock"
|
|
173
233
|
)
|
|
234
|
+
# 1. Upward search
|
|
174
235
|
for _ in range(6):
|
|
175
236
|
for c in candidates:
|
|
176
237
|
cand_path = os.path.join(curr, c)
|
|
@@ -180,6 +241,26 @@ class LockfileReducer:
|
|
|
180
241
|
if parent == curr:
|
|
181
242
|
break
|
|
182
243
|
curr = parent
|
|
244
|
+
|
|
245
|
+
# 2. Downward search (bounded: depth <= 2, skip heavy/vendor dirs, cap 60 directories)
|
|
246
|
+
dirs_checked = 0
|
|
247
|
+
skip_dirs = {"node_modules", ".git", "dist", "build", ".next", ".cache", "data", "target", ".venv", "venv", "__pycache__"}
|
|
248
|
+
for root, dirs, files in os.walk(start):
|
|
249
|
+
dirs[:] = [d for d in dirs if d not in skip_dirs and not d.startswith(".")]
|
|
250
|
+
dirs_checked += 1
|
|
251
|
+
if dirs_checked > 60:
|
|
252
|
+
break
|
|
253
|
+
rel_path = os.path.relpath(root, start)
|
|
254
|
+
rel_depth = 0 if rel_path == "." else rel_path.count(os.sep) + 1
|
|
255
|
+
if rel_depth > 2:
|
|
256
|
+
dirs[:] = []
|
|
257
|
+
continue
|
|
258
|
+
for c in candidates:
|
|
259
|
+
if c in files:
|
|
260
|
+
cand_path = os.path.join(root, c)
|
|
261
|
+
if os.path.isfile(cand_path):
|
|
262
|
+
return cand_path
|
|
263
|
+
|
|
183
264
|
return None
|
|
184
265
|
|
|
185
266
|
@classmethod
|
|
@@ -188,6 +269,22 @@ class LockfileReducer:
|
|
|
188
269
|
os.makedirs(data_dir, exist_ok=True)
|
|
189
270
|
return os.path.join(data_dir, "lockfile_cache.db")
|
|
190
271
|
|
|
272
|
+
@classmethod
|
|
273
|
+
def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 5000) -> None:
|
|
274
|
+
"""Evicts oldest entries when lockfile cache exceeds max_rows."""
|
|
275
|
+
try:
|
|
276
|
+
row = conn.execute("SELECT COUNT(*) FROM lockfile_cache;").fetchone()
|
|
277
|
+
count = row[0] if row else 0
|
|
278
|
+
if count > max_rows:
|
|
279
|
+
excess = count - max_rows
|
|
280
|
+
conn.execute(
|
|
281
|
+
"DELETE FROM lockfile_cache WHERE entry_key IN ("
|
|
282
|
+
"SELECT entry_key FROM lockfile_cache ORDER BY cached_at ASC LIMIT ?"
|
|
283
|
+
");", (excess,)
|
|
284
|
+
)
|
|
285
|
+
except Exception:
|
|
286
|
+
pass
|
|
287
|
+
|
|
191
288
|
@classmethod
|
|
192
289
|
def _init_db(cls):
|
|
193
290
|
db_path = cls._get_db_path()
|
|
@@ -231,6 +328,7 @@ class LockfileReducer:
|
|
|
231
328
|
try:
|
|
232
329
|
with open(target_path, "r", encoding="utf-8", errors="replace") as f:
|
|
233
330
|
content = f.read()
|
|
331
|
+
_lockfile_bytes = os.path.getsize(target_path)
|
|
234
332
|
except Exception as e:
|
|
235
333
|
return {"found": False, "package": package_name, "error": f"Failed to read {fname}: {e}"}
|
|
236
334
|
|
|
@@ -247,8 +345,10 @@ class LockfileReducer:
|
|
|
247
345
|
row = conn.execute("SELECT json_result FROM lockfile_cache WHERE entry_key = ?", (entry_key,)).fetchone()
|
|
248
346
|
if row:
|
|
249
347
|
res = json.loads(row[0])
|
|
250
|
-
res
|
|
251
|
-
|
|
348
|
+
if res.get("found"):
|
|
349
|
+
res["source"] = "L2_cache"
|
|
350
|
+
res["_lockfile_bytes"] = _lockfile_bytes
|
|
351
|
+
return res
|
|
252
352
|
except Exception:
|
|
253
353
|
pass
|
|
254
354
|
finally:
|
|
@@ -264,25 +364,28 @@ class LockfileReducer:
|
|
|
264
364
|
team_val = TeamCache.get("LOCKFILE_INDEX", entry_key, timeout=0.5)
|
|
265
365
|
if team_val:
|
|
266
366
|
res = json.loads(team_val)
|
|
267
|
-
res
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
back_conn =
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
367
|
+
if res.get("found"):
|
|
368
|
+
res["source"] = "L3_team_cache"
|
|
369
|
+
res["_lockfile_bytes"] = _lockfile_bytes
|
|
370
|
+
# Store back to L2
|
|
371
|
+
back_conn = None
|
|
372
|
+
try:
|
|
373
|
+
back_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
374
|
+
back_conn.execute("""
|
|
375
|
+
INSERT OR REPLACE INTO lockfile_cache (entry_key, lockfile_hash, package_name, json_result, cached_at)
|
|
376
|
+
VALUES (?, ?, ?, ?, ?)
|
|
377
|
+
""", (entry_key, lockfile_hash, package_name.strip().lower(), team_val, int(time.time())))
|
|
378
|
+
cls._maybe_evict(back_conn)
|
|
379
|
+
back_conn.commit()
|
|
380
|
+
except Exception:
|
|
381
|
+
pass
|
|
382
|
+
finally:
|
|
383
|
+
if back_conn:
|
|
384
|
+
try:
|
|
385
|
+
back_conn.close()
|
|
386
|
+
except Exception:
|
|
387
|
+
pass
|
|
388
|
+
return res
|
|
286
389
|
except Exception:
|
|
287
390
|
pass
|
|
288
391
|
|
|
@@ -290,40 +393,99 @@ class LockfileReducer:
|
|
|
290
393
|
res = cls._parse_dependency(fname, content, package_name)
|
|
291
394
|
res["lockfile"] = fname
|
|
292
395
|
res["lockfile_path"] = target_path
|
|
396
|
+
res["_lockfile_bytes"] = _lockfile_bytes
|
|
293
397
|
|
|
294
|
-
# 4. Save to L2 SQLite and sync to L3 Team Cache
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
398
|
+
# 4. Save to L2 SQLite and sync to L3 Team Cache (only positive found lookups)
|
|
399
|
+
if res.get("found"):
|
|
400
|
+
save_conn = None
|
|
401
|
+
try:
|
|
402
|
+
raw_json = json.dumps(res, ensure_ascii=False)
|
|
403
|
+
save_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
404
|
+
save_conn.execute("""
|
|
405
|
+
INSERT OR REPLACE INTO lockfile_cache (entry_key, lockfile_hash, package_name, json_result, cached_at)
|
|
406
|
+
VALUES (?, ?, ?, ?, ?)
|
|
407
|
+
""", (entry_key, lockfile_hash, package_name.strip().lower(), raw_json, int(time.time())))
|
|
408
|
+
cls._maybe_evict(save_conn)
|
|
409
|
+
save_conn.commit()
|
|
410
|
+
except Exception:
|
|
411
|
+
pass
|
|
412
|
+
finally:
|
|
413
|
+
if save_conn:
|
|
414
|
+
try:
|
|
415
|
+
save_conn.close()
|
|
416
|
+
except Exception:
|
|
417
|
+
pass
|
|
418
|
+
|
|
419
|
+
# Broadcast to L3 without leaking local filesystem paths or private byte counts
|
|
420
|
+
try:
|
|
421
|
+
from src.team_cache import TeamCache
|
|
422
|
+
team_payload = dict(res)
|
|
423
|
+
team_payload.pop("lockfile_path", None)
|
|
424
|
+
team_payload.pop("_lockfile_bytes", None)
|
|
425
|
+
TeamCache.put("LOCKFILE_INDEX", entry_key, json.dumps(team_payload, ensure_ascii=False), tokens_saved=250)
|
|
426
|
+
except Exception:
|
|
427
|
+
pass
|
|
318
428
|
|
|
319
429
|
res["source"] = "parsed_live"
|
|
320
430
|
return res
|
|
321
431
|
|
|
322
432
|
@classmethod
|
|
323
433
|
def _parse_dependency(cls, fname: str, content: str, pkg_name: str) -> Dict[str, Any]:
|
|
324
|
-
"""Parses dependency entry from npm, cargo, poetry, or
|
|
434
|
+
"""Parses dependency entry from npm, cargo, poetry, pnpm, or bun."""
|
|
325
435
|
norm_pkg = pkg_name.strip()
|
|
326
|
-
if "
|
|
436
|
+
if "bun.lock" in fname:
|
|
437
|
+
try:
|
|
438
|
+
data = cls._load_jsonc(content)
|
|
439
|
+
if isinstance(data, dict):
|
|
440
|
+
packages = data.get("packages")
|
|
441
|
+
if isinstance(packages, dict):
|
|
442
|
+
# 1. Direct package key (e.g. "marked", "@tanstack/react-query")
|
|
443
|
+
val = packages.get(norm_pkg)
|
|
444
|
+
# 2. Nested or prefixed node_modules/<pkg>
|
|
445
|
+
if not val:
|
|
446
|
+
exact_nm = f"node_modules/{norm_pkg}"
|
|
447
|
+
val = packages.get(exact_nm)
|
|
448
|
+
if not val:
|
|
449
|
+
suffix = f"/node_modules/{norm_pkg}"
|
|
450
|
+
for k, v in packages.items():
|
|
451
|
+
if k.endswith(suffix):
|
|
452
|
+
val = v
|
|
453
|
+
break
|
|
454
|
+
if val and isinstance(val, list) and len(val) > 0:
|
|
455
|
+
spec = val[0] if isinstance(val[0], str) else ""
|
|
456
|
+
ver = spec.rsplit("@", 1)[1] if "@" in spec else spec
|
|
457
|
+
meta = val[2] if len(val) > 2 and isinstance(val[2], dict) else {}
|
|
458
|
+
integrity = val[3] if len(val) > 3 and isinstance(val[3], str) else None
|
|
459
|
+
return {
|
|
460
|
+
"found": True,
|
|
461
|
+
"package": norm_pkg,
|
|
462
|
+
"version": ver,
|
|
463
|
+
"resolved": integrity,
|
|
464
|
+
"dependencies": meta.get("dependencies", {}),
|
|
465
|
+
"peerDependencies": meta.get("peerDependencies", {}),
|
|
466
|
+
"dev": False,
|
|
467
|
+
}
|
|
468
|
+
# 3. Fallback to workspaces[""] direct dependencies
|
|
469
|
+
workspaces = data.get("workspaces", {})
|
|
470
|
+
root_ws = workspaces.get("") if isinstance(workspaces, dict) else {}
|
|
471
|
+
if isinstance(root_ws, dict):
|
|
472
|
+
dev_deps = root_ws.get("devDependencies", {}) or {}
|
|
473
|
+
prod_deps = root_ws.get("dependencies", {}) or {}
|
|
474
|
+
all_root = {**prod_deps, **dev_deps}
|
|
475
|
+
if norm_pkg in all_root:
|
|
476
|
+
return {
|
|
477
|
+
"found": True,
|
|
478
|
+
"package": norm_pkg,
|
|
479
|
+
"version": all_root[norm_pkg],
|
|
480
|
+
"resolved": None,
|
|
481
|
+
"dependencies": {},
|
|
482
|
+
"peerDependencies": {},
|
|
483
|
+
"dev": norm_pkg in dev_deps,
|
|
484
|
+
}
|
|
485
|
+
except Exception:
|
|
486
|
+
pass
|
|
487
|
+
|
|
488
|
+
elif "package-lock" in fname:
|
|
327
489
|
try:
|
|
328
490
|
data = json.loads(content)
|
|
329
491
|
packages = data.get("packages")
|
package/src/installer.py
CHANGED
|
@@ -63,6 +63,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
63
63
|
"12. **Proof-of-Savings Turn Footer (strictly English)**:\n"
|
|
64
64
|
"At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer. The ENTIRE footer is product-facing copy — 100% English, including the savings breakdown in parentheses, regardless of the chat language:\n"
|
|
65
65
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown in English>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
|
66
|
+
"13. **External Types & Lockfile Point Queries**: Use `tokensafe:slice_external_type(package_name, type_name)` to extract 3rd-party TypeScript interfaces from `node_modules` without crawling directories (-95% tokens, L1/L2/L3 cached). Use `tokensafe:query_dependency(lockfile_path, package_name)` for instant lockfile point lookups in <50 tokens; raw `read_file` on lockfiles without bounds is redirected to an index summary.\n"
|
|
66
67
|
)
|
|
67
68
|
|
|
68
69
|
# Short pointer written into PROJECT-level rule files when the full protocol is
|
|
@@ -70,10 +71,11 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
70
71
|
# Keeps every session's meta-context lean: ~110 tokens instead of ~850.
|
|
71
72
|
POINTER_RULE = (
|
|
72
73
|
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
73
|
-
"The full
|
|
74
|
+
"The full 13-point protocol is installed globally in the agent-level instructions "
|
|
74
75
|
"(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
|
|
75
76
|
"Core rules: never raw grep/find or `ls -la` — use `tokensafe:get_architecture_graph(project_path)` first for God Nodes, "
|
|
76
|
-
"`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:
|
|
77
|
+
"`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:slice_external_type`, `tokensafe:query_dependency`, "
|
|
78
|
+
"`tokensafe:smart_bundle` and `tokensafe:list_dir`; "
|
|
77
79
|
"sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
|
|
78
80
|
"before large tasks and compact via `tokensafe:compact_conversation` (orientation digest active); never hardcode secret "
|
|
79
81
|
"fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
|
package/src/mcp_server.py
CHANGED
|
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
|
42
42
|
|
|
43
43
|
SERVER_INFO = {
|
|
44
44
|
"name": "tokensafe-mcp",
|
|
45
|
-
"version": "4.4.
|
|
45
|
+
"version": "4.4.1"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -1869,9 +1869,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1869
1869
|
try:
|
|
1870
1870
|
from src.format_parsers.lockfiles import LockfileReducer
|
|
1871
1871
|
res = LockfileReducer.query_dependency(lock_p, pkg)
|
|
1872
|
+
lock_bytes = res.pop("_lockfile_bytes", 0)
|
|
1872
1873
|
json_text = json.dumps(res, indent=2, ensure_ascii=False)
|
|
1873
1874
|
opt_tokens = count_tokens(json_text)
|
|
1874
|
-
|
|
1875
|
+
if res.get("found"):
|
|
1876
|
+
orig_tokens = max(1000, lock_bytes // 4) if lock_bytes else max(opt_tokens, 1000)
|
|
1877
|
+
else:
|
|
1878
|
+
orig_tokens = opt_tokens
|
|
1875
1879
|
tracker.record_event(
|
|
1876
1880
|
session_id=_mcp_session_id(),
|
|
1877
1881
|
event_type="LOCKFILE_QUERY",
|
|
@@ -1892,9 +1896,13 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1892
1896
|
try:
|
|
1893
1897
|
from src.type_slicer import TypeSlicer
|
|
1894
1898
|
res = TypeSlicer.slice_package_type(pkg, sym, project_root=proj_root)
|
|
1899
|
+
dts_bytes = res.pop("_dts_bytes", 0)
|
|
1895
1900
|
json_text = json.dumps(res, indent=2, ensure_ascii=False)
|
|
1896
1901
|
opt_tokens = count_tokens(json_text)
|
|
1897
|
-
|
|
1902
|
+
if res.get("found"):
|
|
1903
|
+
orig_tokens = max(opt_tokens, dts_bytes // 4) if dts_bytes else max(opt_tokens, 500)
|
|
1904
|
+
else:
|
|
1905
|
+
orig_tokens = opt_tokens
|
|
1898
1906
|
tracker.record_event(
|
|
1899
1907
|
session_id=_mcp_session_id(),
|
|
1900
1908
|
event_type="TYPE_SLICE",
|
|
@@ -1958,10 +1966,12 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1958
1966
|
try:
|
|
1959
1967
|
from src.mistakes import MistakesLedger
|
|
1960
1968
|
entries = MistakesLedger.list_mistakes(project_root=proj_root)
|
|
1969
|
+
team_entries = MistakesLedger.get_team_mistakes()
|
|
1961
1970
|
guard = MistakesLedger.get_guard_prompt(project_root=proj_root)
|
|
1962
1971
|
return {"content": [{"type": "text", "text": json.dumps({
|
|
1963
1972
|
"count": len(entries),
|
|
1964
1973
|
"entries": entries,
|
|
1974
|
+
"team_entries": team_entries,
|
|
1965
1975
|
"active_guard": guard
|
|
1966
1976
|
}, indent=2, ensure_ascii=False)}]}
|
|
1967
1977
|
except Exception as e:
|
package/src/mistakes.py
CHANGED
|
@@ -14,6 +14,7 @@ import os
|
|
|
14
14
|
import json
|
|
15
15
|
import time
|
|
16
16
|
import hashlib
|
|
17
|
+
import threading
|
|
17
18
|
import subprocess
|
|
18
19
|
from typing import Dict, Any, List, Optional, Tuple
|
|
19
20
|
from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
|
|
@@ -190,6 +191,43 @@ class MistakesLedger:
|
|
|
190
191
|
pass
|
|
191
192
|
return 0
|
|
192
193
|
|
|
194
|
+
_team_mistakes_cache: List[Dict[str, Any]] = []
|
|
195
|
+
_team_mistakes_fetched_at: float = 0.0
|
|
196
|
+
_team_mistakes_lock = threading.Lock()
|
|
197
|
+
|
|
198
|
+
@classmethod
|
|
199
|
+
def get_team_mistakes(cls, timeout: float = 0.6) -> List[Dict[str, Any]]:
|
|
200
|
+
"""Retrieves scrubbed dead-end summaries shared across team members with 300s TTL cache."""
|
|
201
|
+
now = time.time()
|
|
202
|
+
with cls._team_mistakes_lock:
|
|
203
|
+
if cls._team_mistakes_cache and (now - cls._team_mistakes_fetched_at < 300.0):
|
|
204
|
+
return list(cls._team_mistakes_cache)
|
|
205
|
+
|
|
206
|
+
try:
|
|
207
|
+
from src.team_cache import TeamCache
|
|
208
|
+
raw_entries = TeamCache.list_entries("TEAM_MISTAKE", limit=10, timeout=timeout)
|
|
209
|
+
parsed: List[Dict[str, Any]] = []
|
|
210
|
+
for item in raw_entries:
|
|
211
|
+
val = item.get("value") or item.get("cached_value")
|
|
212
|
+
if isinstance(val, str):
|
|
213
|
+
try:
|
|
214
|
+
p_val = json.loads(val)
|
|
215
|
+
if isinstance(p_val, dict):
|
|
216
|
+
parsed.append(p_val)
|
|
217
|
+
else:
|
|
218
|
+
parsed.append({"summary": str(val)[:120]})
|
|
219
|
+
except Exception:
|
|
220
|
+
parsed.append({"summary": str(val)[:120]})
|
|
221
|
+
elif isinstance(val, dict):
|
|
222
|
+
parsed.append(val)
|
|
223
|
+
|
|
224
|
+
with cls._team_mistakes_lock:
|
|
225
|
+
cls._team_mistakes_cache = parsed
|
|
226
|
+
cls._team_mistakes_fetched_at = now
|
|
227
|
+
return list(parsed)
|
|
228
|
+
except Exception:
|
|
229
|
+
return []
|
|
230
|
+
|
|
193
231
|
@classmethod
|
|
194
232
|
def should_force_ask(
|
|
195
233
|
cls,
|
|
@@ -217,7 +255,19 @@ class MistakesLedger:
|
|
|
217
255
|
f = (m.get("file") or "").lower()
|
|
218
256
|
s = (m.get("summary") or "").lower()
|
|
219
257
|
det = (m.get("details") or "").lower()
|
|
220
|
-
|
|
258
|
+
|
|
259
|
+
matched = False
|
|
260
|
+
if len(norm_target) >= 12:
|
|
261
|
+
# Substring matching for longer specific commands or file paths
|
|
262
|
+
if (f and f in norm_target) or (norm_target in s) or (norm_target in det):
|
|
263
|
+
matched = True
|
|
264
|
+
else:
|
|
265
|
+
# Short targets (e.g. "npm", "ls"): exact equality against file, summary, or extracted command prefix
|
|
266
|
+
cmd_part = s.split(":", 1)[0].strip() if ":" in s else s.split()[0] if s.split() else ""
|
|
267
|
+
if (f and norm_target == f) or (norm_target == s) or (norm_target == cmd_part):
|
|
268
|
+
matched = True
|
|
269
|
+
|
|
270
|
+
if matched:
|
|
221
271
|
matching.append(m)
|
|
222
272
|
|
|
223
273
|
count = len(matching)
|
|
@@ -236,19 +286,40 @@ class MistakesLedger:
|
|
|
236
286
|
max_items: int = 3
|
|
237
287
|
) -> Optional[str]:
|
|
238
288
|
"""
|
|
239
|
-
Generates a compact (<
|
|
289
|
+
Generates a compact (<100 tokens) prompt guard from recent active local and team mistakes.
|
|
240
290
|
Injectable into system instructions or PreInvocation hooks.
|
|
241
291
|
"""
|
|
242
|
-
|
|
243
|
-
|
|
292
|
+
local_mistakes = cls.list_mistakes(project_root=project_root, active_only=True)
|
|
293
|
+
team_mistakes = cls.get_team_mistakes()
|
|
294
|
+
if not local_mistakes and not team_mistakes:
|
|
244
295
|
return None
|
|
245
296
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
297
|
+
lines = ["[TokenSafe Anti-Stuck Guard: Prior Dead-Ends to Avoid]:"]
|
|
298
|
+
local_summaries = set()
|
|
299
|
+
|
|
300
|
+
# Take up to max_items most recent active local entries
|
|
301
|
+
for m in reversed(local_mistakes[-max_items:]):
|
|
302
|
+
s = m.get("summary", "")
|
|
303
|
+
local_summaries.add(s.strip().lower())
|
|
250
304
|
f = m.get("file")
|
|
251
305
|
f_prefix = f"{f}: " if f else ""
|
|
252
|
-
lines.append(f"• {f_prefix}{
|
|
306
|
+
lines.append(f"• {f_prefix}{s}")
|
|
307
|
+
|
|
308
|
+
# Merge up to 2 unique team mistakes
|
|
309
|
+
team_added = 0
|
|
310
|
+
for tm in team_mistakes:
|
|
311
|
+
if team_added >= 2:
|
|
312
|
+
break
|
|
313
|
+
ts = (tm.get("summary") or "").strip()
|
|
314
|
+
if not ts or ts.lower() in local_summaries:
|
|
315
|
+
continue
|
|
316
|
+
tf = tm.get("file")
|
|
317
|
+
tf_prefix = f"{tf}: " if tf else ""
|
|
318
|
+
lines.append(f"• team: {tf_prefix}{ts}")
|
|
319
|
+
local_summaries.add(ts.lower())
|
|
320
|
+
team_added += 1
|
|
321
|
+
|
|
322
|
+
if len(lines) == 1:
|
|
323
|
+
return None
|
|
253
324
|
|
|
254
325
|
return "\n".join(lines)
|
package/src/schema_slicer.py
CHANGED
|
@@ -45,6 +45,31 @@ class SchemaSlicer:
|
|
|
45
45
|
with cls._mem_lock:
|
|
46
46
|
cls._mem_cache.clear()
|
|
47
47
|
|
|
48
|
+
@classmethod
|
|
49
|
+
def _mem_put(cls, key: str, val: Tuple[str, Dict[str, Any]], max_items: int = 80) -> None:
|
|
50
|
+
"""Stores entry in LRU memory cache with fixed cap."""
|
|
51
|
+
with cls._mem_lock:
|
|
52
|
+
cls._mem_cache[key] = val
|
|
53
|
+
cls._mem_cache.move_to_end(key)
|
|
54
|
+
if len(cls._mem_cache) > max_items:
|
|
55
|
+
cls._mem_cache.popitem(last=False)
|
|
56
|
+
|
|
57
|
+
@classmethod
|
|
58
|
+
def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 2000) -> None:
|
|
59
|
+
"""Evicts oldest entries when schema cache exceeds max_rows."""
|
|
60
|
+
try:
|
|
61
|
+
row = conn.execute("SELECT COUNT(*) FROM schema_cache;").fetchone()
|
|
62
|
+
count = row[0] if row else 0
|
|
63
|
+
if count > max_rows:
|
|
64
|
+
excess = count - max_rows
|
|
65
|
+
conn.execute(
|
|
66
|
+
"DELETE FROM schema_cache WHERE cache_key IN ("
|
|
67
|
+
"SELECT cache_key FROM schema_cache ORDER BY cached_at ASC LIMIT ?"
|
|
68
|
+
");", (excess,)
|
|
69
|
+
)
|
|
70
|
+
except Exception:
|
|
71
|
+
pass
|
|
72
|
+
|
|
48
73
|
@classmethod
|
|
49
74
|
def _get_db_path(cls) -> str:
|
|
50
75
|
data_dir = resolve_data_dir()
|
|
@@ -89,8 +114,8 @@ class SchemaSlicer:
|
|
|
89
114
|
"""
|
|
90
115
|
Computes deterministic composite fingerprint:
|
|
91
116
|
- For single file: SHA-256(content)[:16]
|
|
92
|
-
- For multi-file Prisma (prisma/schema/*.prisma): hashes all .prisma files
|
|
93
|
-
- For OpenAPI with local $ref: hashes root + referenced local files
|
|
117
|
+
- For multi-file Prisma (prisma/schema/*.prisma): content hashes of all .prisma files
|
|
118
|
+
- For OpenAPI with local $ref: content hashes of root + referenced local files
|
|
94
119
|
"""
|
|
95
120
|
abs_p = os.path.abspath(path)
|
|
96
121
|
base_dir = os.path.dirname(abs_p)
|
|
@@ -104,8 +129,10 @@ class SchemaSlicer:
|
|
|
104
129
|
if len(prisma_files) > 1:
|
|
105
130
|
hasher = hashlib.sha256()
|
|
106
131
|
for pf in prisma_files:
|
|
107
|
-
|
|
108
|
-
|
|
132
|
+
with open(pf, "rb") as pff:
|
|
133
|
+
pf_bytes = pff.read()
|
|
134
|
+
pf_hash = hashlib.sha256(pf_bytes).hexdigest()
|
|
135
|
+
hasher.update(f"{os.path.basename(pf)}:{pf_hash}".encode("utf-8"))
|
|
109
136
|
return hasher.hexdigest()[:16]
|
|
110
137
|
except Exception:
|
|
111
138
|
pass
|
|
@@ -123,7 +150,13 @@ class SchemaSlicer:
|
|
|
123
150
|
ref_rel = rm.decode("utf-8", errors="ignore")
|
|
124
151
|
cand = os.path.normpath(os.path.join(base_dir, ref_rel))
|
|
125
152
|
if os.path.isfile(cand):
|
|
126
|
-
|
|
153
|
+
try:
|
|
154
|
+
with open(cand, "rb") as cf:
|
|
155
|
+
cand_bytes = cf.read()
|
|
156
|
+
cand_hash = hashlib.sha256(cand_bytes).hexdigest()
|
|
157
|
+
hasher.update(f"{ref_rel}:{cand_hash}".encode("utf-8"))
|
|
158
|
+
except Exception:
|
|
159
|
+
pass
|
|
127
160
|
return hasher.hexdigest()[:16]
|
|
128
161
|
return h
|
|
129
162
|
except Exception:
|
|
@@ -191,8 +224,7 @@ class SchemaSlicer:
|
|
|
191
224
|
text_cached, info_raw = row[0], row[1]
|
|
192
225
|
info_dict = json.loads(info_raw)
|
|
193
226
|
info_dict["source"] = "L2_sqlite"
|
|
194
|
-
|
|
195
|
-
cls._mem_cache[cache_key] = (text_cached, info_dict)
|
|
227
|
+
cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
|
|
196
228
|
return text_cached, info_dict
|
|
197
229
|
except Exception:
|
|
198
230
|
pass
|
|
@@ -212,8 +244,7 @@ class SchemaSlicer:
|
|
|
212
244
|
text_cached = parsed_team.get("sliced", "")
|
|
213
245
|
info_dict = parsed_team.get("info", {})
|
|
214
246
|
info_dict["source"] = "L3_team_cache"
|
|
215
|
-
|
|
216
|
-
cls._mem_cache[cache_key] = (text_cached, info_dict)
|
|
247
|
+
cls._mem_put(cache_key, (text_cached, info_dict), max_items=80)
|
|
217
248
|
# Store back to L2
|
|
218
249
|
back_conn = None
|
|
219
250
|
try:
|
|
@@ -222,6 +253,7 @@ class SchemaSlicer:
|
|
|
222
253
|
INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
|
|
223
254
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
224
255
|
""", (cache_key, kind, fp, norm_target, text_cached, json.dumps(info_dict), int(time.time())))
|
|
256
|
+
cls._maybe_evict(back_conn)
|
|
225
257
|
back_conn.commit()
|
|
226
258
|
except Exception:
|
|
227
259
|
pass
|
|
@@ -260,10 +292,7 @@ class SchemaSlicer:
|
|
|
260
292
|
|
|
261
293
|
# 6. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
|
|
262
294
|
info["source"] = "parsed_live"
|
|
263
|
-
|
|
264
|
-
cls._mem_cache[cache_key] = (sliced, info)
|
|
265
|
-
if len(cls._mem_cache) > 80:
|
|
266
|
-
cls._mem_cache.popitem(last=False)
|
|
295
|
+
cls._mem_put(cache_key, (sliced, info), max_items=80)
|
|
267
296
|
|
|
268
297
|
save_conn = None
|
|
269
298
|
try:
|
|
@@ -272,6 +301,7 @@ class SchemaSlicer:
|
|
|
272
301
|
INSERT OR REPLACE INTO schema_cache (cache_key, schema_kind, fingerprint, target, sliced_text, info_json, cached_at)
|
|
273
302
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
274
303
|
""", (cache_key, kind, fp, norm_target, sliced, json.dumps(info), int(time.time())))
|
|
304
|
+
cls._maybe_evict(save_conn)
|
|
275
305
|
save_conn.commit()
|
|
276
306
|
except Exception:
|
|
277
307
|
pass
|
package/src/team_cache.py
CHANGED
|
@@ -12,7 +12,7 @@ import threading
|
|
|
12
12
|
import urllib.request
|
|
13
13
|
import urllib.error
|
|
14
14
|
import urllib.parse
|
|
15
|
-
from typing import Optional, Dict, Any, Tuple
|
|
15
|
+
from typing import Optional, Dict, Any, Tuple, List
|
|
16
16
|
from src.license_manager import LicenseManager
|
|
17
17
|
from src.ssl_context import shared_ssl_context
|
|
18
18
|
|
|
@@ -208,6 +208,53 @@ class TeamCache:
|
|
|
208
208
|
t = threading.Thread(target=_worker, daemon=True)
|
|
209
209
|
t.start()
|
|
210
210
|
|
|
211
|
+
@classmethod
|
|
212
|
+
def list_entries(
|
|
213
|
+
cls,
|
|
214
|
+
cache_type: str,
|
|
215
|
+
limit: int = 10,
|
|
216
|
+
timeout: Optional[float] = None,
|
|
217
|
+
lic_key: Optional[str] = None,
|
|
218
|
+
) -> List[Dict[str, Any]]:
|
|
219
|
+
"""Queries Shared Team Cache for recent entries of a specific type (e.g. TEAM_MISTAKE)."""
|
|
220
|
+
cloud_url = cls._get_cloud_url()
|
|
221
|
+
if cls._is_in_cooldown(cloud_url):
|
|
222
|
+
return []
|
|
223
|
+
if not lic_key:
|
|
224
|
+
is_team, resolved_key = cls._is_team_tier()
|
|
225
|
+
if not is_team:
|
|
226
|
+
return []
|
|
227
|
+
lic_key = resolved_key
|
|
228
|
+
if not cache_type:
|
|
229
|
+
return []
|
|
230
|
+
|
|
231
|
+
norm_type = cache_type.strip().upper()
|
|
232
|
+
if norm_type not in cls.ALLOWED_CACHE_TYPES:
|
|
233
|
+
return []
|
|
234
|
+
|
|
235
|
+
endpoint = f"{cloud_url}/api/team/cache/list?type={urllib.parse.quote(norm_type)}&limit={max(1, min(50, limit))}"
|
|
236
|
+
req = urllib.request.Request(
|
|
237
|
+
endpoint,
|
|
238
|
+
headers={
|
|
239
|
+
"Authorization": f"Bearer {lic_key}",
|
|
240
|
+
"User-Agent": "TokenSafe-TeamCache/1.0"
|
|
241
|
+
}
|
|
242
|
+
)
|
|
243
|
+
eff_timeout = cls.DEFAULT_TIMEOUT if timeout is None else max(0.05, float(timeout))
|
|
244
|
+
try:
|
|
245
|
+
with urllib.request.urlopen(req, timeout=eff_timeout, context=shared_ssl_context()) as resp:
|
|
246
|
+
if resp.status == 200:
|
|
247
|
+
data = json.loads(resp.read().decode("utf-8"))
|
|
248
|
+
cls._clear_cooldown(cloud_url)
|
|
249
|
+
return data.get("entries") or []
|
|
250
|
+
except urllib.error.HTTPError as he:
|
|
251
|
+
if he.code in (401, 403) or he.code >= 500:
|
|
252
|
+
cls._trip_cooldown(cloud_url)
|
|
253
|
+
return []
|
|
254
|
+
except Exception:
|
|
255
|
+
return []
|
|
256
|
+
return []
|
|
257
|
+
|
|
211
258
|
@classmethod
|
|
212
259
|
def get_stats(cls) -> Dict[str, Any]:
|
|
213
260
|
"""Retrieves team cache hit rates and token savings metrics."""
|
package/src/telemetry_sync.py
CHANGED
|
@@ -241,7 +241,7 @@ class TelemetrySync:
|
|
|
241
241
|
current_last_id = last_id
|
|
242
242
|
headers = {
|
|
243
243
|
"Content-Type": "application/json",
|
|
244
|
-
"User-Agent": "TokenSafe-Sync/4.4.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.4.1"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/type_slicer.py
CHANGED
|
@@ -37,6 +37,31 @@ class TypeSlicer:
|
|
|
37
37
|
with cls._mem_lock:
|
|
38
38
|
cls._mem_cache.clear()
|
|
39
39
|
|
|
40
|
+
@classmethod
|
|
41
|
+
def _mem_put(cls, key: str, val: str, max_items: int = 100) -> None:
|
|
42
|
+
"""Stores entry in LRU memory cache with fixed cap."""
|
|
43
|
+
with cls._mem_lock:
|
|
44
|
+
cls._mem_cache[key] = val
|
|
45
|
+
cls._mem_cache.move_to_end(key)
|
|
46
|
+
if len(cls._mem_cache) > max_items:
|
|
47
|
+
cls._mem_cache.popitem(last=False)
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def _maybe_evict(cls, conn: sqlite3.Connection, max_rows: int = 5000) -> None:
|
|
51
|
+
"""Evicts oldest entries when type cache exceeds max_rows."""
|
|
52
|
+
try:
|
|
53
|
+
row = conn.execute("SELECT COUNT(*) FROM type_cache;").fetchone()
|
|
54
|
+
count = row[0] if row else 0
|
|
55
|
+
if count > max_rows:
|
|
56
|
+
excess = count - max_rows
|
|
57
|
+
conn.execute(
|
|
58
|
+
"DELETE FROM type_cache WHERE type_key IN ("
|
|
59
|
+
"SELECT type_key FROM type_cache ORDER BY cached_at ASC LIMIT ?"
|
|
60
|
+
");", (excess,)
|
|
61
|
+
)
|
|
62
|
+
except Exception:
|
|
63
|
+
pass
|
|
64
|
+
|
|
40
65
|
@classmethod
|
|
41
66
|
def _get_db_path(cls) -> str:
|
|
42
67
|
data_dir = resolve_data_dir()
|
|
@@ -61,10 +86,15 @@ class TypeSlicer:
|
|
|
61
86
|
version TEXT NOT NULL,
|
|
62
87
|
symbol TEXT NOT NULL,
|
|
63
88
|
type_code TEXT NOT NULL,
|
|
89
|
+
dts_bytes INTEGER DEFAULT 0,
|
|
64
90
|
cached_at INTEGER NOT NULL,
|
|
65
91
|
hit_count INTEGER DEFAULT 1
|
|
66
92
|
);
|
|
67
93
|
""")
|
|
94
|
+
try:
|
|
95
|
+
conn.execute("ALTER TABLE type_cache ADD COLUMN dts_bytes INTEGER DEFAULT 0;")
|
|
96
|
+
except Exception:
|
|
97
|
+
pass
|
|
68
98
|
conn.execute("CREATE INDEX IF NOT EXISTS idx_type_pkg ON type_cache(package_name);")
|
|
69
99
|
conn.commit()
|
|
70
100
|
cls._db_init_done = db_path
|
|
@@ -146,7 +176,7 @@ class TypeSlicer:
|
|
|
146
176
|
|
|
147
177
|
@classmethod
|
|
148
178
|
def _extract_symbol_block(cls, content: str, symbol: str) -> Optional[str]:
|
|
149
|
-
"""Extracts full definition block for interface, type, class, function, or
|
|
179
|
+
"""Extracts full definition block for interface, type, class, function, enum, or namespace with balanced braces."""
|
|
150
180
|
pattern = re.compile(
|
|
151
181
|
rf'(?:export\s+)?(?:declare\s+)?(?:default\s+)?(interface|type|class|enum|function|const|namespace)\s+{re.escape(symbol)}\b',
|
|
152
182
|
re.MULTILINE
|
|
@@ -155,14 +185,18 @@ class TypeSlicer:
|
|
|
155
185
|
if not match:
|
|
156
186
|
return None
|
|
157
187
|
|
|
188
|
+
kind = match.group(1)
|
|
189
|
+
is_namespace = (kind == "namespace")
|
|
190
|
+
max_lines = 400 if is_namespace else 150
|
|
191
|
+
|
|
158
192
|
start_pos = match.start()
|
|
159
|
-
# Find start of block or statement
|
|
160
193
|
rest = content[start_pos:]
|
|
161
194
|
lines = rest.splitlines()
|
|
162
195
|
|
|
163
196
|
collected: List[str] = []
|
|
164
197
|
open_braces = 0
|
|
165
198
|
brace_started = False
|
|
199
|
+
truncated = False
|
|
166
200
|
|
|
167
201
|
for line in lines:
|
|
168
202
|
collected.append(line)
|
|
@@ -175,9 +209,15 @@ class TypeSlicer:
|
|
|
175
209
|
break
|
|
176
210
|
if brace_started and open_braces <= 0:
|
|
177
211
|
break
|
|
178
|
-
if len(collected)
|
|
212
|
+
if len(collected) >= max_lines:
|
|
213
|
+
truncated = True
|
|
179
214
|
break
|
|
180
215
|
|
|
216
|
+
if truncated and open_braces > 0:
|
|
217
|
+
collected.append(f" // ... [TokenSafe: truncated {open_braces} nested block(s)]")
|
|
218
|
+
for _ in range(open_braces):
|
|
219
|
+
collected.append("}")
|
|
220
|
+
|
|
181
221
|
return "\n".join(collected)
|
|
182
222
|
|
|
183
223
|
@classmethod
|
|
@@ -266,20 +306,21 @@ class TypeSlicer:
|
|
|
266
306
|
l2_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
267
307
|
l2_conn.execute("PRAGMA busy_timeout=5000;")
|
|
268
308
|
row = l2_conn.execute(
|
|
269
|
-
"SELECT type_code FROM type_cache WHERE type_key = ?",
|
|
309
|
+
"SELECT type_code, dts_bytes FROM type_cache WHERE type_key = ?",
|
|
270
310
|
(type_key,)
|
|
271
311
|
).fetchone()
|
|
272
312
|
if row:
|
|
273
313
|
code = row[0]
|
|
274
|
-
|
|
275
|
-
|
|
314
|
+
dts_b = row[1] if len(row) > 1 and row[1] else 0
|
|
315
|
+
cls._mem_put(type_key, code, max_items=100)
|
|
276
316
|
return {
|
|
277
317
|
"found": True,
|
|
278
318
|
"package": pkg_name,
|
|
279
319
|
"version": version,
|
|
280
320
|
"symbol": sym,
|
|
281
321
|
"type_code": code,
|
|
282
|
-
"source": "L2_sqlite"
|
|
322
|
+
"source": "L2_sqlite",
|
|
323
|
+
"_dts_bytes": dts_b
|
|
283
324
|
}
|
|
284
325
|
except Exception:
|
|
285
326
|
pass
|
|
@@ -295,8 +336,7 @@ class TypeSlicer:
|
|
|
295
336
|
from src.team_cache import TeamCache
|
|
296
337
|
team_val = TeamCache.get("3RD_PARTY_DTS", type_key, timeout=0.5)
|
|
297
338
|
if team_val:
|
|
298
|
-
|
|
299
|
-
cls._mem_cache[type_key] = team_val
|
|
339
|
+
cls._mem_put(type_key, team_val, max_items=100)
|
|
300
340
|
# Backfill L2
|
|
301
341
|
back_conn = None
|
|
302
342
|
try:
|
|
@@ -305,6 +345,7 @@ class TypeSlicer:
|
|
|
305
345
|
INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, cached_at)
|
|
306
346
|
VALUES (?, ?, ?, ?, ?, ?)
|
|
307
347
|
""", (type_key, pkg_name, version, sym, team_val, int(time.time())))
|
|
348
|
+
cls._maybe_evict(back_conn)
|
|
308
349
|
back_conn.commit()
|
|
309
350
|
except Exception:
|
|
310
351
|
pass
|
|
@@ -343,6 +384,8 @@ class TypeSlicer:
|
|
|
343
384
|
"error": f"No .d.ts declaration file located for '{pkg_name}'."
|
|
344
385
|
}
|
|
345
386
|
|
|
387
|
+
dts_bytes = os.path.getsize(dts_file) if os.path.isfile(dts_file) else 0
|
|
388
|
+
|
|
346
389
|
code_block = cls.slice_symbol_from_file(dts_file, sym)
|
|
347
390
|
if not code_block:
|
|
348
391
|
return {
|
|
@@ -354,18 +397,16 @@ class TypeSlicer:
|
|
|
354
397
|
}
|
|
355
398
|
|
|
356
399
|
# 5. Save to L1, L2 SQLite, and broadcast to L3 Team Sync
|
|
357
|
-
|
|
358
|
-
cls._mem_cache[type_key] = code_block
|
|
359
|
-
if len(cls._mem_cache) > 100:
|
|
360
|
-
cls._mem_cache.popitem(last=False)
|
|
400
|
+
cls._mem_put(type_key, code_block, max_items=100)
|
|
361
401
|
|
|
362
402
|
save_conn = None
|
|
363
403
|
try:
|
|
364
404
|
save_conn = sqlite3.connect(db_path, timeout=5.0)
|
|
365
405
|
save_conn.execute("""
|
|
366
|
-
INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, cached_at)
|
|
367
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
368
|
-
""", (type_key, pkg_name, version, sym, code_block, int(time.time())))
|
|
406
|
+
INSERT OR REPLACE INTO type_cache (type_key, package_name, version, symbol, type_code, dts_bytes, cached_at)
|
|
407
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
408
|
+
""", (type_key, pkg_name, version, sym, code_block, dts_bytes, int(time.time())))
|
|
409
|
+
cls._maybe_evict(save_conn)
|
|
369
410
|
save_conn.commit()
|
|
370
411
|
except Exception:
|
|
371
412
|
pass
|
|
@@ -388,5 +429,6 @@ class TypeSlicer:
|
|
|
388
429
|
"version": version,
|
|
389
430
|
"symbol": sym,
|
|
390
431
|
"type_code": code_block,
|
|
391
|
-
"source": "parsed_live"
|
|
432
|
+
"source": "parsed_live",
|
|
433
|
+
"_dts_bytes": dts_bytes
|
|
392
434
|
}
|
package/src/version_checker.py
CHANGED
|
@@ -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 = "4.4.
|
|
20
|
+
CURRENT_VERSION = "4.4.1"
|
|
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
|
package/src/web_reader.py
CHANGED
|
@@ -162,9 +162,14 @@ class WebReader:
|
|
|
162
162
|
|
|
163
163
|
@classmethod
|
|
164
164
|
def sanitize_url(cls, url: str) -> str:
|
|
165
|
-
"""Strips sensitive authentication & signature tokens from query strings for clean canonical caching."""
|
|
165
|
+
"""Strips userinfo (user:pass@) and sensitive authentication & signature tokens from query strings for clean canonical caching."""
|
|
166
166
|
try:
|
|
167
167
|
parsed = urllib.parse.urlparse(url.strip())
|
|
168
|
+
netloc = parsed.netloc
|
|
169
|
+
if "@" in netloc:
|
|
170
|
+
_, _, netloc = netloc.rpartition("@")
|
|
171
|
+
clean_netloc = netloc.lower()
|
|
172
|
+
|
|
168
173
|
qs = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
|
|
169
174
|
cleaned_qs = [
|
|
170
175
|
(k, v) for k, v in qs
|
|
@@ -174,7 +179,7 @@ class WebReader:
|
|
|
174
179
|
new_query = urllib.parse.urlencode(cleaned_qs)
|
|
175
180
|
return urllib.parse.urlunparse((
|
|
176
181
|
parsed.scheme.lower(),
|
|
177
|
-
|
|
182
|
+
clean_netloc,
|
|
178
183
|
parsed.path,
|
|
179
184
|
parsed.params,
|
|
180
185
|
new_query,
|
|
@@ -183,6 +188,22 @@ class WebReader:
|
|
|
183
188
|
except Exception:
|
|
184
189
|
return url.strip()
|
|
185
190
|
|
|
191
|
+
@classmethod
|
|
192
|
+
def has_auth_or_userinfo(cls, url: str, custom_headers: Optional[Dict[str, str]] = None) -> bool:
|
|
193
|
+
"""Checks whether the request carries credentials, auth headers, or userinfo in URL."""
|
|
194
|
+
if custom_headers and any(
|
|
195
|
+
k.lower() in ("authorization", "cookie", "x-api-key")
|
|
196
|
+
for k in custom_headers
|
|
197
|
+
):
|
|
198
|
+
return True
|
|
199
|
+
try:
|
|
200
|
+
parsed = urllib.parse.urlparse(url.strip())
|
|
201
|
+
if parsed.username or parsed.password or "@" in parsed.netloc:
|
|
202
|
+
return True
|
|
203
|
+
except Exception:
|
|
204
|
+
pass
|
|
205
|
+
return False
|
|
206
|
+
|
|
186
207
|
@classmethod
|
|
187
208
|
def _get_db_path(cls) -> str:
|
|
188
209
|
data_dir = resolve_data_dir()
|
|
@@ -279,11 +300,8 @@ class WebReader:
|
|
|
279
300
|
except Exception:
|
|
280
301
|
pass
|
|
281
302
|
|
|
282
|
-
# 3. Check L3 Team Sync (Only if request carried no custom auth/cookie headers)
|
|
283
|
-
has_auth =
|
|
284
|
-
k.lower() in ("authorization", "cookie", "x-api-key")
|
|
285
|
-
for k in custom_headers
|
|
286
|
-
))
|
|
303
|
+
# 3. Check L3 Team Sync (Only if request carried no custom auth/cookie headers or userinfo)
|
|
304
|
+
has_auth = cls.has_auth_or_userinfo(url, custom_headers=custom_headers)
|
|
287
305
|
if not has_auth:
|
|
288
306
|
try:
|
|
289
307
|
from src.team_cache import TeamCache
|
|
@@ -335,10 +353,7 @@ class WebReader:
|
|
|
335
353
|
pass
|
|
336
354
|
|
|
337
355
|
# 3. Broadcast to L3 Team Sync
|
|
338
|
-
has_auth =
|
|
339
|
-
k.lower() in ("authorization", "cookie", "x-api-key")
|
|
340
|
-
for k in custom_headers
|
|
341
|
-
))
|
|
356
|
+
has_auth = cls.has_auth_or_userinfo(url, custom_headers=custom_headers)
|
|
342
357
|
if sync_team and not has_auth:
|
|
343
358
|
try:
|
|
344
359
|
from src.team_cache import TeamCache
|