tokensafe 2.7.2 → 2.8.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/README.md CHANGED
@@ -163,9 +163,11 @@ When an operation is blocked, the agent sees an explicit, constructive message:
163
163
 
164
164
  **Clean context, better code**
165
165
 
166
- - `tokensafe:smart_read_file` returns the target function plus its 1-hop dependencies instead of the whole file. 10+ languages, with CSS design tokens preserved so agents never invent colors or font rules.
167
- - `tokensafe:graph` maps architectural hotspots and dependency topology in under 250 tokens instead of a full repository crawl.
168
- - The command sanitizer strips lockfile noise and stack dumps down to the failing assertion, and forces JS test runners into run-once mode so background tests never hang.
166
+ - `tokensafe:smart_read_file` returns the target function plus its 1-hop dependencies instead of the whole file. 11 languages (Python, TypeScript/JavaScript, Go, Rust, Java, C#, C/C++, PHP, Kotlin, Ruby, Swift), with CSS design tokens preserved so agents never invent colors or font rules.
167
+ - `tokensafe:smart_bundle` reads 3–8 related symbols across files as one merged bundle — shared imports deduplicated, 1-hop signatures unified, a single roundtrip instead of chained reads.
168
+ - OpenAPI/Swagger, Prisma, GraphQL and SQL files are auto-sliced: pass a spec path, model, type, or table as `symbol` and get that entry plus its 1-hop references — a 5,000-line migration drops from ~30k tokens to a few hundred.
169
+ - `tokensafe:graph` maps architectural hotspots and dependency topology in under 250 tokens instead of a full repository crawl — and teams share the result: the indexed graph and API surface are cached per repo state in the Team Symbol Index, so the 19 developers after the first one skip the crawl entirely.
170
+ - The command sanitizer strips lockfile noise and stack dumps down to the failing assertion, caps `git status`/`git diff` floods and docker build tails, and forces JS test runners into run-once mode so background tests never hang. Malformed JSON tool arguments from small local models are repaired in-flight instead of failing the call.
169
171
  - The loop guard halts agents stuck repeating the same broken edit.
170
172
 
171
173
  **Local-first guardrails**
@@ -180,6 +182,7 @@ When an operation is blocked, the agent sees an explicit, constructive message:
180
182
  - The Context Budget HUD shows live window usage with a breakdown (tools / history / prompts) before quality drops.
181
183
  - The shared L3 team cache gives teammates and CI runners warm 0ms hits on repeated reads and prompts.
182
184
  - Managed cloud distillation compacts prompts with zero API keys for developers.
185
+ - The dashboard's live savings strip streams anonymized per-machine savings (tokens and USD) over SSE — you see what the team saves right now, not at the end of the week.
183
186
  - The Friday per-seat ROI digest reports each engineer's savings with the `measured` / `estimated` split; inactive seats show `—`, never guessed figures.
184
187
 
185
188
  Deeper mechanics (language matrix, context tax math, cache tiers, governor) live in [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
@@ -271,13 +274,14 @@ All hook adapters fail open: an internal error never stalls your agent. Failures
271
274
  ## Reference
272
275
 
273
276
  <details>
274
- <summary><b>Local MCP tools (12)</b></summary>
277
+ <summary><b>Local MCP tools (13)</b></summary>
275
278
 
276
279
  | Tool | What it does |
277
280
  |---|---|
278
- | `get_architecture_graph` | Architectural hotspots and dependency topology before multi-file reading |
281
+ | `get_architecture_graph` | Architectural hotspots and dependency topology before multi-file reading; shared team symbol index reuse |
279
282
  | `get_api_surface` | Compact markdown map of all exported interfaces, classes, and types |
280
- | `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies |
283
+ | `smart_read_file` | AST-skeletonized file read preserving a target symbol and 1-hop dependencies; OpenAPI/Prisma/GraphQL/SQL files auto-slice (symbol = spec path / model / type / table) |
284
+ | `smart_bundle` | 3–8 related symbols across files in one call: merged skeletons, deduplicated shared imports, unified 1-hop signatures |
281
285
  | `scoped_search` | Token-bounded symbol and text search with line-numbered matches |
282
286
  | `list_dir` | Clean directory tree without permissions, timestamps, or lockfiles |
283
287
  | `slice_diff` | Unified diff slicing omitting lockfiles and minimizing context lines |
@@ -153,7 +153,7 @@ def handle(event: str, payload: dict) -> dict:
153
153
  tool_input = {}
154
154
  if tool in ("Bash", "Shell", "bash"):
155
155
  command = str(tool_input.get("command") or "")
156
- verdict = guard_command(command, AGENT, session_id)
156
+ verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
157
157
  if verdict["decision"] == "deny":
158
158
  return {
159
159
  "hookSpecificOutput": {
@@ -42,7 +42,7 @@ def handle(event: str, payload: dict) -> dict:
42
42
 
43
43
  if event == "beforeShellExecution":
44
44
  command = str(payload.get("command") or "")
45
- verdict = guard_command(command, AGENT, session_id)
45
+ verdict = guard_command(command, AGENT, session_id, cwd=str(payload.get("cwd") or ""))
46
46
  if verdict["decision"] == "deny":
47
47
  return {"permission": "deny", "user_message": verdict["reason"]}
48
48
  if verdict["decision"] == "ask":
@@ -92,7 +92,7 @@ def _handle(payload: dict) -> dict:
92
92
  }
93
93
  })
94
94
  elif last_user_input and len(last_user_input.strip()) >= 5 and not _proxy_is_active():
95
- compaction = PromptCompactor.compact(last_user_input, enable_deepseek=True)
95
+ compaction = PromptCompactor.compact(last_user_input, enable_distill=True)
96
96
  saved_tokens = compaction["saved_tokens"]
97
97
  reduction_pct = compaction["reduction_pct"]
98
98
 
@@ -12,7 +12,8 @@ Injects:
12
12
  per-turn ephemeral reminders and the every-5th-turn re-nudge)
13
13
  2. Quota / community-limit warning banner (user-facing markdown)
14
14
  3. Environment bloat warning (heavy MCP servers, oversized rule files)
15
- Also kicks off the background OS update notification check.
15
+ Also kicks off the background OS update notification check and the
16
+ zero-config community-license issuance (anonymous free-tier identity).
16
17
  """
17
18
 
18
19
  import sys
@@ -78,6 +79,12 @@ def main():
78
79
  except Exception:
79
80
  pass
80
81
 
82
+ try:
83
+ import threading
84
+ threading.Thread(target=LicenseManager.ensure_community_license, daemon=True).start()
85
+ except Exception:
86
+ pass
87
+
81
88
  try:
82
89
  bloat_warning = EnvironmentAuditor.get_bloat_warning(workspace_root=workspace_root)
83
90
  if bloat_warning:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.7.2",
4
+ "version": "2.8.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,16 +1,16 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.7.2",
4
+ "version": "2.8.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": {
8
8
  "name": "Oleg Savelev",
9
9
  "url": "https://github.com/NekoSin4eG"
10
10
  },
11
- "homepage": "https://github.com/tokensafe-dev/tokensafe-cloud",
11
+ "homepage": "https://tokensafe.dev",
12
12
  "repository": {
13
13
  "type": "git",
14
- "url": "https://github.com/tokensafe-dev/tokensafe-cloud"
14
+ "url": "https://github.com/tokensafe-dev/tokensafe"
15
15
  }
16
16
  }
package/rules/AGENTS.md CHANGED
@@ -27,7 +27,7 @@ Execute the specified action directly based on these extracted parameters.
27
27
 
28
28
  ### 3. Architecture & Code Navigation Directives (Graph-Guided)
29
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.
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
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
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.
33
33
  5. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
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.7.2",
6
+ "version": "2.8.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.7.2",
33
+ "version": "2.8.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.7.2",
49
+ "version": "2.8.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -26,6 +26,8 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
26
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
27
  - **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
28
  - **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
+ - **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.
30
+ - **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.
29
31
  - **Result**: Preserves the exact target definition while folding surrounding inert code into clean 1-line signatures without docstrings (-85% to -98% tokens).
30
32
 
31
33
  3. **ARCHITECTURE SURVEY BEFORE BROWSING (`get_architecture_graph`)**:
@@ -59,7 +61,10 @@ Quick pointers:
59
61
 
60
62
  - Search: `tokensafe:scoped_search(query, scope)` — never raw grep.
61
63
  - Inspect: `tokensafe:smart_read_file(path, symbol)` — definition + 1-hop deps.
64
+ - Bundle: `tokensafe:smart_bundle(targets=[{path, symbol}])` — 3-8 related symbols across files in one call, shared imports deduplicated.
62
65
  - Navigate: `tokensafe:get_architecture_graph(project_path)` / `tokensafe:get_api_surface(project_path)`.
66
+ - Directory: `tokensafe:list_dir(path, depth=2)` — clean tree, never verbose `ls -la`.
67
+ - Terminal: `tokensafe:sanitize_command(command, cwd)` — bounded logs/diffs, test runner guards.
63
68
  - Context: `tokensafe:compact_conversation(transcript_path)` / `tokensafe:context_budget`.
64
69
 
65
70
  ---
@@ -4,7 +4,8 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
4
4
 
5
5
  | MCP Tool | Description | Efficiency Impact |
6
6
  |---|---|---|
7
- | `tokensafe:smart_read_file` | Graph-guided AST reader with `symbol` body retention, `dep_mode` (`signature` default / `full`), and session pointer dedup (`force_full`). | **-90% to -98%** token reduction |
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
+ | `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 |
8
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
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` |
10
11
  | `tokensafe:get_architecture_graph` | Computes dependency topology, hub centrality, and identifies top God Nodes for `project_path`. | **~200 tokens** (replaces 50k crawl) |
@@ -74,7 +75,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
74
75
  ```
75
76
  *Extracts the targeted `LuckyWheelTab` implementation plus compact 1-line signatures for 1-hop dependencies with inert code and imports folded. Pass `"dep_mode": "full"` for full dependency bodies, `"include_deps": false` for 0-hop isolation, or `"force_full": true` to bypass a session pointer hit.*
76
77
 
77
- ### 3. Public API Map Workflow
78
+ ### 4. Public API Map Workflow
78
79
  ```json
79
80
  {
80
81
  "ServerName": "tokensafe",
@@ -86,21 +87,20 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
86
87
  ```
87
88
  *Returns all exported interfaces and types without reading hundreds of module files.*
88
89
 
89
- ### 4. Pre-flight Security & Hygiene Audit
90
+ ### 5. Pre-flight Security & Hygiene Audit
90
91
  ```json
91
92
  {
92
93
  "ServerName": "tokensafe",
93
94
  "ToolName": "guard_inspect",
94
95
  "Arguments": {
95
96
  "command": "git add .env",
96
- "code": "const key = process.env.JWT_SECRET || 'hardcoded_secret';",
97
97
  "file_path": "src/auth.ts"
98
98
  }
99
99
  }
100
100
  ```
101
101
  *Validates commands and code snippets before execution; returns structured pass/block verdict with check_name.*
102
102
 
103
- ### 5. Context Budget → Smart Compact Workflow
103
+ ### 6. Context Budget → Smart Compact Workflow
104
104
  ```json
105
105
  {
106
106
  "ServerName": "tokensafe",
@@ -105,7 +105,7 @@ def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str
105
105
  try:
106
106
  from src.compactor import PromptCompactor
107
107
  from src.tokenizer import count_tokens
108
- compaction = PromptCompactor.compact(prompt, enable_deepseek=False)
108
+ compaction = PromptCompactor.compact(prompt, enable_distill=False)
109
109
  saved = compaction.get("saved_tokens", 0)
110
110
  if saved < 5:
111
111
  return "", meta
@@ -127,7 +127,7 @@ def compact_for_injection(prompt: str, agent: str, session_id: str) -> Tuple[str
127
127
  return "", meta
128
128
 
129
129
 
130
- def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, Any]:
130
+ def guard_command(command: str, agent: str, session_id: str = "", cwd: str = "") -> Dict[str, Any]:
131
131
  """Pre-execution shell guard. Returns:
132
132
  {decision: allow|deny|ask, reason, saved_tokens} where saved_tokens is the
133
133
  MEASURED mass of blocked output (0 for allowed commands)."""
@@ -161,19 +161,19 @@ def guard_command(command: str, agent: str, session_id: str = "") -> Dict[str, A
161
161
  if re.search(pat, text):
162
162
  blocked("DESTRUCTIVE", "Blocked: irreversible/destructive operation")
163
163
  return result
164
- # RAW_CODE_SEARCH (deny): recursive grep/rg/find crawls over source trees
165
- # are the exact workflow the tokensafe MCP tools replace. TokenSafeGuard
166
- # already enforces this on the Antigravity path (inspect_command) — share
167
- # its check here so Claude Code / Cursor adapters honor the same policy
168
- # with the same "use tokensafe:scoped_search" guidance. Fail-open on
169
- # import problems, like every adapter guard path.
164
+ # Full TokenSafeGuard delegation: the Antigravity path (pre_tool_use.py) runs
165
+ # TokenSafeGuard.inspect_command, and the Claude Code / Cursor adapters must
166
+ # honor the SAME policy suite (GIT_SECRET_STAGING, SQL_INJECTION,
167
+ # INSECURE_CORS, DATA_EXFILTRATION, DESTRUCTIVE_RM flag/target variants, and
168
+ # raw code search with the MCP-tools guidance) instead of a regex subset.
169
+ # Fail-open on import problems, like every adapter guard path.
170
170
  try:
171
171
  from src.guard import TokenSafeGuard
172
- search_err = TokenSafeGuard._check_raw_code_search(cmd)
172
+ guard_res = TokenSafeGuard.inspect_command(cmd, cwd=cwd or None)
173
173
  except Exception:
174
- search_err = None
175
- if search_err:
176
- blocked("RAW_CODE_SEARCH", search_err)
174
+ guard_res = None
175
+ if guard_res is not None and getattr(guard_res, "blocked", False):
176
+ blocked(guard_res.check_name or "GUARD", guard_res.reason)
177
177
  return result
178
178
  for pat in _TLS_BYPASS_PATTERNS:
179
179
  if re.search(pat, text):
package/src/benchmark.py CHANGED
@@ -413,9 +413,9 @@ class BenchmarkSuite:
413
413
  sync_remote=False,
414
414
  )
415
415
  distilled_hit = DistillationCache.get(raw_prompt)
416
- compaction_text = distilled_hit or PromptCompactor.compact(raw_prompt, enable_deepseek=True)["compact_text"]
416
+ compaction_text = distilled_hit or PromptCompactor.compact(raw_prompt, enable_distill=True)["compact_text"]
417
417
  else:
418
- compaction_text = PromptCompactor.compact(raw_prompt, enable_deepseek=True)["compact_text"]
418
+ compaction_text = PromptCompactor.compact(raw_prompt, enable_distill=True)["compact_text"]
419
419
  p_base_tokens = count_tokens(raw_prompt)
420
420
  p_opt_tokens = count_tokens(compaction_text)
421
421
 
package/src/cli.py CHANGED
@@ -470,9 +470,9 @@ def main():
470
470
  print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
471
471
  if tier == "free":
472
472
  print(" \033[33mTier: Free Community Edition\033[0m")
473
- print(" Neural Semantic Distillation (Gemini / OpenAI / DeepSeek) is reserved for Solo & Team tiers.")
473
+ print(" Managed Cloud Distillation (zero API keys) is reserved for Solo, Team, and Enterprise tiers.")
474
474
  print(" Free Community Edition operates with the zero-latency, zero-cost Local Regex Compactor.\n")
475
- print(" \033[1mTo unlock Neural LLM Distillation:\033[0m")
475
+ print(" \033[1mTo unlock Cloud Distillation:\033[0m")
476
476
  print(" 1. Start 7-day free trial or upgrade at: \033[36mhttps://tokensafe.dev\033[0m")
477
477
  print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
478
478
  elif not UniversalDistiller.is_self_hosted():
@@ -279,6 +279,13 @@ class CommandSanitizer:
279
279
  subcmd = cmd_args[sub_idx] if sub_idx < len(cmd_args) else ""
280
280
  sub_args = cmd_args[sub_idx + 1 :]
281
281
 
282
+ # git status: compact porcelain format + bounded output (a long-lived
283
+ # monorepo branch can list hundreds of untracked files)
284
+ if subcmd == "status":
285
+ if "--porcelain" not in sub_args and "-s" not in sub_args and "-uno" not in sub_args and "--untracked-files" not in stage:
286
+ new_stage = re.sub(r"\b(git(?:\s+-C\s+\S+)?\s+status)\b", r"\1 --porcelain", stage, count=1)
287
+ return new_stage, 1500, "Switched git status to compact porcelain output, capped to 200 lines", cls._CAP_LINES_200
288
+
282
289
  # git diff: exclude lockfiles/bundles when diffing unscoped repository
283
290
  if subcmd == "diff":
284
291
  if not any(a.startswith(":!") for a in sub_args) and ":!" not in stage:
@@ -363,6 +370,12 @@ class CommandSanitizer:
363
370
  if "--tail" not in stage and not any(a == "-n" or a.startswith(("-n", "--tail=")) for a in cmd_args):
364
371
  return f"{stage} --tail 100", 2000, "Capped docker logs to last 100 lines", None
365
372
 
373
+ # docker build / docker compose build: the failing step sits at the end
374
+ # of the log — keep only the tail instead of a full build dump
375
+ if cmd_tok == "docker" and (cmd_args[:1] == ["build"] or cmd_args[:2] == ["compose", "build"]):
376
+ if not cls._has_redirect(stage) and "|" not in stage:
377
+ return f"{stage} 2>&1 | tail -50", 2500, "Tailed docker build output to the last 50 lines (failing step is last)", None
378
+
366
379
  # kubectl logs
367
380
  if cmd_tok == "kubectl" and cmd_args[:1] == ["logs"]:
368
381
  if "--tail" not in stage:
package/src/compactor.py CHANGED
@@ -360,14 +360,14 @@ class PromptCompactor:
360
360
  def compact(
361
361
  cls,
362
362
  raw_text: str,
363
- enable_deepseek: bool = True,
363
+ enable_distill: bool = True,
364
364
  min_distill_tokens: Optional[int] = None
365
365
  ) -> Dict[str, Any]:
366
366
  """
367
367
  Compresses input prompt via 3-Tier Architecture:
368
368
  - Tier 0: Pass-through for very short inputs (< 6 tokens)
369
369
  - Tier 1: Multilingual Regex Compactor (0ms, 0 external tokens) for inputs < 100 tokens
370
- - Tier 2: Universal Distiller (DeepSeek / Gemini / OpenAI) for long/complex prompts (>= 100 tokens)
370
+ - Tier 2: Managed Cloud Distiller (license-authenticated; BYOK Gemini/OpenAI/DeepSeek for self-hosted) for long/complex prompts (>= 100 tokens)
371
371
  """
372
372
  if not raw_text or not raw_text.strip():
373
373
  return {
@@ -407,10 +407,10 @@ class PromptCompactor:
407
407
  "tier": "PASS_THROUGH"
408
408
  }
409
409
 
410
- # Tier 2: Neural LLM Intent Distiller (Gemini / OpenAI / DeepSeek)
410
+ # Tier 2: Managed Cloud Intent Distiller (BYOK Gemini / OpenAI / DeepSeek for self-hosted)
411
411
  # Exclusive to TokenSafe Solo, Team, and Enterprise (or active trials)
412
412
  min_distill = min_distill_tokens if min_distill_tokens is not None else cls._get_min_distill_tokens()
413
- if enable_deepseek and original_tokens >= min_distill:
413
+ if enable_distill and original_tokens >= min_distill:
414
414
  active_tier, _ = LicenseManager.get_active_license()
415
415
  if active_tier != "free":
416
416
  distilled = UniversalDistiller.distill(raw_text)
@@ -446,7 +446,7 @@ class PromptCompactor:
446
446
  "target_file": target_file,
447
447
  "symbol": symbol,
448
448
  "traits": traits,
449
- "tier": "DEEPSEEK_V3"
449
+ "tier": "DISTILLER"
450
450
  }
451
451
 
452
452
  # Tier 1: Multilingual Local Regex Compactor
package/src/distiller.py CHANGED
@@ -1,7 +1,8 @@
1
1
  """
2
- Universal Multi-Provider Intent Distiller:
2
+ Managed-Cloud-First Intent Distiller:
3
3
  Translates verbose, conversational developer prompts into ultra-dense TOCP S-Expressions.
4
- Supports DeepSeek-V3, OpenAI ChatGPT (gpt-4o-mini), and Google Gemini (2.0 Flash / 1.5 Flash).
4
+ Paid tiers use the TokenSafe Cloud Distiller out of the box (zero API keys, license-key auth).
5
+ Self-hosted/Enterprise optionally supports BYOK: DeepSeek, OpenAI ChatGPT, and Google Gemini.
5
6
  Implemented with pure standard-library urllib (zero dependencies, strict timeout).
6
7
  """
7
8
 
@@ -17,7 +18,7 @@ from src.license_manager import LicenseManager
17
18
  from src.paths import resolve_data_dir
18
19
 
19
20
  class UniversalDistiller:
20
- """Multi-provider semantic intent compiler supporting DeepSeek, OpenAI, and Google Gemini."""
21
+ """Managed-cloud-first semantic intent compiler: TokenSafe Cloud (zero keys) with optional BYOK DeepSeek, OpenAI, and Google Gemini."""
21
22
 
22
23
  DEFAULT_TIMEOUT = 2.5
23
24
  # After a failed roundtrip, skip all remote distillation for this long.
@@ -195,7 +196,7 @@ Rules:
195
196
  def distill(cls, raw_text: str, preferred_provider: Optional[str] = None) -> Optional[str]:
196
197
  """
197
198
  Distills raw conversational text into an S-Expression using the best available provider.
198
- Priority: Explicit preferred -> Gemini -> OpenAI -> DeepSeek.
199
+ Priority: Managed Cloud (license-auth, zero keys) -> Explicit preferred -> Gemini -> OpenAI -> DeepSeek.
199
200
  Requires active TokenSafe Solo or Team subscription.
200
201
  """
201
202
  tier, _ = LicenseManager.get_active_license()
package/src/governor.py CHANGED
@@ -234,7 +234,7 @@ class ContextGovernor:
234
234
  if msg.get("role") == "user" and isinstance(msg.get("content"), str):
235
235
  raw_user = msg["content"]
236
236
  if len(raw_user.strip()) > 15 and "[TOCP Intent]" not in raw_user:
237
- comp = PromptCompactor.compact(raw_user, enable_deepseek=False)
237
+ comp = PromptCompactor.compact(raw_user, enable_distill=False)
238
238
  if comp["saved_tokens"] >= 5:
239
239
  msg["content"] = f"[TOCP Intent]: {comp['compact_text']}"
240
240
  compacted_any = True
@@ -1,7 +1,7 @@
1
1
  """
2
2
  TokenSafe Graph Engine: Dependency-Aware Graph Analysis & Skeletonization.
3
3
  Builds a zero-LLM deterministic code graph for Python, TypeScript/JavaScript, Go,
4
- Rust, Java, C#, C/C++, PHP, Kotlin, and Swift.
4
+ Rust, Java, C#, C/C++, PHP, Kotlin, Ruby, and Swift.
5
5
 
6
6
  Uses the optional Tree-sitter backend when available (`src.treesitter_backend`)
7
7
  and falls back seamlessly to the Python standard library `ast` and `BraceLexer`
@@ -38,7 +38,7 @@ SUPPORTED_EXTS = {
38
38
  ".py", ".ts", ".js", ".tsx", ".jsx", ".mjs", ".cjs",
39
39
  ".go", ".rs", ".java", ".cs",
40
40
  ".c", ".cpp", ".cc", ".cxx", ".h", ".hpp",
41
- ".php", ".kt", ".kts", ".swift",
41
+ ".php", ".kt", ".kts", ".swift", ".rb",
42
42
  }
43
43
 
44
44
  _SKIP_CALLS = {
@@ -344,6 +344,8 @@ class CodeGraph:
344
344
 
345
345
  if ext == ".py":
346
346
  self._parse_python(content, rel_path, file_node)
347
+ elif ext == ".rb":
348
+ self._parse_ruby(content, rel_path, file_node)
347
349
  elif ext in SUPPORTED_EXTS:
348
350
  self._parse_braces(content, rel_path, file_node, ext)
349
351
 
@@ -571,6 +573,83 @@ class CodeGraph:
571
573
  if finished_key in self.symbols:
572
574
  self.symbols[finished_key].line_end = idx
573
575
 
576
+ def _parse_ruby(self, code: str, rel_path: str, file_node: str):
577
+ """Stdlib Ruby parser: keyword-delimited blocks (`def`/`class`/`module` ...
578
+ `end`) instead of braces. Mirrors the brace-parser conventions (kinds,
579
+ quals, call edges) so both backends stay in parity."""
580
+ lines = code.splitlines()
581
+ require_re = re.compile(r'^\s*require(?:_relative)?\s+["\']([^"\']+)["\']')
582
+ opener_re = re.compile(
583
+ r'^\s*(?:def|class|module|if|unless|while|until|case|for|begin)\b|\bdo\s*(?:\|[^|]*\|)?\s*$'
584
+ )
585
+ container_re = re.compile(r'^\s*(?:class|module)\s+([A-Z][A-Za-z0-9_:]*)')
586
+ method_re = re.compile(r'^\s*def\s+(?:self\.)?([a-zA-Z_][a-zA-Z0-9_]*[?!]?)')
587
+ call_re = re.compile(r'\b([a-zA-Z_][a-zA-Z0-9_]*[?!]?)\s*\(')
588
+ end_re = re.compile(r'\bend\b')
589
+
590
+ # Stack items: (sym_key|None, kind|None, qual|None). None entries track
591
+ # non-symbol keyword blocks (if/while/do/...) so `end` counting balances.
592
+ stack: List[Tuple[Optional[str], Optional[str], Optional[str]]] = []
593
+
594
+ for idx, raw in enumerate(lines, 1):
595
+ no_comment = raw.split("#", 1)[0]
596
+ # Blank out string literals so `end`-like words inside strings never count
597
+ no_str = re.sub(r'"[^"]*"', '""', no_comment)
598
+ no_str = re.sub(r"'[^']*'", "''", no_str)
599
+ if not no_str.strip():
600
+ continue
601
+
602
+ rm = require_re.match(raw)
603
+ if rm:
604
+ self.file_imports[rel_path].add(rm.group(1))
605
+ self.add_edge(file_node, f"mod:{rm.group(1)}")
606
+
607
+ opens = len(opener_re.findall(no_str))
608
+ closes = len(end_re.findall(no_str))
609
+
610
+ matched_name: Optional[str] = None
611
+ matched_kind: Optional[str] = None
612
+ cm = container_re.match(no_str)
613
+ if cm:
614
+ matched_kind, matched_name = "class", cm.group(1)
615
+ else:
616
+ mm = method_re.match(no_str)
617
+ if mm:
618
+ matched_kind, matched_name = "function", mm.group(1)
619
+
620
+ if matched_name and matched_kind:
621
+ class_ctx = [e[2] for e in stack if e[1] == "class"]
622
+ qual = f"{class_ctx[-1]}::{matched_name}" if class_ctx else matched_name
623
+ sym_key = f"{rel_path}::{qual}"
624
+ symbol = CodeSymbol(
625
+ name=matched_name,
626
+ kind=matched_kind,
627
+ file_path=rel_path,
628
+ line_start=idx,
629
+ line_end=idx,
630
+ signature=raw.strip(),
631
+ )
632
+ self._register_symbol(rel_path, file_node, symbol, sym_key)
633
+ stack.append((sym_key, matched_kind, qual))
634
+ elif opens:
635
+ stack.append((None, None, None))
636
+
637
+ active_fn = next((e for e in reversed(stack) if e[1] == "function"), None)
638
+ if active_fn and active_fn[0]:
639
+ for cmm in call_re.finditer(no_str):
640
+ callee = cmm.group(1)
641
+ if callee != matched_name and callee not in _SKIP_CALLS:
642
+ self.add_edge(active_fn[0], f"call:{callee}")
643
+
644
+ for _ in range(closes):
645
+ if not stack:
646
+ break
647
+ entry = stack.pop()
648
+ if entry[0]:
649
+ sym = self.symbols.get(entry[0])
650
+ if sym:
651
+ sym.line_end = idx
652
+
574
653
  def _resolve_local_imports(self) -> None:
575
654
  """Resolves raw `file_imports` strings to real `file:<rel_path>` edges."""
576
655
  indexed_files = set(self.file_symbols.keys())
package/src/installer.py CHANGED
@@ -46,12 +46,17 @@ UNIFIED_TOKENSAFE_RULE = (
46
46
  "## TOKENSAFE GRAPH-FIRST OPTIMIZATION PROTOCOL\n"
47
47
  "Always use `tokensafe` MCP tools over default raw file reads or high-output terminal executions to prevent context window exhaustion.\n\n"
48
48
  "1. **Zero Raw Grep/Find (Blocked)**: 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.\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
50
  "3. **Architecture Discovery**: Always call `tokensafe:get_architecture_graph(project_path)` before exploratory multi-file reading. Returns project God Nodes and key dependency hubs in < 250 tokens without file crawling.\n"
51
51
  "4. **API Surface Map**: Use `tokensafe:get_api_surface(project_path)` to get all exported classes, types, and interfaces in a single markdown map.\n"
52
- "5. **Command Sanitization**: 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 via the `tokensafe tests [pytest]` CLI (compact failure report) instead of raw `python3 -m unittest discover`; 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"
53
- "6. **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"
54
- "7. **Proof-of-Savings Turn Footer (always in English)**:\n"
52
+ "5. **No Unconstrained Shell Grep/Find & No Verbose ls -la**: Strictly avoid running raw recursive grep/find across projects. Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees in clean markdown without permissions, timestamps, or lockfiles (-90% tokens).\n"
53
+ "6. **Command Sanitization**: 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 via the `tokensafe tests [pytest]` CLI (compact failure report) instead of raw `python3 -m unittest discover`; 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"
54
+ "7. **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"
55
+ "8. **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"
56
+ "9. **Secret Leak Prevention Directive (Zero Hardcoded Fallbacks)**:\n"
57
+ "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
+ "`🛡️ **TokenSafe Security Guard**: Prevented secret / private key leak into git (<target_file>: <details>)`\n"
59
+ "10. **Proof-of-Savings Turn Footer (always in English)**:\n"
55
60
  "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"
56
61
  "`⚡ **TokenSafe Turn Savings**: +<tokens> tokens saved on this turn (<breakdown>) | Cumulative Total: <total> tokens (≈$<usd> approx)`\n"
57
62
  )