tokensafe 2.8.3 → 2.9.0
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/hooks/claude_code_hook.py +35 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +4 -4
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +15 -11
- package/src/command_sanitizer.py +67 -0
- package/src/installer.py +45 -8
- package/src/mcp_server.py +62 -32
- package/src/proxy.py +1 -1
- package/src/scoped_search.py +33 -10
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
|
@@ -172,6 +172,41 @@ def handle(event: str, payload: dict) -> dict:
|
|
|
172
172
|
}
|
|
173
173
|
return {}
|
|
174
174
|
|
|
175
|
+
if event == "PostToolUse":
|
|
176
|
+
# Auto-mute noisy stdout of successful shell commands (tests/linters/builds):
|
|
177
|
+
# feed the model a compact summary instead of letting it parse the full dump.
|
|
178
|
+
# Fail-open: {} leaves the raw output untouched.
|
|
179
|
+
tool = str(payload.get("tool_name") or "")
|
|
180
|
+
compacted, orig, new = None, 0, 0
|
|
181
|
+
try:
|
|
182
|
+
from src.command_sanitizer import CommandSanitizer
|
|
183
|
+
res = CommandSanitizer.compact_tool_output(tool, payload.get("tool_response"))
|
|
184
|
+
if res:
|
|
185
|
+
compacted, orig, new = res
|
|
186
|
+
except Exception:
|
|
187
|
+
compacted = None
|
|
188
|
+
if compacted:
|
|
189
|
+
try:
|
|
190
|
+
from src.metrics import MetricsTracker
|
|
191
|
+
from src.tokenizer import count_tokens
|
|
192
|
+
MetricsTracker().record_event(
|
|
193
|
+
session_id=session_id,
|
|
194
|
+
event_type="TOOL_OUTPUT_COMPACT",
|
|
195
|
+
original_tokens=count_tokens(str(payload.get("tool_response") or "")),
|
|
196
|
+
optimized_tokens=count_tokens(compacted),
|
|
197
|
+
details={"agent": AGENT, "tool": tool, "chars": f"{orig}->{new}"},
|
|
198
|
+
)
|
|
199
|
+
except Exception:
|
|
200
|
+
pass
|
|
201
|
+
return {
|
|
202
|
+
"decision": "block",
|
|
203
|
+
"reason": (
|
|
204
|
+
f"[TokenSafe] {tool} succeeded (exit 0) — verbose stdout auto-compacted "
|
|
205
|
+
f"({orig:,} → {new:,} chars). Command already completed; do not retry. Summary:\n{compacted}"
|
|
206
|
+
),
|
|
207
|
+
}
|
|
208
|
+
return {}
|
|
209
|
+
|
|
175
210
|
return {}
|
|
176
211
|
|
|
177
212
|
|
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.9.0",
|
|
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,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.
|
|
4
|
+
"version": "2.9.0",
|
|
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/rules/AGENTS.md
CHANGED
|
@@ -29,11 +29,11 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
29
29
|
|
|
30
30
|
### 3. Architecture & Code Navigation Directives (Graph-Guided)
|
|
31
31
|
1. **Zero Raw Terminal Grep/Find (Blocked & Replaced by `scoped_search`)**: 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. To search for text, symbols, or functions across unknown files, ALWAYS call `tokensafe:scoped_search(query, path=".", scope="code")`. The `path` parameter accepts the project root or subfolder (`"."`, `"./src"`), and `scope` accepts file categories (`"code"`, `"config"`, `"all"`), file extensions (`"go"`, `"ts"`), or subfolders (`"internal/promo"`).
|
|
32
|
-
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).
|
|
33
|
-
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.
|
|
34
|
-
4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.
|
|
32
|
+
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `"src/service.ts"` or absolute) 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).
|
|
33
|
+
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 (`project_path` defaults to active workspace).
|
|
34
|
+
4. **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.
|
|
35
35
|
5. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
|
|
36
|
-
6. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens).
|
|
36
|
+
6. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path=".", depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
|
|
37
37
|
7. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
|
|
38
38
|
8. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check window usage (tools/history/prompts breakdown, 50/80/95% thresholds). When it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a State Ledger instead of letting code quality degrade.
|
|
39
39
|
|
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.9.0",
|
|
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.9.0",
|
|
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.9.0",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -24,7 +24,7 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
24
24
|
- **Mandatory Search Tool (`scoped_search`)**: ALWAYS call `tokensafe:scoped_search(query, path=".", scope="code")` to search for text, identifiers, or symbol definitions across unknown files (-90% tokens). The `path` parameter specifies the search directory or project root (e.g. `"."`, `"./src"`). The `scope` parameter filters files (`"code"`, `"config"`, `"all"`), a file extension (`"go"`, `"ts"`), or a subfolder path (`"internal/promo"`).
|
|
25
25
|
|
|
26
26
|
2. **SYMBOL & COMPONENT EXTRACTION (`smart_read_file`)**:
|
|
27
|
-
- 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
|
+
- When locating or reading any function, component, class, or handler (e.g. `<LuckyWheelTab>`, `areSectorEqual`, `useWallet`), ALWAYS call `tokensafe:smart_read_file` with `path` (supports relative paths, e.g. `"src/service.ts"`) and `symbol`.
|
|
28
28
|
- **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.
|
|
29
29
|
- **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.
|
|
30
30
|
- **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.
|
|
@@ -32,31 +32,35 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
32
32
|
- **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -98% tokens).
|
|
33
33
|
|
|
34
34
|
3. **ARCHITECTURE SURVEY BEFORE BROWSING (`get_architecture_graph`)**:
|
|
35
|
-
- Before multi-file exploration or asking where things are located, ALWAYS call `tokensafe:get_architecture_graph(project_path)
|
|
35
|
+
- Before multi-file exploration or asking where things are located, ALWAYS call `tokensafe:get_architecture_graph(project_path=".")` (`project_path` defaults to active workspace).
|
|
36
36
|
- **Result**: Returns top architectural God Nodes, dependency hubs, and centrality rankings in < 250 tokens without file crawling.
|
|
37
37
|
|
|
38
38
|
4. **API SURFACE INSPECTION (`get_api_surface`)**:
|
|
39
|
-
- Call `tokensafe:get_api_surface(project_path)` to get all exported classes, types, interfaces, and function signatures in a single compact markdown map.
|
|
39
|
+
- Call `tokensafe:get_api_surface(project_path=".")` (`project_path` defaults to active workspace) to get all exported classes, types, interfaces, and function signatures in a single compact markdown map.
|
|
40
40
|
|
|
41
|
-
5. **
|
|
41
|
+
5. **DIRECTORY NAVIGATION (`list_dir`)**:
|
|
42
|
+
- NEVER run `ls -la` or `ls -l` in terminal.
|
|
43
|
+
- Call `tokensafe:list_dir(path=".", depth=2)` for clean directory trees without permissions, timestamps, or lockfiles (-90% tokens). Supports relative subfolders (`path="src"`).
|
|
44
|
+
|
|
45
|
+
6. **SURGICAL FILE EDITS (`edit_file`)**:
|
|
42
46
|
- On existing files with >= 40 lines, wholesale rewrites via `write_file` are blocked by **Output Guard**. Always use `edit_file` with precise `Target` and `Replacement` blocks.
|
|
43
47
|
|
|
44
|
-
|
|
48
|
+
7. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
|
|
45
49
|
- Never provide real private keys, API secrets, or credentials as fallback values in `os.environ.get()` or `process.env`. Real credentials must exist strictly in environment variables.
|
|
46
50
|
|
|
47
|
-
|
|
51
|
+
8. **CONTEXT BUDGET BEFORE HEAVY WORK (`context_budget` → `compact_conversation`)**:
|
|
48
52
|
- Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check the window budget (tools/history/prompts breakdown, 50/80/95% thresholds).
|
|
49
53
|
- When it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a State Ledger before continuing — do not let context exhaustion degrade code quality mid-task.
|
|
50
54
|
|
|
51
|
-
|
|
55
|
+
9. **REPEAT READ DEDUPLICATION & CACHE POINTERS**:
|
|
52
56
|
- Never repeatedly re-read the same file or symbol within an active session.
|
|
53
57
|
- When `smart_read_file` returns a pointer hit (`// [TokenSafe: Pointer Hit for ...]`), reuse earlier context; pass `"force_full": true` only if your context was compacted or you are a fresh subagent lacking prior turns.
|
|
54
58
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
59
|
+
10. **ZERO-FLUFF EGRESS & SURGICAL DIFFS**:
|
|
60
|
+
- Eliminate conversational preambles, courtesy fillers, and trailing sign-offs.
|
|
61
|
+
- Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.
|
|
58
62
|
|
|
59
|
-
|
|
63
|
+
11. **COMPACT TEST EXECUTION**:
|
|
60
64
|
- Run unit tests with concise flags or via `tokensafe tests [cmd]` so passing test suites emit a single-line summary (`PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full traceback is strictly preserved on failure.
|
|
61
65
|
|
|
62
66
|
---
|
package/src/command_sanitizer.py
CHANGED
|
@@ -651,3 +651,70 @@ class CommandSanitizer:
|
|
|
651
651
|
return f"PASS: {lines[0]} ... {lines[-1]} (exit code 0)"
|
|
652
652
|
|
|
653
653
|
return raw
|
|
654
|
+
|
|
655
|
+
# PostToolUse shell tools whose stdout can be compacted (hook payload tool_name)
|
|
656
|
+
SHELL_TOOL_NAMES = {
|
|
657
|
+
"Bash", "bash", "Shell", "shell", "sh",
|
|
658
|
+
"run_command", "RunCommand", "execute_command", "ExecuteCommand", "terminal", "Terminal",
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
@staticmethod
|
|
662
|
+
def _extract_tool_stdout(response: Any) -> Tuple[str, Optional[int]]:
|
|
663
|
+
"""Extracts (stdout_text, exit_code_or_None) from a PostToolUse tool_response payload.
|
|
664
|
+
Handles plain strings, {stdout|output|content|text|result} dicts, content-block lists,
|
|
665
|
+
and common exit-code keys (exit_code/exitCode/returncode/code, success booleans)."""
|
|
666
|
+
if isinstance(response, str):
|
|
667
|
+
return response, None
|
|
668
|
+
if isinstance(response, dict):
|
|
669
|
+
stdout = ""
|
|
670
|
+
for key in ("stdout", "output", "content", "text", "result"):
|
|
671
|
+
val = response.get(key)
|
|
672
|
+
if isinstance(val, str) and val:
|
|
673
|
+
stdout = val
|
|
674
|
+
break
|
|
675
|
+
if not stdout:
|
|
676
|
+
blocks = response.get("content")
|
|
677
|
+
if isinstance(blocks, list):
|
|
678
|
+
texts = [
|
|
679
|
+
b.get("text", "") for b in blocks
|
|
680
|
+
if isinstance(b, dict) and isinstance(b.get("text"), str)
|
|
681
|
+
]
|
|
682
|
+
stdout = "\n".join(t for t in texts if t)
|
|
683
|
+
exit_code = None
|
|
684
|
+
for key in ("exit_code", "exitCode", "returncode", "return_code", "code"):
|
|
685
|
+
val = response.get(key)
|
|
686
|
+
if isinstance(val, (int, float)) and not isinstance(val, bool):
|
|
687
|
+
exit_code = int(val)
|
|
688
|
+
break
|
|
689
|
+
if exit_code is None:
|
|
690
|
+
if response.get("success") is True:
|
|
691
|
+
exit_code = 0
|
|
692
|
+
elif response.get("success") is False or response.get("error"):
|
|
693
|
+
exit_code = 1
|
|
694
|
+
return stdout, exit_code
|
|
695
|
+
return "", None
|
|
696
|
+
|
|
697
|
+
@classmethod
|
|
698
|
+
def compact_tool_output(cls, tool_name: str, tool_response: Any) -> Optional[Tuple[str, int, int]]:
|
|
699
|
+
"""
|
|
700
|
+
PostToolUse helper: compacts verbose successful shell output before the model reads it.
|
|
701
|
+
Returns (compacted_text, original_chars, compacted_chars), or None when not applicable:
|
|
702
|
+
non-shell tool, short output, failed command, or when compaction saves too little.
|
|
703
|
+
Fail-open by design — callers must degrade to the raw output on None.
|
|
704
|
+
"""
|
|
705
|
+
if str(tool_name or "") not in cls.SHELL_TOOL_NAMES:
|
|
706
|
+
return None
|
|
707
|
+
raw, resolved_exit = cls._extract_tool_stdout(tool_response)
|
|
708
|
+
if not raw or len(raw) < 400:
|
|
709
|
+
return None
|
|
710
|
+
if resolved_exit is None:
|
|
711
|
+
# Unknown exit status: refuse to mute anything that looks like a failure
|
|
712
|
+
if re.search(r"Traceback|AssertionError|\bERROR\b|FAILED|exit code [1-9]", raw):
|
|
713
|
+
return None
|
|
714
|
+
resolved_exit = 0
|
|
715
|
+
elif resolved_exit != 0:
|
|
716
|
+
return None
|
|
717
|
+
compacted = cls.compact_test_output(raw, resolved_exit)
|
|
718
|
+
if compacted is raw or len(compacted) >= len(raw) * 0.6:
|
|
719
|
+
return None
|
|
720
|
+
return compacted, len(raw), len(compacted)
|
package/src/installer.py
CHANGED
|
@@ -46,12 +46,12 @@ 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 & Replaced by `scoped_search`)**: 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. To search for text, symbols, or functions across unknown files, ALWAYS call `tokensafe:scoped_search(query, path='.', scope='code')`. The `path` parameter accepts the project root or subfolder (`'.'`), and `scope` accepts categories (`'code'`, `'config'`, `'all'`), extensions (`'go'`, `'ts'`), or subfolders (`'internal/promo'`).\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"
|
|
49
|
+
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` (relative e.g. `'src/service.ts'` or absolute) 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. **Repeat Read Deduplication**: Never repeatedly re-read unchanged files or symbols within the same session. Reuse the earlier skeleton or pointer hit (`// [TokenSafe: Pointer Hit ...]`); pass `force_full=true` only if context was compacted or you are a fresh subagent.\n"
|
|
51
51
|
"4. **Zero-Fluff Egress & Surgical Diffs**: Omit conversational filler, courtesy preambles, and sign-offs. Provide concise bullet prose. Never reprint full unmodified files or lengthy boilerplate; link to file line ranges (`file.ts#L10-L25`) and output surgical diffs.\n"
|
|
52
|
-
"5. **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"
|
|
53
|
-
"6. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
|
|
54
|
-
"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).\n"
|
|
52
|
+
"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"
|
|
53
|
+
"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"
|
|
54
|
+
"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"
|
|
55
55
|
"8. **Command Sanitization & 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`) — compound commands (`a && b ; c`) are rewritten per stage. Run unit tests with concise flags or via the `tokensafe tests [cmd]` CLI (compact passing summary `PASS: ...`, full traceback 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
56
|
"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"
|
|
57
57
|
"10. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to inspect window usage; when it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` before continuing.\n"
|
|
@@ -63,6 +63,20 @@ UNIFIED_TOKENSAFE_RULE = (
|
|
|
63
63
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
|
64
64
|
)
|
|
65
65
|
|
|
66
|
+
# Short pointer written into PROJECT-level rule files when the full protocol is
|
|
67
|
+
# already installed at the agent-global level (~/.zcode/AGENTS.md etc.).
|
|
68
|
+
# Keeps every session's meta-context lean: ~110 tokens instead of ~850.
|
|
69
|
+
POINTER_RULE = (
|
|
70
|
+
"## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
|
|
71
|
+
"The full 12-point protocol is installed globally in the agent-level instructions "
|
|
72
|
+
"(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md) and applies to this project. "
|
|
73
|
+
"Core rules: never raw grep/find or `ls -la` — use `tokensafe:scoped_search`, "
|
|
74
|
+
"`tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
|
|
75
|
+
"sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` "
|
|
76
|
+
"before large tasks and compact via `tokensafe:compact_conversation`; never hardcode secret "
|
|
77
|
+
"fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
|
|
78
|
+
)
|
|
79
|
+
|
|
66
80
|
AGENTS_REGISTRY = {
|
|
67
81
|
"antigravity": {
|
|
68
82
|
"name": "Google Antigravity",
|
|
@@ -191,7 +205,7 @@ class AgentInstaller:
|
|
|
191
205
|
def install_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
192
206
|
"""Registers TokenSafe lifecycle-hook adapters with agents that support them.
|
|
193
207
|
Claude Code: SessionStart (one-shot directives) + UserPromptSubmit (TOCP
|
|
194
|
-
injection) + PreToolUse (shell guard).
|
|
208
|
+
injection) + PreToolUse (shell guard) + PostToolUse (stdout compaction).
|
|
195
209
|
Cursor: beforeShellExecution / beforeReadFile guards.
|
|
196
210
|
Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
|
|
197
211
|
if agent_key == "codex":
|
|
@@ -212,6 +226,7 @@ class AgentInstaller:
|
|
|
212
226
|
prompt_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
213
227
|
bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
214
228
|
session_entry = {"hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
229
|
+
post_bash_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": claude_cmd, "timeout": 10}]}
|
|
215
230
|
|
|
216
231
|
def _sync_claude_event(event_name: str, default_entry: dict) -> bool:
|
|
217
232
|
entries = hooks.get(event_name)
|
|
@@ -237,12 +252,13 @@ class AgentInstaller:
|
|
|
237
252
|
_sync_claude_event("SessionStart", session_entry),
|
|
238
253
|
_sync_claude_event("UserPromptSubmit", prompt_entry),
|
|
239
254
|
_sync_claude_event("PreToolUse", bash_entry),
|
|
255
|
+
_sync_claude_event("PostToolUse", post_bash_entry),
|
|
240
256
|
])
|
|
241
257
|
if not changed:
|
|
242
258
|
return True, "TokenSafe Claude Code hooks already registered"
|
|
243
259
|
data["hooks"] = hooks
|
|
244
260
|
cls._atomic_write_json(config_file, data)
|
|
245
|
-
return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard)"
|
|
261
|
+
return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard + PostToolUse stdout compact)"
|
|
246
262
|
|
|
247
263
|
# cursor
|
|
248
264
|
config_file = os.path.join(HOME, ".cursor", "hooks.json")
|
|
@@ -593,6 +609,23 @@ class AgentInstaller:
|
|
|
593
609
|
skill_src = os.path.join(PROJECT_ROOT, "skills", "token-optimizer")
|
|
594
610
|
cls._symlink_dir(skill_src, target_path)
|
|
595
611
|
|
|
612
|
+
@classmethod
|
|
613
|
+
def _global_rule_installed(cls) -> bool:
|
|
614
|
+
"""True if any agent-global rules file already carries the tokensafe block,
|
|
615
|
+
meaning project-level files can reference it instead of duplicating it."""
|
|
616
|
+
for info in AGENTS_REGISTRY.values():
|
|
617
|
+
for key in ("agents_md_path", "rules_path"):
|
|
618
|
+
path = info.get(key)
|
|
619
|
+
if not path or not os.path.isfile(path):
|
|
620
|
+
continue
|
|
621
|
+
try:
|
|
622
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
623
|
+
if "<!-- tokensafe -->" in f.read():
|
|
624
|
+
return True
|
|
625
|
+
except Exception:
|
|
626
|
+
continue
|
|
627
|
+
return False
|
|
628
|
+
|
|
596
629
|
@classmethod
|
|
597
630
|
def install_project(
|
|
598
631
|
cls,
|
|
@@ -627,13 +660,17 @@ class AgentInstaller:
|
|
|
627
660
|
"---\n\n"
|
|
628
661
|
)
|
|
629
662
|
|
|
663
|
+
# Rules dedup: when the full protocol is already installed globally,
|
|
664
|
+
# project files get the short pointer instead of the ~850-token block.
|
|
665
|
+
project_rule = POINTER_RULE if cls._global_rule_installed() else UNIFIED_TOKENSAFE_RULE
|
|
666
|
+
|
|
630
667
|
created = []
|
|
631
668
|
for rf in rule_files:
|
|
632
669
|
try:
|
|
633
670
|
if rf.endswith(".mdc"):
|
|
634
|
-
cls._write_file_safely(rf, cursor_mdc_header +
|
|
671
|
+
cls._write_file_safely(rf, cursor_mdc_header + project_rule)
|
|
635
672
|
else:
|
|
636
|
-
cls._inject_global_rule(rf,
|
|
673
|
+
cls._inject_global_rule(rf, project_rule)
|
|
637
674
|
created.append(os.path.relpath(rf, project_dir))
|
|
638
675
|
except Exception:
|
|
639
676
|
pass
|
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": "2.
|
|
45
|
+
"version": "2.9.0"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -80,15 +80,15 @@ def _client_supports_pointers() -> bool:
|
|
|
80
80
|
TOOLS = [
|
|
81
81
|
{
|
|
82
82
|
"name": "smart_read_file",
|
|
83
|
-
"description": "
|
|
83
|
+
"description": "AST-skeleton file reader: keeps the target function/class body + 1-line 1-hop dependency signatures, folds inert code (-90-99% tokens). Relative or absolute paths. Schema files (OpenAPI/Prisma/GraphQL/SQL) auto-slice via 'symbol'. For 3+ related symbols use smart_bundle instead.",
|
|
84
84
|
"inputSchema": {
|
|
85
85
|
"type": "object",
|
|
86
86
|
"properties": {
|
|
87
|
-
"path": {"type": "string", "description": "
|
|
88
|
-
"symbol": {"type": "string", "description": "Optional:
|
|
89
|
-
"include_deps": {"type": "boolean", "description": "
|
|
90
|
-
"dep_mode": {"type": "string", "enum": ["signature", "full"], "description": "
|
|
91
|
-
"force_full": {"type": "boolean", "description": "
|
|
87
|
+
"path": {"type": "string", "description": "File path (relative to workspace or absolute)"},
|
|
88
|
+
"symbol": {"type": "string", "description": "Optional: function/method/class/component or schema model/type/table to extract (omit for whole-file skeleton)"},
|
|
89
|
+
"include_deps": {"type": "boolean", "description": "Include 1-hop dependency signatures (default true)"},
|
|
90
|
+
"dep_mode": {"type": "string", "enum": ["signature", "full"], "description": "'signature' (default) = 1-line dep signatures; 'full' = inline dependency bodies"},
|
|
91
|
+
"force_full": {"type": "boolean", "description": "Bypass pointer dedup — use only after context compaction or as a fresh subagent"},
|
|
92
92
|
"start_line": {"type": "integer", "description": "Optional: starting line number"},
|
|
93
93
|
"end_line": {"type": "integer", "description": "Optional: ending line number"}
|
|
94
94
|
},
|
|
@@ -97,7 +97,7 @@ TOOLS = [
|
|
|
97
97
|
},
|
|
98
98
|
{
|
|
99
99
|
"name": "smart_bundle",
|
|
100
|
-
"description": "Reads 2-8 related symbols across
|
|
100
|
+
"description": "Reads 2-8 related symbols across files as ONE merged bundle: per-file skeletons, deduplicated shared imports, merged 1-hop dep signatures. Replaces 3+ separate smart_read_file calls in a single roundtrip.",
|
|
101
101
|
"inputSchema": {
|
|
102
102
|
"type": "object",
|
|
103
103
|
"properties": {
|
|
@@ -107,37 +107,37 @@ TOOLS = [
|
|
|
107
107
|
"items": {
|
|
108
108
|
"type": "object",
|
|
109
109
|
"properties": {
|
|
110
|
-
"path": {"type": "string", "description": "
|
|
111
|
-
"symbol": {"type": "string", "description": "Optional symbol to keep unfolded
|
|
110
|
+
"path": {"type": "string", "description": "File path (relative or absolute)"},
|
|
111
|
+
"symbol": {"type": "string", "description": "Optional symbol to keep unfolded"}
|
|
112
112
|
},
|
|
113
113
|
"required": ["path"]
|
|
114
114
|
},
|
|
115
|
-
"description": "Up to 8 {path, symbol} targets;
|
|
115
|
+
"description": "Up to 8 {path, symbol} targets; several symbols of one file = separate entries"
|
|
116
116
|
},
|
|
117
|
-
"include_deps": {"type": "boolean", "description": "
|
|
118
|
-
"dep_mode": {"type": "string", "enum": ["signature", "full"], "description": "
|
|
119
|
-
"force_full": {"type": "boolean", "description": "
|
|
117
|
+
"include_deps": {"type": "boolean", "description": "Include merged 1-hop dep signatures (default true)"},
|
|
118
|
+
"dep_mode": {"type": "string", "enum": ["signature", "full"], "description": "Parity only; bundles always merge signatures"},
|
|
119
|
+
"force_full": {"type": "boolean", "description": "Bypass session pointer dedup"}
|
|
120
120
|
},
|
|
121
121
|
"required": ["targets"]
|
|
122
122
|
}
|
|
123
123
|
},
|
|
124
124
|
{
|
|
125
125
|
"name": "get_architecture_graph",
|
|
126
|
-
"description": "Returns top architectural God Nodes and dependency topology for the target project. Call this BEFORE reading files or searching.",
|
|
126
|
+
"description": "Returns top architectural God Nodes and dependency topology for the target project in < 250 tokens without file crawling. Call this BEFORE reading files or searching.",
|
|
127
127
|
"inputSchema": {
|
|
128
128
|
"type": "object",
|
|
129
129
|
"properties": {
|
|
130
|
-
"project_path": {"type": "string", "description": "
|
|
130
|
+
"project_path": {"type": "string", "description": "Optional root path of the project (defaults to active workspace, or pass '.' or absolute path)"}
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
133
|
},
|
|
134
134
|
{
|
|
135
135
|
"name": "get_api_surface",
|
|
136
|
-
"description": "Generates and returns a compact markdown map of all exported interfaces, classes, and types in the project.",
|
|
136
|
+
"description": "Generates and returns a compact markdown map of all exported interfaces, classes, and types in the project without crawling files.",
|
|
137
137
|
"inputSchema": {
|
|
138
138
|
"type": "object",
|
|
139
139
|
"properties": {
|
|
140
|
-
"project_path": {"type": "string", "description": "
|
|
140
|
+
"project_path": {"type": "string", "description": "Optional root path of the project (defaults to active workspace, or pass '.' or absolute path)"}
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
143
|
},
|
|
@@ -228,11 +228,11 @@ TOOLS = [
|
|
|
228
228
|
},
|
|
229
229
|
{
|
|
230
230
|
"name": "list_dir",
|
|
231
|
-
"description": "Returns a clean, token-efficient directory tree up to depth N without permissions, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces verbose ls -la.",
|
|
231
|
+
"description": "Returns a clean, token-efficient directory tree up to depth N without permissions, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces verbose ls -la. Pass '.' for project root or a subfolder like 'src'.",
|
|
232
232
|
"inputSchema": {
|
|
233
233
|
"type": "object",
|
|
234
234
|
"properties": {
|
|
235
|
-
"path": {"type": "string", "description": "Path to the directory (relative to
|
|
235
|
+
"path": {"type": "string", "description": "Path to the directory (relative to workspace or absolute, e.g. '.', './src')"},
|
|
236
236
|
"depth": {"type": "integer", "description": "Maximum traversal depth (default: 2, max: 4)"},
|
|
237
237
|
"max_entries": {"type": "integer", "description": "Maximum entries to display before pruning (default: 80)"}
|
|
238
238
|
},
|
|
@@ -241,37 +241,37 @@ TOOLS = [
|
|
|
241
241
|
},
|
|
242
242
|
{
|
|
243
243
|
"name": "scoped_search",
|
|
244
|
-
"description": "Safe, token-bounded symbol
|
|
244
|
+
"description": "Safe, token-bounded symbol/text search replacing raw grep/find (-90% tokens). '|' or \\d in query auto-enables regex when use_regex is omitted; false forces literal.",
|
|
245
245
|
"inputSchema": {
|
|
246
246
|
"type": "object",
|
|
247
247
|
"properties": {
|
|
248
248
|
"query": {
|
|
249
249
|
"type": "string",
|
|
250
|
-
"description": "Text, identifier, or symbol name
|
|
250
|
+
"description": "Text, identifier, or symbol name"
|
|
251
251
|
},
|
|
252
252
|
"scope": {
|
|
253
253
|
"type": "string",
|
|
254
|
-
"description": "Filter
|
|
254
|
+
"description": "Filter: 'code', 'config', 'all', extension ('go', '*.py'), or subfolder ('internal/promo') (default 'all')"
|
|
255
255
|
},
|
|
256
256
|
"path": {
|
|
257
257
|
"type": "string",
|
|
258
|
-
"description": "Directory
|
|
258
|
+
"description": "Directory to search (alias for project_path; relative or absolute)"
|
|
259
259
|
},
|
|
260
260
|
"project_path": {
|
|
261
261
|
"type": "string",
|
|
262
|
-
"description": "Optional root directory
|
|
262
|
+
"description": "Optional root directory (defaults to current project)"
|
|
263
263
|
},
|
|
264
264
|
"max_results": {
|
|
265
265
|
"type": "integer",
|
|
266
|
-
"description": "
|
|
266
|
+
"description": "Max matching lines (default 25, max 100)"
|
|
267
267
|
},
|
|
268
268
|
"case_sensitive": {
|
|
269
269
|
"type": "boolean",
|
|
270
|
-
"description": "
|
|
270
|
+
"description": "Case-sensitive search (default false)"
|
|
271
271
|
},
|
|
272
272
|
"use_regex": {
|
|
273
273
|
"type": "boolean",
|
|
274
|
-
"description": "
|
|
274
|
+
"description": "Omit = auto-detect ('|', \\d → regex); false = literal; true = regex"
|
|
275
275
|
}
|
|
276
276
|
},
|
|
277
277
|
"required": ["query"]
|
|
@@ -742,8 +742,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
742
742
|
if start_line is not None:
|
|
743
743
|
start_line = max(1, start_line)
|
|
744
744
|
|
|
745
|
+
active_ws = get_active_workspace()
|
|
746
|
+
if path and not os.path.isabs(path):
|
|
747
|
+
if active_ws and os.path.exists(os.path.join(active_ws, path)):
|
|
748
|
+
path = os.path.abspath(os.path.join(active_ws, path))
|
|
749
|
+
else:
|
|
750
|
+
path = os.path.abspath(path)
|
|
751
|
+
elif path:
|
|
752
|
+
path = os.path.abspath(path)
|
|
753
|
+
|
|
745
754
|
if not path or not os.path.exists(path):
|
|
746
755
|
return {"isError": True, "content": [{"type": "text", "text": f"File not found: {path}"}]}
|
|
756
|
+
if is_plugin_or_system_dir(path):
|
|
757
|
+
return _fallback_error("smart_read_file", f"refusing to read from system root or plugin dir '{path}'")
|
|
747
758
|
try:
|
|
748
759
|
st = os.stat(path)
|
|
749
760
|
if not stat.S_ISREG(st.st_mode):
|
|
@@ -945,11 +956,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
945
956
|
inc_deps, _eff_dep_mode = _resolve_dep_mode(args)
|
|
946
957
|
max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
|
|
947
958
|
|
|
959
|
+
active_ws = get_active_workspace()
|
|
948
960
|
by_file: Dict[str, List[str]] = {}
|
|
949
961
|
for t in targets:
|
|
950
962
|
if not isinstance(t, dict) or not str(t.get("path") or "").strip():
|
|
951
963
|
return _fallback_error("smart_bundle", "each target must be {path: str, symbol?: str}")
|
|
952
|
-
|
|
964
|
+
raw_p = str(t["path"]).strip()
|
|
965
|
+
if not os.path.isabs(raw_p) and active_ws and os.path.exists(os.path.join(active_ws, raw_p)):
|
|
966
|
+
target_p = os.path.abspath(os.path.join(active_ws, raw_p))
|
|
967
|
+
else:
|
|
968
|
+
target_p = os.path.abspath(raw_p)
|
|
969
|
+
if is_plugin_or_system_dir(target_p):
|
|
970
|
+
return _fallback_error("smart_bundle", f"refusing to read from system root or plugin dir '{raw_p}'")
|
|
971
|
+
by_file.setdefault(target_p, []).append(str(t.get("symbol") or "").strip())
|
|
953
972
|
|
|
954
973
|
missing = [p for p in by_file if not os.path.isfile(p)]
|
|
955
974
|
if missing:
|
|
@@ -1440,10 +1459,20 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1440
1459
|
if not path:
|
|
1441
1460
|
return _fallback_error("list_dir", "missing required 'path' argument")
|
|
1442
1461
|
|
|
1443
|
-
# Resolve path relative to
|
|
1444
|
-
|
|
1462
|
+
# Resolve path relative to active workspace, cwd, or absolute
|
|
1463
|
+
active_ws = get_active_workspace()
|
|
1464
|
+
if not os.path.isabs(path):
|
|
1465
|
+
if active_ws and os.path.isdir(os.path.join(active_ws, path)):
|
|
1466
|
+
abs_path = os.path.abspath(os.path.join(active_ws, path))
|
|
1467
|
+
else:
|
|
1468
|
+
abs_path = os.path.abspath(path)
|
|
1469
|
+
else:
|
|
1470
|
+
abs_path = os.path.abspath(path)
|
|
1471
|
+
|
|
1445
1472
|
if not os.path.isdir(abs_path):
|
|
1446
1473
|
return _fallback_error("list_dir", f"directory not found: {abs_path}")
|
|
1474
|
+
if is_plugin_or_system_dir(abs_path):
|
|
1475
|
+
return _fallback_error("list_dir", f"refusing to inspect system root or plugin dir '{path}'")
|
|
1447
1476
|
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
1448
1477
|
depth = _safe_int(args.get("depth"), 2, lo=1, hi=4)
|
|
1449
1478
|
if abs_path in system_roots:
|
|
@@ -1507,7 +1536,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1507
1536
|
|
|
1508
1537
|
max_res = _safe_int(args.get("max_results"), 25, lo=1, hi=100)
|
|
1509
1538
|
c_sens = bool(args.get("case_sensitive", False))
|
|
1510
|
-
|
|
1539
|
+
raw_regex = args.get("use_regex")
|
|
1540
|
+
u_regex = None if raw_regex is None else bool(raw_regex)
|
|
1511
1541
|
|
|
1512
1542
|
res = ScopedSearch.search(
|
|
1513
1543
|
query=query,
|
package/src/proxy.py
CHANGED
|
@@ -30,7 +30,7 @@ from src.governor import ContextGovernor
|
|
|
30
30
|
from src.paths import resolve_data_dir
|
|
31
31
|
|
|
32
32
|
DEFAULT_PORT = 8765
|
|
33
|
-
DEFAULT_HOST = os.environ.get("HOST", os.environ.get("TOKENSAFE_HOST", "
|
|
33
|
+
DEFAULT_HOST = os.environ.get("HOST", os.environ.get("TOKENSAFE_HOST", "127.0.0.1"))
|
|
34
34
|
DEFAULT_UPSTREAM = "https://api.deepseek.com/v1"
|
|
35
35
|
|
|
36
36
|
class EventBroadcaster:
|
package/src/scoped_search.py
CHANGED
|
@@ -77,6 +77,17 @@ class ScopedSearch:
|
|
|
77
77
|
return ext == f".{scope}"
|
|
78
78
|
return True
|
|
79
79
|
|
|
80
|
+
@classmethod
|
|
81
|
+
def _looks_like_regex(cls, query: str) -> bool:
|
|
82
|
+
"""Conservative auto-detection for use_regex=None (omitted): only
|
|
83
|
+
unambiguous regex constructs switch the mode — alternation pipes and
|
|
84
|
+
backslash character classes. Plain dots/brackets stay literal."""
|
|
85
|
+
if "|" in query:
|
|
86
|
+
return True
|
|
87
|
+
if re.search(r"\\[dwsbDWSB]", query):
|
|
88
|
+
return True
|
|
89
|
+
return False
|
|
90
|
+
|
|
80
91
|
@classmethod
|
|
81
92
|
def search(
|
|
82
93
|
cls,
|
|
@@ -85,7 +96,7 @@ class ScopedSearch:
|
|
|
85
96
|
scope: str = "all",
|
|
86
97
|
max_results: int = 25,
|
|
87
98
|
case_sensitive: bool = False,
|
|
88
|
-
use_regex: bool =
|
|
99
|
+
use_regex: Optional[bool] = None
|
|
89
100
|
) -> Dict[str, Any]:
|
|
90
101
|
"""
|
|
91
102
|
Executes a bounded code/config search and returns structured results and compact markdown.
|
|
@@ -121,6 +132,9 @@ class ScopedSearch:
|
|
|
121
132
|
|
|
122
133
|
query = query.strip()
|
|
123
134
|
scope = (scope or "all").lower().strip()
|
|
135
|
+
# use_regex=None (omitted) -> auto-detect; explicit False forces literal, True forces regex
|
|
136
|
+
auto_regex = use_regex is None and cls._looks_like_regex(query)
|
|
137
|
+
regex_mode = bool(use_regex) if use_regex is not None else auto_regex
|
|
124
138
|
if max_results is None or isinstance(max_results, bool):
|
|
125
139
|
max_results = 25
|
|
126
140
|
else:
|
|
@@ -132,18 +146,24 @@ class ScopedSearch:
|
|
|
132
146
|
# Compile search pattern
|
|
133
147
|
flags = 0 if case_sensitive else re.IGNORECASE
|
|
134
148
|
try:
|
|
135
|
-
if
|
|
149
|
+
if regex_mode:
|
|
136
150
|
pattern = re.compile(query, flags)
|
|
137
151
|
else:
|
|
138
152
|
pattern = re.compile(re.escape(query), flags)
|
|
139
153
|
except Exception as e:
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
154
|
+
if regex_mode and use_regex is None:
|
|
155
|
+
# Malformed auto-detected regex: degrade to literal instead of failing
|
|
156
|
+
regex_mode = False
|
|
157
|
+
auto_regex = False
|
|
158
|
+
pattern = re.compile(re.escape(query), flags)
|
|
159
|
+
else:
|
|
160
|
+
return {
|
|
161
|
+
"success": False,
|
|
162
|
+
"error": f"Invalid regex pattern: {str(e)}",
|
|
163
|
+
"matches": [],
|
|
164
|
+
"total_matches": 0,
|
|
165
|
+
"markdown": f"Regex compilation error: {str(e)}"
|
|
166
|
+
}
|
|
147
167
|
|
|
148
168
|
matches: List[Dict[str, Any]] = []
|
|
149
169
|
total_scanned_files = 0
|
|
@@ -222,11 +242,14 @@ class ScopedSearch:
|
|
|
222
242
|
|
|
223
243
|
# Generate ultra-compact Markdown output (< 150 tokens)
|
|
224
244
|
display_root = os.path.basename(root_dir) or root_dir
|
|
245
|
+
mode_suffix = ", auto-regex" if auto_regex and regex_mode else ""
|
|
225
246
|
lines = [
|
|
226
|
-
f"### TokenSafe Scoped Search: '{query}' ({len(matches)} match{'es' if len(matches) != 1 else ''} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, dir: `{display_root}`, scope: {scope})"
|
|
247
|
+
f"### TokenSafe Scoped Search: '{query}' ({len(matches)} match{'es' if len(matches) != 1 else ''} in {len(hit_files)} file{'s' if len(hit_files) != 1 else ''}, dir: `{display_root}`, scope: {scope}{mode_suffix})"
|
|
227
248
|
]
|
|
228
249
|
if not matches:
|
|
229
250
|
lines.append(f"_No matches found across {total_scanned_files} scanned files in `{root_dir}`._")
|
|
251
|
+
if auto_regex and regex_mode:
|
|
252
|
+
lines.append("_Auto-regex mode found nothing; pass use_regex=false to force a literal search._")
|
|
230
253
|
else:
|
|
231
254
|
for m in matches:
|
|
232
255
|
lines.append(f"- `{m['file']}:{m['line']}`: `{m['text']}`")
|
package/src/telemetry_sync.py
CHANGED
|
@@ -228,7 +228,7 @@ class TelemetrySync:
|
|
|
228
228
|
current_last_id = last_id
|
|
229
229
|
headers = {
|
|
230
230
|
"Content-Type": "application/json",
|
|
231
|
-
"User-Agent": "TokenSafe-Sync/2.
|
|
231
|
+
"User-Agent": "TokenSafe-Sync/2.9.0"
|
|
232
232
|
}
|
|
233
233
|
if active_key:
|
|
234
234
|
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 = "2.
|
|
20
|
+
CURRENT_VERSION = "2.9.0"
|
|
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
|