tokensafe 3.1.5 → 4.0.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.
Files changed (44) hide show
  1. package/README.md +79 -58
  2. package/bin/tokensafe.js +25 -9
  3. package/hooks/claude_code_hook.py +7 -0
  4. package/hooks/pre_tool_use.py +24 -0
  5. package/hooks/session_start.py +8 -0
  6. package/package.json +3 -3
  7. package/plugin.json +1 -1
  8. package/rules/AGENTS.md +13 -7
  9. package/server.json +3 -3
  10. package/skills/token-optimizer/SKILL.md +7 -2
  11. package/skills/token-optimizer/references/cli-reference.md +11 -1
  12. package/skills/token-optimizer/references/mcp-tools.md +44 -2
  13. package/src/bench_scenarios.json +376 -0
  14. package/src/cache_normalizer.py +21 -0
  15. package/src/cli.py +425 -4
  16. package/src/command_sanitizer.py +2 -0
  17. package/src/compactor.py +1 -1
  18. package/src/competitors.py +179 -0
  19. package/src/environment_auditor.py +110 -1
  20. package/src/format_parsers/__init__.py +20 -0
  21. package/src/format_parsers/ansi.py +41 -0
  22. package/src/format_parsers/compiler_errors.py +159 -0
  23. package/src/format_parsers/docker_k8s.py +95 -0
  24. package/src/format_parsers/json_log.py +89 -0
  25. package/src/format_parsers/lockfiles.py +157 -0
  26. package/src/format_parsers/tabular.py +175 -0
  27. package/src/fts_index.py +296 -0
  28. package/src/graph_engine.py +395 -48
  29. package/src/image_downscale.py +228 -0
  30. package/src/installer.py +47 -1
  31. package/src/license_manager.py +103 -7
  32. package/src/loop_detector.py +5 -0
  33. package/src/mcp_config_manager.py +197 -0
  34. package/src/mcp_proxy.py +154 -0
  35. package/src/mcp_server.py +215 -1
  36. package/src/mistakes.py +203 -0
  37. package/src/result_ledger.py +8 -1
  38. package/src/scoped_search.py +32 -0
  39. package/src/stash.py +199 -0
  40. package/src/superseded.py +220 -0
  41. package/src/telemetry_sync.py +14 -1
  42. package/src/test_parsers.py +271 -0
  43. package/src/version_checker.py +1 -1
  44. package/src/web_reader.py +202 -0
package/src/stash.py ADDED
@@ -0,0 +1,199 @@
1
+ """
2
+ TokenSafe Reversible Hash Stash (v3.3.0).
3
+
4
+ Stores raw tool, command, MCP, and file content folded or truncated by TokenSafe.
5
+ Each folded block is tagged with an 8-character deterministic hex hash:
6
+ [TokenSafe folded: #a1b2c3d4 (184 lines omitted) — call tokensafe:expand_ref('a1b2c3d4') to restore raw content]
7
+
8
+ Any agent or developer can immediately restore the exact original bytes via:
9
+ - MCP Tool: tokensafe:expand_ref(hash="a1b2c3d4")
10
+ - CLI: tokensafe expand-ref a1b2c3d4
11
+ """
12
+
13
+ import os
14
+ import re
15
+ import json
16
+ import time
17
+ import hashlib
18
+ from typing import Tuple, Optional, Dict, Any
19
+
20
+ from src.paths import resolve_data_dir
21
+
22
+ STASH_DIRNAME = "stash"
23
+ MAX_STASH_CHARS = 5 * 1024 * 1024 # Cap single artifact at 5 MB
24
+ DEFAULT_MAX_AGE_DAYS = 7
25
+ DEFAULT_MAX_TOTAL_MB = 50
26
+ _HASH_PATTERN = re.compile(r"#?([0-9a-fA-F]{8})\b")
27
+ _LAST_CLEANUP_TS = 0.0
28
+
29
+
30
+ def get_stash_dir() -> str:
31
+ """Returns absolute path to the active stash directory."""
32
+ d = os.path.join(resolve_data_dir(), STASH_DIRNAME)
33
+ os.makedirs(d, exist_ok=True)
34
+ return d
35
+
36
+
37
+ def compute_hash(text: str) -> Tuple[str, str]:
38
+ """Returns (hash8, sha256) for content."""
39
+ sha = hashlib.sha256(text.encode("utf-8", errors="replace")).hexdigest()
40
+ return sha[:8], sha
41
+
42
+
43
+ def stash_block(content: str, source: str = "tool") -> Tuple[str, str]:
44
+ """
45
+ Saves raw content to the local stash directory and returns (hash8, fold_marker).
46
+ """
47
+ global _LAST_CLEANUP_TS
48
+ if not content:
49
+ return "", ""
50
+
51
+ hash8, full_sha = compute_hash(content)
52
+ lines_count = len(content.splitlines())
53
+ chars_count = len(content)
54
+
55
+ marker = (
56
+ f"[TokenSafe folded: #{hash8} ({lines_count} lines / {chars_count} chars omitted) "
57
+ f"— call tokensafe:expand_ref('{hash8}') to restore raw content]"
58
+ )
59
+
60
+ if chars_count > MAX_STASH_CHARS:
61
+ # Don't exhaust local disk on massive blobs > 5MB
62
+ return hash8, marker
63
+
64
+ try:
65
+ stash_dir = get_stash_dir()
66
+ path = os.path.join(stash_dir, f"{hash8}.json")
67
+ if not os.path.exists(path):
68
+ payload = {
69
+ "hash": hash8,
70
+ "sha256": full_sha,
71
+ "timestamp": int(time.time()),
72
+ "source": source,
73
+ "lines": lines_count,
74
+ "chars": chars_count,
75
+ "content": content,
76
+ }
77
+ tmp_path = f"{path}.tmp.{os.getpid()}"
78
+ with open(tmp_path, "w", encoding="utf-8") as f:
79
+ json.dump(payload, f, ensure_ascii=False)
80
+ os.replace(tmp_path, path)
81
+
82
+ # Trigger passive cleanup once per hour
83
+ now = time.time()
84
+ if now - _LAST_CLEANUP_TS > 3600.0:
85
+ _LAST_CLEANUP_TS = now
86
+ cleanup_old_stashes()
87
+ except Exception:
88
+ pass
89
+
90
+ return hash8, marker
91
+
92
+
93
+ def retrieve_block(hash_or_marker: str) -> Optional[str]:
94
+ """
95
+ Retrieves full raw content by 8-character hex hash or by a fold marker string.
96
+ Returns None if not found or corrupted.
97
+ """
98
+ if not hash_or_marker:
99
+ return None
100
+
101
+ clean_str = str(hash_or_marker).strip()
102
+ match = _HASH_PATTERN.search(clean_str)
103
+ if not match:
104
+ return None
105
+
106
+ hash8 = match.group(1).lower()
107
+ stash_dir = get_stash_dir()
108
+ path = os.path.join(stash_dir, f"{hash8}.json")
109
+
110
+ if os.path.isfile(path):
111
+ try:
112
+ with open(path, "r", encoding="utf-8") as f:
113
+ data = json.load(f)
114
+ if isinstance(data, dict) and "content" in data:
115
+ return data["content"]
116
+ except Exception:
117
+ pass
118
+
119
+ # Fallback to tool_ledger (legacy 16-char ledger files)
120
+ try:
121
+ ledger_dir = os.path.join(resolve_data_dir(), "tool_ledger")
122
+ if os.path.isdir(ledger_dir):
123
+ for fname in os.listdir(ledger_dir):
124
+ if fname.startswith(hash8) and fname.endswith(".json"):
125
+ with open(os.path.join(ledger_dir, fname), "r", encoding="utf-8") as f:
126
+ data = json.load(f)
127
+ if isinstance(data, dict) and "content" in data:
128
+ return data["content"]
129
+ except Exception:
130
+ pass
131
+
132
+ return None
133
+
134
+
135
+ # Alias for expand_ref
136
+ expand_ref = retrieve_block
137
+
138
+
139
+ def cleanup_old_stashes(
140
+ max_age_days: int = DEFAULT_MAX_AGE_DAYS,
141
+ max_total_mb: int = DEFAULT_MAX_TOTAL_MB,
142
+ ) -> int:
143
+ """
144
+ Prunes files older than max_age_days or when total stash size exceeds max_total_mb.
145
+ Returns number of pruned files.
146
+ """
147
+ pruned = 0
148
+ try:
149
+ stash_dir = get_stash_dir()
150
+ if not os.path.isdir(stash_dir):
151
+ return 0
152
+
153
+ now = time.time()
154
+ max_age_seconds = max_age_days * 86400
155
+ entries = []
156
+ total_size = 0
157
+
158
+ for fname in os.listdir(stash_dir):
159
+ if not fname.endswith(".json"):
160
+ continue
161
+ fpath = os.path.join(stash_dir, fname)
162
+ try:
163
+ st = os.stat(fpath)
164
+ entries.append((fpath, st.st_mtime, st.st_size))
165
+ total_size += st.st_size
166
+ except OSError:
167
+ continue
168
+
169
+ # 1. Prune by age
170
+ remaining = []
171
+ for fpath, mtime, size in entries:
172
+ if (now - mtime) > max_age_seconds:
173
+ try:
174
+ os.remove(fpath)
175
+ pruned += 1
176
+ total_size -= size
177
+ except OSError:
178
+ remaining.append((fpath, mtime, size))
179
+ else:
180
+ remaining.append((fpath, mtime, size))
181
+
182
+ # 2. Prune by total size if still over limit
183
+ max_bytes = max_total_mb * 1024 * 1024
184
+ if total_size > max_bytes:
185
+ # Sort by mtime ascending (oldest first)
186
+ remaining.sort(key=lambda x: x[1])
187
+ for fpath, _, size in remaining:
188
+ if total_size <= (max_bytes * 0.8):
189
+ break
190
+ try:
191
+ os.remove(fpath)
192
+ pruned += 1
193
+ total_size -= size
194
+ except OSError:
195
+ pass
196
+ except Exception:
197
+ pass
198
+
199
+ return pruned
@@ -0,0 +1,220 @@
1
+ """
2
+ TokenSafe Superseded Tool Output Pruning (v3.3.0).
3
+
4
+ Identifies intermediate file read results in multi-turn transcripts that have
5
+ since been modified by subsequent edits or re-read in subsequent steps.
6
+ Replaces obsolete intermediate payloads with a 1-line reversible tombstone
7
+ pointing to TokenSafe's local stash, recovering 30-50% context window mass.
8
+ """
9
+
10
+ import os
11
+ import json
12
+ from typing import List, Dict, Any, Tuple, Optional, Set
13
+ from src.stash import stash_block
14
+ from src.tokenizer import count_tokens
15
+
16
+ _READ_TOOLS = {
17
+ "read_file", "view_file", "Read", "smart_read_file",
18
+ }
19
+ _EDIT_TOOLS = {
20
+ "edit_file", "write_file", "Edit", "Write", "MultiEdit", "NotebookEdit", "replace_file_content"
21
+ }
22
+ _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "notebook_path")
23
+
24
+
25
+ def _extract_path_from_args(args: Any) -> Optional[str]:
26
+ if not isinstance(args, dict):
27
+ return None
28
+ for k in _PATH_KEYS:
29
+ val = args.get(k)
30
+ if isinstance(val, str) and val.strip():
31
+ return os.path.abspath(val.strip())
32
+ return None
33
+
34
+
35
+ class SupersededPruner:
36
+ """Detects and prunes outdated tool outputs in agent conversations."""
37
+
38
+ @classmethod
39
+ def prune_steps(cls, steps: List[dict]) -> Tuple[List[dict], int, int, Dict[str, Any]]:
40
+ """
41
+ Analyzes sequential conversation steps, identifies reads that were superseded
42
+ by subsequent edits or reads of the same file, and replaces them with a stash tombstone.
43
+
44
+ Returns: (pruned_steps, orig_tokens, pruned_tokens, stats)
45
+ """
46
+ if not steps or len(steps) < 3:
47
+ return steps, 0, 0, {"pruned_count": 0, "saved_tokens": 0}
48
+
49
+ # Track file actions: map file_path -> list of (step_index, action_type, call_dict)
50
+ # action_type: "READ" or "EDIT"
51
+ file_actions: Dict[str, List[Tuple[int, str]]] = {}
52
+ step_read_files: Dict[int, str] = {}
53
+
54
+ for idx, step in enumerate(steps):
55
+ if not isinstance(step, dict):
56
+ continue
57
+
58
+ # Antigravity format: tool_calls
59
+ tool_calls = step.get("tool_calls")
60
+ if isinstance(tool_calls, list):
61
+ for tc in tool_calls:
62
+ if not isinstance(tc, dict):
63
+ continue
64
+ tname = tc.get("name", "")
65
+ args = tc.get("args")
66
+ fpath = _extract_path_from_args(args)
67
+ if not fpath:
68
+ continue
69
+ if tname in _READ_TOOLS:
70
+ file_actions.setdefault(fpath, []).append((idx, "READ"))
71
+ step_read_files[idx] = fpath
72
+ elif tname in _EDIT_TOOLS:
73
+ file_actions.setdefault(fpath, []).append((idx, "EDIT"))
74
+
75
+ # Claude Code format: message.content blocks
76
+ msg = step.get("message")
77
+ if isinstance(msg, dict):
78
+ content = msg.get("content")
79
+ if isinstance(content, list):
80
+ for b in content:
81
+ if isinstance(b, dict) and b.get("type") == "tool_use":
82
+ tname = b.get("name", "")
83
+ inp = b.get("input")
84
+ fpath = _extract_path_from_args(inp)
85
+ if not fpath:
86
+ continue
87
+ if tname in _READ_TOOLS:
88
+ file_actions.setdefault(fpath, []).append((idx, "READ"))
89
+ step_read_files[idx] = fpath
90
+ elif tname in _EDIT_TOOLS:
91
+ file_actions.setdefault(fpath, []).append((idx, "EDIT"))
92
+
93
+ # Identify superseded read step indices:
94
+ # A read at step i is superseded if there is an EDIT at step j > i,
95
+ # OR another READ at step k > i of the same file.
96
+ superseded_map: Dict[int, Tuple[int, str, str]] = {} # step_idx -> (superseded_by_step, action, fpath)
97
+
98
+ for fpath, actions in file_actions.items():
99
+ for i, (step_idx, action) in enumerate(actions):
100
+ if action == "READ":
101
+ # Check if there is any subsequent action on this file
102
+ subsequent = actions[i + 1:]
103
+ if subsequent:
104
+ next_step_idx, next_action = subsequent[0]
105
+ superseded_map[step_idx] = (next_step_idx, next_action, fpath)
106
+
107
+ if not superseded_map:
108
+ return steps, 0, 0, {"pruned_count": 0, "saved_tokens": 0}
109
+
110
+ # Apply tombstoning to the tool results of the superseded steps
111
+ pruned_steps: List[dict] = []
112
+ orig_tokens_total = 0
113
+ pruned_tokens_total = 0
114
+ pruned_count = 0
115
+
116
+ for idx, step in enumerate(steps):
117
+ if idx not in superseded_map:
118
+ pruned_steps.append(step)
119
+ continue
120
+
121
+ by_step, by_action, fpath = superseded_map[idx]
122
+ fname = os.path.basename(fpath)
123
+ new_step = json.loads(json.dumps(step)) # deep copy
124
+ modified = False
125
+
126
+ # Check Antigravity output/content in this step or subsequent tool response step
127
+ content = new_step.get("content")
128
+ if isinstance(content, str) and len(content) > 150:
129
+ orig_t = count_tokens(content)
130
+ _, marker = stash_block(content, source="superseded_read")
131
+ tombstone = (
132
+ f"[TokenSafe: Output superseded by step #{by_step + 1} ({by_action.lower()} {fname}) — {marker}]"
133
+ )
134
+ new_step["content"] = tombstone
135
+ pruned_t = count_tokens(tombstone)
136
+ orig_tokens_total += orig_t
137
+ pruned_tokens_total += pruned_t
138
+ modified = True
139
+
140
+ # Claude Code message content tool_result blocks
141
+ msg = new_step.get("message")
142
+ if isinstance(msg, dict):
143
+ mc = msg.get("content")
144
+ if isinstance(mc, list):
145
+ for block in mc:
146
+ if isinstance(block, dict) and block.get("type") == "tool_result":
147
+ tc = block.get("content")
148
+ if isinstance(tc, str) and len(tc) > 150:
149
+ orig_t = count_tokens(tc)
150
+ _, marker = stash_block(tc, source="superseded_read")
151
+ tombstone = (
152
+ f"[TokenSafe: Output superseded by step #{by_step + 1} ({by_action.lower()} {fname}) — {marker}]"
153
+ )
154
+ block["content"] = tombstone
155
+ pruned_t = count_tokens(tombstone)
156
+ orig_tokens_total += orig_t
157
+ pruned_tokens_total += pruned_t
158
+ modified = True
159
+
160
+ if modified:
161
+ pruned_count += 1
162
+ pruned_steps.append(new_step)
163
+
164
+ saved_tokens = max(0, orig_tokens_total - pruned_tokens_total)
165
+ stats = {
166
+ "pruned_count": pruned_count,
167
+ "saved_tokens": saved_tokens,
168
+ "orig_tokens": orig_tokens_total,
169
+ "pruned_tokens": pruned_tokens_total
170
+ }
171
+ return pruned_steps, orig_tokens_total, pruned_tokens_total, stats
172
+
173
+ @classmethod
174
+ def prune_transcript(
175
+ cls,
176
+ transcript_path: str,
177
+ output_path: Optional[str] = None
178
+ ) -> Dict[str, Any]:
179
+ """
180
+ Loads a JSONL transcript, prunes superseded reads, and saves the result.
181
+ If output_path is omitted or identical to transcript_path, overwrites safely.
182
+ """
183
+ if not os.path.exists(transcript_path):
184
+ return {"success": False, "error": f"Transcript not found: {transcript_path}"}
185
+
186
+ steps = []
187
+ try:
188
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
189
+ for line in f:
190
+ line = line.strip()
191
+ if line:
192
+ try:
193
+ steps.append(json.loads(line))
194
+ except Exception:
195
+ pass
196
+ except Exception as e:
197
+ return {"success": False, "error": str(e)}
198
+
199
+ pruned_steps, orig_t, pruned_t, stats = cls.prune_steps(steps)
200
+ if stats["pruned_count"] > 0:
201
+ target = output_path or transcript_path
202
+ tmp_target = f"{target}.tmp.{os.getpid()}"
203
+ try:
204
+ with open(tmp_target, "w", encoding="utf-8") as f:
205
+ for s in pruned_steps:
206
+ f.write(json.dumps(s, ensure_ascii=False) + "\n")
207
+ os.replace(tmp_target, target)
208
+ except Exception as e:
209
+ try:
210
+ if os.path.exists(tmp_target):
211
+ os.unlink(tmp_target)
212
+ except OSError:
213
+ pass
214
+ return {"success": False, "error": f"Failed to save pruned transcript: {e}"}
215
+
216
+ return {
217
+ "success": True,
218
+ "transcript_path": transcript_path,
219
+ **stats
220
+ }
@@ -186,6 +186,19 @@ class TelemetrySync:
186
186
  target_url = f"{base_url}/api/telemetry/sync"
187
187
  active_key = license_key or LicenseManager.get_active_license_key()
188
188
 
189
+ # Silent license renewal: if device has a device_token and license expires in < 7 days (or expired), refresh
190
+ try:
191
+ dev_tok = LicenseManager.get_device_token()
192
+ if dev_tok:
193
+ _, active_lic = LicenseManager.get_active_license()
194
+ exp_ts = int(active_lic.get("expires_at") or 0)
195
+ if not active_key or (exp_ts and (exp_ts - time.time()) < 7 * 86400):
196
+ refreshed, _ = LicenseManager.refresh_device_license()
197
+ if refreshed:
198
+ active_key = LicenseManager.get_active_license_key()
199
+ except Exception:
200
+ pass
201
+
189
202
  target_email = (email or "").strip().lower()
190
203
  if active_key and not active_key.startswith("ts_live_"):
191
204
  is_valid, payload, _ = LicenseManager.validate_license(active_key)
@@ -228,7 +241,7 @@ class TelemetrySync:
228
241
  current_last_id = last_id
229
242
  headers = {
230
243
  "Content-Type": "application/json",
231
- "User-Agent": "TokenSafe-Sync/3.1.5"
244
+ "User-Agent": "TokenSafe-Sync/4.0.0"
232
245
  }
233
246
  if active_key:
234
247
  headers["Authorization"] = f"Bearer {active_key}"