tokensafe 4.1.5 → 4.1.6
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 +3 -3
- package/hooks/claude_code_hook.py +2 -2
- package/hooks/session_start.py +2 -1
- package/package.json +2 -2
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/build_parsers.py +10 -0
- package/src/cli.py +21 -0
- package/src/command_sanitizer.py +56 -4
- package/src/fts_index.py +25 -6
- package/src/installer.py +8 -1
- package/src/mcp_server.py +56 -12
- package/src/mistakes.py +2 -1
- package/src/paths.py +44 -0
- package/src/result_ledger.py +23 -1
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/README.md
CHANGED
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
<!-- mcp-name: dev.tokensafe/tokensafe -->
|
|
7
7
|
|
|
8
8
|
<p align="center">
|
|
9
|
-
<b>
|
|
10
|
-
|
|
11
|
-
TokenSafe
|
|
9
|
+
<b>Your coding agent isn't getting dumber. Your context is just full of trash.</b><br>
|
|
10
|
+
When chat sessions fill up with massive lockfiles and endless build logs, your AI loses focus.<br>
|
|
11
|
+
TokenSafe strips the noise with Tree-sitter AST slicing so your agent stays razor-sharp, changes only the lines you asked for, and never leaks your secrets.<br>
|
|
12
12
|
Works with <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Gemini CLI, and ChatGPT</b>.
|
|
13
13
|
</p>
|
|
14
14
|
|
|
@@ -231,8 +231,8 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
231
231
|
return {
|
|
232
232
|
"decision": "block",
|
|
233
233
|
"reason": (
|
|
234
|
-
f"[TokenSafe] {tool}
|
|
235
|
-
f"({orig:,} → {new:,} chars).
|
|
234
|
+
f"[TokenSafe] {tool} output auto-compacted "
|
|
235
|
+
f"({orig:,} → {new:,} chars). Output summary:\n{compacted}"
|
|
236
236
|
),
|
|
237
237
|
}
|
|
238
238
|
return {}
|
package/hooks/session_start.py
CHANGED
|
@@ -61,8 +61,9 @@ def main():
|
|
|
61
61
|
workspace_paths = raw_ws if isinstance(raw_ws, list) else []
|
|
62
62
|
workspace_root = str(workspace_paths[0]) if workspace_paths else os.getcwd()
|
|
63
63
|
try:
|
|
64
|
-
from src.paths import save_active_workspace
|
|
64
|
+
from src.paths import save_active_workspace, ensure_tokensafe_gitignore
|
|
65
65
|
save_active_workspace(workspace_root)
|
|
66
|
+
ensure_tokensafe_gitignore(workspace_root)
|
|
66
67
|
except Exception:
|
|
67
68
|
pass
|
|
68
69
|
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.1.
|
|
5
|
-
"description": "
|
|
4
|
+
"version": "4.1.6",
|
|
5
|
+
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"tokensafe": "bin/tokensafe.js"
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.1.
|
|
4
|
+
"version": "4.1.6",
|
|
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": {
|
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": "4.1.
|
|
6
|
+
"version": "4.1.6",
|
|
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": "4.1.
|
|
33
|
+
"version": "4.1.6",
|
|
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": "4.1.
|
|
49
|
+
"version": "4.1.6",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
package/src/build_parsers.py
CHANGED
|
@@ -153,6 +153,16 @@ class BuildOutputParser:
|
|
|
153
153
|
error_lines.append(ln)
|
|
154
154
|
|
|
155
155
|
result = "\n".join(error_lines).strip()
|
|
156
|
+
# If the build failure contains TypeScript compiler error cascades (e.g. vue-tsc, vite build type error),
|
|
157
|
+
# compact using CompilerErrorCompactor to save massive token cascades.
|
|
158
|
+
try:
|
|
159
|
+
from src.format_parsers.compiler_errors import CompilerErrorCompactor
|
|
160
|
+
if CompilerErrorCompactor.is_tsc_output(result or cleaned):
|
|
161
|
+
compacted_tsc, was_tsc = CompilerErrorCompactor.compact_tsc(result or cleaned)
|
|
162
|
+
if was_tsc:
|
|
163
|
+
return compacted_tsc, True
|
|
164
|
+
except Exception:
|
|
165
|
+
pass
|
|
156
166
|
return result or cleaned.strip(), True
|
|
157
167
|
|
|
158
168
|
@classmethod
|
package/src/cli.py
CHANGED
|
@@ -1021,6 +1021,27 @@ def main(argv: Optional[List[str]] = None):
|
|
|
1021
1021
|
print(compacted_build)
|
|
1022
1022
|
sys.exit(proc.returncode)
|
|
1023
1023
|
|
|
1024
|
+
# Container build reducer (docker build, docker compose build)
|
|
1025
|
+
try:
|
|
1026
|
+
from src.format_parsers.docker_k8s import ContainerAndK8sReducer
|
|
1027
|
+
compacted_docker, was_docker = ContainerAndK8sReducer.reduce_docker_build(raw)
|
|
1028
|
+
if was_docker:
|
|
1029
|
+
print(compacted_docker)
|
|
1030
|
+
sys.exit(proc.returncode)
|
|
1031
|
+
except Exception:
|
|
1032
|
+
pass
|
|
1033
|
+
|
|
1034
|
+
# Structured NDJSON / JSON log reducer
|
|
1035
|
+
try:
|
|
1036
|
+
from src.format_parsers.json_log import JSONLogReducer
|
|
1037
|
+
if JSONLogReducer.is_ndjson_log(raw):
|
|
1038
|
+
compacted_logs, was_logs = JSONLogReducer.reduce(raw)
|
|
1039
|
+
if was_logs:
|
|
1040
|
+
print(compacted_logs)
|
|
1041
|
+
sys.exit(proc.returncode)
|
|
1042
|
+
except Exception:
|
|
1043
|
+
pass
|
|
1044
|
+
|
|
1024
1045
|
lines = raw.splitlines()
|
|
1025
1046
|
if len(lines) > 40:
|
|
1026
1047
|
head = lines[:15]
|
package/src/command_sanitizer.py
CHANGED
|
@@ -540,6 +540,10 @@ class CommandSanitizer:
|
|
|
540
540
|
return None
|
|
541
541
|
|
|
542
542
|
is_build = False
|
|
543
|
+
saved = 1800
|
|
544
|
+
reason = "Wrapped build command with tokensafe wrap to fold progress noise and asset tables"
|
|
545
|
+
|
|
546
|
+
# 1. Build commands
|
|
543
547
|
if cmd_tok == "npm":
|
|
544
548
|
is_build = any(a in ("build", "build:prod", "build:cloud") or a.startswith("build:") for a in cmd_args) or (
|
|
545
549
|
"run" in cmd_args and any("build" in a for a in cmd_args)
|
|
@@ -555,6 +559,37 @@ class CommandSanitizer:
|
|
|
555
559
|
elif cmd_tok == "cargo" and cmd_args[:1] == ["build"]:
|
|
556
560
|
is_build = True
|
|
557
561
|
|
|
562
|
+
# 2. TypeScript compiler & type-checking commands (tsc, npx tsc, npm run typecheck)
|
|
563
|
+
if not is_build:
|
|
564
|
+
if cmd_tok == "tsc":
|
|
565
|
+
is_build = True
|
|
566
|
+
saved = 2500
|
|
567
|
+
reason = "Wrapped TypeScript compiler command with tokensafe wrap to compact error cascades"
|
|
568
|
+
elif cmd_tok in ("npx", "bunx") and "tsc" in cmd_args:
|
|
569
|
+
is_build = True
|
|
570
|
+
saved = 2500
|
|
571
|
+
reason = f"Wrapped {cmd_tok} tsc command with tokensafe wrap to compact error cascades"
|
|
572
|
+
elif cmd_tok in ("npm", "yarn", "pnpm", "bun"):
|
|
573
|
+
typecheck_hit = any(
|
|
574
|
+
a in ("typecheck", "type-check", "tsc", "check-types") or "typecheck" in a or "type-check" in a
|
|
575
|
+
for a in cmd_args
|
|
576
|
+
)
|
|
577
|
+
if typecheck_hit:
|
|
578
|
+
is_build = True
|
|
579
|
+
saved = 2500
|
|
580
|
+
reason = f"Wrapped {cmd_tok} typecheck command with tokensafe wrap to compact error cascades"
|
|
581
|
+
|
|
582
|
+
# 3. Linter commands (eslint, npx eslint, biome, npx biome)
|
|
583
|
+
if not is_build:
|
|
584
|
+
if cmd_tok in ("eslint", "biome"):
|
|
585
|
+
is_build = True
|
|
586
|
+
saved = 1500
|
|
587
|
+
reason = f"Wrapped {cmd_tok} linter command with tokensafe wrap to bound output"
|
|
588
|
+
elif cmd_tok in ("npx", "bunx") and any(a in ("eslint", "biome") for a in cmd_args):
|
|
589
|
+
is_build = True
|
|
590
|
+
saved = 1500
|
|
591
|
+
reason = f"Wrapped {cmd_tok} linter command with tokensafe wrap to bound output"
|
|
592
|
+
|
|
558
593
|
if not is_build:
|
|
559
594
|
return None
|
|
560
595
|
|
|
@@ -562,15 +597,21 @@ class CommandSanitizer:
|
|
|
562
597
|
import shutil
|
|
563
598
|
has_tokensafe = bool(shutil.which("tokensafe"))
|
|
564
599
|
if not has_tokensafe:
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
600
|
+
for candidate in (
|
|
601
|
+
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bin", "tokensafe"),
|
|
602
|
+
os.path.expanduser("~/.tokensafe/bin/tokensafe"),
|
|
603
|
+
os.path.expanduser("~/.local/bin/tokensafe"),
|
|
604
|
+
"/usr/local/bin/tokensafe"
|
|
605
|
+
):
|
|
606
|
+
if os.path.exists(candidate):
|
|
607
|
+
has_tokensafe = True
|
|
608
|
+
break
|
|
568
609
|
|
|
569
610
|
if not has_tokensafe:
|
|
570
611
|
return None
|
|
571
612
|
|
|
572
613
|
wrapped = f"tokensafe wrap {shlex.quote(stage)}"
|
|
573
|
-
return wrapped,
|
|
614
|
+
return wrapped, saved, reason, None
|
|
574
615
|
|
|
575
616
|
@classmethod
|
|
576
617
|
def sanitize(cls, command: str, cwd: Optional[str] = None) -> Tuple[Optional[str], int, str]:
|
|
@@ -787,6 +828,17 @@ class CommandSanitizer:
|
|
|
787
828
|
return None
|
|
788
829
|
resolved_exit = 0
|
|
789
830
|
elif resolved_exit != 0:
|
|
831
|
+
# Check test & compiler error compactor first (tsc error cascades, pytest failures)
|
|
832
|
+
from src.test_parsers import TestOutputParser
|
|
833
|
+
compacted_test, was_test = TestOutputParser.compact(raw)
|
|
834
|
+
if was_test and len(compacted_test) < len(raw) * 0.85:
|
|
835
|
+
return compacted_test, len(raw), len(compacted_test)
|
|
836
|
+
|
|
837
|
+
from src.build_parsers import BuildOutputParser
|
|
838
|
+
compacted_build, was_build = BuildOutputParser.compact(raw, resolved_exit)
|
|
839
|
+
if was_build and len(compacted_build) < len(raw) * 0.85:
|
|
840
|
+
return compacted_build, len(raw), len(compacted_build)
|
|
841
|
+
|
|
790
842
|
# Failed run: failure noise (progress dots / blank runs / verbose PASSED lines)
|
|
791
843
|
# is stripped while every traceback frame stays intact; skip when it saves <15%.
|
|
792
844
|
stripped = cls._strip_failure_noise(raw)
|
package/src/fts_index.py
CHANGED
|
@@ -13,6 +13,7 @@ import os
|
|
|
13
13
|
import sqlite3
|
|
14
14
|
import time
|
|
15
15
|
import hashlib
|
|
16
|
+
import shutil
|
|
16
17
|
from typing import List, Dict, Any, Optional, Tuple
|
|
17
18
|
|
|
18
19
|
from src.paths import resolve_data_dir
|
|
@@ -41,18 +42,36 @@ CODE_EXTS = {
|
|
|
41
42
|
}
|
|
42
43
|
|
|
43
44
|
|
|
45
|
+
from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
|
|
46
|
+
|
|
47
|
+
|
|
44
48
|
def _resolve_fts_db_path(project_root: str) -> str:
|
|
45
|
-
"""Returns path to the SQLite FTS database for a project.
|
|
46
|
-
|
|
49
|
+
"""Returns path to the SQLite FTS database for a project.
|
|
50
|
+
|
|
51
|
+
Always stores index in global user cache ~/.tokensafe/cache/fts/<project_hash>.db
|
|
52
|
+
so the project working tree is never polluted with binary database files.
|
|
53
|
+
"""
|
|
54
|
+
ensure_tokensafe_gitignore(project_root)
|
|
55
|
+
|
|
56
|
+
# Legacy cleanup: if fts.db was mistakenly created in project .tokensafe, migrate or remove
|
|
47
57
|
proj_tokensafe = os.path.join(project_root, ".tokensafe")
|
|
48
|
-
|
|
49
|
-
return os.path.join(proj_tokensafe, "fts.db")
|
|
58
|
+
legacy_file = os.path.join(proj_tokensafe, "fts.db")
|
|
50
59
|
|
|
51
|
-
# Otherwise store in ~/.tokensafe/cache/fts/<project_hash>.db
|
|
52
60
|
cache_dir = os.path.join(resolve_data_dir(), "cache", "fts")
|
|
53
61
|
os.makedirs(cache_dir, exist_ok=True)
|
|
54
62
|
p_hash = hashlib.sha256(os.path.abspath(project_root).encode("utf-8")).hexdigest()[:16]
|
|
55
|
-
|
|
63
|
+
target_path = os.path.join(cache_dir, f"fts_{p_hash}.db")
|
|
64
|
+
|
|
65
|
+
if os.path.isfile(legacy_file) and not os.path.isfile(target_path):
|
|
66
|
+
try:
|
|
67
|
+
shutil.move(legacy_file, target_path)
|
|
68
|
+
for extra in (f"{legacy_file}-wal", f"{legacy_file}-shm"):
|
|
69
|
+
if os.path.isfile(extra):
|
|
70
|
+
os.remove(extra)
|
|
71
|
+
except Exception:
|
|
72
|
+
pass
|
|
73
|
+
|
|
74
|
+
return target_path
|
|
56
75
|
|
|
57
76
|
|
|
58
77
|
class CodeFTSIndex:
|
package/src/installer.py
CHANGED
|
@@ -53,7 +53,7 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
53
53
|
"5. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path='.')` before exploratory multi-file reading (`project_path` defaults to active workspace). Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
|
|
54
54
|
"6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path='.')` to get all exported classes, types, and interfaces in a single markdown map without crawling files.\n"
|
|
55
55
|
"7. **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). Supports relative subfolders (`path='src'`).\n"
|
|
56
|
-
"8. **Command Sanitization, Build Compaction & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`, and build commands like `npm run build`, `vite build`, `next build`, `cargo build`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 3-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
|
|
56
|
+
"8. **Command Sanitization, Build Compaction & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`, and build/typecheck commands like `npm run build`, `vite build`, `next build`, `cargo build`, `tsc`, `tsc --noEmit`, `npm run typecheck`, `npx eslint`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 3-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest` in watch mode — pass the optional `cwd` to `sanitize_command` for test commands so the package.json peek can identify the runner behind opaque `yarn/npm test` scripts.\n"
|
|
57
57
|
"9. **Styles & Design Token Preservation**: When inspecting CSS, SCSS, LESS, or Tailwind, `smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors to protect project design integrity.\n"
|
|
58
58
|
"10. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage and Context Quality Score (Grade S-F); when it reports `warning` or `critical` (or Grade C/F), call `tokensafe:compact_conversation(transcript_path=...)` to fold history into a State Ledger with a 3-line Post-Compaction Orientation Digest before continuing.\n"
|
|
59
59
|
"11. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
|
|
@@ -1016,6 +1016,13 @@ WantedBy=default.target
|
|
|
1016
1016
|
cls._write_agents_plugins_config(project_dir, agents_plugin_path)
|
|
1017
1017
|
created.append(".agents/plugins.json")
|
|
1018
1018
|
|
|
1019
|
+
try:
|
|
1020
|
+
from src.paths import ensure_tokensafe_gitignore
|
|
1021
|
+
if ensure_tokensafe_gitignore(project_dir):
|
|
1022
|
+
created.append(".gitignore (.tokensafe/ registered)")
|
|
1023
|
+
except Exception:
|
|
1024
|
+
pass
|
|
1025
|
+
|
|
1019
1026
|
return {
|
|
1020
1027
|
"success": True,
|
|
1021
1028
|
"project_dir": project_dir,
|
package/src/mcp_server.py
CHANGED
|
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
|
42
42
|
|
|
43
43
|
SERVER_INFO = {
|
|
44
44
|
"name": "tokensafe-mcp",
|
|
45
|
-
"version": "4.1.
|
|
45
|
+
"version": "4.1.6"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -189,9 +189,9 @@ TOOLS = [
|
|
|
189
189
|
"type": "object",
|
|
190
190
|
"properties": {
|
|
191
191
|
"command": {"type": "string", "description": "Raw bash command line"},
|
|
192
|
+
"cmd": {"type": "string", "description": "Alias for command"},
|
|
192
193
|
"cwd": {"type": "string", "description": "Optional working directory the command will run in; enables the package.json peek that identifies the runner behind opaque yarn/npm test scripts"}
|
|
193
|
-
}
|
|
194
|
-
"required": ["command"]
|
|
194
|
+
}
|
|
195
195
|
}
|
|
196
196
|
},
|
|
197
197
|
{
|
|
@@ -221,6 +221,7 @@ TOOLS = [
|
|
|
221
221
|
"type": "object",
|
|
222
222
|
"properties": {
|
|
223
223
|
"command": {"type": "string", "description": "Optional: Terminal command line to audit"},
|
|
224
|
+
"cmd": {"type": "string", "description": "Alias for command"},
|
|
224
225
|
"code": {"type": "string", "description": "Optional: Code snippet, replacement diff, or file content to audit"},
|
|
225
226
|
"file_path": {"type": "string", "description": "Optional: File path being written or modified"}
|
|
226
227
|
}
|
|
@@ -735,8 +736,8 @@ def handle_tool_call(name: str, args: dict) -> dict:
|
|
|
735
736
|
if name == "smart_read_file" and isinstance(result, dict) and not result.get("isError"):
|
|
736
737
|
content_parts = result.get("content") or []
|
|
737
738
|
text_out = "".join(p.get("text", "") for p in content_parts if isinstance(p, dict))
|
|
738
|
-
path = args.get("path"
|
|
739
|
-
symbol = (args.get("symbol") or "").strip()
|
|
739
|
+
path = args.get("path") or args.get("file_path") or args.get("file") or ""
|
|
740
|
+
symbol = (args.get("symbol") or args.get("sym") or args.get("target") or "").strip()
|
|
740
741
|
_, eff_dep_mode = _resolve_dep_mode(args)
|
|
741
742
|
cache_sym = f"{symbol}@{eff_dep_mode}" if (symbol and eff_dep_mode != "signature") else symbol
|
|
742
743
|
is_ranged = args.get("start_line") is not None or args.get("end_line") is not None
|
|
@@ -779,8 +780,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
779
780
|
is_quota_exceeded = bool(quota.get("is_quota_exceeded", False))
|
|
780
781
|
|
|
781
782
|
if name == "smart_read_file":
|
|
782
|
-
path = args.get("path"
|
|
783
|
-
symbol = args.get("symbol"
|
|
783
|
+
path = args.get("path") or args.get("file_path") or args.get("file") or ""
|
|
784
|
+
symbol = args.get("symbol") or args.get("sym") or args.get("target") or ""
|
|
784
785
|
inc_deps, eff_dep_mode = _resolve_dep_mode(args)
|
|
785
786
|
force_full = bool(args.get("force_full", False))
|
|
786
787
|
start_line = args.get("start_line")
|
|
@@ -880,6 +881,49 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
880
881
|
except Exception:
|
|
881
882
|
pass
|
|
882
883
|
|
|
884
|
+
# Kubernetes manifests (.yaml / .yml with multiple resources):
|
|
885
|
+
if path.lower().endswith((".yaml", ".yml")):
|
|
886
|
+
from src.format_parsers.docker_k8s import ContainerAndK8sReducer
|
|
887
|
+
try:
|
|
888
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
889
|
+
raw_k8s_text = f.read()
|
|
890
|
+
reduced_k8s, was_k8s = ContainerAndK8sReducer.reduce_k8s_yaml(raw_k8s_text)
|
|
891
|
+
if was_k8s:
|
|
892
|
+
orig_t = count_tokens(raw_k8s_text)
|
|
893
|
+
opt_t = count_tokens(reduced_k8s)
|
|
894
|
+
tracker.record_event(
|
|
895
|
+
session_id=_mcp_session_id(),
|
|
896
|
+
event_type="K8S_MANIFEST_REDUCE",
|
|
897
|
+
original_tokens=orig_t,
|
|
898
|
+
optimized_tokens=opt_t,
|
|
899
|
+
details={"file": os.path.basename(path), "saved": orig_t - opt_t}
|
|
900
|
+
)
|
|
901
|
+
return {"content": [{"type": "text", "text": reduced_k8s}]}
|
|
902
|
+
except Exception:
|
|
903
|
+
pass
|
|
904
|
+
|
|
905
|
+
# Structured NDJSON / JSON log files (.ndjson, .log, .jsonl):
|
|
906
|
+
if path.lower().endswith((".ndjson", ".log", ".jsonl")):
|
|
907
|
+
from src.format_parsers.json_log import JSONLogReducer
|
|
908
|
+
try:
|
|
909
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
910
|
+
raw_log_text = f.read()
|
|
911
|
+
if JSONLogReducer.is_ndjson_log(raw_log_text):
|
|
912
|
+
reduced_log, was_log = JSONLogReducer.reduce(raw_log_text)
|
|
913
|
+
if was_log:
|
|
914
|
+
orig_t = count_tokens(raw_log_text)
|
|
915
|
+
opt_t = count_tokens(reduced_log)
|
|
916
|
+
tracker.record_event(
|
|
917
|
+
session_id=_mcp_session_id(),
|
|
918
|
+
event_type="JSON_LOG_REDUCE",
|
|
919
|
+
original_tokens=orig_t,
|
|
920
|
+
optimized_tokens=opt_t,
|
|
921
|
+
details={"file": os.path.basename(path), "saved": orig_t - opt_t}
|
|
922
|
+
)
|
|
923
|
+
return {"content": [{"type": "text", "text": reduced_log}]}
|
|
924
|
+
except Exception:
|
|
925
|
+
pass
|
|
926
|
+
|
|
883
927
|
# Heavy declarative schema files (OpenAPI/Swagger/Prisma/GraphQL/SQL DDL):
|
|
884
928
|
# generic AST skeletonization does not apply — route to the schema slicer.
|
|
885
929
|
# `symbol` carries the target (a spec path, model, type or table); an empty
|
|
@@ -1274,7 +1318,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1274
1318
|
}, indent=2, ensure_ascii=False)}]}
|
|
1275
1319
|
|
|
1276
1320
|
elif name == "sanitize_command":
|
|
1277
|
-
cmd = args.get("command"
|
|
1321
|
+
cmd = args.get("command") or args.get("cmd") or args.get("c") or ""
|
|
1278
1322
|
# Step 1: TokenSafe Guard security inspection
|
|
1279
1323
|
guard_res = TokenSafeGuard.inspect_command(cmd)
|
|
1280
1324
|
if guard_res.blocked:
|
|
@@ -1323,9 +1367,9 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1323
1367
|
return {"content": [{"type": "text", "text": json.dumps(result, indent=2)}]}
|
|
1324
1368
|
|
|
1325
1369
|
elif name == "guard_inspect":
|
|
1326
|
-
cmd = args.get("command")
|
|
1327
|
-
code = args.get("code")
|
|
1328
|
-
file_path = args.get("file_path"
|
|
1370
|
+
cmd = args.get("command") or args.get("cmd") or args.get("c")
|
|
1371
|
+
code = args.get("code") or args.get("snippet")
|
|
1372
|
+
file_path = args.get("file_path") or args.get("path") or args.get("file") or ""
|
|
1329
1373
|
|
|
1330
1374
|
results = []
|
|
1331
1375
|
if cmd is not None:
|
|
@@ -1618,7 +1662,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1618
1662
|
return {"content": [{"type": "text", "text": tree_output}]}
|
|
1619
1663
|
|
|
1620
1664
|
elif name == "scoped_search":
|
|
1621
|
-
query = args.get("query"
|
|
1665
|
+
query = args.get("query") or args.get("q") or args.get("pattern") or args.get("text") or ""
|
|
1622
1666
|
if not query:
|
|
1623
1667
|
return _fallback_error("scoped_search", "missing required 'query' argument")
|
|
1624
1668
|
|
package/src/mistakes.py
CHANGED
|
@@ -16,7 +16,7 @@ import time
|
|
|
16
16
|
import hashlib
|
|
17
17
|
import subprocess
|
|
18
18
|
from typing import Dict, Any, List, Optional
|
|
19
|
-
from src.paths import resolve_data_dir
|
|
19
|
+
from src.paths import resolve_data_dir, ensure_tokensafe_gitignore
|
|
20
20
|
|
|
21
21
|
|
|
22
22
|
def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
|
|
@@ -25,6 +25,7 @@ def _find_project_mistakes_file(project_root: Optional[str] = None) -> str:
|
|
|
25
25
|
proj_dir = os.path.join(project_root, ".tokensafe")
|
|
26
26
|
try:
|
|
27
27
|
os.makedirs(proj_dir, exist_ok=True)
|
|
28
|
+
ensure_tokensafe_gitignore(project_root)
|
|
28
29
|
return os.path.join(proj_dir, "mistakes.jsonl")
|
|
29
30
|
except Exception:
|
|
30
31
|
pass
|
package/src/paths.py
CHANGED
|
@@ -157,3 +157,47 @@ def get_active_workspace() -> Optional[str]:
|
|
|
157
157
|
except Exception:
|
|
158
158
|
pass
|
|
159
159
|
return None
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def ensure_tokensafe_gitignore(project_root: Optional[str]) -> bool:
|
|
163
|
+
"""
|
|
164
|
+
Ensures .tokensafe/ and local caches never leak into git.
|
|
165
|
+
1. If <project_root>/.tokensafe exists, drops an internal .gitignore (*\n!.gitignore\n).
|
|
166
|
+
2. If <project_root>/.gitignore exists, ensures .tokensafe/ is ignored.
|
|
167
|
+
"""
|
|
168
|
+
if not project_root or not os.path.isdir(project_root):
|
|
169
|
+
return False
|
|
170
|
+
|
|
171
|
+
updated = False
|
|
172
|
+
proj_tokensafe = os.path.join(project_root, ".tokensafe")
|
|
173
|
+
if os.path.isdir(proj_tokensafe):
|
|
174
|
+
inner_ignore = os.path.join(proj_tokensafe, ".gitignore")
|
|
175
|
+
if not os.path.isfile(inner_ignore):
|
|
176
|
+
try:
|
|
177
|
+
with open(inner_ignore, "w", encoding="utf-8") as f:
|
|
178
|
+
f.write("# TokenSafe local runtime artifacts & caches\n*\n!.gitignore\n")
|
|
179
|
+
updated = True
|
|
180
|
+
except Exception:
|
|
181
|
+
pass
|
|
182
|
+
|
|
183
|
+
root_gitignore = os.path.join(project_root, ".gitignore")
|
|
184
|
+
if os.path.isfile(root_gitignore):
|
|
185
|
+
try:
|
|
186
|
+
with open(root_gitignore, "r", encoding="utf-8", errors="replace") as f:
|
|
187
|
+
content = f.read()
|
|
188
|
+
lines = [ln.strip() for ln in content.splitlines()]
|
|
189
|
+
has_entry = any(
|
|
190
|
+
ln in (".tokensafe", ".tokensafe/", "/.tokensafe", "/.tokensafe/")
|
|
191
|
+
for ln in lines
|
|
192
|
+
)
|
|
193
|
+
if not has_entry:
|
|
194
|
+
with open(root_gitignore, "a", encoding="utf-8") as f:
|
|
195
|
+
if content and not content.endswith("\n"):
|
|
196
|
+
f.write("\n")
|
|
197
|
+
f.write("\n# TokenSafe local cache & runtime metrics\n.tokensafe/\n")
|
|
198
|
+
updated = True
|
|
199
|
+
except Exception:
|
|
200
|
+
pass
|
|
201
|
+
|
|
202
|
+
return updated
|
|
203
|
+
|
package/src/result_ledger.py
CHANGED
|
@@ -113,7 +113,7 @@ def _compact_read_result(text: str, path: str) -> Optional[str]:
|
|
|
113
113
|
|
|
114
114
|
|
|
115
115
|
def _compact_command_result(text: str) -> Optional[str]:
|
|
116
|
-
"""Test summaries first (PASS: ...), log-style head/tail otherwise."""
|
|
116
|
+
"""Test summaries first (PASS: ...), build/docker/log compaction next, log-style head/tail otherwise."""
|
|
117
117
|
try:
|
|
118
118
|
from src.test_parsers import TestOutputParser
|
|
119
119
|
compacted, was_test = TestOutputParser.compact(text)
|
|
@@ -121,6 +121,28 @@ def _compact_command_result(text: str) -> Optional[str]:
|
|
|
121
121
|
return compacted
|
|
122
122
|
except Exception:
|
|
123
123
|
pass
|
|
124
|
+
try:
|
|
125
|
+
from src.build_parsers import BuildOutputParser
|
|
126
|
+
compacted_b, was_b = BuildOutputParser.compact(text)
|
|
127
|
+
if was_b:
|
|
128
|
+
return compacted_b
|
|
129
|
+
except Exception:
|
|
130
|
+
pass
|
|
131
|
+
try:
|
|
132
|
+
from src.format_parsers.docker_k8s import ContainerAndK8sReducer
|
|
133
|
+
compacted_d, was_d = ContainerAndK8sReducer.reduce_docker_build(text)
|
|
134
|
+
if was_d:
|
|
135
|
+
return compacted_d
|
|
136
|
+
except Exception:
|
|
137
|
+
pass
|
|
138
|
+
try:
|
|
139
|
+
from src.format_parsers.json_log import JSONLogReducer
|
|
140
|
+
if JSONLogReducer.is_ndjson_log(text):
|
|
141
|
+
compacted_j, was_j = JSONLogReducer.reduce(text)
|
|
142
|
+
if was_j:
|
|
143
|
+
return compacted_j
|
|
144
|
+
except Exception:
|
|
145
|
+
pass
|
|
124
146
|
try:
|
|
125
147
|
from src.command_sanitizer import CommandSanitizer
|
|
126
148
|
compacted = CommandSanitizer.compact_test_output(text, 0)
|
package/src/telemetry_sync.py
CHANGED
|
@@ -241,7 +241,7 @@ class TelemetrySync:
|
|
|
241
241
|
current_last_id = last_id
|
|
242
242
|
headers = {
|
|
243
243
|
"Content-Type": "application/json",
|
|
244
|
-
"User-Agent": "TokenSafe-Sync/4.1.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.1.6"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.1.
|
|
20
|
+
CURRENT_VERSION = "4.1.6"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|