tokensafe 1.5.0 → 1.6.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
@@ -7,7 +7,7 @@
7
7
 
8
8
  <p align="center">
9
9
  <b>Autonomous Zero-Loss Token Economy & Context Optimizer for AI Coding Agents</b><br>
10
- Slashes LLM token costs by <b>up to 90%</b> with zero quality loss.<br>
10
+ Slashes LLM token costs by <b>up to [90%*](METRICS.md)</b> with zero context loss.<br>
11
11
  Built for <b>Cursor, Claude Desktop, Google Antigravity, Windsurf & Cline</b>.
12
12
  </p>
13
13
 
@@ -316,7 +316,9 @@ tokensafe providers
316
316
 
317
317
  ## 📊 Zero-Loss SWE-bench Benchmark Results
318
318
 
319
- Verified across 8 real-world production software engineering scenarios (131,604 baseline tokens down to 7,251 tokens, **-94.5% net token reduction**, **+28.1% turn latency speedup** with **100% Zero-Loss accuracy retention**):
319
+ Reference run across 8 real-world production software engineering scenarios (131,552 baseline tokens down to 7,263 tokens, **-94.5% net token reduction**, **+28.1% turn latency speedup** with **100% Zero-Loss accuracy retention**):
320
+
321
+ > Token counts vary by ±1% between runs because prompt compaction is **measured live** on every execution; baseline sizes are modeled constants. The harness now ships a SIMULATION DISCLOSURE with a measured-vs-modeled evidence breakdown — see [METRICS.md](METRICS.md).
320
322
 
321
323
  | Benchmark Scenario | Task Complexity | Baseline Tokens | TokenSafe Tokens | Reduction | Turn Speedup | Accuracy |
322
324
  |---|---|---|---|---|---|---|
@@ -519,11 +521,8 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
519
521
  | `POST` | `/api/team/seat/revoke` | **Bearer Auth** | `Authorization: Bearer <jwt\|key>`, JSON `{ owner_email, license_key }` | Revokes an active team seat license key. |
520
522
  | `POST` | `/api/telemetry/sync` | **License Auth** | JSON `{ license_key, email, events: [...] }` | Syncs batch telemetry events (enforces max 50 events/batch). |
521
523
  | `POST` | `/webhook/stripe` | **HMAC Sig** | `Stripe-Signature: t=...,v1=...` | Verifies Stripe webhook payload against `STRIPE_WEBHOOK_SECRET`. |
522
- | `GET` | `/api/admin/overview` | **Admin Only** | `X-Admin-Secret` or Admin JWT | Global overview of MRR, seats, active licenses, and system health. |
523
- | `POST` | `/api/admin/digest/send` | **Admin Only** | `X-Admin-Secret` or Admin JWT | Dispatches scheduled Friday weekly ROI digest emails to team leads. |
524
- | `POST` | `/api/admin/license/issue`| **Admin Only** | `X-Admin-Secret` or Admin JWT | Manually issues or provisions a custom tier license. |
525
- | `POST` | `/api/admin/license/revoke`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Immediately revokes a license. |
526
- | `POST` | `/api/admin/license/extend`| **Admin Only**| `X-Admin-Secret` or Admin JWT | Extends an active license duration. |
524
+
525
+ > **Note:** administrative endpoints are intentionally **not documented in the public API surface** — not even their paths. They are restricted by a dedicated admin secret / admin JWT and live in the private operations manual only. Public clients never need them — seat and license management is available through the [dashboard](https://dashboard.tokensafe.dev).
527
526
 
528
527
  ### 3. Server Configuration & Environment Variables
529
528
 
@@ -531,7 +530,7 @@ TokenSafe Cloud Backend enforces enterprise zero-trust security across all commu
531
530
  |---|---|---|
532
531
  | `TOKENSAFE_PRIVATE_KEY` | Production | 64-character hex Ed25519 seed for issuing `TS2.` licenses. |
533
532
  | `ADMIN_SECRET_KEY` | Yes | High-entropy secret for administrative API access (`X-Admin-Secret`). |
534
- | `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `nekosin4eg@gmail.com`). |
533
+ | `ADMIN_EMAILS` | Optional | Comma-separated admin emails (e.g. `admin@yourcompany.com`). |
535
534
  | `STRIPE_WEBHOOK_SECRET` | Production | Webhook secret (`whsec_...`) used to verify Stripe webhooks. |
536
535
  | `SMTP_PASS` | Production | Password/token for transactional mail delivery via ImprovMX SMTP. |
537
536
  | `JWT_SECRET` | Optional | Shared HMAC secret for verifying custom JWT tokens. Set a persistent value in production — otherwise sessions invalidate on every restart. |
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "1.5.0",
4
+ "version": "1.6.0",
5
5
  "description": "Autonomous Zero-Loss Token Economy & 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": "agy-token-optimizer",
3
3
  "displayName": "TokenSafe",
4
- "version": "1.5.0",
4
+ "version": "1.6.0",
5
5
  "description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
package/server.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "name": "dev.tokensafe/tokensafe",
4
4
  "title": "TokenSafe",
5
5
  "description": "Cut AI coding agent token usage up to 90% via AST slicing, dependency graphs & security guards.",
6
- "version": "1.5.0",
6
+ "version": "1.6.0",
7
7
  "websiteUrl": "https://tokensafe.dev",
8
8
  "repository": {
9
9
  "url": "https://github.com/NekoSin4eG/tokensafe",
@@ -30,7 +30,7 @@
30
30
  "registryType": "npm",
31
31
  "registryBaseUrl": "https://registry.npmjs.org",
32
32
  "identifier": "tokensafe",
33
- "version": "1.5.0",
33
+ "version": "1.6.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": "1.5.0",
49
+ "version": "1.6.0",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -56,6 +56,7 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
56
56
  | `tokensafe:sanitize_command` | Intercepts shell commands to strip lockfiles, cap unbounded git logs, and quiet test tracebacks. | Saves **10k-50k tokens** per run |
57
57
  | `tokensafe:slice_diff` | Slices unified git diffs, eliminating lockfiles and minimizing hunk context lines. | **-50% to -80%** diff size |
58
58
  | `tokensafe:compress_prompt` | Compresses verbose user instructions into lean TOCP S-expressions via DeepSeek/Regex. | **-40% to -65%** prompt tokens |
59
+ | `tokensafe:compact_conversation` | On-demand context compaction: folds a long JSONL session transcript into a lean Consolidated State Ledger (`transcript_path`, optional `invocation_num`). Call when the context window feels heavy or before a new subtask. | **-80% to -95%** history tokens |
59
60
  | `tokensafe:guard_inspect` | Pre-flight security & hygiene audit for commands or code snippets (secrets, TLS, SQLi, raw grep). | **Zero-Risk** pre-flight gate |
60
61
  | `tokensafe:get_token_savings_metrics` | Returns cumulative analytics: tokens saved, context ratio, USD value, and optimization source breakdown. | Persistent SQLite analytics |
61
62
 
@@ -168,6 +169,7 @@ For long-running autonomous sessions, TokenSafe actively manages context bloat:
168
169
  1. **Multi-Turn History Compaction**:
169
170
  - At conversation turn >= 3, automatically compiles past turns into a lean **Consolidated State Ledger**.
170
171
  - Preserves active file paths, modified symbols, and pending tasks while discarding transient tool output noise.
172
+ - **Manual trigger**: call `tokensafe:compact_conversation` with the session's `transcript_path` any time you need to shed context between subtasks — it returns the ledger JSON plus exact original/folded token counts.
171
173
  2. **Subagent Deduplication Firewall**:
172
174
  - Caches file reads across subagents. If subagent B attempts to read a file already inspected by subagent A, returns the cached skeleton instantly.
173
175
  3. **Loop Guard**:
package/src/benchmark.py CHANGED
@@ -136,33 +136,47 @@ class BenchmarkSuite:
136
136
  # 2. Measure Tool / Command Execution
137
137
  t_base_tokens = 0
138
138
  t_opt_tokens = 0
139
+ # Honesty bookkeeping (see METRICS.md): which optimized-side tokens are
140
+ # produced live by the real tools vs. taken from modeled constants.
141
+ opt_measured_tokens = 0
142
+ opt_modeled_tokens = 0
139
143
  opt_turns = task.get("baseline_turns", 1)
140
144
 
141
145
  if "raw_tool_tokens" in task:
142
146
  t_base_tokens += task["raw_tool_tokens"]
143
147
  if task.get("is_graph_discovery"):
148
+ opt_modeled_tokens += task.get("graph_opt_tokens", 220)
144
149
  t_opt_tokens += task.get("graph_opt_tokens", 220)
145
150
  elif task.get("is_graph_slicer"):
151
+ opt_modeled_tokens += task.get("slicer_opt_tokens", 340)
146
152
  t_opt_tokens += task.get("slicer_opt_tokens", 340)
147
153
  else:
154
+ opt_modeled_tokens += 280
148
155
  t_opt_tokens += 280
149
156
 
150
157
  if "raw_command_tokens" in task:
151
158
  cmd = task["command"]
152
159
  new_cmd, saved, _ = CommandSanitizer.sanitize(cmd)
153
160
  t_base_tokens += task["raw_command_tokens"]
161
+ # NOTE: `saved` is the sanitizer's downstream output ESTIMATE, not a
162
+ # live token delta, so it stays out of the measured bucket.
154
163
  if task.get("is_git_grep"):
164
+ opt_modeled_tokens += task.get("sanitized_tokens", 180)
155
165
  t_opt_tokens += task.get("sanitized_tokens", 180)
156
166
  elif task.get("id") == "SWE-03":
167
+ opt_modeled_tokens += 350
157
168
  t_opt_tokens += 350
158
169
  elif task.get("id") == "SWE-04":
170
+ opt_modeled_tokens += 320
159
171
  t_opt_tokens += 320
160
172
  else:
173
+ opt_modeled_tokens += max(150, task["raw_command_tokens"] - saved)
161
174
  t_opt_tokens += max(150, task["raw_command_tokens"] - saved)
162
175
 
163
176
  if "accumulated_history_tokens" in task:
164
177
  t_base_tokens += task["accumulated_history_tokens"]
165
178
  # History fold CSL is ~120 tokens
179
+ opt_modeled_tokens += 120
166
180
  t_opt_tokens += 120
167
181
 
168
182
  # 3. Measure Output Guard
@@ -171,10 +185,13 @@ class BenchmarkSuite:
171
185
  # Baseline rewrites whole file (1600-2200 output tokens)
172
186
  # Optimized Output Guard enforces edit_file (80-120 diff tokens)
173
187
  out_opt_tokens = 95
188
+ opt_modeled_tokens += out_opt_tokens
174
189
  elif "opt_output_tokens" in task:
175
190
  out_opt_tokens = task["opt_output_tokens"]
191
+ opt_modeled_tokens += out_opt_tokens
176
192
  else:
177
193
  out_opt_tokens = out_base_tokens
194
+ opt_modeled_tokens += out_opt_tokens # no guard win: mass is still modeled
178
195
 
179
196
  # 4. Measure Turn Savings
180
197
  if "opt_turns" in task:
@@ -204,6 +221,8 @@ class BenchmarkSuite:
204
221
  "name": name,
205
222
  "base_tokens": task_base_total,
206
223
  "opt_tokens": task_opt_total,
224
+ "opt_measured_tokens": opt_measured_tokens + p_opt_tokens, # prompt compaction is always live
225
+ "opt_modeled_tokens": opt_modeled_tokens,
207
226
  "saved_tokens": task_saved,
208
227
  "reduction_pct": round(task_pct, 1),
209
228
  "base_turns": task.get("baseline_turns", 1),
@@ -222,6 +241,8 @@ class BenchmarkSuite:
222
241
  "tasks": results,
223
242
  "total_base_tokens": total_base_tokens,
224
243
  "total_opt_tokens": total_opt_tokens,
244
+ "total_opt_measured_tokens": sum(t["opt_measured_tokens"] for t in results),
245
+ "total_opt_modeled_tokens": sum(t["opt_modeled_tokens"] for t in results),
225
246
  "total_saved_tokens": net_saved,
226
247
  "net_reduction_pct": round(net_pct, 1),
227
248
  "base_cost_usd": round(base_cost, 4),
@@ -245,6 +266,12 @@ class BenchmarkSuite:
245
266
  out.append(f" {BOLD}Cost Comparison:{RESET} ${data['base_cost_usd']:.4f} ➔ {GREEN}${data['opt_cost_usd']:.4f} USD{RESET} (Saved: ${data['cost_saved_usd']:.4f})")
246
267
  out.append(f" {BOLD}Agent Latency / Turns:{RESET} {data['total_base_turns']} turns ➔ {GREEN}{data['total_opt_turns']} turns{RESET} ({data['speedup_pct']}% faster via Prefetching)\n")
247
268
 
269
+ # SIMULATION DISCLOSURE — honest provenance of every number (METRICS.md)
270
+ out.append(f" {BOLD}Evidence Breakdown:{RESET}")
271
+ out.append(f" • {GREEN}Measured live{RESET}: {data['total_opt_measured_tokens']:,} optimized tokens (real tool outputs produced during this run)")
272
+ out.append(f" • {YELLOW}Modeled{RESET}: {data['total_opt_modeled_tokens']:,} optimized tokens (constants for typical production sizes)")
273
+ out.append(f" • All baseline sizes and turn counts are {YELLOW}modeled{RESET}; this is a simulation harness, not a metered production run.\n")
274
+
248
275
  out.append(f"{BOLD}── Task Breakdown ───────────────────────────────────────────────────{RESET}")
249
276
  for t in data["tasks"]:
250
277
  out.append(f" • {BOLD}{t['id']}: {t['name']:<48}{RESET}")
@@ -258,6 +285,11 @@ class BenchmarkSuite:
258
285
  md = []
259
286
  md.append("# 🏆 Zero-Loss SWE-bench Benchmark Report\n")
260
287
  md.append("> **Objective Proof of 80%+ Cost Reduction with 100% Accuracy Retention.**\n")
288
+ md.append("> **SIMULATION DISCLOSURE:** this is a simulated harness. All *baseline* sizes and turn")
289
+ md.append("> counts are **modeled** from typical production values. On the optimized side,")
290
+ md.append(f"> **{data['total_opt_measured_tokens']:,} tokens are measured live** by running the real tools during this run,")
291
+ md.append(f"> while **{data['total_opt_modeled_tokens']:,} tokens are modeled constants**. Task success is self-verified.")
292
+ md.append("> Production savings are tracked separately with measured/estimated labels — see [METRICS.md](METRICS.md).\n")
261
293
  md.append("| Metric | Baseline (Standard Agent) | Optimized (`agy-token-optimizer`) | Gain |")
262
294
  md.append("| :--- | :--- | :--- | :--- |")
263
295
  md.append(f"| **Context Tokens** | `{data['total_base_tokens']:,}` | `{data['total_opt_tokens']:,}` | **-{data['net_reduction_pct']}%** |")
package/src/installer.py CHANGED
@@ -643,6 +643,36 @@ class AgentInstaller:
643
643
 
644
644
  return restarted
645
645
 
646
+ @staticmethod
647
+ def _find_npm(home: Optional[str] = None) -> Optional[str]:
648
+ """Locates an npm executable even in a clean non-interactive environment.
649
+
650
+ The updater dialog runs via `do shell script` + login shell, where .zshrc
651
+ (and therefore nvm) is never sourced; PATH-only discovery made the npm
652
+ channel silently skip updates. Falls back to well-known locations."""
653
+ found = shutil.which("npm")
654
+ if found:
655
+ return found
656
+ base = home or HOME
657
+ candidates: List[str] = []
658
+ nvm_dir = os.path.join(base, ".nvm", "versions", "node")
659
+ try:
660
+ if os.path.isdir(nvm_dir):
661
+ # Newest installed node version wins.
662
+ for version_dir in sorted(os.listdir(nvm_dir), reverse=True):
663
+ candidates.append(os.path.join(nvm_dir, version_dir, "bin", "npm"))
664
+ except OSError:
665
+ pass
666
+ candidates += [
667
+ "/opt/homebrew/bin/npm",
668
+ "/usr/local/bin/npm",
669
+ "/usr/bin/npm",
670
+ ]
671
+ for cand in candidates:
672
+ if os.path.isfile(cand) and os.access(cand, os.X_OK):
673
+ return cand
674
+ return None
675
+
646
676
  @classmethod
647
677
  def self_update(cls):
648
678
  """
@@ -668,29 +698,43 @@ class AgentInstaller:
668
698
  print(f" {YELLOW}⚠{RESET} Git pull skipped: {e}")
669
699
 
670
700
  # 2. Check npm global
671
- if shutil.which("npm"):
701
+ # The updater dialog runs via `do shell script` + login shell, which skips
702
+ # .zshrc — nvm is NOT on PATH there, so PATH-only discovery silently
703
+ # downgraded the npm channel (the active one for many installs).
704
+ npm_bin = cls._find_npm()
705
+ if npm_bin:
672
706
  try:
673
- res = subprocess.run(["npm", "list", "-g", "--depth=0", "tokensafe"], capture_output=True, text=True, timeout=5)
707
+ res = subprocess.run([npm_bin, "list", "-g", "--depth=0", "tokensafe"], capture_output=True, text=True, timeout=15)
674
708
  if "tokensafe@" in res.stdout:
675
709
  print(f" {CYAN}→{RESET} Updating global npm package (npm install -g tokensafe@latest)...")
676
- up_res = subprocess.run(["npm", "install", "-g", "tokensafe@latest"], capture_output=True, text=True, timeout=30)
710
+ up_res = subprocess.run([npm_bin, "install", "-g", "tokensafe@latest"], capture_output=True, text=True, timeout=120)
677
711
  if up_res.returncode == 0:
678
712
  print(f" {GREEN}✔{RESET} npm package upgraded successfully.")
679
- except Exception:
680
- pass
713
+ else:
714
+ detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
715
+ print(f" {YELLOW}⚠{RESET} npm upgrade failed: {detail}")
716
+ else:
717
+ print(f" {CYAN}ℹ{RESET} tokensafe not installed via npm — skipping npm channel.")
718
+ except Exception as e:
719
+ print(f" {YELLOW}⚠{RESET} npm update skipped: {e}")
720
+ else:
721
+ print(f" {YELLOW}⚠{RESET} npm not found — skipping npm channel.")
681
722
 
682
723
  # 3. Check pip
683
724
  pip_cmd = "pip3" if shutil.which("pip3") else ("pip" if shutil.which("pip") else None)
684
725
  if pip_cmd:
685
726
  try:
686
- res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=5)
727
+ res = subprocess.run([pip_cmd, "list"], capture_output=True, text=True, timeout=15)
687
728
  if "tokensafe" in res.stdout:
688
729
  print(f" {CYAN}→{RESET} Updating Python package ({pip_cmd} install --upgrade tokensafe)...")
689
- up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=30)
730
+ up_res = subprocess.run([pip_cmd, "install", "--upgrade", "tokensafe"], capture_output=True, text=True, timeout=120)
690
731
  if up_res.returncode == 0:
691
732
  print(f" {GREEN}✔{RESET} Python package upgraded successfully.")
692
- except Exception:
693
- pass
733
+ else:
734
+ detail = (up_res.stderr or up_res.stdout or "").strip()[:200]
735
+ print(f" {YELLOW}⚠{RESET} pip upgrade failed: {detail}")
736
+ except Exception as e:
737
+ print(f" {YELLOW}⚠{RESET} pip update skipped: {e}")
694
738
 
695
739
  # 4. Re-synchronize all detected agents
696
740
  print(f"\n {CYAN}→{RESET} Re-synchronizing AI Agent MCP configs & rules...")
@@ -722,7 +766,8 @@ class AgentInstaller:
722
766
 
723
767
  print(f"\n{BOLD}{GREEN}✅ Self-update complete!{RESET}")
724
768
  print(f" Synchronized {synced_count} agent environments with zero-loss AST & God Nodes rules.")
725
- print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.\n")
769
+ print(f" Run {BOLD}tokensafe stats{RESET} to view token savings.")
770
+ print(f" {CYAN}ℹ{RESET} If your terminal still shows the old version, open a new window or run {BOLD}hash -r{RESET}.")
726
771
 
727
772
  def main():
728
773
  args = sys.argv[1:]
package/src/mcp_server.py CHANGED
@@ -28,6 +28,8 @@ from src.metrics import MetricsTracker
28
28
  from src.dashboard import Dashboard
29
29
  from src.graph_engine import GraphEngine
30
30
  from src.tokenizer import count_tokens
31
+ from src.history_compactor import HistoryCompactor
32
+ from src.team_cache import TeamCache
31
33
  from src.agent_firewall import AgentFirewall
32
34
  from src.diff_slicer import DiffSlicer
33
35
  from src.guard import TokenSafeGuard
@@ -35,7 +37,7 @@ from src.scoped_search import ScopedSearch
35
37
 
36
38
  SERVER_INFO = {
37
39
  "name": "tokensafe-mcp",
38
- "version": "1.5.0"
40
+ "version": "1.6.0"
39
41
  }
40
42
 
41
43
  TOOLS = [
@@ -85,6 +87,18 @@ TOOLS = [
85
87
  "required": ["prompt"]
86
88
  }
87
89
  },
90
+ {
91
+ "name": "compact_conversation",
92
+ "description": "On-demand context compaction: folds a long agent conversation transcript into a compact Consolidated State Ledger. Use when the context window feels heavy or before starting a new subtask inside the same session.",
93
+ "inputSchema": {
94
+ "type": "object",
95
+ "properties": {
96
+ "transcript_path": {"type": "string", "description": "Path to the JSONL transcript of the current session"},
97
+ "invocation_num": {"type": "integer", "description": "Optional: current turn number (default 3; folding requires >= 3 turns)"}
98
+ },
99
+ "required": ["transcript_path"]
100
+ }
101
+ },
88
102
  {
89
103
  "name": "sanitize_command",
90
104
  "description": "Rewrites shell commands (git diff, git log, pytest, grep) to prune lockfiles and unbounded logs.",
@@ -378,6 +392,42 @@ def _get_safe_tracker():
378
392
  return _NoOpTracker()
379
393
 
380
394
 
395
+ def _team_skeleton_lookup(path: str, symbol: str) -> Optional[str]:
396
+ """Team cache pre-warm lookup: returns a teammate's cached skeleton or None.
397
+
398
+ Never blocks the caller for more than ~250ms: the network fetch runs in a
399
+ daemon thread with a short join. Non-team installs skip the network entirely."""
400
+ try:
401
+ is_team, _ = TeamCache._is_team_tier()
402
+ if not is_team:
403
+ return None
404
+ box: dict = {}
405
+
406
+ def _fetch():
407
+ try:
408
+ box["value"] = TeamCache.get("SKELETON", f"{path}::{symbol or ''}")
409
+ except Exception:
410
+ pass
411
+
412
+ t = threading.Thread(target=_fetch, daemon=True)
413
+ t.start()
414
+ t.join(0.25)
415
+ return box.get("value")
416
+ except Exception:
417
+ return None
418
+
419
+
420
+ def _team_skeleton_prewarm(path: str, symbol: str, skeleton_text: str, tokens_saved: int):
421
+ """Publishes a freshly built skeleton to the team cache (async, team tier only).
422
+
423
+ Teammate B's later smart_read_file on the same symbol hits the cache instead
424
+ of re-reading and re-skeletonizing the file."""
425
+ try:
426
+ TeamCache.put("SKELETON", f"{path}::{symbol or ''}", skeleton_text, tokens_saved=tokens_saved)
427
+ except Exception:
428
+ pass
429
+
430
+
381
431
  def handle_tool_call(name: str, args: dict) -> dict:
382
432
  if args is None or not isinstance(args, dict):
383
433
  args = {}
@@ -454,6 +504,23 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
454
504
  return {"content": [{"type": "text", "text": (prefetch_block or "") + content}]}
455
505
 
456
506
  if symbol:
507
+ # Team pre-warm hit: a teammate already skeletonized this symbol
508
+ team_skel = _team_skeleton_lookup(path, symbol)
509
+ if team_skel:
510
+ with open(path, "r", encoding="utf-8", errors="replace") as f:
511
+ raw_code = f.read()
512
+ orig_t = count_tokens(raw_code)
513
+ skel_t = count_tokens(team_skel)
514
+ tracker.record_event(
515
+ session_id="mcp_session",
516
+ event_type="TEAM_CACHE_HIT",
517
+ original_tokens=orig_t,
518
+ optimized_tokens=skel_t,
519
+ details={"file": os.path.basename(path), "symbol": symbol, "source": "team_cache"}
520
+ )
521
+ header = f"// [TokenSafe Team-Cached Skeleton for '{symbol}' | shared by a teammate]\n"
522
+ return {"content": [{"type": "text", "text": (prefetch_block or "") + header + team_skel}]}
523
+
457
524
  try:
458
525
  graph, rel_path = GraphEngine.for_file(path)
459
526
  inc_deps = bool(args.get("include_deps", True))
@@ -473,6 +540,7 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
473
540
  )
474
541
  dep_label = "Full body + 1-hop dependencies" if inc_deps else "Surgical single-symbol isolation"
475
542
  header = f"// [TokenSafe Graph-Guided Skeleton for '{symbol}' | {dep_label}]\n"
543
+ _team_skeleton_prewarm(path, symbol, graph_skel, saved)
476
544
  return {"content": [{"type": "text", "text": (prefetch_block or "") + header + graph_skel}]}
477
545
  except Exception:
478
546
  pass
@@ -504,6 +572,38 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
504
572
  res = PromptCompactor.compact(prompt, enable_deepseek=True)
505
573
  return {"content": [{"type": "text", "text": json.dumps(res, indent=2, ensure_ascii=False)}]}
506
574
 
575
+ elif name == "compact_conversation":
576
+ transcript_path = args.get("transcript_path", "")
577
+ try:
578
+ invocation_num = max(3, int(args.get("invocation_num", 3) or 3))
579
+ except (TypeError, ValueError):
580
+ invocation_num = 3
581
+ if not transcript_path or not os.path.exists(transcript_path):
582
+ return {"isError": True, "content": [{"type": "text", "text": f"Transcript not found: {transcript_path}"}]}
583
+ ledger, orig_t, folded_t, stats = HistoryCompactor.fold_transcript(transcript_path, invocation_num)
584
+ if not ledger:
585
+ return {"content": [{"type": "text", "text": json.dumps({
586
+ "compactable": False,
587
+ "reason": "Transcript too short to fold (needs >= 4 steps and >= 1000 history tokens)"
588
+ }, indent=2)}]}
589
+ saved = max(0, orig_t - folded_t)
590
+ tracker.record_event(
591
+ session_id="mcp_session",
592
+ event_type="HISTORY_FOLD",
593
+ original_tokens=orig_t,
594
+ optimized_tokens=folded_t,
595
+ details={"mode": "manual_compact_conversation", "turns": invocation_num, **stats}
596
+ )
597
+ return {"content": [{"type": "text", "text": json.dumps({
598
+ "compactable": True,
599
+ "ledger": ledger,
600
+ "original_tokens": orig_t,
601
+ "folded_tokens": folded_t,
602
+ "saved_tokens": saved,
603
+ "note": "Inject this ledger as a system message and start fresh context from it; savings are labeled estimated (digest injected, history not removed).",
604
+ "stats": stats
605
+ }, indent=2, ensure_ascii=False)}]}
606
+
507
607
  elif name == "sanitize_command":
508
608
  cmd = args.get("command", "")
509
609
  # Step 1: TokenSafe Guard security inspection
@@ -173,7 +173,8 @@ class Skeletonizer:
173
173
  @classmethod
174
174
  def skeletonize_code(cls, code: str, file_ext: str, keep_symbols: Optional[Set[str]] = None) -> str:
175
175
  """Skeletons source code based on file extension, optionally preserving keep_symbols."""
176
- ext = file_ext.lower()
176
+ ext = file_ext.lower().lstrip(".")
177
+ ext = f".{ext}" if ext else ""
177
178
  if ext == ".py":
178
179
  return cls._skeletonize_python(code, keep_symbols=keep_symbols)
179
180
  elif ext in (
@@ -264,7 +264,7 @@ class TelemetrySync:
264
264
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
265
265
  headers = {
266
266
  "Content-Type": "application/json",
267
- "User-Agent": "TokenSafe-Sync/1.5.0"
267
+ "User-Agent": "TokenSafe-Sync/1.6.0"
268
268
  }
269
269
  if active_key:
270
270
  headers["Authorization"] = f"Bearer {active_key}"
@@ -16,7 +16,7 @@ import urllib.request
16
16
  import urllib.error
17
17
  from typing import Dict, Any, Optional, Tuple
18
18
 
19
- CURRENT_VERSION = "1.5.0"
19
+ CURRENT_VERSION = "1.6.0"
20
20
  CACHE_TTL = 86400 # 24 hours
21
21
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
22
22
  # answer for a full day — otherwise an update released right after an outage