tokensafe 2.7.3 → 2.8.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/README.md +10 -6
- package/hooks/pre_invocation.py +1 -1
- package/hooks/session_start.py +8 -1
- package/package.json +1 -1
- package/plugin.json +3 -3
- package/rules/AGENTS.md +1 -1
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +3 -0
- package/skills/token-optimizer/references/mcp-tools.md +2 -1
- package/src/adapter_core.py +1 -1
- package/src/benchmark.py +2 -2
- package/src/cli.py +2 -2
- package/src/command_sanitizer.py +13 -0
- package/src/compactor.py +5 -5
- package/src/distiller.py +5 -4
- package/src/governor.py +1 -1
- package/src/graph_engine.py +81 -2
- package/src/installer.py +1 -1
- package/src/json_repair.py +165 -0
- package/src/license_manager.py +141 -6
- package/src/live_relay.py +105 -0
- package/src/mcp_server.py +239 -9
- package/src/metrics.py +14 -0
- package/src/proxy.py +11 -2
- package/src/schema_slicer.py +302 -0
- package/src/telemetry_sync.py +1 -1
- package/src/treesitter_backend.py +28 -4
- package/src/version_checker.py +1 -1
- package/src/deepseek_distiller.py +0 -141
package/README.md
CHANGED
|
@@ -163,9 +163,11 @@ When an operation is blocked, the agent sees an explicit, constructive message:
|
|
|
163
163
|
|
|
164
164
|
**Clean context, better code**
|
|
165
165
|
|
|
166
|
-
- `tokensafe:smart_read_file` returns the target function plus its 1-hop dependencies instead of the whole file.
|
|
167
|
-
- `tokensafe:
|
|
168
|
-
-
|
|
166
|
+
- `tokensafe:smart_read_file` returns the target function plus its 1-hop dependencies instead of the whole file. 11 languages (Python, TypeScript/JavaScript, Go, Rust, Java, C#, C/C++, PHP, Kotlin, Ruby, Swift), with CSS design tokens preserved so agents never invent colors or font rules.
|
|
167
|
+
- `tokensafe:smart_bundle` reads 3–8 related symbols across files as one merged bundle — shared imports deduplicated, 1-hop signatures unified, a single roundtrip instead of chained reads.
|
|
168
|
+
- OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced: pass a spec path, model, type, or table as `symbol` and get that entry plus its 1-hop references — a 5,000-line migration drops from ~30k tokens to a few hundred.
|
|
169
|
+
- `tokensafe:graph` maps architectural hotspots and dependency topology in under 250 tokens instead of a full repository crawl — and teams share the result: the indexed graph and API surface are cached per repo state in the Team Symbol Index, so the 19 developers after the first one skip the crawl entirely.
|
|
170
|
+
- The command sanitizer strips lockfile noise and stack dumps down to the failing assertion, caps `git status`/`git diff` floods and docker build tails, and forces JS test runners into run-once mode so background tests never hang. Malformed JSON tool arguments from small local models are repaired in-flight instead of failing the call.
|
|
169
171
|
- The loop guard halts agents stuck repeating the same broken edit.
|
|
170
172
|
|
|
171
173
|
**Local-first guardrails**
|
|
@@ -180,6 +182,7 @@ When an operation is blocked, the agent sees an explicit, constructive message:
|
|
|
180
182
|
- The Context Budget HUD shows live window usage with a breakdown (tools / history / prompts) before quality drops.
|
|
181
183
|
- The shared L3 team cache gives teammates and CI runners warm 0ms hits on repeated reads and prompts.
|
|
182
184
|
- Managed cloud distillation compacts prompts with zero API keys for developers.
|
|
185
|
+
- The dashboard's live savings strip streams anonymized per-machine savings (tokens and USD) over SSE — you see what the team saves right now, not at the end of the week.
|
|
183
186
|
- The Friday per-seat ROI digest reports each engineer's savings with the `measured` / `estimated` split; inactive seats show `—`, never guessed figures.
|
|
184
187
|
|
|
185
188
|
Deeper mechanics (language matrix, context tax math, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
|
|
@@ -271,13 +274,14 @@ All hook adapters fail open: an internal error never stalls your agent. Failures
|
|
|
271
274
|
## Reference
|
|
272
275
|
|
|
273
276
|
<details>
|
|
274
|
-
<summary><b>Local MCP tools (
|
|
277
|
+
<summary><b>Local MCP tools (13)</b></summary>
|
|
275
278
|
|
|
276
279
|
| Tool | What it does |
|
|
277
280
|
|---|---|
|
|
278
|
-
| `get_architecture_graph` | Architectural hotspots and dependency topology before multi-file reading |
|
|
281
|
+
| `get_architecture_graph` | Architectural hotspots and dependency topology before multi-file reading; shared team symbol index reuse |
|
|
279
282
|
| `get_api_surface` | Compact markdown map of all exported interfaces, classes, and types |
|
|
280
|
-
| `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies |
|
|
283
|
+
| `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies; OpenAPI/Prisma/GraphQL/SQL files auto-slice (symbol = spec path / model / type / table) |
|
|
284
|
+
| `smart_bundle` | 3–8 related symbols across files in one call: merged skeletons, deduplicated shared imports, unified 1-hop signatures |
|
|
281
285
|
| `scoped_search` | Token-bounded symbol and text search with line-numbered matches |
|
|
282
286
|
| `list_dir` | Clean directory tree without permissions, timestamps, or lockfiles |
|
|
283
287
|
| `slice_diff` | Unified diff slicing omitting lockfiles and minimizing context lines |
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -92,7 +92,7 @@ def _handle(payload: dict) -> dict:
|
|
|
92
92
|
}
|
|
93
93
|
})
|
|
94
94
|
elif last_user_input and len(last_user_input.strip()) >= 5 and not _proxy_is_active():
|
|
95
|
-
compaction = PromptCompactor.compact(last_user_input,
|
|
95
|
+
compaction = PromptCompactor.compact(last_user_input, enable_distill=True)
|
|
96
96
|
saved_tokens = compaction["saved_tokens"]
|
|
97
97
|
reduction_pct = compaction["reduction_pct"]
|
|
98
98
|
|
package/hooks/session_start.py
CHANGED
|
@@ -12,7 +12,8 @@ Injects:
|
|
|
12
12
|
per-turn ephemeral reminders and the every-5th-turn re-nudge)
|
|
13
13
|
2. Quota / community-limit warning banner (user-facing markdown)
|
|
14
14
|
3. Environment bloat warning (heavy MCP servers, oversized rule files)
|
|
15
|
-
Also kicks off the background OS update notification check
|
|
15
|
+
Also kicks off the background OS update notification check and the
|
|
16
|
+
zero-config community-license issuance (anonymous free-tier identity).
|
|
16
17
|
"""
|
|
17
18
|
|
|
18
19
|
import sys
|
|
@@ -78,6 +79,12 @@ def main():
|
|
|
78
79
|
except Exception:
|
|
79
80
|
pass
|
|
80
81
|
|
|
82
|
+
try:
|
|
83
|
+
import threading
|
|
84
|
+
threading.Thread(target=LicenseManager.ensure_community_license, daemon=True).start()
|
|
85
|
+
except Exception:
|
|
86
|
+
pass
|
|
87
|
+
|
|
81
88
|
try:
|
|
82
89
|
bloat_warning = EnvironmentAuditor.get_bloat_warning(workspace_root=workspace_root)
|
|
83
90
|
if bloat_warning:
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.8.1",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.8.1",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally. Your agents read only needed code, keep prompt caches intact across turns, and keep secrets out of git.",
|
|
6
6
|
"logo": "assets/logo.svg",
|
|
7
7
|
"author": {
|
|
8
8
|
"name": "Oleg Savelev",
|
|
9
9
|
"url": "https://github.com/NekoSin4eG"
|
|
10
10
|
},
|
|
11
|
-
"homepage": "https://
|
|
11
|
+
"homepage": "https://tokensafe.dev",
|
|
12
12
|
"repository": {
|
|
13
13
|
"type": "git",
|
|
14
|
-
"url": "https://github.com/tokensafe-dev/tokensafe
|
|
14
|
+
"url": "https://github.com/tokensafe-dev/tokensafe"
|
|
15
15
|
}
|
|
16
16
|
}
|
package/rules/AGENTS.md
CHANGED
|
@@ -27,7 +27,7 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
27
27
|
|
|
28
28
|
### 3. Architecture & Code Navigation Directives (Graph-Guided)
|
|
29
29
|
1. **Zero Raw Terminal Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.
|
|
30
|
-
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context.
|
|
30
|
+
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).
|
|
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.
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Reduce your AI bills by up to 99% locally: focused code, warm prompt caches & zero secret leaks.",
|
|
6
|
-
"version": "2.
|
|
6
|
+
"version": "2.8.1",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "2.
|
|
33
|
+
"version": "2.8.1",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "2.
|
|
49
|
+
"version": "2.8.1",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -26,6 +26,8 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
26
26
|
- When locating or reading any function, component, class, or handler (e.g. `<LuckyWheelTab>`, `areSectorEqual`, `useWallet`), ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`.
|
|
27
27
|
- **1-Hop Dependency Modes (`dep_mode` & `include_deps`)**: By default (`dep_mode="signature"`), `smart_read_file` returns the full target implementation plus compact 1-line 1-hop dependency signatures and collapsed imports (-95%+ tokens). Pass `"dep_mode": "full"` when full 1-hop dependency bodies are required, or `"include_deps": false` for 0-hop surgical isolation.
|
|
28
28
|
- **Cache Pointer Recovery (`force_full`)**: When repeating an unchanged read in the same MCP session, `smart_read_file` may return a compact pointer referencing the prior output. Reuse that earlier output; only pass `"force_full": true` if your context was compacted or you are a fresh subagent lacking prior turns.
|
|
29
|
+
- **Multi-Symbol Bundles (`smart_bundle`)**: When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of chained `smart_read_file` calls (max 8 targets). It merges per-file skeletons, deduplicates shared import/type lines into one block, and unifies 1-hop dependency signatures — one roundtrip instead of many.
|
|
30
|
+
- **Schema Auto-Slicing**: OpenAPI/Swagger, Prisma, GraphQL and SQL files bypass AST skeletonization. Pass the spec path (`/users/{id}`), Prisma model, GraphQL type, or SQL table as `symbol` for a targeted slice with 1-hop references; an empty `symbol` returns a compact overview (paths/models/types/tables index) instead of a 20k-50k token dump.
|
|
29
31
|
- **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -98% tokens).
|
|
30
32
|
|
|
31
33
|
3. **ARCHITECTURE SURVEY BEFORE BROWSING (`get_architecture_graph`)**:
|
|
@@ -59,6 +61,7 @@ Quick pointers:
|
|
|
59
61
|
|
|
60
62
|
- Search: `tokensafe:scoped_search(query, scope)` — never raw grep.
|
|
61
63
|
- Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps.
|
|
64
|
+
- Bundle: `tokensafe:smart_bundle(targets=[{path, symbol}])` — 3-8 related symbols across files in one call, shared imports deduplicated.
|
|
62
65
|
- Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
|
|
63
66
|
- Directory: `tokensafe:list_dir(path, depth=2)` — clean tree, never verbose `ls -la`.
|
|
64
67
|
- Terminal: `tokensafe:sanitize_command(command, cwd)` — bounded logs/diffs, test runner guards.
|
|
@@ -4,7 +4,8 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
4
4
|
|
|
5
5
|
| MCP Tool | Description | Efficiency Impact |
|
|
6
6
|
|---|---|---|
|
|
7
|
-
| `tokensafe:smart_read_file` | Graph-guided AST reader with `symbol` body retention, `dep_mode` (`signature` default / `full`), and session pointer dedup (`force_full`). | **-90% to -98%** token reduction |
|
|
7
|
+
| `tokensafe:smart_read_file` | Graph-guided AST reader with `symbol` body retention, `dep_mode` (`signature` default / `full`), and session pointer dedup (`force_full`). OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced: `symbol` = spec path/model/type/table; empty `symbol` returns a compact overview. | **-90% to -98%** token reduction |
|
|
8
|
+
| `tokensafe:smart_bundle` | Multi-symbol context bundle: up to 8 `{path, symbol}` targets in ONE call — per-file skeletons with shared import lines deduplicated and merged 1-hop dependency signatures. Replaces 3+ chained `smart_read_file` calls. | **-85% to -95%** + one roundtrip instead of many |
|
|
8
9
|
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path`, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
|
|
9
10
|
| `tokensafe:list_dir` | Token-efficient directory tree without lockfiles, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces `ls -la`. | **-90%** vs verbose `ls` |
|
|
10
11
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
package/src/adapter_core.py
CHANGED
|
@@ -105,7 +105,7 @@ def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str
|
|
|
105
105
|
try:
|
|
106
106
|
from src.compactor import PromptCompactor
|
|
107
107
|
from src.tokenizer import count_tokens
|
|
108
|
-
compaction = PromptCompactor.compact(prompt,
|
|
108
|
+
compaction = PromptCompactor.compact(prompt, enable_distill=False)
|
|
109
109
|
saved = compaction.get("saved_tokens", 0)
|
|
110
110
|
if saved < 5:
|
|
111
111
|
return "", meta
|
package/src/benchmark.py
CHANGED
|
@@ -413,9 +413,9 @@ class BenchmarkSuite:
|
|
|
413
413
|
sync_remote=False,
|
|
414
414
|
)
|
|
415
415
|
distilled_hit = DistillationCache.get(raw_prompt)
|
|
416
|
-
compaction_text = distilled_hit or PromptCompactor.compact(raw_prompt,
|
|
416
|
+
compaction_text = distilled_hit or PromptCompactor.compact(raw_prompt, enable_distill=True)["compact_text"]
|
|
417
417
|
else:
|
|
418
|
-
compaction_text = PromptCompactor.compact(raw_prompt,
|
|
418
|
+
compaction_text = PromptCompactor.compact(raw_prompt, enable_distill=True)["compact_text"]
|
|
419
419
|
p_base_tokens = count_tokens(raw_prompt)
|
|
420
420
|
p_opt_tokens = count_tokens(compaction_text)
|
|
421
421
|
|
package/src/cli.py
CHANGED
|
@@ -470,9 +470,9 @@ def main():
|
|
|
470
470
|
print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
|
|
471
471
|
if tier == "free":
|
|
472
472
|
print(" \033[33mTier: Free Community Edition\033[0m")
|
|
473
|
-
print("
|
|
473
|
+
print(" Managed Cloud Distillation (zero API keys) is reserved for Solo, Team, and Enterprise tiers.")
|
|
474
474
|
print(" Free Community Edition operates with the zero-latency, zero-cost Local Regex Compactor.\n")
|
|
475
|
-
print(" \033[1mTo unlock
|
|
475
|
+
print(" \033[1mTo unlock Cloud Distillation:\033[0m")
|
|
476
476
|
print(" 1. Start 7-day free trial or upgrade at: \033[36mhttps://tokensafe.dev\033[0m")
|
|
477
477
|
print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
|
|
478
478
|
elif not UniversalDistiller.is_self_hosted():
|
package/src/command_sanitizer.py
CHANGED
|
@@ -279,6 +279,13 @@ class CommandSanitizer:
|
|
|
279
279
|
subcmd = cmd_args[sub_idx] if sub_idx < len(cmd_args) else ""
|
|
280
280
|
sub_args = cmd_args[sub_idx + 1 :]
|
|
281
281
|
|
|
282
|
+
# git status: compact porcelain format + bounded output (a long-lived
|
|
283
|
+
# monorepo branch can list hundreds of untracked files)
|
|
284
|
+
if subcmd == "status":
|
|
285
|
+
if "--porcelain" not in sub_args and "-s" not in sub_args and "-uno" not in sub_args and "--untracked-files" not in stage:
|
|
286
|
+
new_stage = re.sub(r"\b(git(?:\s+-C\s+\S+)?\s+status)\b", r"\1 --porcelain", stage, count=1)
|
|
287
|
+
return new_stage, 1500, "Switched git status to compact porcelain output, capped to 200 lines", cls._CAP_LINES_200
|
|
288
|
+
|
|
282
289
|
# git diff: exclude lockfiles/bundles when diffing unscoped repository
|
|
283
290
|
if subcmd == "diff":
|
|
284
291
|
if not any(a.startswith(":!") for a in sub_args) and ":!" not in stage:
|
|
@@ -363,6 +370,12 @@ class CommandSanitizer:
|
|
|
363
370
|
if "--tail" not in stage and not any(a == "-n" or a.startswith(("-n", "--tail=")) for a in cmd_args):
|
|
364
371
|
return f"{stage} --tail 100", 2000, "Capped docker logs to last 100 lines", None
|
|
365
372
|
|
|
373
|
+
# docker build / docker compose build: the failing step sits at the end
|
|
374
|
+
# of the log — keep only the tail instead of a full build dump
|
|
375
|
+
if cmd_tok == "docker" and (cmd_args[:1] == ["build"] or cmd_args[:2] == ["compose", "build"]):
|
|
376
|
+
if not cls._has_redirect(stage) and "|" not in stage:
|
|
377
|
+
return f"{stage} 2>&1 | tail -50", 2500, "Tailed docker build output to the last 50 lines (failing step is last)", None
|
|
378
|
+
|
|
366
379
|
# kubectl logs
|
|
367
380
|
if cmd_tok == "kubectl" and cmd_args[:1] == ["logs"]:
|
|
368
381
|
if "--tail" not in stage:
|
package/src/compactor.py
CHANGED
|
@@ -360,14 +360,14 @@ class PromptCompactor:
|
|
|
360
360
|
def compact(
|
|
361
361
|
cls,
|
|
362
362
|
raw_text: str,
|
|
363
|
-
|
|
363
|
+
enable_distill: bool = True,
|
|
364
364
|
min_distill_tokens: Optional[int] = None
|
|
365
365
|
) -> Dict[str, Any]:
|
|
366
366
|
"""
|
|
367
367
|
Compresses input prompt via 3-Tier Architecture:
|
|
368
368
|
- Tier 0: Pass-through for very short inputs (< 6 tokens)
|
|
369
369
|
- Tier 1: Multilingual Regex Compactor (0ms, 0 external tokens) for inputs < 100 tokens
|
|
370
|
-
- Tier 2:
|
|
370
|
+
- Tier 2: Managed Cloud Distiller (license-authenticated; BYOK Gemini/OpenAI/DeepSeek for self-hosted) for long/complex prompts (>= 100 tokens)
|
|
371
371
|
"""
|
|
372
372
|
if not raw_text or not raw_text.strip():
|
|
373
373
|
return {
|
|
@@ -407,10 +407,10 @@ class PromptCompactor:
|
|
|
407
407
|
"tier": "PASS_THROUGH"
|
|
408
408
|
}
|
|
409
409
|
|
|
410
|
-
# Tier 2:
|
|
410
|
+
# Tier 2: Managed Cloud Intent Distiller (BYOK Gemini / OpenAI / DeepSeek for self-hosted)
|
|
411
411
|
# Exclusive to TokenSafe Solo, Team, and Enterprise (or active trials)
|
|
412
412
|
min_distill = min_distill_tokens if min_distill_tokens is not None else cls._get_min_distill_tokens()
|
|
413
|
-
if
|
|
413
|
+
if enable_distill and original_tokens >= min_distill:
|
|
414
414
|
active_tier, _ = LicenseManager.get_active_license()
|
|
415
415
|
if active_tier != "free":
|
|
416
416
|
distilled = UniversalDistiller.distill(raw_text)
|
|
@@ -446,7 +446,7 @@ class PromptCompactor:
|
|
|
446
446
|
"target_file": target_file,
|
|
447
447
|
"symbol": symbol,
|
|
448
448
|
"traits": traits,
|
|
449
|
-
"tier": "
|
|
449
|
+
"tier": "DISTILLER"
|
|
450
450
|
}
|
|
451
451
|
|
|
452
452
|
# Tier 1: Multilingual Local Regex Compactor
|
package/src/distiller.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
"""
|
|
2
|
-
|
|
2
|
+
Managed-Cloud-First Intent Distiller:
|
|
3
3
|
Translates verbose, conversational developer prompts into ultra-dense TOCP S-Expressions.
|
|
4
|
-
|
|
4
|
+
Paid tiers use the TokenSafe Cloud Distiller out of the box (zero API keys, license-key auth).
|
|
5
|
+
Self-hosted/Enterprise optionally supports BYOK: DeepSeek, OpenAI ChatGPT, and Google Gemini.
|
|
5
6
|
Implemented with pure standard-library urllib (zero dependencies, strict timeout).
|
|
6
7
|
"""
|
|
7
8
|
|
|
@@ -17,7 +18,7 @@ from src.license_manager import LicenseManager
|
|
|
17
18
|
from src.paths import resolve_data_dir
|
|
18
19
|
|
|
19
20
|
class UniversalDistiller:
|
|
20
|
-
"""
|
|
21
|
+
"""Managed-cloud-first semantic intent compiler: TokenSafe Cloud (zero keys) with optional BYOK DeepSeek, OpenAI, and Google Gemini."""
|
|
21
22
|
|
|
22
23
|
DEFAULT_TIMEOUT = 2.5
|
|
23
24
|
# After a failed roundtrip, skip all remote distillation for this long.
|
|
@@ -195,7 +196,7 @@ Rules:
|
|
|
195
196
|
def distill(cls, raw_text: str, preferred_provider: Optional[str] = None) -> Optional[str]:
|
|
196
197
|
"""
|
|
197
198
|
Distills raw conversational text into an S-Expression using the best available provider.
|
|
198
|
-
Priority: Explicit preferred -> Gemini -> OpenAI -> DeepSeek.
|
|
199
|
+
Priority: Managed Cloud (license-auth, zero keys) -> Explicit preferred -> Gemini -> OpenAI -> DeepSeek.
|
|
199
200
|
Requires active TokenSafe Solo or Team subscription.
|
|
200
201
|
"""
|
|
201
202
|
tier, _ = LicenseManager.get_active_license()
|
package/src/governor.py
CHANGED
|
@@ -234,7 +234,7 @@ class ContextGovernor:
|
|
|
234
234
|
if msg.get("role") == "user" and isinstance(msg.get("content"), str):
|
|
235
235
|
raw_user = msg["content"]
|
|
236
236
|
if len(raw_user.strip()) > 15 and "[TOCP Intent]" not in raw_user:
|
|
237
|
-
comp = PromptCompactor.compact(raw_user,
|
|
237
|
+
comp = PromptCompactor.compact(raw_user, enable_distill=False)
|
|
238
238
|
if comp["saved_tokens"] >= 5:
|
|
239
239
|
msg["content"] = f"[TOCP Intent]: {comp['compact_text']}"
|
|
240
240
|
compacted_any = True
|
package/src/graph_engine.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""
|
|
2
2
|
TokenSafe Graph Engine: Dependency-Aware Graph Analysis & Skeletonization.
|
|
3
3
|
Builds a zero-LLM deterministic code graph for Python, TypeScript/JavaScript, Go,
|
|
4
|
-
Rust, Java, C#, C/C++, PHP, Kotlin, and Swift.
|
|
4
|
+
Rust, Java, C#, C/C++, PHP, Kotlin, Ruby, and Swift.
|
|
5
5
|
|
|
6
6
|
Uses the optional Tree-sitter backend when available (`src.treesitter_backend`)
|
|
7
7
|
and falls back seamlessly to the Python standard library `ast` and `BraceLexer`
|
|
@@ -38,7 +38,7 @@ SUPPORTED_EXTS = {
|
|
|
38
38
|
".py", ".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs",
|
|
39
39
|
".go", ".rs", ".java", ".cs",
|
|
40
40
|
".c", ".cpp", ".cc", ".cxx", ".h", ".hpp",
|
|
41
|
-
".php", ".kt", ".kts", ".swift",
|
|
41
|
+
".php", ".kt", ".kts", ".swift", ".rb",
|
|
42
42
|
}
|
|
43
43
|
|
|
44
44
|
_SKIP_CALLS = {
|
|
@@ -344,6 +344,8 @@ class CodeGraph:
|
|
|
344
344
|
|
|
345
345
|
if ext == ".py":
|
|
346
346
|
self._parse_python(content, rel_path, file_node)
|
|
347
|
+
elif ext == ".rb":
|
|
348
|
+
self._parse_ruby(content, rel_path, file_node)
|
|
347
349
|
elif ext in SUPPORTED_EXTS:
|
|
348
350
|
self._parse_braces(content, rel_path, file_node, ext)
|
|
349
351
|
|
|
@@ -571,6 +573,83 @@ class CodeGraph:
|
|
|
571
573
|
if finished_key in self.symbols:
|
|
572
574
|
self.symbols[finished_key].line_end = idx
|
|
573
575
|
|
|
576
|
+
def _parse_ruby(self, code: str, rel_path: str, file_node: str):
|
|
577
|
+
"""Stdlib Ruby parser: keyword-delimited blocks (`def`/`class`/`module` ...
|
|
578
|
+
`end`) instead of braces. Mirrors the brace-parser conventions (kinds,
|
|
579
|
+
quals, call edges) so both backends stay in parity."""
|
|
580
|
+
lines = code.splitlines()
|
|
581
|
+
require_re = re.compile(r'^\s*require(?:_relative)?\s+["\']([^"\']+)["\']')
|
|
582
|
+
opener_re = re.compile(
|
|
583
|
+
r'^\s*(?:def|class|module|if|unless|while|until|case|for|begin)\b|\bdo\s*(?:\|[^|]*\|)?\s*$'
|
|
584
|
+
)
|
|
585
|
+
container_re = re.compile(r'^\s*(?:class|module)\s+([A-Z][A-Za-z0-9_:]*)')
|
|
586
|
+
method_re = re.compile(r'^\s*def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_]*[?!]?)')
|
|
587
|
+
call_re = re.compile(r'\b([a-zA-Z_][a-zA-Z0-9_]*[?!]?)\s*\(')
|
|
588
|
+
end_re = re.compile(r'\bend\b')
|
|
589
|
+
|
|
590
|
+
# Stack items: (sym_key|None, kind|None, qual|None). None entries track
|
|
591
|
+
# non-symbol keyword blocks (if/while/do/...) so `end` counting balances.
|
|
592
|
+
stack: List[Tuple[Optional[str], Optional[str], Optional[str]]] = []
|
|
593
|
+
|
|
594
|
+
for idx, raw in enumerate(lines, 1):
|
|
595
|
+
no_comment = raw.split("#", 1)[0]
|
|
596
|
+
# Blank out string literals so `end`-like words inside strings never count
|
|
597
|
+
no_str = re.sub(r'"[^"]*"', '""', no_comment)
|
|
598
|
+
no_str = re.sub(r"'[^']*'", "''", no_str)
|
|
599
|
+
if not no_str.strip():
|
|
600
|
+
continue
|
|
601
|
+
|
|
602
|
+
rm = require_re.match(raw)
|
|
603
|
+
if rm:
|
|
604
|
+
self.file_imports[rel_path].add(rm.group(1))
|
|
605
|
+
self.add_edge(file_node, f"mod:{rm.group(1)}")
|
|
606
|
+
|
|
607
|
+
opens = len(opener_re.findall(no_str))
|
|
608
|
+
closes = len(end_re.findall(no_str))
|
|
609
|
+
|
|
610
|
+
matched_name: Optional[str] = None
|
|
611
|
+
matched_kind: Optional[str] = None
|
|
612
|
+
cm = container_re.match(no_str)
|
|
613
|
+
if cm:
|
|
614
|
+
matched_kind, matched_name = "class", cm.group(1)
|
|
615
|
+
else:
|
|
616
|
+
mm = method_re.match(no_str)
|
|
617
|
+
if mm:
|
|
618
|
+
matched_kind, matched_name = "function", mm.group(1)
|
|
619
|
+
|
|
620
|
+
if matched_name and matched_kind:
|
|
621
|
+
class_ctx = [e[2] for e in stack if e[1] == "class"]
|
|
622
|
+
qual = f"{class_ctx[-1]}::{matched_name}" if class_ctx else matched_name
|
|
623
|
+
sym_key = f"{rel_path}::{qual}"
|
|
624
|
+
symbol = CodeSymbol(
|
|
625
|
+
name=matched_name,
|
|
626
|
+
kind=matched_kind,
|
|
627
|
+
file_path=rel_path,
|
|
628
|
+
line_start=idx,
|
|
629
|
+
line_end=idx,
|
|
630
|
+
signature=raw.strip(),
|
|
631
|
+
)
|
|
632
|
+
self._register_symbol(rel_path, file_node, symbol, sym_key)
|
|
633
|
+
stack.append((sym_key, matched_kind, qual))
|
|
634
|
+
elif opens:
|
|
635
|
+
stack.append((None, None, None))
|
|
636
|
+
|
|
637
|
+
active_fn = next((e for e in reversed(stack) if e[1] == "function"), None)
|
|
638
|
+
if active_fn and active_fn[0]:
|
|
639
|
+
for cmm in call_re.finditer(no_str):
|
|
640
|
+
callee = cmm.group(1)
|
|
641
|
+
if callee != matched_name and callee not in _SKIP_CALLS:
|
|
642
|
+
self.add_edge(active_fn[0], f"call:{callee}")
|
|
643
|
+
|
|
644
|
+
for _ in range(closes):
|
|
645
|
+
if not stack:
|
|
646
|
+
break
|
|
647
|
+
entry = stack.pop()
|
|
648
|
+
if entry[0]:
|
|
649
|
+
sym = self.symbols.get(entry[0])
|
|
650
|
+
if sym:
|
|
651
|
+
sym.line_end = idx
|
|
652
|
+
|
|
574
653
|
def _resolve_local_imports(self) -> None:
|
|
575
654
|
"""Resolves raw `file_imports` strings to real `file:<rel_path>` edges."""
|
|
576
655
|
indexed_files = set(self.file_symbols.keys())
|
package/src/installer.py
CHANGED
|
@@ -46,7 +46,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
46
46
|
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
47
47
|
"Always use `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
|
|
48
48
|
"1. **Zero Raw Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.\n"
|
|
49
|
-
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context.\n"
|
|
49
|
+
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).\n"
|
|
50
50
|
"3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
|
|
51
51
|
"4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
|
|
52
52
|
"5. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens).\n"
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"""Heuristic JSON repair for malformed tool-call arguments.
|
|
2
|
+
|
|
3
|
+
Small/local models (Haiku, Llama, Qwen) intermittently emit broken JSON in
|
|
4
|
+
tool-call argument strings: a missing closing bracket, trailing commas,
|
|
5
|
+
Python literals, raw newlines inside strings, or single quotes. Instead of
|
|
6
|
+
failing the tool call and burning a full retry roundtrip, the MCP server and
|
|
7
|
+
the proxy run the payload through this best-effort repairer first.
|
|
8
|
+
|
|
9
|
+
Standard library only. Every stage is tried strictly: a repaired candidate is
|
|
10
|
+
accepted only when `json.loads` really accepts it — no fabricated output.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import re
|
|
15
|
+
from typing import Any, List, Optional
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def parse_tool_arguments(raw: Any) -> Optional[dict]:
|
|
19
|
+
"""Parses tool-call arguments. Dicts pass through; strings go through strict
|
|
20
|
+
json.loads first, then heuristic repair. Returns None when unrepairable."""
|
|
21
|
+
if isinstance(raw, dict):
|
|
22
|
+
return raw
|
|
23
|
+
if not isinstance(raw, str):
|
|
24
|
+
return None
|
|
25
|
+
s = raw.strip()
|
|
26
|
+
if not s:
|
|
27
|
+
return None
|
|
28
|
+
try:
|
|
29
|
+
val = json.loads(s)
|
|
30
|
+
return val if isinstance(val, dict) else None
|
|
31
|
+
except Exception:
|
|
32
|
+
pass
|
|
33
|
+
repaired = repair_json(s)
|
|
34
|
+
if repaired is None:
|
|
35
|
+
return None
|
|
36
|
+
try:
|
|
37
|
+
val = json.loads(repaired)
|
|
38
|
+
return val if isinstance(val, dict) else None
|
|
39
|
+
except Exception:
|
|
40
|
+
return None
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def repair_json(s: str) -> Optional[str]:
|
|
44
|
+
"""Best-effort repair of a broken JSON string. Returns repaired text that
|
|
45
|
+
strict json.loads accepts, or None when nothing sensible can be produced."""
|
|
46
|
+
s = s.strip().lstrip("\ufeff")
|
|
47
|
+
if not s:
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
py_fixed = re.sub(r"\bTrue\b", "true", s)
|
|
51
|
+
py_fixed = re.sub(r"\bFalse\b", "false", py_fixed)
|
|
52
|
+
py_fixed = re.sub(r"\bNone\b", "null", py_fixed)
|
|
53
|
+
|
|
54
|
+
ctrl_fixed = _escape_control_chars_in_strings(py_fixed)
|
|
55
|
+
|
|
56
|
+
def _strip_trailing_commas(text: str) -> str:
|
|
57
|
+
return re.sub(r",(\s*[}\]])", r"\1", text)
|
|
58
|
+
|
|
59
|
+
candidates: List[Optional[str]] = [py_fixed, ctrl_fixed, _strip_trailing_commas(ctrl_fixed)]
|
|
60
|
+
|
|
61
|
+
# Balance missing closers, then strip trailing commas AGAIN — appending a
|
|
62
|
+
# closer can leave a dangling comma right before it (e.g. '{"a": 1,').
|
|
63
|
+
balanced0 = _balance_brackets(ctrl_fixed)
|
|
64
|
+
for base in (balanced0, _balance_brackets(_strip_trailing_commas(ctrl_fixed))):
|
|
65
|
+
if base is not None:
|
|
66
|
+
candidates.append(base)
|
|
67
|
+
candidates.append(_strip_trailing_commas(base))
|
|
68
|
+
|
|
69
|
+
# Single-quote conversion only as a late resort (apostrophe risk)
|
|
70
|
+
for base in list(candidates):
|
|
71
|
+
sq = _single_to_double_quotes(base) if base else None
|
|
72
|
+
if sq:
|
|
73
|
+
candidates.append(sq)
|
|
74
|
+
sb = _balance_brackets(sq)
|
|
75
|
+
if sb:
|
|
76
|
+
candidates.append(sb)
|
|
77
|
+
|
|
78
|
+
for cand in candidates:
|
|
79
|
+
if cand is None:
|
|
80
|
+
continue
|
|
81
|
+
try:
|
|
82
|
+
json.loads(cand)
|
|
83
|
+
return cand
|
|
84
|
+
except Exception:
|
|
85
|
+
continue
|
|
86
|
+
return None
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _escape_control_chars_in_strings(s: str) -> str:
|
|
90
|
+
"""Escapes raw newlines/tabs/CRs that appear inside string literals."""
|
|
91
|
+
out: List[str] = []
|
|
92
|
+
in_str = False
|
|
93
|
+
quote = ""
|
|
94
|
+
escaped = False
|
|
95
|
+
for ch in s:
|
|
96
|
+
if in_str:
|
|
97
|
+
if escaped:
|
|
98
|
+
out.append(ch)
|
|
99
|
+
escaped = False
|
|
100
|
+
continue
|
|
101
|
+
if ch == "\\":
|
|
102
|
+
out.append(ch)
|
|
103
|
+
escaped = True
|
|
104
|
+
continue
|
|
105
|
+
if ch == quote:
|
|
106
|
+
in_str = False
|
|
107
|
+
out.append(ch)
|
|
108
|
+
continue
|
|
109
|
+
if ch == "\n":
|
|
110
|
+
out.append("\\n")
|
|
111
|
+
continue
|
|
112
|
+
if ch == "\r":
|
|
113
|
+
out.append("\\r")
|
|
114
|
+
continue
|
|
115
|
+
if ch == "\t":
|
|
116
|
+
out.append("\\t")
|
|
117
|
+
continue
|
|
118
|
+
out.append(ch)
|
|
119
|
+
else:
|
|
120
|
+
if ch in ('"', "'"):
|
|
121
|
+
in_str = True
|
|
122
|
+
quote = ch
|
|
123
|
+
out.append(ch)
|
|
124
|
+
return "".join(out)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _balance_brackets(s: str) -> Optional[str]:
|
|
128
|
+
"""Appends missing closing brackets/braces (string-aware). Returns None when
|
|
129
|
+
the structure cannot be balanced by appending closers alone."""
|
|
130
|
+
if not s:
|
|
131
|
+
return None
|
|
132
|
+
stack: List[str] = []
|
|
133
|
+
in_str = False
|
|
134
|
+
quote = ""
|
|
135
|
+
escaped = False
|
|
136
|
+
for ch in s:
|
|
137
|
+
if in_str:
|
|
138
|
+
if escaped:
|
|
139
|
+
escaped = False
|
|
140
|
+
elif ch == "\\":
|
|
141
|
+
escaped = True
|
|
142
|
+
elif ch == quote:
|
|
143
|
+
in_str = False
|
|
144
|
+
continue
|
|
145
|
+
if ch in ('"', "'"):
|
|
146
|
+
in_str = True
|
|
147
|
+
quote = ch
|
|
148
|
+
elif ch in "{[":
|
|
149
|
+
stack.append("}" if ch == "{" else "]")
|
|
150
|
+
elif ch in "}]":
|
|
151
|
+
if not stack or stack[-1] != ch:
|
|
152
|
+
return None
|
|
153
|
+
stack.pop()
|
|
154
|
+
if in_str:
|
|
155
|
+
# Unterminated string: close it before the pending brackets
|
|
156
|
+
return s + '"' + "".join(reversed(stack))
|
|
157
|
+
return s + "".join(reversed(stack))
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _single_to_double_quotes(s: str) -> Optional[str]:
|
|
161
|
+
"""Converts single-quoted strings to double quotes. Only safe when the text
|
|
162
|
+
contains no double quotes at all (so an unambiguous dialect is broken)."""
|
|
163
|
+
if '"' in s or "'" not in s:
|
|
164
|
+
return None
|
|
165
|
+
return s.replace("'", '"')
|