tokensafe 2.8.1 → 2.8.4
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/pre_invocation.py +8 -0
- package/hooks/pre_tool_use.py +8 -0
- package/hooks/session_start.py +5 -0
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/rules/AGENTS.md +7 -5
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +24 -8
- package/skills/token-optimizer/references/mcp-tools.md +3 -3
- package/src/adapter_core.py +4 -0
- package/src/command_sanitizer.py +57 -0
- package/src/installer.py +12 -10
- package/src/mcp_server.py +93 -29
- package/src/paths.py +47 -0
- package/src/proxy.py +1 -1
- package/src/scoped_search.py +9 -2
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
package/hooks/pre_invocation.py
CHANGED
|
@@ -64,6 +64,14 @@ def _handle(payload: dict) -> dict:
|
|
|
64
64
|
invocation_num = 1
|
|
65
65
|
transcript_path = str(payload.get("transcriptPath") or "")
|
|
66
66
|
|
|
67
|
+
try:
|
|
68
|
+
from src.paths import save_active_workspace
|
|
69
|
+
raw_ws = payload.get("workspacePaths")
|
|
70
|
+
if raw_ws and isinstance(raw_ws, list) and raw_ws[0]:
|
|
71
|
+
save_active_workspace(str(raw_ws[0]))
|
|
72
|
+
except Exception:
|
|
73
|
+
pass
|
|
74
|
+
|
|
67
75
|
tracker = MetricsTracker()
|
|
68
76
|
inject_steps = []
|
|
69
77
|
|
package/hooks/pre_tool_use.py
CHANGED
|
@@ -53,6 +53,14 @@ def _handle(payload: dict) -> dict:
|
|
|
53
53
|
# package.json and Guard audit git staging in the user's repo (never plugin CWD).
|
|
54
54
|
workspace_paths = payload.get("workspacePaths") if isinstance(payload.get("workspacePaths"), list) else []
|
|
55
55
|
hook_cwd = str(payload.get("cwd") or (workspace_paths[0] if workspace_paths else "") or os.getcwd())
|
|
56
|
+
try:
|
|
57
|
+
from src.paths import save_active_workspace
|
|
58
|
+
if workspace_paths and workspace_paths[0]:
|
|
59
|
+
save_active_workspace(str(workspace_paths[0]))
|
|
60
|
+
elif hook_cwd:
|
|
61
|
+
save_active_workspace(hook_cwd)
|
|
62
|
+
except Exception:
|
|
63
|
+
pass
|
|
56
64
|
|
|
57
65
|
tracker = MetricsTracker()
|
|
58
66
|
quota = LicenseManager.check_quota(tracker)
|
package/hooks/session_start.py
CHANGED
|
@@ -60,6 +60,11 @@ def main():
|
|
|
60
60
|
raw_ws = payload.get("workspacePaths")
|
|
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
|
+
try:
|
|
64
|
+
from src.paths import save_active_workspace
|
|
65
|
+
save_active_workspace(workspace_root)
|
|
66
|
+
except Exception:
|
|
67
|
+
pass
|
|
63
68
|
|
|
64
69
|
inject_steps = [
|
|
65
70
|
{"systemMessage": {"systemMessage": PROTOCOL_DIRECTIVES, "metadata": {}}}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.8.
|
|
4
|
+
"version": "2.8.4",
|
|
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.8.
|
|
4
|
+
"version": "2.8.4",
|
|
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
|
@@ -24,14 +24,16 @@ Execute the specified action directly based on these extracted parameters.
|
|
|
24
24
|
2. **Surgical Code Edits**: Prefer `edit_file` with concise `Target` and `Replacement` over `write_file` on large existing files.
|
|
25
25
|
3. **Diff-Centric Responses**: Never reprint entire unmodified files or long boilerplate blocks. Reference file lines instead (e.g., `wallet.ts#L42-L50`).
|
|
26
26
|
4. **Dense Formatting**: Use compact bullet points and direct technical prose.
|
|
27
|
+
5. **Repeat Read Deduplication**: Never re-read unchanged files or symbols in the same session. Reuse the skeleton or pointer reference (`// [TokenSafe: Pointer Hit ...]`) returned earlier; only pass `force_full=true` if your context was compacted or you are a fresh subagent.
|
|
28
|
+
6. **Compact Test Output Execution**: Run unit tests with concise flags or via `tokensafe tests [cmd]` so passing test runs return a 1-line summary (`PASS: ...`) rather than flooding `Messages` history with hundreds of verbose log lines. Full output is preserved only on failure.
|
|
27
29
|
|
|
28
30
|
### 3. Architecture & Code Navigation Directives (Graph-Guided)
|
|
29
|
-
1. **Zero Raw Terminal Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.
|
|
30
|
-
2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode="signature"`), it preserves the full executable target and compact 1-line 1-hop dependency signatures while folding inert code (-95%+ tokens). Pass `dep_mode="full"` only when dependency bodies are needed, or `force_full=true` if a cache pointer references content missing from your context. When you need 3+ related symbols across several files, call `tokensafe:smart_bundle(targets=[{path, symbol}])` ONCE instead of repeated `smart_read_file` calls — it merges the skeletons and deduplicates shared imports/types in a single roundtrip. For OpenAPI/Prisma/GraphQL/SQL schema files `smart_read_file` auto-slices: pass the spec path/model/type/table as `symbol` (empty `symbol` returns a compact overview).
|
|
31
|
-
3. **Architecture Discovery**: Before executing multi-file exploration, ALWAYS call `tokensafe:get_architecture_graph(project_path)` to locate God Nodes and dependency topology in < 250 tokens without file crawling.
|
|
32
|
-
4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.
|
|
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` (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.
|
|
33
35
|
5. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
|
|
34
|
-
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"`).
|
|
35
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.
|
|
36
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.
|
|
37
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.8.
|
|
6
|
+
"version": "2.8.4",
|
|
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.8.
|
|
33
|
+
"version": "2.8.4",
|
|
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.8.
|
|
49
|
+
"version": "2.8.4",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
|
@@ -18,12 +18,13 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
18
18
|
|
|
19
19
|
## MANDATORY AGENT DIRECTIVES
|
|
20
20
|
|
|
21
|
-
1. **ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED)**:
|
|
21
|
+
1. **ZERO RAW TERMINAL GREP / FIND (HARD-BLOCKED & REPLACED BY `scoped_search`)**:
|
|
22
22
|
- Strictly NEVER run `grep`, `egrep`, `ripgrep`, or `find` in `run_command` on source code files (`.ts`, `.tsx`, `.py`, `.js`, `src/`, `views/`, `components/`).
|
|
23
23
|
- Raw code searches via bash burn thousands of context tokens and are blocked by **TokenSafe Guard** (`decision: deny`).
|
|
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"`).
|
|
24
25
|
|
|
25
26
|
2. **SYMBOL & COMPONENT EXTRACTION (`smart_read_file`)**:
|
|
26
|
-
- When locating or reading any function, component, class, or handler (e.g. `<LuckyWheelTab>`, `areSectorEqual`, `useWallet`), ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`.
|
|
27
|
+
- 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`.
|
|
27
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.
|
|
28
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.
|
|
29
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.
|
|
@@ -31,22 +32,37 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
|
|
|
31
32
|
- **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -98% tokens).
|
|
32
33
|
|
|
33
34
|
3. **ARCHITECTURE SURVEY BEFORE BROWSING (`get_architecture_graph`)**:
|
|
34
|
-
- 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).
|
|
35
36
|
- **Result**: Returns top architectural God Nodes, dependency hubs, and centrality rankings in < 250 tokens without file crawling.
|
|
36
37
|
|
|
37
38
|
4. **API SURFACE INSPECTION (`get_api_surface`)**:
|
|
38
|
-
- 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.
|
|
39
40
|
|
|
40
|
-
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`)**:
|
|
41
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.
|
|
42
47
|
|
|
43
|
-
|
|
48
|
+
7. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
|
|
44
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.
|
|
45
50
|
|
|
46
|
-
|
|
51
|
+
8. **CONTEXT BUDGET BEFORE HEAVY WORK (`context_budget` → `compact_conversation`)**:
|
|
47
52
|
- Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check the window budget (tools/history/prompts breakdown, 50/80/95% thresholds).
|
|
48
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.
|
|
49
54
|
|
|
55
|
+
9. **REPEAT READ DEDUPLICATION & CACHE POINTERS**:
|
|
56
|
+
- Never repeatedly re-read the same file or symbol within an active session.
|
|
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.
|
|
58
|
+
|
|
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.
|
|
62
|
+
|
|
63
|
+
11. **COMPACT TEST EXECUTION**:
|
|
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.
|
|
65
|
+
|
|
50
66
|
---
|
|
51
67
|
|
|
52
68
|
## Core MCP Tools (`tokensafe`)
|
|
@@ -59,7 +75,7 @@ The full tool table with efficiency impact, JSON workflow examples, the Guard ch
|
|
|
59
75
|
|
|
60
76
|
Quick pointers:
|
|
61
77
|
|
|
62
|
-
- Search: `tokensafe:scoped_search(query, scope)` — never raw grep.
|
|
78
|
+
- Search: `tokensafe:scoped_search(query, path=".", scope="code")` — safe keyword & symbol search, never raw grep.
|
|
63
79
|
- Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps.
|
|
64
80
|
- Bundle: `tokensafe:smart_bundle(targets=[{path, symbol}])` — 3-8 related symbols across files in one call, shared imports deduplicated.
|
|
65
81
|
- Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
|
|
@@ -6,7 +6,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
6
6
|
|---|---|---|
|
|
7
7
|
| `tokensafe:smart_read_file` | Graph-guided AST reader with `symbol` body retention, `dep_mode` (`signature` default / `full`), and session pointer dedup (`force_full`). OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced: `symbol` = spec path/model/type/table; empty `symbol` returns a compact overview. | **-90% to -98%** token reduction |
|
|
8
8
|
| `tokensafe:smart_bundle` | Multi-symbol context bundle: up to 8 `{path, symbol}` targets in ONE call — per-file skeletons with shared import lines deduplicated and merged 1-hop dependency signatures. Replaces 3+ chained `smart_read_file` calls. | **-85% to -95%** + one roundtrip instead of many |
|
|
9
|
-
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path`, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
|
|
9
|
+
| `tokensafe:scoped_search` | Safe, token-bounded keyword, symbol, or config search across the codebase (supports `path='.'`, `scope='code'`/`'config'`/`'all'`/file extension/subfolder, 4s safety timeout, system root protection). | **-90% to -95%** vs raw grep/find |
|
|
10
10
|
| `tokensafe:list_dir` | Token-efficient directory tree without lockfiles, timestamps, or ignored folders (node_modules, .git, dist, .env). Replaces `ls -la`. | **-90%** vs verbose `ls` |
|
|
11
11
|
| `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
|
|
12
12
|
| `tokensafe:get_api_surface` | Generates a compact markdown map of all exported types, interfaces, and classes. | **~500 tokens** for entire project |
|
|
@@ -41,12 +41,12 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
|
|
|
41
41
|
"ToolName": "scoped_search",
|
|
42
42
|
"Arguments": {
|
|
43
43
|
"query": "HARDCODED_VERSION",
|
|
44
|
-
"path": "
|
|
44
|
+
"path": "./src",
|
|
45
45
|
"scope": "code"
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
48
|
```
|
|
49
|
-
*Locates exact occurrences with file and line references in < 100 tokens. Always pass
|
|
49
|
+
*Locates exact occurrences with file and line references in < 100 tokens. Always pass `path` (defaults to active project root, e.g. ".") and optional `scope` ('code', 'config', 'all', file extension like 'go', or subfolder like 'internal/promo'). Auto-guarded against system roots.*
|
|
50
50
|
|
|
51
51
|
### 2b. Directory Navigation Workflow (`list_dir`)
|
|
52
52
|
```json
|
package/src/adapter_core.py
CHANGED
|
@@ -32,6 +32,10 @@ TOKENSAFE_DIRECTIVES = (
|
|
|
32
32
|
"• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)' "
|
|
33
33
|
"(1-hop deps default to compact signatures via dep_mode='signature'; pass dep_mode='full' only when "
|
|
34
34
|
"dependency bodies are needed, or force_full=true if a cache pointer references content missing from context).\n"
|
|
35
|
+
"• Deduplication & Cache Pointers: Never re-read unchanged files repeatedly; reuse earlier context or pointer references.\n"
|
|
36
|
+
"• Zero-Fluff Egress: Omit conversational filler, courtesy preambles, and wrap-ups. Format responses in dense, technical prose.\n"
|
|
37
|
+
"• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.\n"
|
|
38
|
+
"• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
|
|
35
39
|
"• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
|
|
36
40
|
"• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
|
|
37
41
|
"• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check the context window budget.\n"
|
package/src/command_sanitizer.py
CHANGED
|
@@ -333,6 +333,11 @@ class CommandSanitizer:
|
|
|
333
333
|
if "--tb=" not in stage and "-q" not in cmd_args and "--quiet" not in cmd_args:
|
|
334
334
|
return f"{stage} -q --tb=short", 800, "Applied short traceback to pytest", None
|
|
335
335
|
|
|
336
|
+
# cargo test: quiet test runner by default when not specified
|
|
337
|
+
if cmd_tok == "cargo" and cmd_args[:1] == ["test"]:
|
|
338
|
+
if "--quiet" not in stage and "-q" not in stage and "--" not in stage:
|
|
339
|
+
return f"{stage} -- --quiet", 600, "Applied quiet mode to cargo test", None
|
|
340
|
+
|
|
336
341
|
# test runners: agents block on watch mode
|
|
337
342
|
guard = cls._optimize_test_stage(stage, cwd)
|
|
338
343
|
if guard:
|
|
@@ -594,3 +599,55 @@ class CommandSanitizer:
|
|
|
594
599
|
return None, 0, ""
|
|
595
600
|
|
|
596
601
|
return cls.join_stages(pairs), total_saved, "; ".join(reasons)
|
|
602
|
+
|
|
603
|
+
@classmethod
|
|
604
|
+
def compact_test_output(cls, raw: str, exit_code: int = 0) -> str:
|
|
605
|
+
"""
|
|
606
|
+
Compacts test execution output to prevent context bloating in Messages history.
|
|
607
|
+
- If exit_code != 0: returns full raw output untouched to preserve error context.
|
|
608
|
+
- If exit_code == 0: extracts concise summary lines (e.g. 'PASS: 42 passed in 1.2s')
|
|
609
|
+
discarding repetitive passing test lines.
|
|
610
|
+
"""
|
|
611
|
+
if exit_code != 0 or not raw or not raw.strip():
|
|
612
|
+
return raw
|
|
613
|
+
|
|
614
|
+
lines = [line.strip() for line in raw.splitlines() if line.strip()]
|
|
615
|
+
if not lines:
|
|
616
|
+
return raw
|
|
617
|
+
|
|
618
|
+
# 1. pytest check
|
|
619
|
+
for line in reversed(lines):
|
|
620
|
+
if re.search(r"=\s*(?:[0-9]+\s+passed.*in\s+[\d\.]+s|passed in\s+[\d\.]+s)\s*=", line):
|
|
621
|
+
clean = re.sub(r"^=+\s*|\s*=+$", "", line)
|
|
622
|
+
return f"PASS: {clean}"
|
|
623
|
+
|
|
624
|
+
# 2. unittest check
|
|
625
|
+
ran_line = ""
|
|
626
|
+
for line in lines:
|
|
627
|
+
if line.startswith("Ran ") and " test" in line:
|
|
628
|
+
ran_line = line
|
|
629
|
+
elif line.startswith("OK"):
|
|
630
|
+
return f"PASS: {ran_line or 'all tests passed'} ({line})"
|
|
631
|
+
|
|
632
|
+
# 3. jest / vitest check
|
|
633
|
+
for line in reversed(lines):
|
|
634
|
+
if "Tests:" in line and "passed" in line:
|
|
635
|
+
return f"PASS: {line}"
|
|
636
|
+
if re.search(r"✓.*tests? passed", line):
|
|
637
|
+
return f"PASS: {line}"
|
|
638
|
+
|
|
639
|
+
# 4. cargo test check
|
|
640
|
+
for line in reversed(lines):
|
|
641
|
+
if line.startswith("test result: ok."):
|
|
642
|
+
return f"PASS: {line}"
|
|
643
|
+
|
|
644
|
+
# 5. go test check
|
|
645
|
+
for line in reversed(lines):
|
|
646
|
+
if line.startswith("ok \t") or line.startswith("PASS"):
|
|
647
|
+
return f"PASS: {line}"
|
|
648
|
+
|
|
649
|
+
# Fallback for verbose outputs: if > 12 lines, cap to first line + last line
|
|
650
|
+
if len(lines) > 12:
|
|
651
|
+
return f"PASS: {lines[0]} ... {lines[-1]} (exit code 0)"
|
|
652
|
+
|
|
653
|
+
return raw
|
package/src/installer.py
CHANGED
|
@@ -45,18 +45,20 @@ def _app_data_dir(*parts: str) -> str:
|
|
|
45
45
|
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
|
-
"1. **Zero Raw Grep/Find (Blocked)**: Strictly NEVER execute terminal `grep`, `egrep`, `ripgrep`, or `find` on source code files or directories (`src/`, `views/`, `components/`, `.ts`, `.tsx`, `.py`, `.js`). These commands are hard-blocked by TokenSafe Guard.\n"
|
|
49
|
-
"2. **Mandatory Symbol & Component Inspection**: Whenever locating or reading a function, class, component, or method, ALWAYS call `tokensafe:smart_read_file` with `path` and `symbol`. By default (`dep_mode='signature'`), it preserves the target body and compact 1-line 1-hop dependency signatures (-95%+ tokens); pass `dep_mode='full'` only when dependency bodies are required, or `force_full=true` if a cache pointer references content missing from your context. 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
|
-
"3. **
|
|
51
|
-
"4. **
|
|
52
|
-
"5. **
|
|
53
|
-
"6. **
|
|
54
|
-
"7. **
|
|
55
|
-
"8. **
|
|
56
|
-
"9. **
|
|
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` (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
|
+
"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
|
+
"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 (`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
|
+
"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
|
+
"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
|
+
"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"
|
|
58
|
+
"11. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
|
|
57
59
|
"Never hardcode real private keys, API secrets, access tokens, or webhook secrets as default fallback arguments in `os.environ.get()`, `os.getenv()`, or `process.env`. If an environment variable is absent, raise an explicit configuration error or use an empty string / test mock. Whenever a secret fallback attempt is blocked, state:\n"
|
|
58
60
|
"`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
|
|
59
|
-
"
|
|
61
|
+
"12. **Proof-of-Savings Turn Footer (always in English)**:\n"
|
|
60
62
|
"At the end of your response for any turn where tools were executed, files were inspected, commands were sanitized, or prompts were compacted, append a compact 1-line footer in English:\n"
|
|
61
63
|
"`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
|
|
62
64
|
)
|
package/src/mcp_server.py
CHANGED
|
@@ -38,10 +38,11 @@ from src.diff_slicer import DiffSlicer
|
|
|
38
38
|
from src.guard import TokenSafeGuard
|
|
39
39
|
from src.scoped_search import ScopedSearch
|
|
40
40
|
from src.license_manager import LicenseManager
|
|
41
|
+
from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
41
42
|
|
|
42
43
|
SERVER_INFO = {
|
|
43
44
|
"name": "tokensafe-mcp",
|
|
44
|
-
"version": "2.8.
|
|
45
|
+
"version": "2.8.4"
|
|
45
46
|
}
|
|
46
47
|
|
|
47
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -79,12 +80,12 @@ def _client_supports_pointers() -> bool:
|
|
|
79
80
|
TOOLS = [
|
|
80
81
|
{
|
|
81
82
|
"name": "smart_read_file",
|
|
82
|
-
"description": "Reads a code file using AST skeletonization and graph-guided slicing to save 90-99% context tokens. OpenAPI
|
|
83
|
+
"description": "Reads a code file using AST skeletonization and graph-guided slicing to save 90-99% context tokens. Automatically preserves target function/class implementation and 1-line 1-hop dependency signatures while folding inert code. Supports relative paths (e.g. 'src/index.ts'). Declarative schemas (OpenAPI, Prisma, GraphQL, SQL) are auto-sliced: pass model/type/table/endpoint as 'symbol' or omit for a compact overview. For 3+ related symbols across files prefer smart_bundle.",
|
|
83
84
|
"inputSchema": {
|
|
84
85
|
"type": "object",
|
|
85
86
|
"properties": {
|
|
86
|
-
"path": {"type": "string", "description": "
|
|
87
|
-
"symbol": {"type": "string", "description": "Optional: targeted function
|
|
87
|
+
"path": {"type": "string", "description": "File path to read (relative to workspace or absolute, e.g. './src/index.ts')"},
|
|
88
|
+
"symbol": {"type": "string", "description": "Optional: targeted function, method, class, component, or schema model/type to extract with 1-hop dependencies while folding surrounding code (omit for whole-file AST skeleton or schema overview)"},
|
|
88
89
|
"include_deps": {"type": "boolean", "description": "Optional: whether to include 1-hop dependencies (default: true). Set false for 0-hop surgical isolation."},
|
|
89
90
|
"dep_mode": {"type": "string", "enum": ["signature", "full"], "description": "Optional: how 1-hop dependencies are returned when include_deps is true. 'signature' (default, -95%+ tokens) returns compact 1-line signatures; 'full' inlines full dependency bodies."},
|
|
90
91
|
"force_full": {"type": "boolean", "description": "Optional: bypass session pointer deduplication and return the full skeleton directly (use only if your context was compacted or you are a fresh subagent lacking earlier reads)."},
|
|
@@ -96,7 +97,7 @@ TOOLS = [
|
|
|
96
97
|
},
|
|
97
98
|
{
|
|
98
99
|
"name": "smart_bundle",
|
|
99
|
-
"description": "Reads 2-8 related symbols across multiple files as ONE merged context bundle: per-file AST skeletons with shared import lines deduplicated and merged 1-hop dependency signatures. Use it instead of 3+ separate smart_read_file calls on related code (one roundtrip, no duplicated imports/types).",
|
|
100
|
+
"description": "Reads 2-8 related symbols across multiple files as ONE merged context bundle: per-file AST skeletons with shared import lines deduplicated and merged 1-hop dependency signatures. Use it instead of 3+ separate smart_read_file calls on related code (one roundtrip, no duplicated imports/types). Supports relative paths (e.g. targets=[{'path': 'src/api.ts', 'symbol': 'handler'}]).",
|
|
100
101
|
"inputSchema": {
|
|
101
102
|
"type": "object",
|
|
102
103
|
"properties": {
|
|
@@ -106,8 +107,8 @@ TOOLS = [
|
|
|
106
107
|
"items": {
|
|
107
108
|
"type": "object",
|
|
108
109
|
"properties": {
|
|
109
|
-
"path": {"type": "string", "description": "
|
|
110
|
-
"symbol": {"type": "string", "description": "Optional symbol to keep unfolded (class
|
|
110
|
+
"path": {"type": "string", "description": "File path to code file (relative to workspace or absolute)"},
|
|
111
|
+
"symbol": {"type": "string", "description": "Optional symbol to keep unfolded (class, function, or component name)"}
|
|
111
112
|
},
|
|
112
113
|
"required": ["path"]
|
|
113
114
|
},
|
|
@@ -122,21 +123,21 @@ TOOLS = [
|
|
|
122
123
|
},
|
|
123
124
|
{
|
|
124
125
|
"name": "get_architecture_graph",
|
|
125
|
-
"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.",
|
|
126
127
|
"inputSchema": {
|
|
127
128
|
"type": "object",
|
|
128
129
|
"properties": {
|
|
129
|
-
"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)"}
|
|
130
131
|
}
|
|
131
132
|
}
|
|
132
133
|
},
|
|
133
134
|
{
|
|
134
135
|
"name": "get_api_surface",
|
|
135
|
-
"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.",
|
|
136
137
|
"inputSchema": {
|
|
137
138
|
"type": "object",
|
|
138
139
|
"properties": {
|
|
139
|
-
"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)"}
|
|
140
141
|
}
|
|
141
142
|
}
|
|
142
143
|
},
|
|
@@ -227,11 +228,11 @@ TOOLS = [
|
|
|
227
228
|
},
|
|
228
229
|
{
|
|
229
230
|
"name": "list_dir",
|
|
230
|
-
"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'.",
|
|
231
232
|
"inputSchema": {
|
|
232
233
|
"type": "object",
|
|
233
234
|
"properties": {
|
|
234
|
-
"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')"},
|
|
235
236
|
"depth": {"type": "integer", "description": "Maximum traversal depth (default: 2, max: 4)"},
|
|
236
237
|
"max_entries": {"type": "integer", "description": "Maximum entries to display before pruning (default: 80)"}
|
|
237
238
|
},
|
|
@@ -250,12 +251,11 @@ TOOLS = [
|
|
|
250
251
|
},
|
|
251
252
|
"scope": {
|
|
252
253
|
"type": "string",
|
|
253
|
-
"
|
|
254
|
-
"description": "Scope of search: 'code' (source files only), 'config' (json, toml, yaml), or 'all' (default: 'all')"
|
|
254
|
+
"description": "Filter scope: 'code', 'config', 'all', a file extension (e.g. 'go', 'ts', '*.py'), or a subfolder path (e.g. 'internal/promo') (default: 'all')"
|
|
255
255
|
},
|
|
256
256
|
"path": {
|
|
257
257
|
"type": "string",
|
|
258
|
-
"description": "Directory or project path to search (alias for project_path)"
|
|
258
|
+
"description": "Directory or project path to search (alias for project_path, e.g. '.', './src', 'internal/promo')"
|
|
259
259
|
},
|
|
260
260
|
"project_path": {
|
|
261
261
|
"type": "string",
|
|
@@ -399,17 +399,24 @@ def build_dir_tree(dir_path: str, max_depth: int = 2, max_entries: int = 80) ->
|
|
|
399
399
|
|
|
400
400
|
def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
401
401
|
"""
|
|
402
|
-
Safely resolves the target project root without falling back to system root dirs.
|
|
402
|
+
Safely resolves the target project root without falling back to system root dirs or plugin dirs.
|
|
403
403
|
"""
|
|
404
404
|
target = args.get("project_path") or args.get("root_dir") or args.get("path") or args.get("directory")
|
|
405
|
-
|
|
405
|
+
active_ws = get_active_workspace()
|
|
406
406
|
|
|
407
407
|
if target:
|
|
408
|
-
|
|
408
|
+
if not os.path.isabs(target):
|
|
409
|
+
if active_ws and os.path.isdir(os.path.join(active_ws, target)):
|
|
410
|
+
target_abs = os.path.abspath(os.path.join(active_ws, target))
|
|
411
|
+
else:
|
|
412
|
+
target_abs = os.path.abspath(target)
|
|
413
|
+
else:
|
|
414
|
+
target_abs = os.path.abspath(target)
|
|
415
|
+
|
|
409
416
|
if os.path.isfile(target_abs):
|
|
410
417
|
target_abs = os.path.dirname(target_abs)
|
|
411
|
-
if target_abs
|
|
412
|
-
return None, f"Error: Refusing to scan system root or
|
|
418
|
+
if is_plugin_or_system_dir(target_abs):
|
|
419
|
+
return None, f"Error: Refusing to scan system root or plugin directory '{target}'. Please provide a specific project directory."
|
|
413
420
|
if not os.path.isdir(target_abs):
|
|
414
421
|
return None, f"Error: project_path not found or not a directory: '{target}'."
|
|
415
422
|
return target_abs, None
|
|
@@ -419,14 +426,18 @@ def _resolve_project_root(args: dict) -> Tuple[Optional[str], Optional[str]]:
|
|
|
419
426
|
candidate = os.environ.get(env_var)
|
|
420
427
|
if candidate:
|
|
421
428
|
cand_abs = os.path.abspath(candidate)
|
|
422
|
-
if
|
|
429
|
+
if not is_plugin_or_system_dir(cand_abs) and os.path.isdir(cand_abs):
|
|
423
430
|
return cand_abs, None
|
|
424
431
|
|
|
425
|
-
# Check
|
|
432
|
+
# Check active workspace recorded by lifecycle hooks
|
|
433
|
+
if active_ws and not is_plugin_or_system_dir(active_ws) and os.path.isdir(active_ws):
|
|
434
|
+
return active_ws, None
|
|
435
|
+
|
|
436
|
+
# Check cwd (only if it is not inside an agent plugin or system root directory)
|
|
426
437
|
cwd = os.getcwd()
|
|
427
438
|
if cwd:
|
|
428
439
|
cwd_abs = os.path.abspath(cwd)
|
|
429
|
-
if
|
|
440
|
+
if not is_plugin_or_system_dir(cwd_abs) and os.path.isdir(cwd_abs):
|
|
430
441
|
return cwd_abs, None
|
|
431
442
|
|
|
432
443
|
# Hint with active projects if found under ~/Documents/projects
|
|
@@ -731,8 +742,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
731
742
|
if start_line is not None:
|
|
732
743
|
start_line = max(1, start_line)
|
|
733
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
|
+
|
|
734
754
|
if not path or not os.path.exists(path):
|
|
735
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}'")
|
|
736
758
|
try:
|
|
737
759
|
st = os.stat(path)
|
|
738
760
|
if not stat.S_ISREG(st.st_mode):
|
|
@@ -934,11 +956,19 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
934
956
|
inc_deps, _eff_dep_mode = _resolve_dep_mode(args)
|
|
935
957
|
max_tokens = _safe_int(os.environ.get("TOKENSAFE_BUNDLE_MAX_TOKENS"), 6000, lo=1000, hi=50000)
|
|
936
958
|
|
|
959
|
+
active_ws = get_active_workspace()
|
|
937
960
|
by_file: Dict[str, List[str]] = {}
|
|
938
961
|
for t in targets:
|
|
939
962
|
if not isinstance(t, dict) or not str(t.get("path") or "").strip():
|
|
940
963
|
return _fallback_error("smart_bundle", "each target must be {path: str, symbol?: str}")
|
|
941
|
-
|
|
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())
|
|
942
972
|
|
|
943
973
|
missing = [p for p in by_file if not os.path.isfile(p)]
|
|
944
974
|
if missing:
|
|
@@ -1429,10 +1459,20 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1429
1459
|
if not path:
|
|
1430
1460
|
return _fallback_error("list_dir", "missing required 'path' argument")
|
|
1431
1461
|
|
|
1432
|
-
# Resolve path relative to
|
|
1433
|
-
|
|
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
|
+
|
|
1434
1472
|
if not os.path.isdir(abs_path):
|
|
1435
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}'")
|
|
1436
1476
|
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
1437
1477
|
depth = _safe_int(args.get("depth"), 2, lo=1, hi=4)
|
|
1438
1478
|
if abs_path in system_roots:
|
|
@@ -1458,18 +1498,42 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1458
1498
|
if not query:
|
|
1459
1499
|
return _fallback_error("scoped_search", "missing required 'query' argument")
|
|
1460
1500
|
|
|
1461
|
-
|
|
1501
|
+
raw_scope = str(args.get("scope") or "all").strip()
|
|
1462
1502
|
raw_path = args.get("project_path") or args.get("path") or args.get("root_dir") or args.get("directory")
|
|
1503
|
+
active_ws = get_active_workspace()
|
|
1504
|
+
|
|
1505
|
+
# 1. Resolve base directory safely without scanning plugin or system roots
|
|
1463
1506
|
if raw_path:
|
|
1464
|
-
|
|
1507
|
+
if not os.path.isabs(raw_path):
|
|
1508
|
+
if active_ws and os.path.isdir(os.path.join(active_ws, raw_path)):
|
|
1509
|
+
target_path = os.path.abspath(os.path.join(active_ws, raw_path))
|
|
1510
|
+
else:
|
|
1511
|
+
target_path = os.path.abspath(raw_path)
|
|
1512
|
+
else:
|
|
1513
|
+
target_path = os.path.abspath(raw_path)
|
|
1514
|
+
|
|
1465
1515
|
if os.path.isfile(target_path):
|
|
1466
1516
|
target_path = os.path.dirname(target_path)
|
|
1517
|
+
if is_plugin_or_system_dir(target_path):
|
|
1518
|
+
return _fallback_error("scoped_search", f"refusing to search system root or plugin dir '{raw_path}'")
|
|
1467
1519
|
else:
|
|
1468
1520
|
resolved_path, err = _resolve_project_root(args)
|
|
1469
1521
|
if err or not resolved_path:
|
|
1470
1522
|
return _fallback_error("scoped_search", err or "unspecified project_path")
|
|
1471
1523
|
target_path = resolved_path
|
|
1472
1524
|
|
|
1525
|
+
# 2. Smart scope routing: handle agents passing subdirectories or extensions in `scope`
|
|
1526
|
+
scope = raw_scope
|
|
1527
|
+
if raw_scope and raw_scope.lower() not in ("code", "config", "all"):
|
|
1528
|
+
candidate_subdir = os.path.normpath(os.path.join(target_path, raw_scope))
|
|
1529
|
+
if os.path.isdir(candidate_subdir):
|
|
1530
|
+
target_path = candidate_subdir
|
|
1531
|
+
scope = "all"
|
|
1532
|
+
elif "/" in raw_scope or "\\" in raw_scope:
|
|
1533
|
+
if os.path.exists(candidate_subdir):
|
|
1534
|
+
target_path = candidate_subdir
|
|
1535
|
+
scope = "all"
|
|
1536
|
+
|
|
1473
1537
|
max_res = _safe_int(args.get("max_results"), 25, lo=1, hi=100)
|
|
1474
1538
|
c_sens = bool(args.get("case_sensitive", False))
|
|
1475
1539
|
u_regex = bool(args.get("use_regex", False))
|
package/src/paths.py
CHANGED
|
@@ -19,6 +19,7 @@ active directory is identical for every agent on the machine.
|
|
|
19
19
|
import os
|
|
20
20
|
import shutil
|
|
21
21
|
import sqlite3
|
|
22
|
+
from typing import Optional
|
|
22
23
|
|
|
23
24
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
24
25
|
|
|
@@ -110,3 +111,49 @@ def _migrate_into(target: str) -> None:
|
|
|
110
111
|
f.write("1")
|
|
111
112
|
except Exception:
|
|
112
113
|
pass
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def is_plugin_or_system_dir(path: str) -> bool:
|
|
117
|
+
"""Returns True if path is a system root or inside an agent plugin directory."""
|
|
118
|
+
if not path:
|
|
119
|
+
return True
|
|
120
|
+
abs_p = os.path.abspath(path)
|
|
121
|
+
system_roots = {"/", "/Users", "/home", "/root", os.path.expanduser("~")}
|
|
122
|
+
if abs_p in system_roots:
|
|
123
|
+
return True
|
|
124
|
+
lower = abs_p.lower()
|
|
125
|
+
if any(k in lower for k in (".gemini/config/plugins", "/.tokensafe", "plugins/tokensafe", ".cursor/extensions")):
|
|
126
|
+
return True
|
|
127
|
+
return False
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def save_active_workspace(path: str) -> None:
|
|
131
|
+
"""Records the active user workspace directory observed by lifecycle hooks."""
|
|
132
|
+
if not path or not os.path.isabs(path) or not os.path.isdir(path):
|
|
133
|
+
return
|
|
134
|
+
if is_plugin_or_system_dir(path):
|
|
135
|
+
return
|
|
136
|
+
try:
|
|
137
|
+
data_dir = resolve_data_dir()
|
|
138
|
+
os.makedirs(data_dir, exist_ok=True)
|
|
139
|
+
marker = os.path.join(data_dir, ".active_workspace")
|
|
140
|
+
with open(marker, "w", encoding="utf-8") as f:
|
|
141
|
+
f.write(os.path.abspath(path))
|
|
142
|
+
except Exception:
|
|
143
|
+
pass
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def get_active_workspace() -> Optional[str]:
|
|
147
|
+
"""Retrieves the last known active user workspace directory."""
|
|
148
|
+
try:
|
|
149
|
+
data_dir = resolve_data_dir()
|
|
150
|
+
marker = os.path.join(data_dir, ".active_workspace")
|
|
151
|
+
if os.path.isfile(marker):
|
|
152
|
+
with open(marker, "r", encoding="utf-8") as f:
|
|
153
|
+
path = f.read().strip()
|
|
154
|
+
if path and os.path.isabs(path) and os.path.isdir(path):
|
|
155
|
+
if not is_plugin_or_system_dir(path):
|
|
156
|
+
return path
|
|
157
|
+
except Exception:
|
|
158
|
+
pass
|
|
159
|
+
return None
|
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
|
@@ -69,6 +69,12 @@ class ScopedSearch:
|
|
|
69
69
|
return lower_base in CONFIG_FILENAMES or ext in CONFIG_EXTENSIONS
|
|
70
70
|
elif scope == "all":
|
|
71
71
|
return True
|
|
72
|
+
elif scope.startswith("*."):
|
|
73
|
+
return ext == scope[1:].lower()
|
|
74
|
+
elif scope.startswith("."):
|
|
75
|
+
return ext == scope.lower()
|
|
76
|
+
elif f".{scope}" in CODE_EXTENSIONS or scope in ("go", "py", "ts", "js", "tsx", "jsx", "rs", "java", "cpp", "c", "php", "rb", "swift", "kt", "sql", "html", "css", "json", "yaml", "yml", "toml"):
|
|
77
|
+
return ext == f".{scope}"
|
|
72
78
|
return True
|
|
73
79
|
|
|
74
80
|
@classmethod
|
|
@@ -215,11 +221,12 @@ class ScopedSearch:
|
|
|
215
221
|
break
|
|
216
222
|
|
|
217
223
|
# Generate ultra-compact Markdown output (< 150 tokens)
|
|
224
|
+
display_root = os.path.basename(root_dir) or root_dir
|
|
218
225
|
lines = [
|
|
219
|
-
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 ''}, scope: {scope})"
|
|
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})"
|
|
220
227
|
]
|
|
221
228
|
if not matches:
|
|
222
|
-
lines.append(f"_No matches found across {total_scanned_files} scanned files
|
|
229
|
+
lines.append(f"_No matches found across {total_scanned_files} scanned files in `{root_dir}`._")
|
|
223
230
|
else:
|
|
224
231
|
for m in matches:
|
|
225
232
|
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.8.
|
|
231
|
+
"User-Agent": "TokenSafe-Sync/2.8.4"
|
|
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.8.
|
|
20
|
+
CURRENT_VERSION = "2.8.4"
|
|
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
|