tokensafe 2.8.4 → 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/server.json +3 -3
- package/src/command_sanitizer.py +67 -0
- package/src/installer.py +41 -4
- package/src/mcp_server.py +24 -23
- 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/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"
|
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
|
@@ -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": "File path
|
|
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,16 +107,16 @@ TOOLS = [
|
|
|
107
107
|
"items": {
|
|
108
108
|
"type": "object",
|
|
109
109
|
"properties": {
|
|
110
|
-
"path": {"type": "string", "description": "File path
|
|
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
|
}
|
|
@@ -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"]
|
|
@@ -1536,7 +1536,8 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1536
1536
|
|
|
1537
1537
|
max_res = _safe_int(args.get("max_results"), 25, lo=1, hi=100)
|
|
1538
1538
|
c_sens = bool(args.get("case_sensitive", False))
|
|
1539
|
-
|
|
1539
|
+
raw_regex = args.get("use_regex")
|
|
1540
|
+
u_regex = None if raw_regex is None else bool(raw_regex)
|
|
1540
1541
|
|
|
1541
1542
|
res = ScopedSearch.search(
|
|
1542
1543
|
query=query,
|
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
|