tokensafe 1.4.13 → 1.4.14
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 +24 -2
- package/bin/tokensafe.js +11 -1
- package/hooks/pre_invocation.py +1 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/src/command_sanitizer.py +42 -3
- package/src/compactor.py +3 -1
- package/src/deepseek_distiller.py +1 -1
- package/src/distiller.py +52 -1
- package/src/graph_engine.py +4 -1
- package/src/guard.py +54 -17
- package/src/installer.py +108 -1
- package/src/license_manager.py +39 -2
- package/src/loop_detector.py +73 -26
- package/src/mcp_server.py +58 -4
- package/src/metrics.py +46 -15
- package/src/skeletonizer.py +73 -10
- package/src/slicer.py +16 -6
- package/src/telemetry_sync.py +62 -12
- package/src/tokenizer.py +12 -3
- package/src/version_checker.py +20 -8
package/README.md
CHANGED
|
@@ -46,6 +46,26 @@ pip install tokensafe && tokensafe
|
|
|
46
46
|
curl -fsSL https://tokensafe.dev/install.sh | bash
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
+
### Optional dependency: `cryptography` (recommended)
|
|
50
|
+
|
|
51
|
+
The TokenSafe engine itself is **standard-library only** and works out of the box.
|
|
52
|
+
A single optional dependency — [`cryptography`](https://pypi.org/project/cryptography/) —
|
|
53
|
+
is installed automatically by `install.sh` / `requirements.txt` when available:
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
pip install cryptography # or: brew install cryptography
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
| Component | With `cryptography` | Without (pure-stdlib fallback) |
|
|
60
|
+
|---|---|---|
|
|
61
|
+
| Client: license verification | Instant Ed25519 fast-path | Pure-Python Ed25519 (~0.3s once, then cached — see below) |
|
|
62
|
+
| Client: everything else | Identical | Identical |
|
|
63
|
+
| Cloud backend: Clerk session tokens | RS256 signature verified | **Rejected** (fail-closed — unsigned tokens are never accepted) |
|
|
64
|
+
| Cloud backend: everything else | Identical | Identical |
|
|
65
|
+
|
|
66
|
+
The client caches a successful license verification for up to 1 hour, so even the
|
|
67
|
+
pure-Python path adds no measurable latency after the first hook invocation.
|
|
68
|
+
|
|
49
69
|
---
|
|
50
70
|
|
|
51
71
|
## 🔌 Universal MCP Server Configuration
|
|
@@ -500,7 +520,9 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
|
|
|
500
520
|
| `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `nekosin4eg@gmail.com`). |
|
|
501
521
|
| `STRIPE_WEBHOOK_SECRET` | Production | Webhook secret (`whsec_...`) used to verify Stripe webhooks. |
|
|
502
522
|
| `SMTP_PASS` | Production | Password/token for transactional mail delivery via ImprovMX SMTP. |
|
|
503
|
-
| `JWT_SECRET` | Optional | Shared HMAC secret for verifying custom JWT tokens. |
|
|
523
|
+
| `JWT_SECRET` | Optional | Shared HMAC secret for verifying custom JWT tokens. Set a persistent value in production — otherwise sessions invalidate on every restart. |
|
|
524
|
+
| `CLERK_JWT_KEY` | Production (web) | Clerk public key (PEM) or HMAC key for verifying Clerk session tokens. Without it — or without the `cryptography` package — Clerk tokens are rejected (fail-closed). |
|
|
525
|
+
| `TOKENSAFE_TELEMETRY_DISABLED` | Optional | Set to `1` to fully disable cloud telemetry sync (privacy / offline / CI). |
|
|
504
526
|
|
|
505
527
|
|
|
506
528
|
---
|
|
@@ -510,7 +532,7 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
|
|
|
510
532
|
```bash
|
|
511
533
|
python3 -m unittest discover tests
|
|
512
534
|
```
|
|
513
|
-
*Zero
|
|
535
|
+
*Zero mandatory runtime dependencies — runs on standard Python 3.10+. The optional `cryptography` package (`requirements.txt`) accelerates Ed25519 license verification and enables fail-closed RS256 Clerk verification on the cloud backend.*
|
|
514
536
|
|
|
515
537
|
---
|
|
516
538
|
|
package/bin/tokensafe.js
CHANGED
|
@@ -22,7 +22,12 @@ function findPython() {
|
|
|
22
22
|
stdio: 'pipe'
|
|
23
23
|
});
|
|
24
24
|
if (res.status === 0) return cmd;
|
|
25
|
-
|
|
25
|
+
if (res.error && res.error.code !== 'ENOENT') {
|
|
26
|
+
console.error(`TokenSafe: python probe for '${cmd}' failed: ${res.error.message}`);
|
|
27
|
+
}
|
|
28
|
+
} catch (err) {
|
|
29
|
+
console.error(`TokenSafe: python probe for '${cmd}' threw: ${err.message}`);
|
|
30
|
+
}
|
|
26
31
|
}
|
|
27
32
|
return null;
|
|
28
33
|
}
|
|
@@ -89,6 +94,11 @@ const child = spawn(python, [scriptPath, ...scriptArgs], {
|
|
|
89
94
|
}
|
|
90
95
|
});
|
|
91
96
|
|
|
97
|
+
child.on('error', (err) => {
|
|
98
|
+
console.error(`TokenSafe: failed to launch Python CLI: ${err.message}`);
|
|
99
|
+
process.exit(1);
|
|
100
|
+
});
|
|
101
|
+
|
|
92
102
|
child.on('exit', (code, signal) => {
|
|
93
103
|
if (signal) {
|
|
94
104
|
process.kill(process.pid, signal);
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -125,6 +125,7 @@ def main():
|
|
|
125
125
|
})
|
|
126
126
|
|
|
127
127
|
# 2. Multi-turn History Compaction (Paused when community quota is exceeded)
|
|
128
|
+
folded_text = None
|
|
128
129
|
if not quota.get("is_quota_exceeded", False) and invocation_num >= 3 and transcript_path:
|
|
129
130
|
folded_text, orig_hist_tokens, folded_tokens, stats = HistoryCompactor.fold_transcript(
|
|
130
131
|
transcript_path, invocation_num
|
package/package.json
CHANGED
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.14",
|
|
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/src/command_sanitizer.py
CHANGED
|
@@ -5,11 +5,50 @@ and verbose test output.
|
|
|
5
5
|
"""
|
|
6
6
|
|
|
7
7
|
import re
|
|
8
|
-
from typing import Tuple, Dict, Any, Optional
|
|
8
|
+
from typing import Tuple, Dict, Any, List, Optional
|
|
9
9
|
|
|
10
10
|
class CommandSanitizer:
|
|
11
11
|
"""Optimizes terminal command lines to eliminate token waste."""
|
|
12
12
|
|
|
13
|
+
@staticmethod
|
|
14
|
+
def _split_pipeline_stages(cmd: str) -> List[str]:
|
|
15
|
+
"""
|
|
16
|
+
Splits a shell command on single '|' pipe operators while respecting
|
|
17
|
+
quoting ('...', "...", `...`) and '||' logical OR, so regex patterns like
|
|
18
|
+
grep "foo|bar" are never torn apart mid-string.
|
|
19
|
+
"""
|
|
20
|
+
stages: List[str] = []
|
|
21
|
+
buf: List[str] = []
|
|
22
|
+
quote = ""
|
|
23
|
+
i = 0
|
|
24
|
+
n = len(cmd)
|
|
25
|
+
while i < n:
|
|
26
|
+
ch = cmd[i]
|
|
27
|
+
if quote:
|
|
28
|
+
if ch == "\\" and quote != "`" and i + 1 < n:
|
|
29
|
+
buf.append(ch)
|
|
30
|
+
buf.append(cmd[i + 1])
|
|
31
|
+
i += 2
|
|
32
|
+
continue
|
|
33
|
+
if ch == quote:
|
|
34
|
+
quote = ""
|
|
35
|
+
buf.append(ch)
|
|
36
|
+
elif ch in ("'", '"', "`"):
|
|
37
|
+
quote = ch
|
|
38
|
+
buf.append(ch)
|
|
39
|
+
elif ch == "|":
|
|
40
|
+
if i + 1 < n and cmd[i + 1] == "|":
|
|
41
|
+
buf.append("||")
|
|
42
|
+
i += 2
|
|
43
|
+
continue
|
|
44
|
+
stages.append("".join(buf))
|
|
45
|
+
buf = []
|
|
46
|
+
else:
|
|
47
|
+
buf.append(ch)
|
|
48
|
+
i += 1
|
|
49
|
+
stages.append("".join(buf))
|
|
50
|
+
return [s for s in (st.strip() for st in stages) if s]
|
|
51
|
+
|
|
13
52
|
# Lockfiles and binary patterns that should never be dumped in git diffs or searches
|
|
14
53
|
LOCKFILE_EXCLUDES = [
|
|
15
54
|
"':!package-lock.json'",
|
|
@@ -88,7 +127,7 @@ class CommandSanitizer:
|
|
|
88
127
|
if re.search(r"\bgit\b.*?\bgrep\b", cmd):
|
|
89
128
|
if ":!*.lock" not in cmd and ":!bun.lock" not in cmd:
|
|
90
129
|
git_excludes = "':!*.lock' ':!bun.lock' ':!bun.lockb' ':!package-lock.json' ':!dist' ':!build' ':!node_modules'"
|
|
91
|
-
stages =
|
|
130
|
+
stages = cls._split_pipeline_stages(cmd)
|
|
92
131
|
for i, stage in enumerate(stages):
|
|
93
132
|
if re.search(r"\bgit\b.*?\bgrep\b", stage):
|
|
94
133
|
if "||" in stage:
|
|
@@ -115,7 +154,7 @@ class CommandSanitizer:
|
|
|
115
154
|
is_recursive = bool(re.search(r"\b(grep|egrep)\b.*?\s-[a-zA-Z]*[rR]", cmd))
|
|
116
155
|
if is_recursive and "--exclude-dir" not in cmd and "node_modules" not in cmd:
|
|
117
156
|
excludes = "--exclude='*.lock' --exclude='*.lockb' --exclude-dir={dist,build,node_modules,.git,coverage,__pycache__,.next,data}"
|
|
118
|
-
stages =
|
|
157
|
+
stages = cls._split_pipeline_stages(cmd)
|
|
119
158
|
for i, stage in enumerate(stages):
|
|
120
159
|
if re.search(r"\b(grep|egrep)\b", stage):
|
|
121
160
|
stages[i] = f"{stage} {excludes}"
|
package/src/compactor.py
CHANGED
|
@@ -80,7 +80,9 @@ class PromptCompactor:
|
|
|
80
80
|
r"\b(как думаешь|как считаешь|по твоему мнению|в чем проблема|почему|почему падает|не работает)\b",
|
|
81
81
|
r"\b(в файле|из файла|внутри файла|файле|файл|функцию|функция|функции|метод|методе|метода|класс|классе|класса|код|кода|строку|строка|проект|проекта|проекте|описани\w*|пояснени\w*|информаци\w*|баз\w*\s+данных|баз[аеуоы]|бд|database)\b",
|
|
82
82
|
r"\b(добавь туда|сделай её|сделай его|сделай их|чтобы было|чтобы он|чтобы она|чтобы оно|для этого|для того чтобы)\b",
|
|
83
|
-
|
|
83
|
+
# Note: «не» (negation) is deliberately NOT stripped — removing it inverted
|
|
84
|
+
# the meaning of prompts like "не удаляй файл" ("do not delete the file").
|
|
85
|
+
r"\b(и|в|на|с|при|по|к|из|у|о|об|от|под|над|для|бы|ли|же|то|это|этот|эта|эти|он|она|оно|они|ему|ей|им|их|его|ее)\b",
|
|
84
86
|
|
|
85
87
|
# Chinese (中文)
|
|
86
88
|
r"(请|麻烦|谢谢|多谢|你好|您好|早上好|晚上好)",
|
|
@@ -18,7 +18,7 @@ class DeepSeekDistiller:
|
|
|
18
18
|
|
|
19
19
|
DEFAULT_URL = "https://api.deepseek.com/chat/completions"
|
|
20
20
|
DEFAULT_MODEL = "deepseek-flash"
|
|
21
|
-
DEFAULT_TIMEOUT =
|
|
21
|
+
DEFAULT_TIMEOUT = 2.5
|
|
22
22
|
|
|
23
23
|
SYSTEM_PROMPT = """You are a multilingual semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
|
|
24
24
|
(ACTION [filepath] [symbol] [[traits...]] ["minimal_intent"])
|
package/src/distiller.py
CHANGED
|
@@ -8,6 +8,7 @@ Implemented with pure standard-library urllib (zero dependencies, strict timeout
|
|
|
8
8
|
import os
|
|
9
9
|
import json
|
|
10
10
|
import re
|
|
11
|
+
import time
|
|
11
12
|
import urllib.request
|
|
12
13
|
import urllib.error
|
|
13
14
|
from typing import Optional, Dict, Any, Tuple
|
|
@@ -17,7 +18,46 @@ from src.license_manager import LicenseManager
|
|
|
17
18
|
class UniversalDistiller:
|
|
18
19
|
"""Multi-provider semantic intent compiler supporting DeepSeek, OpenAI, and Google Gemini."""
|
|
19
20
|
|
|
20
|
-
DEFAULT_TIMEOUT =
|
|
21
|
+
DEFAULT_TIMEOUT = 2.5
|
|
22
|
+
# After a failed roundtrip, skip all remote distillation for this long.
|
|
23
|
+
# distill() runs synchronously inside the PreInvocation lifecycle hook, so a
|
|
24
|
+
# dead/slow provider must not add seconds of latency to every single prompt.
|
|
25
|
+
FAILURE_COOLDOWN_SECONDS = 180.0
|
|
26
|
+
|
|
27
|
+
@classmethod
|
|
28
|
+
def _failure_state_path(cls) -> str:
|
|
29
|
+
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
30
|
+
data_dir = os.environ.get("TOKENSAFE_DATA_DIR", os.path.join(base_dir, "data"))
|
|
31
|
+
return os.path.join(data_dir, "distill_failure_state.json")
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def _cooldown_active(cls) -> bool:
|
|
35
|
+
"""True when a recent provider failure put distillation into cooldown."""
|
|
36
|
+
try:
|
|
37
|
+
with open(cls._failure_state_path(), "r", encoding="utf-8") as f:
|
|
38
|
+
state = json.load(f)
|
|
39
|
+
return (time.time() - float(state.get("last_failure_ts", 0.0))) < cls.FAILURE_COOLDOWN_SECONDS
|
|
40
|
+
except Exception:
|
|
41
|
+
return False
|
|
42
|
+
|
|
43
|
+
@classmethod
|
|
44
|
+
def _record_failure(cls):
|
|
45
|
+
try:
|
|
46
|
+
path = cls._failure_state_path()
|
|
47
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
48
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
49
|
+
json.dump({"last_failure_ts": time.time()}, f)
|
|
50
|
+
except Exception:
|
|
51
|
+
pass
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def _clear_failure(cls):
|
|
55
|
+
try:
|
|
56
|
+
path = cls._failure_state_path()
|
|
57
|
+
if os.path.exists(path):
|
|
58
|
+
os.remove(path)
|
|
59
|
+
except Exception:
|
|
60
|
+
pass
|
|
21
61
|
|
|
22
62
|
SYSTEM_PROMPT = """You are a multilingual semantic code intent compiler for the Token-Optimized Communication Protocol (TOCP). Your task is to compress verbose, conversational developer requests into an ultra-dense S-Expression with this exact syntax:
|
|
23
63
|
(ACTION [filepath] [symbol] [[traits...]] ["minimal_intent"])
|
|
@@ -162,6 +202,11 @@ Rules:
|
|
|
162
202
|
if cached:
|
|
163
203
|
return cached
|
|
164
204
|
|
|
205
|
+
# Circuit breaker: a recent provider failure suspends remote roundtrips so a
|
|
206
|
+
# dead endpoint cannot add seconds of latency to every prompt invocation.
|
|
207
|
+
if cls._cooldown_active():
|
|
208
|
+
return None
|
|
209
|
+
|
|
165
210
|
providers = cls.get_configured_providers()
|
|
166
211
|
if not providers:
|
|
167
212
|
return None
|
|
@@ -185,7 +230,10 @@ Rules:
|
|
|
185
230
|
clean = cls._sanitize_s_expression(cloud_res)
|
|
186
231
|
if clean:
|
|
187
232
|
DistillationCache.set(raw_text, clean, provider="cloud-managed")
|
|
233
|
+
cls._clear_failure()
|
|
188
234
|
return clean
|
|
235
|
+
# Failure (network/timeout/invalid shape): trip the cooldown breaker
|
|
236
|
+
cls._record_failure()
|
|
189
237
|
return None
|
|
190
238
|
|
|
191
239
|
# 2. Self-Hosted Docker Mode (BYOK local providers)
|
|
@@ -222,10 +270,13 @@ Rules:
|
|
|
222
270
|
clean = cls._sanitize_s_expression(result)
|
|
223
271
|
if clean:
|
|
224
272
|
DistillationCache.set(raw_text, clean, provider=p_key)
|
|
273
|
+
cls._clear_failure()
|
|
225
274
|
return clean
|
|
226
275
|
except Exception:
|
|
227
276
|
continue
|
|
228
277
|
|
|
278
|
+
# All providers failed: trip the cooldown breaker
|
|
279
|
+
cls._record_failure()
|
|
229
280
|
return None
|
|
230
281
|
|
|
231
282
|
@classmethod
|
package/src/graph_engine.py
CHANGED
|
@@ -438,13 +438,16 @@ class GraphEngine:
|
|
|
438
438
|
@classmethod
|
|
439
439
|
def get_instance(cls, root_dir: str = ".") -> CodeGraph:
|
|
440
440
|
root_abs = os.path.abspath(root_dir)
|
|
441
|
+
# Rescans are full AST crawls; a 3s TTL caused near-constant rescans on every
|
|
442
|
+
# smart_read_file(symbol=...) call. 60s keeps graphs fresh without the churn.
|
|
443
|
+
rescan_ttl = float(os.environ.get("TOKENSAFE_GRAPH_TTL", "60.0"))
|
|
441
444
|
if root_abs not in cls._instances:
|
|
442
445
|
graph = CodeGraph(root_abs)
|
|
443
446
|
graph.scan()
|
|
444
447
|
cls._instances[root_abs] = graph
|
|
445
448
|
else:
|
|
446
449
|
graph = cls._instances[root_abs]
|
|
447
|
-
if time.time() - graph.last_scanned >
|
|
450
|
+
if time.time() - graph.last_scanned > rescan_ttl:
|
|
448
451
|
graph.scan()
|
|
449
452
|
return graph
|
|
450
453
|
|
package/src/guard.py
CHANGED
|
@@ -14,6 +14,7 @@ Protects local workspaces and repository integrity by intercepting dangerous ope
|
|
|
14
14
|
import os
|
|
15
15
|
import re
|
|
16
16
|
import fnmatch
|
|
17
|
+
import subprocess
|
|
17
18
|
from typing import Tuple, Optional, Dict, Any, List, NamedTuple
|
|
18
19
|
from src.secret_redactor import SecretRedactor
|
|
19
20
|
|
|
@@ -237,23 +238,17 @@ class TokenSafeGuard:
|
|
|
237
238
|
# Catch blanket 'git add .' or 'git add -A' when sensitive files exist in directory
|
|
238
239
|
if re.search(r"""\bgit\s+(?:add\s+(?:\.|\-A|\*)|commit\s+-[a-zA-Z]*a)""", cmd):
|
|
239
240
|
target_dir = cwd or os.getcwd()
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
reason=(
|
|
252
|
-
f"Blocked blanket git staging: '{cmd}'. "
|
|
253
|
-
f"Unignored sensitive file '{rel_path}' detected in working tree. "
|
|
254
|
-
f"Add '{rel_path}' to .gitignore or stage files explicitly to prevent credential leaks into git."
|
|
255
|
-
)
|
|
256
|
-
)
|
|
241
|
+
sensitive = cls._find_unignored_sensitive_file(target_dir)
|
|
242
|
+
if sensitive:
|
|
243
|
+
return GuardResult(
|
|
244
|
+
blocked=True,
|
|
245
|
+
check_name="GIT_SECRET_STAGING",
|
|
246
|
+
reason=(
|
|
247
|
+
f"Blocked blanket git staging: '{cmd}'. "
|
|
248
|
+
f"Unignored sensitive file '{sensitive}' detected in working tree. "
|
|
249
|
+
f"Add '{sensitive}' to .gitignore or stage files explicitly to prevent credential leaks into git."
|
|
250
|
+
)
|
|
251
|
+
)
|
|
257
252
|
|
|
258
253
|
# 3. Network Data Exfiltration Prevention (piping secrets to curl/wget)
|
|
259
254
|
exfil_pattern = re.search(
|
|
@@ -363,6 +358,48 @@ class TokenSafeGuard:
|
|
|
363
358
|
|
|
364
359
|
return None
|
|
365
360
|
|
|
361
|
+
@classmethod
|
|
362
|
+
def _find_unignored_sensitive_file(cls, target_dir: str) -> Optional[str]:
|
|
363
|
+
"""
|
|
364
|
+
Returns the repo-relative path of the first unignored sensitive file, or None.
|
|
365
|
+
Prefers `git status --porcelain -uall` (exact .gitignore semantics incl.
|
|
366
|
+
negation and nested ignore files) over crawling the tree with os.walk,
|
|
367
|
+
which was both slow on large repos and inaccurate about ignore rules.
|
|
368
|
+
"""
|
|
369
|
+
def _is_sensitive_name(name: str) -> bool:
|
|
370
|
+
return name in cls.SENSITIVE_GIT_FILES or (name.startswith(".env") and not name.endswith(".example"))
|
|
371
|
+
|
|
372
|
+
# 1. Fast & exact: ask git itself (only lists non-ignored files).
|
|
373
|
+
try:
|
|
374
|
+
res = subprocess.run(
|
|
375
|
+
["git", "-C", target_dir, "status", "--porcelain", "-uall"],
|
|
376
|
+
capture_output=True, text=True, timeout=5
|
|
377
|
+
)
|
|
378
|
+
if res.returncode == 0:
|
|
379
|
+
for line in res.stdout.splitlines():
|
|
380
|
+
# Format: "XY PATH" (path may be quoted; renames use "old -> new")
|
|
381
|
+
path_part = line[3:].strip() if len(line) > 3 else ""
|
|
382
|
+
if path_part.startswith('"') and path_part.endswith('"'):
|
|
383
|
+
path_part = path_part[1:-1]
|
|
384
|
+
for candidate in (seg.strip() for seg in path_part.split("->")):
|
|
385
|
+
if candidate and _is_sensitive_name(os.path.basename(candidate)):
|
|
386
|
+
return candidate
|
|
387
|
+
return None
|
|
388
|
+
except Exception:
|
|
389
|
+
pass
|
|
390
|
+
|
|
391
|
+
# 2. Fallback: bounded manual walk with naive gitignore matching.
|
|
392
|
+
for root, dirs, files in os.walk(target_dir):
|
|
393
|
+
# Prune common heavy/inert subtrees
|
|
394
|
+
dirs[:] = [d for d in dirs if d not in (".git", "node_modules", ".venv", "venv", "__pycache__", "dist", "build", ".next", ".turbo")]
|
|
395
|
+
for f in files:
|
|
396
|
+
if _is_sensitive_name(f):
|
|
397
|
+
full = os.path.join(root, f)
|
|
398
|
+
rel_path = os.path.relpath(full, target_dir)
|
|
399
|
+
if not cls._is_git_ignored(full, target_dir):
|
|
400
|
+
return rel_path
|
|
401
|
+
return None
|
|
402
|
+
|
|
366
403
|
@classmethod
|
|
367
404
|
def _is_git_ignored(cls, file_path: str, repo_root: str) -> bool:
|
|
368
405
|
"""Checks if a file is covered by .gitignore in the repository."""
|
package/src/installer.py
CHANGED
|
@@ -15,7 +15,10 @@ import sys
|
|
|
15
15
|
import json
|
|
16
16
|
import shutil
|
|
17
17
|
import re
|
|
18
|
+
import shlex
|
|
19
|
+
import signal
|
|
18
20
|
import subprocess
|
|
21
|
+
import time
|
|
19
22
|
from typing import Dict, List, Any, Optional, Tuple
|
|
20
23
|
|
|
21
24
|
RESET = "\033[0m"
|
|
@@ -542,6 +545,104 @@ class AgentInstaller:
|
|
|
542
545
|
print(f"\n\033[32m\033[1m✅ TokenSafe successfully connected to {installed_count} agent(s)!\033[0m")
|
|
543
546
|
print(" Restart your IDE / Agent to start saving tokens automatically.\n")
|
|
544
547
|
|
|
548
|
+
@staticmethod
|
|
549
|
+
def _is_tokensafe_mcp_command(cmd: str) -> bool:
|
|
550
|
+
"""Returns True if a process command line represents a running TokenSafe MCP server daemon."""
|
|
551
|
+
if not cmd or not cmd.strip():
|
|
552
|
+
return False
|
|
553
|
+
try:
|
|
554
|
+
tokens = shlex.split(cmd)
|
|
555
|
+
except ValueError:
|
|
556
|
+
tokens = cmd.split()
|
|
557
|
+
if not tokens:
|
|
558
|
+
return False
|
|
559
|
+
|
|
560
|
+
# Ignore shell wrappers or inline python -c inspection commands
|
|
561
|
+
exe_base = os.path.basename(tokens[0]).lower()
|
|
562
|
+
if exe_base in ("sh", "bash", "zsh", "fish", "dash") and "-c" in tokens:
|
|
563
|
+
return False
|
|
564
|
+
if exe_base.startswith("python") and "-c" in tokens:
|
|
565
|
+
return False
|
|
566
|
+
|
|
567
|
+
for idx, tok in enumerate(tokens):
|
|
568
|
+
base = os.path.basename(tok).lower()
|
|
569
|
+
if base == "mcp_server.py" and ("tokensafe" in tok.lower() or "agy-token-optimizer" in tok.lower() or "src/mcp_server.py" in tok.replace("\\", "/")):
|
|
570
|
+
return True
|
|
571
|
+
if base in ("tokensafe", "tokensafe.js", "agy-tokens"):
|
|
572
|
+
rest = tokens[idx + 1:]
|
|
573
|
+
if rest and rest[0] == "mcp":
|
|
574
|
+
subcmd = rest[1] if len(rest) > 1 else "serve"
|
|
575
|
+
if subcmd not in ("disable", "off", "rm", "enable", "on", "add", "list", "ls", "status"):
|
|
576
|
+
return True
|
|
577
|
+
return False
|
|
578
|
+
|
|
579
|
+
@classmethod
|
|
580
|
+
def restart_mcp_daemons(cls) -> int:
|
|
581
|
+
"""
|
|
582
|
+
Touches the MCP reload marker and terminates active TokenSafe MCP server daemons
|
|
583
|
+
so auto-reconnecting IDEs (Antigravity, Cursor, Claude Code) spawn the updated version.
|
|
584
|
+
"""
|
|
585
|
+
try:
|
|
586
|
+
data_dir = os.path.join(PROJECT_ROOT, "data")
|
|
587
|
+
os.makedirs(data_dir, exist_ok=True)
|
|
588
|
+
reload_marker = os.path.join(data_dir, ".mcp_reload")
|
|
589
|
+
with open(reload_marker, "w", encoding="utf-8") as f:
|
|
590
|
+
f.write(str(time.time()))
|
|
591
|
+
except Exception:
|
|
592
|
+
pass
|
|
593
|
+
|
|
594
|
+
if os.name == "nt":
|
|
595
|
+
return 0
|
|
596
|
+
|
|
597
|
+
my_pid = os.getpid()
|
|
598
|
+
parent_pid = os.getppid()
|
|
599
|
+
target_pids: List[int] = []
|
|
600
|
+
|
|
601
|
+
try:
|
|
602
|
+
res = subprocess.run(
|
|
603
|
+
["ps", "-ax", "-o", "pid=,command="],
|
|
604
|
+
capture_output=True,
|
|
605
|
+
text=True,
|
|
606
|
+
timeout=3
|
|
607
|
+
)
|
|
608
|
+
if res.returncode == 0:
|
|
609
|
+
for line in res.stdout.splitlines():
|
|
610
|
+
line = line.strip()
|
|
611
|
+
if not line:
|
|
612
|
+
continue
|
|
613
|
+
parts = line.split(None, 1)
|
|
614
|
+
if len(parts) < 2:
|
|
615
|
+
continue
|
|
616
|
+
try:
|
|
617
|
+
pid = int(parts[0])
|
|
618
|
+
except ValueError:
|
|
619
|
+
continue
|
|
620
|
+
if pid in (my_pid, parent_pid) or pid <= 1:
|
|
621
|
+
continue
|
|
622
|
+
if cls._is_tokensafe_mcp_command(parts[1]):
|
|
623
|
+
target_pids.append(pid)
|
|
624
|
+
except Exception:
|
|
625
|
+
return 0
|
|
626
|
+
|
|
627
|
+
restarted = 0
|
|
628
|
+
for pid in target_pids:
|
|
629
|
+
try:
|
|
630
|
+
os.kill(pid, signal.SIGTERM)
|
|
631
|
+
restarted += 1
|
|
632
|
+
except (ProcessLookupError, PermissionError, OSError):
|
|
633
|
+
continue
|
|
634
|
+
|
|
635
|
+
if restarted > 0:
|
|
636
|
+
time.sleep(0.2)
|
|
637
|
+
for pid in target_pids:
|
|
638
|
+
try:
|
|
639
|
+
os.kill(pid, 0)
|
|
640
|
+
os.kill(pid, signal.SIGKILL)
|
|
641
|
+
except (ProcessLookupError, PermissionError, OSError):
|
|
642
|
+
pass
|
|
643
|
+
|
|
644
|
+
return restarted
|
|
645
|
+
|
|
545
646
|
@classmethod
|
|
546
647
|
def self_update(cls):
|
|
547
648
|
"""
|
|
@@ -549,7 +650,7 @@ class AgentInstaller:
|
|
|
549
650
|
1. Detects package installation source (git, npm, pip).
|
|
550
651
|
2. Upgrades TokenSafe engine to latest release.
|
|
551
652
|
3. Re-synchronizes MCP configs and rules for all active agents.
|
|
552
|
-
4. Refreshes local version cache.
|
|
653
|
+
4. Refreshes local version cache and restarts running MCP daemons.
|
|
553
654
|
"""
|
|
554
655
|
print(f"\n{BOLD}{CYAN}╔════════════════════════════════════════════════════════════════════╗{RESET}")
|
|
555
656
|
print(f"{BOLD}{CYAN}║ ⚡ TOKENSAFE ONE-CLICK SELF-UPDATE ⚡ ║{RESET}")
|
|
@@ -613,6 +714,12 @@ class AgentInstaller:
|
|
|
613
714
|
except Exception:
|
|
614
715
|
pass
|
|
615
716
|
|
|
717
|
+
# 6. Restart running MCP server daemons so IDEs load the new version
|
|
718
|
+
restarted_count = cls.restart_mcp_daemons()
|
|
719
|
+
if restarted_count > 0:
|
|
720
|
+
print(f" {GREEN}✔{RESET} Restarted {restarted_count} running TokenSafe MCP daemon(s).")
|
|
721
|
+
print(f" {CYAN}ℹ{RESET} Antigravity/Cursor/Claude Code reconnect automatically; reload MCP in Claude Desktop/VS Code if disconnected.")
|
|
722
|
+
|
|
616
723
|
print(f"\n{BOLD}{GREEN}✅ Self-update complete!{RESET}")
|
|
617
724
|
print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
|
|
618
725
|
print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.\n")
|
package/src/license_manager.py
CHANGED
|
@@ -11,6 +11,7 @@ import time
|
|
|
11
11
|
import hmac
|
|
12
12
|
import hashlib
|
|
13
13
|
import base64
|
|
14
|
+
import threading
|
|
14
15
|
from typing import Dict, Any, Tuple, Optional
|
|
15
16
|
|
|
16
17
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
@@ -132,6 +133,15 @@ def _ed25519_verify_bytes(sig: bytes, msg: bytes, pub_bytes: bytes) -> bool:
|
|
|
132
133
|
class LicenseManager:
|
|
133
134
|
"""Manages TokenSafe subscription tiers, offline signature verification, and 7-day trials."""
|
|
134
135
|
|
|
136
|
+
# Successful signature verifications are cached per license key (thread-safe).
|
|
137
|
+
# Rationale: the pure-Python Ed25519 fallback path costs ~0.6s per verification and
|
|
138
|
+
# validate_license() runs on every lifecycle hook invocation (check_quota). The cache
|
|
139
|
+
# TTL never outlives the license's own expiry window.
|
|
140
|
+
_VALIDATION_CACHE: Dict[str, Tuple[Dict[str, Any], float]] = {}
|
|
141
|
+
_VALIDATION_CACHE_LOCK = threading.Lock()
|
|
142
|
+
_VALIDATION_CACHE_TTL = 3600.0 # 1 hour
|
|
143
|
+
_VALIDATION_CACHE_MAX = 64
|
|
144
|
+
|
|
135
145
|
TIERS = {
|
|
136
146
|
"free": {"max_tokens_monthly": 500_000, "deepseek_cloud": False, "team_analytics": False},
|
|
137
147
|
"solo": {"max_tokens_monthly": None, "deepseek_cloud": True, "team_analytics": False},
|
|
@@ -147,7 +157,9 @@ class LicenseManager:
|
|
|
147
157
|
duration_days: int = 30,
|
|
148
158
|
signing_key: Optional[str] = None,
|
|
149
159
|
is_trial: bool = False,
|
|
150
|
-
version: int = 2
|
|
160
|
+
version: int = 2,
|
|
161
|
+
org_id: Optional[str] = None,
|
|
162
|
+
jti: Optional[str] = None
|
|
151
163
|
) -> str:
|
|
152
164
|
"""
|
|
153
165
|
Generates a tamper-proof cryptographically signed license key.
|
|
@@ -157,7 +169,7 @@ class LicenseManager:
|
|
|
157
169
|
now = int(time.time())
|
|
158
170
|
expires_at = 0 if duration_days == 0 else now + (duration_days * 86400)
|
|
159
171
|
|
|
160
|
-
payload = {
|
|
172
|
+
payload: Dict[str, Any] = {
|
|
161
173
|
"tier": tier.lower(),
|
|
162
174
|
"email": email.strip().lower(),
|
|
163
175
|
"issued_at": now,
|
|
@@ -165,6 +177,10 @@ class LicenseManager:
|
|
|
165
177
|
"trial": is_trial,
|
|
166
178
|
"v": version
|
|
167
179
|
}
|
|
180
|
+
if org_id:
|
|
181
|
+
payload["org"] = org_id.strip()
|
|
182
|
+
if jti:
|
|
183
|
+
payload["jti"] = jti.strip()
|
|
168
184
|
|
|
169
185
|
payload_bytes = json.dumps(payload, sort_keys=True, separators=(',', ':')).encode("utf-8")
|
|
170
186
|
payload_b64 = base64.urlsafe_b64encode(payload_bytes).decode("ascii").rstrip("=")
|
|
@@ -202,6 +218,16 @@ class LicenseManager:
|
|
|
202
218
|
return False, {}, "Empty license key"
|
|
203
219
|
|
|
204
220
|
license_key = license_key.strip()
|
|
221
|
+
|
|
222
|
+
# Fast path: recently verified signature (avoids ~0.6s pure-Python Ed25519
|
|
223
|
+
# verification on every hook invocation when the 'cryptography' package is absent)
|
|
224
|
+
now = time.time()
|
|
225
|
+
cache_key = f"{public_key or ''}|{license_key}"
|
|
226
|
+
with cls._VALIDATION_CACHE_LOCK:
|
|
227
|
+
cached = cls._VALIDATION_CACHE.get(cache_key)
|
|
228
|
+
if cached and now < cached[1]:
|
|
229
|
+
return True, dict(cached[0]), "License is active and valid (cached)"
|
|
230
|
+
|
|
205
231
|
parts = license_key.split(".")
|
|
206
232
|
if len(parts) != 3 or parts[0] not in ("TS1", "TS2"):
|
|
207
233
|
return False, {}, "Invalid license key format (must start with TS2. or TS1.)"
|
|
@@ -255,6 +281,17 @@ class LicenseManager:
|
|
|
255
281
|
expired_days_ago = (now - expires_at) // 86400
|
|
256
282
|
return False, payload, f"License expired {expired_days_ago} day(s) ago"
|
|
257
283
|
|
|
284
|
+
# Cache the successful verification, bounded by both the TTL and the
|
|
285
|
+
# license's own expiry so an expiring key is re-checked in time.
|
|
286
|
+
ttl = cls._VALIDATION_CACHE_TTL
|
|
287
|
+
if expires_at > 0:
|
|
288
|
+
ttl = min(ttl, max(1.0, float(expires_at - now)))
|
|
289
|
+
with cls._VALIDATION_CACHE_LOCK:
|
|
290
|
+
if len(cls._VALIDATION_CACHE) >= cls._VALIDATION_CACHE_MAX:
|
|
291
|
+
oldest = min(cls._VALIDATION_CACHE, key=lambda k: cls._VALIDATION_CACHE[k][1])
|
|
292
|
+
cls._VALIDATION_CACHE.pop(oldest, None)
|
|
293
|
+
cls._VALIDATION_CACHE[cache_key] = (payload, now + ttl)
|
|
294
|
+
|
|
258
295
|
return True, payload, "License is active and valid"
|
|
259
296
|
|
|
260
297
|
@classmethod
|