tokensafe 1.4.2 → 1.4.4
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/README.md +5 -0
- package/bin/tokensafe.js +1 -0
- package/hooks/pre_invocation.py +5 -0
- package/package.json +3 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +2 -0
- package/src/cli.py +37 -2
- package/src/command_sanitizer.py +7 -0
- package/src/license_manager.py +26 -1
- package/src/mcp_server.py +139 -1
- package/src/metrics.py +6 -0
- package/src/skeletonizer.py +274 -35
- package/src/telemetry_sync.py +309 -0
- package/src/version_checker.py +11 -2
- package/hooks/__pycache__/pre_tool_use.cpython-313.pyc +0 -0
package/README.md
CHANGED
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
<p align="center">
|
|
14
14
|
<a href="https://github.com/NekoSin4eG/tokensafe/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/NekoSin4eG/tokensafe/test.yml?branch=main&label=tests&style=flat-square" alt="Tests"></a>
|
|
15
15
|
<a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/v/tokensafe.svg?color=CB3837&style=flat-square" alt="npm"></a>
|
|
16
|
+
<a href="https://www.npmjs.com/package/tokensafe"><img src="https://img.shields.io/npm/dw/tokensafe.svg?color=10B981&label=npm%20downloads&style=flat-square" alt="npm downloads"></a>
|
|
16
17
|
<a href="https://pypi.org/project/tokensafe/"><img src="https://img.shields.io/pypi/v/tokensafe.svg?color=3775A9&style=flat-square" alt="PyPI"></a>
|
|
17
18
|
<a href="https://github.com/NekoSin4eG/tokensafe/stargazers"><img src="https://img.shields.io/github/stars/NekoSin4eG/tokensafe?style=flat-square&color=yellow" alt="Stars"></a>
|
|
18
19
|
<a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-emerald.svg?style=flat-square" alt="License"></a>
|
|
@@ -133,8 +134,12 @@ TokenSafe is built from the ground up to support modern polyglot monorepos. Its
|
|
|
133
134
|
| **Java & C#** | `.java`, `.cs` | Classes, records, methods with access modifiers (`public`, `protected`, `static`, `async`, `override`), generic return types (`Task<T>`, `List<E>`), `throws` | Method bodies folded; classes and interfaces remain structural |
|
|
134
135
|
| **C & C++** | `.c`, `.cpp`, `.cc`, `.cxx`, `.h`, `.hpp` | Classes, structs, namespaces, scoped methods `ClassName::method`, `const`, `noexcept`, `override`, destructors | Functions folded; namespace and class hierarchies preserved |
|
|
135
136
|
| **PHP, Kotlin, Swift** | `.php`, `.kt`, `.kts`, `.swift` | Classes, `function`, `fun`, `func` declarations with visibility modifiers | Function bodies folded into `{ /* ... */ }` |
|
|
137
|
+
| **CSS, SCSS, LESS, Tailwind** | `.css`, `.scss`, `.sass`, `.less` | **Design tokens (`:root`, `@theme`, CSS variables, `$var`, `@var`) 100% preserved**, container queries (`@media`, `@supports`, `@container`, `@layer`) kept open | Component selectors, `@keyframes`, and mixins folded into `{ /* ... */ }` unless matching `target_symbol` |
|
|
136
138
|
|
|
137
139
|
### Key Engine Guarantees:
|
|
140
|
+
- **Design Token & Palette Preservation**: When skeletonizing stylesheets, TokenSafe **always preserves all design tokens** (`:root { ... }`, Tailwind v4 `@theme { ... }`, CSS variables `--*`, SCSS `$vars`) so agents never hallucinate colors, radii, or fonts, while pruning 90%+ of bloated component styles.
|
|
141
|
+
- **Strict Arrow Function Parser**: Arrow functions strictly require `=>` before any `{` can be considered a function body; destructuring parameters (`({ a, b }: Props) =>`) and parenthesized ternary expressions (`const x = (flag) ? { a: 1 } : { b: 2 }`) are never corrupted.
|
|
142
|
+
- **Directory Tree Optimization (`tokensafe:list_dir`)**: Replaces verbose and noisy terminal `ls -la` commands with a compact, depth-bounded markdown tree without permissions, timestamps, or lockfiles.
|
|
138
143
|
- **Graph-Guided Neighborhood Slicing**: When your AI agent inspects a function or component (via `tokensafe:smart_read_file(path, symbol="Target")`), TokenSafe automatically keeps the full implementation of the target **and its 1-hop callees/callers**, while collapsing all unrelated code.
|
|
139
144
|
- **Comment & String Bracket Immunity**: Multi-line block comments (`/* ... */`, JSX `{/* ... */}`), template strings (`` `${...}` ``), and escaped quotes are tracked in a dedicated token lexer (`BraceLexer`), guaranteeing zero bracket desynchronization.
|
|
140
145
|
- **Control-Flow Statement Immunity**: Statements like `if (...)`, `catch (err) {`, `for (...)`, and `while (...)` are strictly protected and never corrupted into placeholders.
|
package/bin/tokensafe.js
CHANGED
|
@@ -39,6 +39,7 @@ Usage:
|
|
|
39
39
|
|
|
40
40
|
Commands:
|
|
41
41
|
tokensafe stats Show token economy savings & performance metrics
|
|
42
|
+
tokensafe sync Synchronize local token metrics with Cloud Dashboard
|
|
42
43
|
tokensafe html Generate and open interactive browser dashboard
|
|
43
44
|
tokensafe test "<prompt>" Test prompt compression on custom input
|
|
44
45
|
tokensafe doctor Audit MCP servers & skills context token tax
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -45,6 +45,11 @@ def main():
|
|
|
45
45
|
# 0. Quota and Environment Audits (Fires on first invocation)
|
|
46
46
|
quota = LicenseManager.check_quota(tracker)
|
|
47
47
|
if invocation_num <= 1:
|
|
48
|
+
try:
|
|
49
|
+
from src.telemetry_sync import TelemetrySync
|
|
50
|
+
TelemetrySync.sync_background()
|
|
51
|
+
except Exception:
|
|
52
|
+
pass
|
|
48
53
|
if quota.get("warning"):
|
|
49
54
|
inject_steps.append({
|
|
50
55
|
"systemMessage": {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.4",
|
|
4
4
|
"description": "Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents",
|
|
5
5
|
"main": "bin/tokensafe.js",
|
|
6
6
|
"bin": {
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
"src/*.py",
|
|
14
14
|
"!src/cloud_backend.py",
|
|
15
15
|
"!src/mailer.py",
|
|
16
|
+
"!**/__pycache__/**",
|
|
17
|
+
"!**/*.pyc",
|
|
16
18
|
"rules/",
|
|
17
19
|
"skills/",
|
|
18
20
|
"hooks/",
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agy-token-optimizer",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "1.4.
|
|
4
|
+
"version": "1.4.4",
|
|
5
5
|
"description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
package/rules/AGENTS.md
CHANGED
|
@@ -31,6 +31,8 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
31
31
|
3. **Architecture Discovery**: Before executing multi-file exploration, ALWAYS call `tokensafe:get_architecture_graph(project_path)` to locate God Nodes and dependency topology in < 250 tokens without file crawling.
|
|
32
32
|
4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.
|
|
33
33
|
5. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
|
|
34
|
+
6. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens).
|
|
35
|
+
7. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
|
|
34
36
|
|
|
35
37
|
### 4. Turn Token Savings Footer (Proof-of-Savings)
|
|
36
38
|
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:
|
package/src/cli.py
CHANGED
|
@@ -29,6 +29,11 @@ def main():
|
|
|
29
29
|
command = args[0] if args else "stats"
|
|
30
30
|
|
|
31
31
|
if command in ("stats", "dashboard"):
|
|
32
|
+
try:
|
|
33
|
+
from src.telemetry_sync import TelemetrySync
|
|
34
|
+
TelemetrySync.sync_background()
|
|
35
|
+
except Exception:
|
|
36
|
+
pass
|
|
32
37
|
print(dashboard.render_terminal())
|
|
33
38
|
|
|
34
39
|
elif command in ("html", "web"):
|
|
@@ -207,11 +212,41 @@ def main():
|
|
|
207
212
|
key = args[1].strip()
|
|
208
213
|
ok, msg = LicenseManager.save_license(key)
|
|
209
214
|
if ok:
|
|
210
|
-
print(f"\n\033[32m\033[1m✔ {msg}\033[0m
|
|
215
|
+
print(f"\n\033[32m\033[1m✔ {msg}\033[0m")
|
|
216
|
+
# Automatically report version and seat activation to cloud
|
|
217
|
+
try:
|
|
218
|
+
from src.version_checker import VersionChecker
|
|
219
|
+
VersionChecker.check_version(license_key=key, force_fetch=True)
|
|
220
|
+
except Exception:
|
|
221
|
+
pass
|
|
222
|
+
# Automatically sync existing local token metrics to newly activated license
|
|
223
|
+
try:
|
|
224
|
+
from src.telemetry_sync import TelemetrySync
|
|
225
|
+
sync_res = TelemetrySync.sync(license_key=key, timeout=3.0)
|
|
226
|
+
if sync_res.get("success") and sync_res.get("synced_events", 0) > 0:
|
|
227
|
+
print(f" \033[36m✔ Synced {sync_res['synced_events']:,} past optimization events to cloud dashboard.\033[0m")
|
|
228
|
+
except Exception:
|
|
229
|
+
pass
|
|
230
|
+
print()
|
|
211
231
|
else:
|
|
212
232
|
print(f"\n\033[31m\033[1m✖ {msg}\033[0m\n")
|
|
213
233
|
sys.exit(1)
|
|
214
234
|
|
|
235
|
+
elif command in ("sync", "push"):
|
|
236
|
+
from src.telemetry_sync import TelemetrySync
|
|
237
|
+
print("\n\033[1m\033[36m⚡ SYNCHRONIZING TOKEN METRICS WITH DASHBOARD ⚡\033[0m\n")
|
|
238
|
+
force_sync = "--force" in args or "-f" in args
|
|
239
|
+
status_before = TelemetrySync.get_sync_status()
|
|
240
|
+
print(f" Local recorded events: {status_before['total_local_events']:,}")
|
|
241
|
+
print(f" Pending sync: {status_before['pending_events']:,}\n")
|
|
242
|
+
res = TelemetrySync.sync(force=force_sync, verbose=True)
|
|
243
|
+
if res.get("success"):
|
|
244
|
+
print(f" \033[32m✔ {res.get('message', 'Synchronized successfully.')}\033[0m")
|
|
245
|
+
status_after = TelemetrySync.get_sync_status()
|
|
246
|
+
print(f" Total synced events: {status_after['total_synced_events']:,}\n")
|
|
247
|
+
else:
|
|
248
|
+
print(f" \033[31m✖ Sync failed: {res.get('error', 'Unknown error')}\033[0m\n")
|
|
249
|
+
|
|
215
250
|
elif command in ("license", "tier"):
|
|
216
251
|
from src.license_manager import LicenseManager
|
|
217
252
|
tier, payload = LicenseManager.get_active_license()
|
|
@@ -391,7 +426,7 @@ def main():
|
|
|
391
426
|
|
|
392
427
|
else:
|
|
393
428
|
print(f"Unknown command: {command}")
|
|
394
|
-
print("Available commands: stats, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, vacuum, prune, digest, activate, license, markdown, setup, reset")
|
|
429
|
+
print("Available commands: stats, sync, html, test, doctor, providers, mcp, benchmark, proxy, graph, map, vacuum, prune, digest, activate, license, markdown, setup, reset")
|
|
395
430
|
sys.exit(1)
|
|
396
431
|
|
|
397
432
|
if __name__ == "__main__":
|
package/src/command_sanitizer.py
CHANGED
|
@@ -126,4 +126,11 @@ class CommandSanitizer:
|
|
|
126
126
|
est_saved = 2500
|
|
127
127
|
return new_cmd, est_saved, "Sanitized grep directories and capped output to 30 matches"
|
|
128
128
|
|
|
129
|
+
# 7. ls command optimization (Replace verbose permissions/timestamps with compact single-column format)
|
|
130
|
+
if re.search(r"\bls\b", cmd):
|
|
131
|
+
if re.search(r"\bls\s+-[a-zA-Z]*(l|a)[a-zA-Z]*\b", cmd):
|
|
132
|
+
new_cmd = re.sub(r"\bls\s+-[a-zA-Z]+\b", "ls -1 -p", cmd)
|
|
133
|
+
est_saved = 380
|
|
134
|
+
return new_cmd, est_saved, "Replaced verbose ls flags with compact, secret-safe format (-1 -p)"
|
|
135
|
+
|
|
129
136
|
return None, 0, ""
|
package/src/license_manager.py
CHANGED
|
@@ -19,6 +19,8 @@ LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
|
|
|
19
19
|
|
|
20
20
|
# Master Public Key for client-side offline verification (RFC 8032 Ed25519)
|
|
21
21
|
DEFAULT_ED25519_PUBLIC_KEY = os.environ.get("TOKENSAFE_PUBLIC_KEY", "3911e2ffe5ad07ee23be392b88f238af302f9d3a0bf51881de8b5e0e6af71430")
|
|
22
|
+
# Pre-rotation public keys accepted for backwards compatibility
|
|
23
|
+
LEGACY_ED25519_PUBLIC_KEYS = ("8a2c9d550180ab5b00a06174cb6aecfd712740c59d0bdcff66a56515348c855e",)
|
|
22
24
|
# Private key for cloud server signing (never distributed to client, loaded strictly from environment)
|
|
23
25
|
DEFAULT_ED25519_PRIVATE_KEY = os.environ.get("TOKENSAFE_PRIVATE_KEY", "")
|
|
24
26
|
# Rotated HMAC salt for backward compatibility with TS1 legacy licenses
|
|
@@ -221,7 +223,17 @@ class LicenseManager:
|
|
|
221
223
|
return False, {}, "Invalid signature encoding"
|
|
222
224
|
|
|
223
225
|
if not _ed25519_verify_bytes(sig_bytes, payload_bytes, pub_bytes):
|
|
224
|
-
|
|
226
|
+
verified = False
|
|
227
|
+
if not public_key:
|
|
228
|
+
for leg_hex in LEGACY_ED25519_PUBLIC_KEYS:
|
|
229
|
+
try:
|
|
230
|
+
if _ed25519_verify_bytes(sig_bytes, payload_bytes, bytes.fromhex(leg_hex)):
|
|
231
|
+
verified = True
|
|
232
|
+
break
|
|
233
|
+
except Exception:
|
|
234
|
+
pass
|
|
235
|
+
if not verified:
|
|
236
|
+
return False, {}, "Invalid digital signature: license key has been tampered with or is counterfeit"
|
|
225
237
|
|
|
226
238
|
# 2. Legacy TS1 Verification
|
|
227
239
|
else:
|
|
@@ -262,6 +274,19 @@ class LicenseManager:
|
|
|
262
274
|
|
|
263
275
|
return "free", {"tier": "free", "max_tokens_monthly": 500_000}
|
|
264
276
|
|
|
277
|
+
@classmethod
|
|
278
|
+
def get_active_license_key(cls) -> str:
|
|
279
|
+
"""Retrieves active raw license key string from env or data/license.json, or empty string."""
|
|
280
|
+
key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
|
|
281
|
+
if not key and os.path.exists(LICENSE_FILE):
|
|
282
|
+
try:
|
|
283
|
+
with open(LICENSE_FILE, "r", encoding="utf-8") as f:
|
|
284
|
+
data = json.load(f)
|
|
285
|
+
key = data.get("license_key", "").strip()
|
|
286
|
+
except Exception:
|
|
287
|
+
pass
|
|
288
|
+
return key
|
|
289
|
+
|
|
265
290
|
@classmethod
|
|
266
291
|
def save_license(cls, license_key: str) -> Tuple[bool, str]:
|
|
267
292
|
"""Saves a verified license key to local persistent storage."""
|
package/src/mcp_server.py
CHANGED
|
@@ -8,6 +8,7 @@ import sys
|
|
|
8
8
|
import os
|
|
9
9
|
import json
|
|
10
10
|
import traceback
|
|
11
|
+
import fnmatch
|
|
11
12
|
from typing import Tuple, Optional
|
|
12
13
|
|
|
13
14
|
# Ensure project root in sys.path
|
|
@@ -30,7 +31,7 @@ from src.guard import TokenSafeGuard
|
|
|
30
31
|
|
|
31
32
|
SERVER_INFO = {
|
|
32
33
|
"name": "tokensafe-mcp",
|
|
33
|
-
"version": "1.4.
|
|
34
|
+
"version": "1.4.3"
|
|
34
35
|
}
|
|
35
36
|
|
|
36
37
|
TOOLS = [
|
|
@@ -121,9 +122,118 @@ TOOLS = [
|
|
|
121
122
|
"file_path": {"type": "string", "description": "Optional: File path being written or modified"}
|
|
122
123
|
}
|
|
123
124
|
}
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
"name": "list_dir",
|
|
128
|
+
"description": "Returns a clean, token-efficient directory tree up to depth N without permissions, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces verbose ls -la.",
|
|
129
|
+
"inputSchema": {
|
|
130
|
+
"type": "object",
|
|
131
|
+
"properties": {
|
|
132
|
+
"path": {"type": "string", "description": "Path to the directory (relative to project root or absolute)"},
|
|
133
|
+
"depth": {"type": "integer", "description": "Maximum traversal depth (default: 2, max: 4)"},
|
|
134
|
+
"max_entries": {"type": "integer", "description": "Maximum entries to display before pruning (default: 80)"}
|
|
135
|
+
},
|
|
136
|
+
"required": ["path"]
|
|
137
|
+
}
|
|
124
138
|
}
|
|
125
139
|
]
|
|
126
140
|
|
|
141
|
+
def format_file_size(size_bytes: int) -> str:
|
|
142
|
+
if size_bytes < 1024:
|
|
143
|
+
return f"{size_bytes} B"
|
|
144
|
+
elif size_bytes < 1024 * 1024:
|
|
145
|
+
return f"{size_bytes / 1024:.1f} KB"
|
|
146
|
+
else:
|
|
147
|
+
return f"{size_bytes / (1024 * 1024):.1f} MB"
|
|
148
|
+
|
|
149
|
+
def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) -> str:
|
|
150
|
+
"""
|
|
151
|
+
Builds a clean, compact markdown tree for dir_path.
|
|
152
|
+
Ignores heavy folders (node_modules, dist, .git, etc.) and redacts sensitive files (.env*).
|
|
153
|
+
"""
|
|
154
|
+
IGNORE_DIRS = {
|
|
155
|
+
'node_modules', '.git', 'dist', 'build', '.next', 'coverage',
|
|
156
|
+
'__pycache__', '.turbo', '.vite', '.output', '.bunny', 'data',
|
|
157
|
+
'.venv', 'venv', '.cache', '.idea', '.vscode'
|
|
158
|
+
}
|
|
159
|
+
IGNORE_FILES = {
|
|
160
|
+
'*.lock', '*.lockb', '*.map', '.DS_Store', 'Thumbs.db', 'package-lock.json',
|
|
161
|
+
'pnpm-lock.yaml', 'yarn.lock', 'Cargo.lock', 'composer.lock'
|
|
162
|
+
}
|
|
163
|
+
SECRET_FILES = {
|
|
164
|
+
'.env', '.env.local', '.env.production', '.env.staging', '.env.development'
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
if not os.path.exists(dir_path):
|
|
168
|
+
return f"Error: Directory not found: {dir_path}"
|
|
169
|
+
if not os.path.isdir(dir_path):
|
|
170
|
+
return f"Error: Path is not a directory: {dir_path}"
|
|
171
|
+
|
|
172
|
+
base_name = os.path.basename(os.path.abspath(dir_path)) or dir_path
|
|
173
|
+
lines = [f"📁 **{base_name}/** (max depth: {max_depth})"]
|
|
174
|
+
entries_count = 0
|
|
175
|
+
|
|
176
|
+
def _traverse(curr_dir: str, prefix: str, current_depth: int):
|
|
177
|
+
nonlocal entries_count
|
|
178
|
+
if current_depth > max_depth or entries_count >= max_entries:
|
|
179
|
+
return
|
|
180
|
+
|
|
181
|
+
try:
|
|
182
|
+
items = sorted(os.listdir(curr_dir))
|
|
183
|
+
except Exception as e:
|
|
184
|
+
lines.append(f"{prefix}└── [Permission Denied: {e}]")
|
|
185
|
+
return
|
|
186
|
+
|
|
187
|
+
dirs = []
|
|
188
|
+
files = []
|
|
189
|
+
for it in items:
|
|
190
|
+
if it.startswith('.') and it not in SECRET_FILES and it != '.gitignore':
|
|
191
|
+
continue
|
|
192
|
+
full_p = os.path.join(curr_dir, it)
|
|
193
|
+
if os.path.isdir(full_p):
|
|
194
|
+
if it in IGNORE_DIRS:
|
|
195
|
+
continue
|
|
196
|
+
dirs.append(it)
|
|
197
|
+
else:
|
|
198
|
+
files.append(it)
|
|
199
|
+
|
|
200
|
+
all_items = [(d, True) for d in dirs] + [(f, False) for f in files]
|
|
201
|
+
total_items = len(all_items)
|
|
202
|
+
|
|
203
|
+
for i, (name, is_dir) in enumerate(all_items):
|
|
204
|
+
if entries_count >= max_entries:
|
|
205
|
+
lines.append(f"{prefix}└── ... ({total_items - i} more items omitted for token efficiency)")
|
|
206
|
+
break
|
|
207
|
+
|
|
208
|
+
is_last = (i == total_items - 1)
|
|
209
|
+
pointer = "└── " if is_last else "├── "
|
|
210
|
+
extension_prefix = " " if is_last else "│ "
|
|
211
|
+
item_path = os.path.join(curr_dir, name)
|
|
212
|
+
|
|
213
|
+
if is_dir:
|
|
214
|
+
entries_count += 1
|
|
215
|
+
lines.append(f"{prefix}{pointer}📁 {name}/")
|
|
216
|
+
_traverse(item_path, prefix + extension_prefix, current_depth + 1)
|
|
217
|
+
else:
|
|
218
|
+
if name in SECRET_FILES:
|
|
219
|
+
lines.append(f"{prefix}{pointer}🔒 {name} [PROTECTED SECRET]")
|
|
220
|
+
entries_count += 1
|
|
221
|
+
continue
|
|
222
|
+
if any(fnmatch.fnmatch(name, pat) for pat in IGNORE_FILES):
|
|
223
|
+
continue
|
|
224
|
+
try:
|
|
225
|
+
sz = os.path.getsize(item_path)
|
|
226
|
+
sz_str = format_file_size(sz)
|
|
227
|
+
except Exception:
|
|
228
|
+
sz_str = ""
|
|
229
|
+
entries_count += 1
|
|
230
|
+
size_label = f" ({sz_str})" if sz_str else ""
|
|
231
|
+
lines.append(f"{prefix}{pointer}{name}{size_label}")
|
|
232
|
+
|
|
233
|
+
_traverse(dir_path, "", 1)
|
|
234
|
+
lines.append("\n*Pruned noisy directories (node_modules, dist, .git) & lockfiles to conserve tokens.*")
|
|
235
|
+
return "\n".join(lines)
|
|
236
|
+
|
|
127
237
|
def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
128
238
|
"""
|
|
129
239
|
Safely resolves the target project root without falling back to system root dirs.
|
|
@@ -413,6 +523,29 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
413
523
|
)
|
|
414
524
|
return {"content": [{"type": "text", "text": surface_md}]}
|
|
415
525
|
|
|
526
|
+
elif name == "list_dir":
|
|
527
|
+
path = args.get("path", "")
|
|
528
|
+
if not path:
|
|
529
|
+
return {"isError": True, "content": [{"type": "text", "text": "Error: 'path' argument is required for list_dir."}]}
|
|
530
|
+
|
|
531
|
+
# Resolve path relative to current working directory or absolute
|
|
532
|
+
abs_path = os.path.abspath(path)
|
|
533
|
+
depth = min(4, max(1, int(args.get("depth", 2))))
|
|
534
|
+
max_entries = min(150, max(10, int(args.get("max_entries", 80))))
|
|
535
|
+
|
|
536
|
+
tree_output = build_dir_tree(abs_path, max_depth=depth, max_entries=max_entries)
|
|
537
|
+
tree_tokens = count_tokens(tree_output)
|
|
538
|
+
# Estimate equivalent tokens from multiple verbose ls -la calls (at least ~800 tokens)
|
|
539
|
+
est_orig_tokens = max(800, tree_tokens * 6)
|
|
540
|
+
tracker.record_event(
|
|
541
|
+
session_id="mcp_session",
|
|
542
|
+
event_type="DIR_LIST",
|
|
543
|
+
original_tokens=est_orig_tokens,
|
|
544
|
+
optimized_tokens=tree_tokens,
|
|
545
|
+
details={"path": os.path.basename(abs_path) or abs_path, "depth": depth, "tokens_saved": est_orig_tokens - tree_tokens}
|
|
546
|
+
)
|
|
547
|
+
return {"content": [{"type": "text", "text": tree_output}]}
|
|
548
|
+
|
|
416
549
|
return {"isError": True, "content": [{"type": "text", "text": f"Unknown tool: {name}"}]}
|
|
417
550
|
|
|
418
551
|
def run_mcp_server():
|
|
@@ -437,6 +570,11 @@ def run_mcp_server():
|
|
|
437
570
|
response = {"jsonrpc": "2.0", "id": msg_id}
|
|
438
571
|
|
|
439
572
|
if method == "initialize":
|
|
573
|
+
try:
|
|
574
|
+
from src.telemetry_sync import TelemetrySync
|
|
575
|
+
TelemetrySync.sync_background()
|
|
576
|
+
except Exception:
|
|
577
|
+
pass
|
|
440
578
|
response["result"] = {
|
|
441
579
|
"protocolVersion": "2024-11-05",
|
|
442
580
|
"capabilities": {"tools": {}},
|
package/src/metrics.py
CHANGED
|
@@ -133,6 +133,12 @@ class MetricsTracker:
|
|
|
133
133
|
|
|
134
134
|
# Periodic amortized auto-retention check (every 100 events)
|
|
135
135
|
self._event_counter += 1
|
|
136
|
+
if self._event_counter % 20 == 0:
|
|
137
|
+
try:
|
|
138
|
+
from src.telemetry_sync import TelemetrySync
|
|
139
|
+
TelemetrySync.sync_background()
|
|
140
|
+
except Exception:
|
|
141
|
+
pass
|
|
136
142
|
if self._event_counter >= 100:
|
|
137
143
|
self._event_counter = 0
|
|
138
144
|
try:
|
package/src/skeletonizer.py
CHANGED
|
@@ -36,13 +36,31 @@ RUST_FN_REGEX = re.compile(
|
|
|
36
36
|
)
|
|
37
37
|
|
|
38
38
|
# 4. Arrow function / React component: const Foo = (...) => { or export const Foo: React.FC<Props> = (...) => {
|
|
39
|
+
# Supports single-line return types, generics, React.memo, useCallback
|
|
39
40
|
ARROW_FN_REGEX = re.compile(
|
|
40
|
-
r'^(?:export\s+)?(?:
|
|
41
|
+
r'^(?:export\s+)?(?:default\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)'
|
|
42
|
+
r'(?:\s*:\s*[^=]+)?\s*=\s*'
|
|
43
|
+
r'(?:async\s*)?'
|
|
44
|
+
r'(?:React\.(?:memo|forwardRef)\s*\()?'
|
|
45
|
+
r'(?:useCallback\s*\()?'
|
|
46
|
+
r'(?:'
|
|
47
|
+
r'(?:<[^>]+>\s*)?'
|
|
48
|
+
r'(?:\([^)]*\)|[a-zA-Z0-9_$]+)'
|
|
49
|
+
r'(?:\s*:\s*[^=>]+)?'
|
|
50
|
+
r'\s*=>'
|
|
51
|
+
r'|function\b'
|
|
52
|
+
r')'
|
|
41
53
|
)
|
|
42
54
|
|
|
43
55
|
# 4b. Multi-line arrow function start: const Foo: React.FC<Props> = (
|
|
44
56
|
ARROW_MULTILINE_START = re.compile(
|
|
45
|
-
r'^(?:export\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)
|
|
57
|
+
r'^(?:export\s+)?(?:default\s+)?(?:const|let|var)\s+([a-zA-Z0-9_$]+)'
|
|
58
|
+
r'(?:\s*:\s*[^=]+)?\s*=\s*'
|
|
59
|
+
r'(?:async\s*)?'
|
|
60
|
+
r'(?:React\.(?:memo|forwardRef)\s*\()?'
|
|
61
|
+
r'(?:useCallback\s*\()?\s*'
|
|
62
|
+
r'(?:<[^>]+>\s*)?'
|
|
63
|
+
r'\('
|
|
46
64
|
)
|
|
47
65
|
|
|
48
66
|
# 5. Method definition (Java, C#, C++, TS, PHP)
|
|
@@ -105,6 +123,8 @@ class Skeletonizer:
|
|
|
105
123
|
".go", ".java", ".rs", ".cpp", ".cc", ".cxx", ".c", ".h", ".hpp", ".cs", ".php", ".kt", ".swift"
|
|
106
124
|
):
|
|
107
125
|
return cls._skeletonize_braces(code, ext, keep_symbols=keep_symbols)
|
|
126
|
+
elif ext in (".css", ".scss", ".sass", ".less"):
|
|
127
|
+
return cls._skeletonize_css(code, ext, keep_symbols=keep_symbols)
|
|
108
128
|
return code
|
|
109
129
|
|
|
110
130
|
@classmethod
|
|
@@ -165,7 +185,9 @@ class Skeletonizer:
|
|
|
165
185
|
|
|
166
186
|
m = ARROW_MULTILINE_START.match(line_clean)
|
|
167
187
|
if m and not line_clean.endswith(";"):
|
|
168
|
-
|
|
188
|
+
# Multi-line parameter list MUST have unclosed parentheses on this line (unless '=>' is present)
|
|
189
|
+
if line_clean.count("(") > line_clean.count(")") or "=>" in line_clean:
|
|
190
|
+
return (m.group(1), "arrow_multiline")
|
|
169
191
|
|
|
170
192
|
m = METHOD_REGEX.match(line_clean)
|
|
171
193
|
if m:
|
|
@@ -198,12 +220,13 @@ class Skeletonizer:
|
|
|
198
220
|
pending_header_lines = []
|
|
199
221
|
pending_name = None
|
|
200
222
|
pending_kind = None
|
|
223
|
+
arrow_seen = False
|
|
201
224
|
|
|
202
225
|
comment_token = "/* ... */" if ext != ".py" else "..."
|
|
203
226
|
|
|
204
227
|
for line in lines:
|
|
205
228
|
raw_line = line
|
|
206
|
-
|
|
229
|
+
clean_line = lexer.clean_line(line).strip()
|
|
207
230
|
|
|
208
231
|
# 1. If currently skipping a folded function body
|
|
209
232
|
if in_folding:
|
|
@@ -224,58 +247,141 @@ class Skeletonizer:
|
|
|
224
247
|
# 2. If accumulating a multi-line header
|
|
225
248
|
if pending_header_lines:
|
|
226
249
|
pending_header_lines.append(raw_line)
|
|
227
|
-
if "=>" in line_clean or "{" in line_clean:
|
|
228
|
-
fn_name = pending_name
|
|
229
|
-
should_keep = keep_symbols is not None and fn_name in keep_symbols
|
|
230
250
|
|
|
231
|
-
|
|
232
|
-
if
|
|
233
|
-
|
|
251
|
+
if pending_kind == "arrow_multiline":
|
|
252
|
+
if "=>" in clean_line:
|
|
253
|
+
arrow_seen = True
|
|
254
|
+
|
|
255
|
+
has_body_brace = False
|
|
256
|
+
body_brace_idx = -1
|
|
257
|
+
if arrow_seen:
|
|
258
|
+
if "=>" in clean_line:
|
|
259
|
+
arrow_idx = clean_line.find("=>")
|
|
260
|
+
body_brace_idx = clean_line.find("{", arrow_idx + 2)
|
|
261
|
+
if body_brace_idx != -1:
|
|
262
|
+
has_body_brace = True
|
|
263
|
+
elif "{" in clean_line:
|
|
264
|
+
body_brace_idx = clean_line.find("{")
|
|
265
|
+
has_body_brace = True
|
|
266
|
+
|
|
267
|
+
if has_body_brace:
|
|
268
|
+
fn_name = pending_name
|
|
269
|
+
should_keep = keep_symbols is not None and fn_name in keep_symbols
|
|
270
|
+
|
|
271
|
+
sig_lines = pending_header_lines[:-1] + [raw_line[:body_brace_idx]]
|
|
234
272
|
temp_lexer = BraceLexer()
|
|
235
273
|
sig_open = sum(temp_lexer.count_braces(sl)[0] for sl in sig_lines)
|
|
236
274
|
sig_close = sum(temp_lexer.count_braces(sl)[1] for sl in sig_lines)
|
|
237
275
|
base_depth = current_depth + (sig_open - sig_close)
|
|
238
|
-
else:
|
|
239
|
-
base_depth = current_depth
|
|
240
276
|
|
|
241
|
-
|
|
277
|
+
if should_keep:
|
|
278
|
+
out.extend(pending_header_lines)
|
|
279
|
+
for phl in pending_header_lines:
|
|
280
|
+
op, cl = lexer.count_braces(phl)
|
|
281
|
+
current_depth += op - cl
|
|
282
|
+
else:
|
|
283
|
+
folded_head = raw_line[:body_brace_idx] + f"{{ {comment_token} }}"
|
|
284
|
+
if raw_line.rstrip().endswith(";"):
|
|
285
|
+
folded_head += ";"
|
|
286
|
+
elif raw_line.rstrip().endswith(","):
|
|
287
|
+
folded_head += ","
|
|
288
|
+
pending_header_lines[-1] = folded_head
|
|
289
|
+
out.extend(pending_header_lines)
|
|
290
|
+
fold_depth = base_depth
|
|
291
|
+
current_depth = base_depth + 1
|
|
292
|
+
in_folding = True
|
|
293
|
+
|
|
294
|
+
pending_header_lines = []
|
|
295
|
+
pending_name = None
|
|
296
|
+
pending_kind = None
|
|
297
|
+
arrow_seen = False
|
|
298
|
+
continue
|
|
299
|
+
elif ";" in clean_line and not has_body_brace:
|
|
300
|
+
# Non-function variable assignment or ternary expression (e.g. gramBalanceDeduct)
|
|
242
301
|
out.extend(pending_header_lines)
|
|
243
302
|
for phl in pending_header_lines:
|
|
244
303
|
op, cl = lexer.count_braces(phl)
|
|
245
304
|
current_depth += op - cl
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
305
|
+
pending_header_lines = []
|
|
306
|
+
pending_name = None
|
|
307
|
+
pending_kind = None
|
|
308
|
+
arrow_seen = False
|
|
309
|
+
continue
|
|
310
|
+
elif len(pending_header_lines) > 25:
|
|
249
311
|
out.extend(pending_header_lines)
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
for phl in pending_header_lines:
|
|
261
|
-
op, cl = lexer.count_braces(phl)
|
|
262
|
-
current_depth += op - cl
|
|
263
|
-
pending_header_lines = []
|
|
264
|
-
pending_name = None
|
|
265
|
-
pending_kind = None
|
|
266
|
-
continue
|
|
312
|
+
for phl in pending_header_lines:
|
|
313
|
+
op, cl = lexer.count_braces(phl)
|
|
314
|
+
current_depth += op - cl
|
|
315
|
+
pending_header_lines = []
|
|
316
|
+
pending_name = None
|
|
317
|
+
pending_kind = None
|
|
318
|
+
arrow_seen = False
|
|
319
|
+
continue
|
|
320
|
+
else:
|
|
321
|
+
continue
|
|
267
322
|
else:
|
|
268
|
-
|
|
323
|
+
# Non-arrow multiline (function foo(, method, func)
|
|
324
|
+
if "{" in clean_line:
|
|
325
|
+
body_brace_idx = raw_line.rfind("{")
|
|
326
|
+
fn_name = pending_name
|
|
327
|
+
should_keep = keep_symbols is not None and fn_name in keep_symbols
|
|
328
|
+
|
|
329
|
+
sig_lines = pending_header_lines[:-1] + [raw_line[:body_brace_idx]]
|
|
330
|
+
temp_lexer = BraceLexer()
|
|
331
|
+
sig_open = sum(temp_lexer.count_braces(sl)[0] for sl in sig_lines)
|
|
332
|
+
sig_close = sum(temp_lexer.count_braces(sl)[1] for sl in sig_lines)
|
|
333
|
+
base_depth = current_depth + (sig_open - sig_close)
|
|
334
|
+
|
|
335
|
+
if should_keep:
|
|
336
|
+
out.extend(pending_header_lines)
|
|
337
|
+
for phl in pending_header_lines:
|
|
338
|
+
op, cl = lexer.count_braces(phl)
|
|
339
|
+
current_depth += op - cl
|
|
340
|
+
else:
|
|
341
|
+
folded_last_line = re.sub(r'\{.*$', f'{{ {comment_token} }}', raw_line)
|
|
342
|
+
pending_header_lines[-1] = folded_last_line
|
|
343
|
+
out.extend(pending_header_lines)
|
|
344
|
+
fold_depth = base_depth
|
|
345
|
+
current_depth = base_depth + 1
|
|
346
|
+
in_folding = True
|
|
347
|
+
|
|
348
|
+
pending_header_lines = []
|
|
349
|
+
pending_name = None
|
|
350
|
+
pending_kind = None
|
|
351
|
+
continue
|
|
352
|
+
elif ";" in clean_line and "{" not in clean_line:
|
|
353
|
+
out.extend(pending_header_lines)
|
|
354
|
+
for phl in pending_header_lines:
|
|
355
|
+
op, cl = lexer.count_braces(phl)
|
|
356
|
+
current_depth += op - cl
|
|
357
|
+
pending_header_lines = []
|
|
358
|
+
pending_name = None
|
|
359
|
+
pending_kind = None
|
|
360
|
+
continue
|
|
361
|
+
else:
|
|
362
|
+
continue
|
|
269
363
|
|
|
270
364
|
# 3. Check for function start
|
|
271
365
|
fn_info = cls._extract_fn(raw_line)
|
|
272
366
|
if fn_info:
|
|
273
367
|
name, kind = fn_info
|
|
274
368
|
|
|
275
|
-
if
|
|
369
|
+
if kind == 'arrow_multiline':
|
|
370
|
+
clean = lexer.clean_line(raw_line)
|
|
371
|
+
if "=>" in clean and clean.find("{") > clean.find("=>"):
|
|
372
|
+
kind = 'arrow_fn'
|
|
373
|
+
else:
|
|
374
|
+
pending_header_lines = [raw_line]
|
|
375
|
+
pending_name = name
|
|
376
|
+
pending_kind = 'arrow_multiline'
|
|
377
|
+
arrow_seen = "=>" in clean
|
|
378
|
+
continue
|
|
379
|
+
|
|
380
|
+
if kind == 'arrow_fn' and "=>" not in raw_line:
|
|
276
381
|
pending_header_lines = [raw_line]
|
|
277
382
|
pending_name = name
|
|
278
383
|
pending_kind = 'arrow_multiline'
|
|
384
|
+
arrow_seen = False
|
|
279
385
|
continue
|
|
280
386
|
|
|
281
387
|
if "{" in raw_line:
|
|
@@ -287,6 +393,8 @@ class Skeletonizer:
|
|
|
287
393
|
current_depth += open_b - close_b
|
|
288
394
|
else:
|
|
289
395
|
folded_line = re.sub(r'\{.*$', f'{{ {comment_token} }}', raw_line)
|
|
396
|
+
if raw_line.rstrip().endswith(";"):
|
|
397
|
+
folded_line += ";"
|
|
290
398
|
out.append(folded_line)
|
|
291
399
|
open_b_head, _ = lexer.count_braces(raw_line[:raw_line.find("{") + 1])
|
|
292
400
|
fold_depth = current_depth + open_b_head - 1
|
|
@@ -302,6 +410,137 @@ class Skeletonizer:
|
|
|
302
410
|
|
|
303
411
|
return "\n".join(out)
|
|
304
412
|
|
|
413
|
+
@classmethod
|
|
414
|
+
def _skeletonize_css(cls, code: str, ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
|
|
415
|
+
"""
|
|
416
|
+
Specialized CSS / SCSS / SASS / LESS AST skeletonizer.
|
|
417
|
+
Design tokens (:root, @theme, html, body, $variables, @variables) are ALWAYS preserved in full
|
|
418
|
+
so AI agents always possess the complete project design palette and variables.
|
|
419
|
+
Container at-rules (@media, @supports, @container, @layer) preserve structure and track depth.
|
|
420
|
+
Component selectors and mixins are folded into '{ /* ... */ }' unless matching keep_symbols.
|
|
421
|
+
"""
|
|
422
|
+
lines = code.splitlines()
|
|
423
|
+
out = []
|
|
424
|
+
lexer = BraceLexer()
|
|
425
|
+
in_folding = False
|
|
426
|
+
fold_depth = 0
|
|
427
|
+
current_depth = 0
|
|
428
|
+
|
|
429
|
+
CONTAINER_RULES = ("@media", "@supports", "@container", "@layer", "@document")
|
|
430
|
+
TOKEN_SELECTORS = (":root", "@theme", "html", "body")
|
|
431
|
+
|
|
432
|
+
pending_sel = []
|
|
433
|
+
|
|
434
|
+
for line in lines:
|
|
435
|
+
raw_line = line
|
|
436
|
+
clean_line = lexer.clean_line(line).strip()
|
|
437
|
+
|
|
438
|
+
if in_folding:
|
|
439
|
+
open_b, close_b = lexer.count_braces(raw_line)
|
|
440
|
+
current_depth += open_b - close_b
|
|
441
|
+
if current_depth <= fold_depth:
|
|
442
|
+
in_folding = False
|
|
443
|
+
trailing = ""
|
|
444
|
+
idx = raw_line.rfind("}")
|
|
445
|
+
if idx != -1 and idx < len(raw_line) - 1:
|
|
446
|
+
suffix = raw_line[idx + 1:].strip()
|
|
447
|
+
if suffix.startswith(";") or suffix.startswith(","):
|
|
448
|
+
trailing = suffix
|
|
449
|
+
if trailing and out:
|
|
450
|
+
out[-1] = out[-1] + trailing
|
|
451
|
+
continue
|
|
452
|
+
|
|
453
|
+
if pending_sel:
|
|
454
|
+
pending_sel.append(raw_line)
|
|
455
|
+
if "{" in clean_line:
|
|
456
|
+
full_sel = " ".join(s.strip() for s in pending_sel)
|
|
457
|
+
brace_idx = raw_line.find("{")
|
|
458
|
+
is_container = any(full_sel.strip().startswith(c) for c in CONTAINER_RULES)
|
|
459
|
+
is_token = any(ts in full_sel for ts in TOKEN_SELECTORS)
|
|
460
|
+
|
|
461
|
+
matched_symbol = False
|
|
462
|
+
if keep_symbols:
|
|
463
|
+
for sym in keep_symbols:
|
|
464
|
+
clean_sym = sym.lstrip(".#")
|
|
465
|
+
if clean_sym and (clean_sym in full_sel or sym in full_sel):
|
|
466
|
+
matched_symbol = True
|
|
467
|
+
break
|
|
468
|
+
|
|
469
|
+
should_keep = is_container or is_token or matched_symbol
|
|
470
|
+
if should_keep:
|
|
471
|
+
out.extend(pending_sel)
|
|
472
|
+
for pl in pending_sel:
|
|
473
|
+
op, cl = lexer.count_braces(pl)
|
|
474
|
+
current_depth += op - cl
|
|
475
|
+
else:
|
|
476
|
+
head = raw_line[:brace_idx] + "{ /* ... */ }"
|
|
477
|
+
if raw_line.rstrip().endswith(";"):
|
|
478
|
+
head += ";"
|
|
479
|
+
pending_sel[-1] = head
|
|
480
|
+
out.extend(pending_sel)
|
|
481
|
+
open_b_head, _ = lexer.count_braces(raw_line[:brace_idx + 1])
|
|
482
|
+
fold_depth = current_depth + open_b_head - 1
|
|
483
|
+
open_b, close_b = lexer.count_braces(raw_line)
|
|
484
|
+
current_depth += open_b - close_b
|
|
485
|
+
if current_depth > fold_depth:
|
|
486
|
+
in_folding = True
|
|
487
|
+
pending_sel = []
|
|
488
|
+
elif ";" in clean_line and "{" not in clean_line:
|
|
489
|
+
out.extend(pending_sel)
|
|
490
|
+
for pl in pending_sel:
|
|
491
|
+
op, cl = lexer.count_braces(pl)
|
|
492
|
+
current_depth += op - cl
|
|
493
|
+
pending_sel = []
|
|
494
|
+
continue
|
|
495
|
+
|
|
496
|
+
if "{" in clean_line:
|
|
497
|
+
is_container = any(clean_line.startswith(c) for c in CONTAINER_RULES)
|
|
498
|
+
is_token = any(ts in clean_line for ts in TOKEN_SELECTORS)
|
|
499
|
+
|
|
500
|
+
matched_symbol = False
|
|
501
|
+
if keep_symbols:
|
|
502
|
+
for sym in keep_symbols:
|
|
503
|
+
clean_sym = sym.lstrip(".#")
|
|
504
|
+
if clean_sym and (clean_sym in clean_line or sym in clean_line):
|
|
505
|
+
matched_symbol = True
|
|
506
|
+
break
|
|
507
|
+
|
|
508
|
+
should_keep = is_container or is_token or matched_symbol
|
|
509
|
+
open_b, close_b = lexer.count_braces(raw_line)
|
|
510
|
+
|
|
511
|
+
if should_keep:
|
|
512
|
+
out.append(raw_line)
|
|
513
|
+
current_depth += open_b - close_b
|
|
514
|
+
else:
|
|
515
|
+
brace_idx = raw_line.find("{")
|
|
516
|
+
folded = raw_line[:brace_idx] + "{ /* ... */ }"
|
|
517
|
+
if raw_line.rstrip().endswith(";"):
|
|
518
|
+
folded += ";"
|
|
519
|
+
out.append(folded)
|
|
520
|
+
open_b_head, _ = lexer.count_braces(raw_line[:brace_idx + 1])
|
|
521
|
+
fold_depth = current_depth + open_b_head - 1
|
|
522
|
+
current_depth += open_b - close_b
|
|
523
|
+
if current_depth > fold_depth:
|
|
524
|
+
in_folding = True
|
|
525
|
+
continue
|
|
526
|
+
|
|
527
|
+
# Closing braces or standalone operators
|
|
528
|
+
if clean_line.startswith("}"):
|
|
529
|
+
out.append(raw_line)
|
|
530
|
+
open_b, close_b = lexer.count_braces(raw_line)
|
|
531
|
+
current_depth += open_b - close_b
|
|
532
|
+
continue
|
|
533
|
+
|
|
534
|
+
if clean_line and not clean_line.endswith(";") and not clean_line.startswith("//") and not clean_line.startswith("/*") and not clean_line.startswith("*"):
|
|
535
|
+
pending_sel = [raw_line]
|
|
536
|
+
continue
|
|
537
|
+
|
|
538
|
+
out.append(raw_line)
|
|
539
|
+
open_b, close_b = lexer.count_braces(raw_line)
|
|
540
|
+
current_depth += open_b - close_b
|
|
541
|
+
|
|
542
|
+
return "\n".join(out)
|
|
543
|
+
|
|
305
544
|
@classmethod
|
|
306
545
|
def get_skeleton_file(cls, original_path: str, target_symbol: Optional[str] = None) -> Tuple[Optional[str], int, int]:
|
|
307
546
|
"""
|
|
@@ -0,0 +1,309 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Telemetry Sync Engine.
|
|
3
|
+
Synchronizes local token optimization metrics from SQLite (data/metrics.db)
|
|
4
|
+
with TokenSafe Cloud Dashboard API.
|
|
5
|
+
|
|
6
|
+
Features:
|
|
7
|
+
- Zero external runtime dependencies (Python standard library only).
|
|
8
|
+
- Offline-safe with fast connection timeout (< 2.5s).
|
|
9
|
+
- Non-blocking asynchronous background sync support.
|
|
10
|
+
- Idempotent tracking of synced event IDs to prevent duplicate counting.
|
|
11
|
+
- Lifetime aggregate preservation for pruned historical events.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
import os
|
|
15
|
+
import sys
|
|
16
|
+
import json
|
|
17
|
+
import time
|
|
18
|
+
import sqlite3
|
|
19
|
+
import threading
|
|
20
|
+
import urllib.request
|
|
21
|
+
import urllib.parse
|
|
22
|
+
import urllib.error
|
|
23
|
+
from datetime import datetime
|
|
24
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
25
|
+
|
|
26
|
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
27
|
+
if PROJECT_ROOT not in sys.path:
|
|
28
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
29
|
+
|
|
30
|
+
from src.license_manager import LicenseManager
|
|
31
|
+
|
|
32
|
+
DATA_DIR = os.path.join(PROJECT_ROOT, "data")
|
|
33
|
+
METRICS_DB_PATH = os.path.join(DATA_DIR, "metrics.db")
|
|
34
|
+
SYNC_STATE_PATH = os.path.join(DATA_DIR, "sync_state.json")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _get_cloud_url() -> str:
|
|
38
|
+
base = os.environ.get("TOKENSAFE_CLOUD_URL")
|
|
39
|
+
if not base:
|
|
40
|
+
base = "https://api.tokensafe.dev"
|
|
41
|
+
return base.rstrip("/")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class TelemetrySync:
|
|
45
|
+
"""Manages secure telemetry synchronization between local metrics and cloud dashboard."""
|
|
46
|
+
|
|
47
|
+
_sync_lock = threading.Lock()
|
|
48
|
+
_last_bg_sync_time = 0.0
|
|
49
|
+
|
|
50
|
+
@classmethod
|
|
51
|
+
def get_state(cls) -> Dict[str, Any]:
|
|
52
|
+
"""Loads sync cursor state from persistent JSON."""
|
|
53
|
+
if not os.path.exists(SYNC_STATE_PATH):
|
|
54
|
+
return {
|
|
55
|
+
"last_synced_event_id": 0,
|
|
56
|
+
"last_synced_at": 0,
|
|
57
|
+
"total_synced_events": 0,
|
|
58
|
+
"lifetime_rollup_synced": False
|
|
59
|
+
}
|
|
60
|
+
try:
|
|
61
|
+
with open(SYNC_STATE_PATH, "r", encoding="utf-8") as f:
|
|
62
|
+
return json.load(f)
|
|
63
|
+
except Exception:
|
|
64
|
+
return {
|
|
65
|
+
"last_synced_event_id": 0,
|
|
66
|
+
"last_synced_at": 0,
|
|
67
|
+
"total_synced_events": 0,
|
|
68
|
+
"lifetime_rollup_synced": False
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
@classmethod
|
|
72
|
+
def save_state(cls, state: Dict[str, Any]):
|
|
73
|
+
"""Persists sync cursor state."""
|
|
74
|
+
os.makedirs(DATA_DIR, exist_ok=True)
|
|
75
|
+
try:
|
|
76
|
+
with open(SYNC_STATE_PATH, "w", encoding="utf-8") as f:
|
|
77
|
+
json.dump(state, f, indent=2)
|
|
78
|
+
except Exception:
|
|
79
|
+
pass
|
|
80
|
+
|
|
81
|
+
@classmethod
|
|
82
|
+
def get_sync_status(cls) -> Dict[str, Any]:
|
|
83
|
+
"""Returns statistics on local events, synced events, and pending sync count."""
|
|
84
|
+
state = cls.get_state()
|
|
85
|
+
last_id = state.get("last_synced_event_id", 0)
|
|
86
|
+
|
|
87
|
+
total_local = 0
|
|
88
|
+
pending = 0
|
|
89
|
+
if os.path.exists(METRICS_DB_PATH):
|
|
90
|
+
try:
|
|
91
|
+
conn = sqlite3.connect(METRICS_DB_PATH)
|
|
92
|
+
c = conn.cursor()
|
|
93
|
+
row = c.execute("SELECT COUNT(*) FROM events").fetchone()
|
|
94
|
+
total_local = row[0] if row else 0
|
|
95
|
+
row_pending = c.execute("SELECT COUNT(*) FROM events WHERE id > ?", (last_id,)).fetchone()
|
|
96
|
+
pending = row_pending[0] if row_pending else 0
|
|
97
|
+
conn.close()
|
|
98
|
+
except Exception:
|
|
99
|
+
pass
|
|
100
|
+
|
|
101
|
+
return {
|
|
102
|
+
"total_local_events": total_local,
|
|
103
|
+
"last_synced_event_id": last_id,
|
|
104
|
+
"pending_events": pending,
|
|
105
|
+
"last_synced_at": state.get("last_synced_at", 0),
|
|
106
|
+
"total_synced_events": state.get("total_synced_events", 0)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
@classmethod
|
|
110
|
+
def sync(
|
|
111
|
+
cls,
|
|
112
|
+
cloud_url: Optional[str] = None,
|
|
113
|
+
license_key: Optional[str] = None,
|
|
114
|
+
email: Optional[str] = None,
|
|
115
|
+
force: bool = False,
|
|
116
|
+
batch_size: int = 500,
|
|
117
|
+
timeout: float = 2.5,
|
|
118
|
+
verbose: bool = False
|
|
119
|
+
) -> Dict[str, Any]:
|
|
120
|
+
"""
|
|
121
|
+
Synchronizes all un-synced events from data/metrics.db to the TokenSafe cloud server.
|
|
122
|
+
Returns a dict with sync results and totals.
|
|
123
|
+
"""
|
|
124
|
+
with cls._sync_lock:
|
|
125
|
+
base_url = (cloud_url or _get_cloud_url()).rstrip("/")
|
|
126
|
+
target_url = f"{base_url}/api/telemetry/sync"
|
|
127
|
+
active_key = license_key or LicenseManager.get_active_license_key()
|
|
128
|
+
|
|
129
|
+
target_email = (email or "").strip().lower()
|
|
130
|
+
if not target_email and active_key:
|
|
131
|
+
_, payload, _ = LicenseManager.validate_license(active_key)
|
|
132
|
+
target_email = payload.get("email", "").strip().lower()
|
|
133
|
+
|
|
134
|
+
# Community fallback: unauthenticated users participate in global token savings
|
|
135
|
+
if not target_email:
|
|
136
|
+
target_email = "community@tokensafe.dev"
|
|
137
|
+
if not active_key:
|
|
138
|
+
active_key = "community"
|
|
139
|
+
|
|
140
|
+
if not os.path.exists(METRICS_DB_PATH):
|
|
141
|
+
return {
|
|
142
|
+
"success": True,
|
|
143
|
+
"synced_events": 0,
|
|
144
|
+
"total_synced": 0,
|
|
145
|
+
"message": "No local metrics database found."
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
state = cls.get_state()
|
|
149
|
+
last_id = 0 if force else state.get("last_synced_event_id", 0)
|
|
150
|
+
|
|
151
|
+
try:
|
|
152
|
+
conn = sqlite3.connect(METRICS_DB_PATH)
|
|
153
|
+
conn.row_factory = sqlite3.Row
|
|
154
|
+
cur = conn.cursor()
|
|
155
|
+
|
|
156
|
+
synthetic_events: List[Dict[str, Any]] = []
|
|
157
|
+
if not state.get("lifetime_rollup_synced", False):
|
|
158
|
+
try:
|
|
159
|
+
life_row = cur.execute("SELECT * FROM lifetime_aggregates WHERE id = 1").fetchone()
|
|
160
|
+
if life_row and life_row["total_saved_tokens"] > 0:
|
|
161
|
+
synthetic_events.append({
|
|
162
|
+
"event_type": "ROLLUP_LIFETIME",
|
|
163
|
+
"original_tokens": int(life_row["total_original_tokens"]),
|
|
164
|
+
"saved_tokens": int(life_row["total_saved_tokens"]),
|
|
165
|
+
"usd_saved": float(life_row["total_usd_saved"]),
|
|
166
|
+
"model": "aggregate",
|
|
167
|
+
"timestamp": int(time.time())
|
|
168
|
+
})
|
|
169
|
+
except Exception:
|
|
170
|
+
pass
|
|
171
|
+
|
|
172
|
+
rows = cur.execute(
|
|
173
|
+
"SELECT id, timestamp, event_type, original_tokens, saved_tokens, est_usd_saved, details "
|
|
174
|
+
"FROM events WHERE id > ? ORDER BY id ASC LIMIT 2000",
|
|
175
|
+
(last_id,)
|
|
176
|
+
).fetchall()
|
|
177
|
+
conn.close()
|
|
178
|
+
except Exception as e:
|
|
179
|
+
return {
|
|
180
|
+
"success": False,
|
|
181
|
+
"synced_events": 0,
|
|
182
|
+
"error": f"Failed to read local metrics database: {str(e)}"
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if not rows and not synthetic_events:
|
|
186
|
+
return {
|
|
187
|
+
"success": True,
|
|
188
|
+
"synced_events": 0,
|
|
189
|
+
"total_synced": state.get("total_synced_events", 0),
|
|
190
|
+
"message": "All metrics are already up to date."
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
formatted_events: List[Dict[str, Any]] = list(synthetic_events)
|
|
194
|
+
max_id = last_id
|
|
195
|
+
|
|
196
|
+
for r in rows:
|
|
197
|
+
ev_id = r["id"]
|
|
198
|
+
if ev_id > max_id:
|
|
199
|
+
max_id = ev_id
|
|
200
|
+
|
|
201
|
+
raw_ts = r["timestamp"]
|
|
202
|
+
ts_int = int(time.time())
|
|
203
|
+
if isinstance(raw_ts, (int, float)):
|
|
204
|
+
ts_int = int(raw_ts)
|
|
205
|
+
elif isinstance(raw_ts, str) and raw_ts.strip():
|
|
206
|
+
try:
|
|
207
|
+
ts_int = int(float(raw_ts.strip()))
|
|
208
|
+
except ValueError:
|
|
209
|
+
try:
|
|
210
|
+
clean_iso = raw_ts.strip().replace("Z", "+00:00")
|
|
211
|
+
dt = datetime.fromisoformat(clean_iso)
|
|
212
|
+
ts_int = int(dt.timestamp())
|
|
213
|
+
except Exception:
|
|
214
|
+
ts_int = int(time.time())
|
|
215
|
+
|
|
216
|
+
model_name = "default"
|
|
217
|
+
if r["details"]:
|
|
218
|
+
try:
|
|
219
|
+
det = json.loads(r["details"]) if isinstance(r["details"], str) else r["details"]
|
|
220
|
+
if isinstance(det, dict) and det.get("model"):
|
|
221
|
+
model_name = str(det["model"])
|
|
222
|
+
except Exception:
|
|
223
|
+
pass
|
|
224
|
+
|
|
225
|
+
formatted_events.append({
|
|
226
|
+
"event_type": str(r["event_type"] or "PROMPT"),
|
|
227
|
+
"original_tokens": int(r["original_tokens"] or 0),
|
|
228
|
+
"saved_tokens": int(r["saved_tokens"] or 0),
|
|
229
|
+
"usd_saved": float(r["est_usd_saved"] or 0.0),
|
|
230
|
+
"model": model_name,
|
|
231
|
+
"timestamp": ts_int
|
|
232
|
+
})
|
|
233
|
+
|
|
234
|
+
total_sent = 0
|
|
235
|
+
headers = {
|
|
236
|
+
"Content-Type": "application/json",
|
|
237
|
+
"User-Agent": "TokenSafe-Sync/1.4.4"
|
|
238
|
+
}
|
|
239
|
+
if active_key:
|
|
240
|
+
headers["Authorization"] = f"Bearer {active_key}"
|
|
241
|
+
|
|
242
|
+
for i in range(0, len(formatted_events), batch_size):
|
|
243
|
+
chunk = formatted_events[i:i + batch_size]
|
|
244
|
+
body_dict = {
|
|
245
|
+
"email": target_email,
|
|
246
|
+
"license_key": active_key,
|
|
247
|
+
"events": chunk
|
|
248
|
+
}
|
|
249
|
+
body_bytes = json.dumps(body_dict).encode("utf-8")
|
|
250
|
+
|
|
251
|
+
req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
|
|
252
|
+
try:
|
|
253
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
254
|
+
if resp.status == 200:
|
|
255
|
+
total_sent += len(chunk)
|
|
256
|
+
else:
|
|
257
|
+
return {
|
|
258
|
+
"success": False,
|
|
259
|
+
"synced_events": total_sent,
|
|
260
|
+
"error": f"Server returned HTTP {resp.status}"
|
|
261
|
+
}
|
|
262
|
+
except urllib.error.HTTPError as he:
|
|
263
|
+
return {
|
|
264
|
+
"success": False,
|
|
265
|
+
"synced_events": total_sent,
|
|
266
|
+
"error": f"Cloud API error: {he.code} {he.reason}"
|
|
267
|
+
}
|
|
268
|
+
except Exception as ex:
|
|
269
|
+
return {
|
|
270
|
+
"success": False,
|
|
271
|
+
"synced_events": total_sent,
|
|
272
|
+
"error": f"Network error during sync: {str(ex)}"
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
new_state = {
|
|
276
|
+
"last_synced_event_id": max_id,
|
|
277
|
+
"last_synced_at": int(time.time()),
|
|
278
|
+
"total_synced_events": state.get("total_synced_events", 0) + total_sent,
|
|
279
|
+
"lifetime_rollup_synced": True
|
|
280
|
+
}
|
|
281
|
+
cls.save_state(new_state)
|
|
282
|
+
|
|
283
|
+
return {
|
|
284
|
+
"success": True,
|
|
285
|
+
"synced_events": total_sent,
|
|
286
|
+
"total_synced": new_state["total_synced_events"],
|
|
287
|
+
"message": f"Successfully synchronized {total_sent:,} events to TokenSafe Cloud."
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
@classmethod
|
|
291
|
+
def sync_background(cls, throttle_seconds: float = 300.0):
|
|
292
|
+
"""
|
|
293
|
+
Spawns a detached, non-blocking daemon thread to sync metrics.
|
|
294
|
+
Throttled to run at most once every `throttle_seconds` (default: 5 minutes).
|
|
295
|
+
"""
|
|
296
|
+
now = time.time()
|
|
297
|
+
if now - cls._last_bg_sync_time < throttle_seconds:
|
|
298
|
+
return
|
|
299
|
+
|
|
300
|
+
cls._last_bg_sync_time = now
|
|
301
|
+
|
|
302
|
+
def _worker():
|
|
303
|
+
try:
|
|
304
|
+
cls.sync(timeout=2.0)
|
|
305
|
+
except Exception:
|
|
306
|
+
pass
|
|
307
|
+
|
|
308
|
+
t = threading.Thread(target=_worker, daemon=True)
|
|
309
|
+
t.start()
|
package/src/version_checker.py
CHANGED
|
@@ -14,7 +14,7 @@ import urllib.request
|
|
|
14
14
|
import urllib.error
|
|
15
15
|
from typing import Dict, Any, Optional, Tuple
|
|
16
16
|
|
|
17
|
-
CURRENT_VERSION = "1.
|
|
17
|
+
CURRENT_VERSION = "1.4.4"
|
|
18
18
|
CACHE_TTL = 86400 # 24 hours
|
|
19
19
|
|
|
20
20
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
@@ -87,6 +87,13 @@ class VersionChecker:
|
|
|
87
87
|
Falls back gracefully on network or offline scenarios.
|
|
88
88
|
"""
|
|
89
89
|
now = int(time.time())
|
|
90
|
+
if not license_key:
|
|
91
|
+
try:
|
|
92
|
+
from src.license_manager import LicenseManager
|
|
93
|
+
license_key = LicenseManager.get_active_license_key()
|
|
94
|
+
except Exception:
|
|
95
|
+
license_key = ""
|
|
96
|
+
|
|
90
97
|
cached = cls.load_cache()
|
|
91
98
|
|
|
92
99
|
if not force_fetch and cached:
|
|
@@ -107,7 +114,9 @@ class VersionChecker:
|
|
|
107
114
|
}
|
|
108
115
|
|
|
109
116
|
try:
|
|
110
|
-
|
|
117
|
+
import platform as _plat
|
|
118
|
+
plat_str = f"{_plat.system().lower()}-{_plat.machine().lower()}"
|
|
119
|
+
params = f"?version={urllib.parse.quote(current_version)}&license={urllib.parse.quote(license_key)}&platform={urllib.parse.quote(plat_str)}&client_type=cli"
|
|
111
120
|
url = f"{CLOUD_CHECK_URL}{params}"
|
|
112
121
|
req = urllib.request.Request(
|
|
113
122
|
url,
|
|
Binary file
|