tokensafe 4.2.6 → 4.2.8

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "4.2.6",
2
+ "version": "4.2.8",
3
3
  "name": "tokensafe",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "author": {
@@ -67,8 +67,23 @@ def main():
67
67
  except Exception:
68
68
  pass
69
69
 
70
+ directives = PROTOCOL_DIRECTIVES
71
+ try:
72
+ from src.graph_engine import GraphEngine
73
+ graph = GraphEngine.get_instance(workspace_root)
74
+ banner = graph.format_topology_banner()
75
+ if banner:
76
+ directives = (
77
+ f"{directives}\n\n"
78
+ f"{banner}\n"
79
+ "⚡ Core God Nodes and dependency hubs mapped above. "
80
+ "Call 'tokensafe:get_architecture_graph(project_path)' for full dependency trees."
81
+ )
82
+ except Exception:
83
+ pass
84
+
70
85
  inject_steps = [
71
- {"systemMessage": {"systemMessage": PROTOCOL_DIRECTIVES, "metadata": {}}}
86
+ {"systemMessage": {"systemMessage": directives, "metadata": {}}}
72
87
  ]
73
88
 
74
89
  try:
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokensafe",
3
- "version": "4.2.6",
3
+ "version": "4.2.8",
4
4
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
5
5
  "homepage": "https://tokensafe.dev",
6
6
  "license": "MIT",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "4.2.6",
4
+ "version": "4.2.8",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
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": "4.2.6",
4
+ "version": "4.2.8",
5
5
  "description": "Your AI agent is smart enough to code all day. Now it actually can. Local runtime firewall & zero-loss context optimizer for AI coding agents.",
6
6
  "logo": "https://tokensafe.dev/logo.png",
7
7
  "developerName": "TokenSafe",
package/rules/AGENTS.md CHANGED
@@ -32,8 +32,8 @@ Execute the specified action directly based on these extracted parameters.
32
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). Lockfiles (`package-lock.json`, `Cargo.lock`) and tabular data (`.csv`, `.tsv`, `.sql`, `.har`) auto-reduce to compact schemas with reversible hash anchors.
33
33
  3. **Reversible Hash Stashing (`expand_ref`)**: Whenever TokenSafe folds a long command output, test log, file, or MCP payload, it tags it with an 8-character hash `[TokenSafe folded: #a1b2c3d4 ...]`. If full raw content is ever needed, ALWAYS call `tokensafe:expand_ref(hash="a1b2c3d4")` or run `tokensafe expand-ref a1b2c3d4` to retrieve the exact original bytes without re-running.
34
34
  4. **Web & Documentation Reading (`read_web_page`)**: To read web pages, documentation, or API references, ALWAYS call `tokensafe:read_web_page(url)` or run `tokensafe web <url>` instead of raw HTML fetches — it strips scripts, styles, navbars, and cookie banners (-80-95% tokens).
35
- 5. **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).
36
- 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.
35
+ 5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` to locate God Nodes and dependency topology in < 250 tokens before reading individual files or searching (pass the target project's absolute path when working across multiple workspaces or outside CWD).
36
+ 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 (pass the target project's absolute path when working across multiple workspaces or outside CWD).
37
37
  7. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
38
38
  8. **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"`).
39
39
  9. **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.
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Your AI agent is smart enough to code all day. Local firewall & zero-loss runtime.",
6
- "version": "4.2.6",
6
+ "version": "4.2.8",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/tokensafe-dev/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "4.2.6",
33
+ "version": "4.2.8",
34
34
  "runtimeHint": "npx",
35
35
  "transport": {
36
36
  "type": "stdio"
@@ -46,7 +46,7 @@
46
46
  "registryType": "pypi",
47
47
  "registryBaseUrl": "https://pypi.org",
48
48
  "identifier": "tokensafe",
49
- "version": "4.2.6",
49
+ "version": "4.2.8",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -31,8 +31,8 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
31
31
  - **Schema Auto-Slicing**: OpenAPI/Swagger, Prisma, GraphQL and SQL files bypass AST skeletonization. Pass the spec path (`/users/{id}`), Prisma model, GraphQL type, or SQL table as `symbol` for a targeted slice with 1-hop references; an empty `symbol` returns a compact overview (paths/models/types/tables index) instead of a 20k-50k token dump.
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
- 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=".")` (`project_path` defaults to active workspace).
34
+ 3. **MANDATORY ARCHITECTURE GRAPH & GOD NODES FIRST (`get_architecture_graph`)**:
35
+ - For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` before diving into individual files or running searches. Always pass the target project's absolute path (e.g. `"/path/to/repo"`) when working across multiple workspaces or outside CWD.
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`)**:
@@ -38,7 +38,7 @@ TOKENSAFE_DIRECTIVES = (
38
38
  "• Zero-Fluff Egress: Omit conversational filler, courtesy preambles, and wrap-ups. Format responses in dense, technical prose.\n"
39
39
  "• Surgical Code Diffs: Never reprint full unmodified files or lengthy boilerplate; cite line ranges and provide targeted diffs.\n"
40
40
  "• Compact Test Execution: Run unit tests with concise flags or via 'tokensafe tests [cmd]' so passing suites emit a 1-line summary.\n"
41
- "• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
41
+ "• Mandatory Architecture Graph & God Nodes: For any codebase inquiry, navigation, or multi-component work, ALWAYS inspect God Nodes via 'tokensafe:get_architecture_graph(project_path)' first before diving into files (pass target project's absolute path in multi-repo setups).\n"
42
42
  "• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
43
43
  "• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check context headroom and Quality Score (Grade S-F).\n"
44
44
  "• When context_budget reports warning/critical or Grade C/F: call 'tokensafe:compact_conversation(transcript_path=...)' to fold history before continuing.\n"
@@ -134,6 +134,22 @@ def _is_test_file(rel_path: str) -> bool:
134
134
  or base.endswith(("_test.py", "_test.go", ".test.ts", ".test.tsx", ".test.js", ".test.jsx", ".spec.ts", ".spec.tsx", ".spec.js"))
135
135
  )
136
136
 
137
+
138
+ def _is_generated_file(rel_path: str) -> bool:
139
+ norm = rel_path.replace("\\", "/").lower()
140
+ base = os.path.basename(norm)
141
+ parts = norm.split("/")
142
+ if any(p in ("generated", "__generated__", ".gen", "gen", "swagger", "openapi") for p in parts[:-1]):
143
+ return True
144
+ if any(p.endswith((".gen", "__generated__")) for p in parts[:-1]):
145
+ return True
146
+ return (
147
+ base.startswith(("swagger", "openapi", "generated"))
148
+ or base.endswith((".swagger.ts", ".swagger.js", ".gen.ts", ".gen.js", ".gen.go", ".pb.go", "_pb2.py"))
149
+ or "swaggerapi" in base
150
+ or "openapi" in base
151
+ )
152
+
137
153
  class CodeSymbol:
138
154
  """Represents a structural code entity (file, class, or function)."""
139
155
  __slots__ = ("name", "kind", "file_path", "line_start", "line_end", "signature", "body")
@@ -1090,7 +1106,7 @@ class CodeGraph:
1090
1106
  Prioritizes resolved file-to-file imports and import-verified symbol calls,
1091
1107
  and downweights test files when production files are present.
1092
1108
  """
1093
- has_prod_files = any(not _is_test_file(p) for p in self.file_symbols.keys())
1109
+ has_prod_files = any(not _is_test_file(p) and not _is_generated_file(p) for p in self.file_symbols.keys())
1094
1110
  has_resolved_imports = any(
1095
1111
  t.startswith("file:")
1096
1112
  for src, targets in self.edges.items()
@@ -1120,7 +1136,14 @@ class CodeGraph:
1120
1136
  in_degree += 1
1121
1137
 
1122
1138
  raw_centrality = in_degree * 2 + out_degree
1123
- rank_score = raw_centrality * 0.2 if (has_prod_files and _is_test_file(rel_path)) else float(raw_centrality)
1139
+ if has_prod_files and _is_test_file(rel_path):
1140
+ rank_score = raw_centrality * 0.1
1141
+ elif has_prod_files and _is_generated_file(rel_path):
1142
+ rank_score = raw_centrality * 0.01
1143
+ elif has_prod_files and in_degree == 0:
1144
+ rank_score = raw_centrality * 0.15
1145
+ else:
1146
+ rank_score = float(in_degree * 3 + out_degree)
1124
1147
  scores[rel_path] = {
1125
1148
  "file": rel_path,
1126
1149
  "centrality": raw_centrality,
@@ -1443,10 +1466,13 @@ class CodeGraph:
1443
1466
 
1444
1467
  def format_topology_banner(self) -> str:
1445
1468
  """Creates a compact 1-line prompt injection banner for coding agents."""
1446
- god_nodes = self.get_god_nodes(top_n=4)
1469
+ god_nodes = self.get_god_nodes(top_n=6)
1447
1470
  if not god_nodes:
1448
1471
  return ""
1449
- items = [f"{g['file']} ({g['dependents']} deps)" for g in god_nodes]
1472
+ # In multi-file projects, Core Hubs must have incoming dependents (dependents > 0)
1473
+ hubs = [g for g in god_nodes if g.get("dependents", 0) > 0]
1474
+ nodes_to_show = hubs[:4] if hubs else god_nodes[:4]
1475
+ items = [f"{g['file']} ({g['dependents']} deps)" for g in nodes_to_show]
1450
1476
  return f"[TokenSafe Architecture Map | Core Hubs: {', '.join(items)}]"
1451
1477
 
1452
1478
 
package/src/installer.py CHANGED
@@ -51,8 +51,8 @@ UNIFIED_TOKENSAFE_RULE = (
51
51
  "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"
52
52
  "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"
53
53
  "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"
54
- "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"
55
- "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
+ "5. **Mandatory Architecture Graph & God Nodes First**: For ANY codebase inquiry, feature design, refactoring, or multi-component investigation, your FIRST tool call MUST be `tokensafe:get_architecture_graph(project_path)` to inspect project God Nodes and key dependency hubs in < 250 tokens before reading individual files or searching (pass target project's absolute path in multi-repo setups).\n"
55
+ "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 (pass target project's absolute path in multi-repo setups).\n"
56
56
  "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"
57
57
  "8. **Command Sanitization, Build Compaction & Compact Tests**: Use `sanitize_command` on high-output terminal commands (`git diff/log/show/blame`, `git push` --no-progress, `git commit` hook protection, `rg`, `find`, `grep`, `docker`/`kubectl logs`, `npm`/`pip install`, `cat` of lockfiles, `curl`, and build/typecheck commands like `npm run build`, `vite build`, `next build`, `cargo build`, `tsc`, `tsc --noEmit`, `npm run typecheck`, `npx eslint`) — compound commands (`a && b ; c`) are rewritten per stage. Run noisy commands, builds, and test suites (`bun test`, `pytest`, `python -m unittest`, `vitest`, `jest`, `cargo test`, `go test`) via `tokensafe wrap '<command>'` or `tokensafe tests [cmd]` (clean 1-line build/pass summary, full traceback/compiler error only on failure) instead of raw verbose test crawls; never leave `vitest`/`jest`/`bun` 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"
58
58
  "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"
@@ -72,8 +72,8 @@ POINTER_RULE = (
72
72
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
73
73
  "The full 12-point protocol is installed globally in the agent-level instructions "
74
74
  "(~/.zcode/AGENTS.md, ~/.claude/CLAUDE.md, ~/.codex/AGENTS.md, ~/.kimi-code/AGENTS.md) and applies to this project. "
75
- "Core rules: never raw grep/find or `ls -la` — use `tokensafe:scoped_search`, "
76
- "`tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
75
+ "Core rules: never raw grep/find or `ls -la` — use `tokensafe:get_architecture_graph(project_path)` first for God Nodes, "
76
+ "`tokensafe:scoped_search`, `tokensafe:smart_read_file(path, symbol)`, `tokensafe:smart_bundle` and `tokensafe:list_dir`; "
77
77
  "sanitize high-output commands via `tokensafe:sanitize_command`; check `tokensafe:context_budget` (Grade S-F) "
78
78
  "before large tasks and compact via `tokensafe:compact_conversation` (orientation digest active); never hardcode secret "
79
79
  "fallbacks; append the `⚡ TokenSafe Turn Savings` footer on tool-using turns.\n"
package/src/mcp_server.py CHANGED
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
42
42
 
43
43
  SERVER_INFO = {
44
44
  "name": "tokensafe-mcp",
45
- "version": "4.2.6"
45
+ "version": "4.2.8"
46
46
  }
47
47
 
48
48
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -127,7 +127,7 @@ TOOLS = [
127
127
  "inputSchema": {
128
128
  "type": "object",
129
129
  "properties": {
130
- "project_path": {"type": "string", "description": "Optional root path of the project (defaults to active workspace, or pass '.' or absolute path)"}
130
+ "project_path": {"type": "string", "description": "Target project root directory. IMPORTANT: Always pass the absolute directory path (e.g. '/path/to/repo') when working in multi-workspace setups or repositories outside CWD."}
131
131
  }
132
132
  }
133
133
  },
@@ -137,7 +137,7 @@ TOOLS = [
137
137
  "inputSchema": {
138
138
  "type": "object",
139
139
  "properties": {
140
- "project_path": {"type": "string", "description": "Optional root path of the project (defaults to active workspace, or pass '.' or absolute path)"}
140
+ "project_path": {"type": "string", "description": "Target project root directory. IMPORTANT: Always pass the absolute directory path (e.g. '/path/to/repo') when working in multi-workspace setups or repositories outside CWD."}
141
141
  }
142
142
  }
143
143
  },
@@ -241,7 +241,7 @@ class TelemetrySync:
241
241
  current_last_id = last_id
242
242
  headers = {
243
243
  "Content-Type": "application/json",
244
- "User-Agent": "TokenSafe-Sync/4.2.6"
244
+ "User-Agent": "TokenSafe-Sync/4.2.8"
245
245
  }
246
246
  if active_key:
247
247
  headers["Authorization"] = f"Bearer {active_key}"
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.2.6"
20
+ CURRENT_VERSION = "4.2.8"
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