tokensafe 2.4.0 → 2.4.2

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.
@@ -35,6 +35,11 @@ def handle(event: str, payload: dict) -> dict:
35
35
  # hook): persistent directives instead of per-turn re-injection.
36
36
  # No matcher on `source` — inject for startup/resume/clear/compact.
37
37
  # Well under the 10k-char additionalContext cap.
38
+ try:
39
+ from src.version_checker import VersionChecker
40
+ VersionChecker.notify_os_update_background()
41
+ except Exception:
42
+ pass
38
43
  return {
39
44
  "hookSpecificOutput": {
40
45
  "hookEventName": "SessionStart",
@@ -44,16 +49,63 @@ def handle(event: str, payload: dict) -> dict:
44
49
 
45
50
  if event == "UserPromptSubmit":
46
51
  prompt = str(payload.get("prompt") or "")
52
+ parts = []
47
53
  context, meta = compact_for_injection(prompt, AGENT, session_id)
48
54
  if context and meta.get("compacted"):
55
+ parts.append(
56
+ f"{context}\n"
57
+ f"(TokenSafe: compacted ~{meta['saved_tokens']} prompt tokens, "
58
+ f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
59
+ )
60
+
61
+ # History auto-fold (parity with the Antigravity PreInvocation hook):
62
+ # Claude Code ships transcript_path in every hook payload. Once the
63
+ # transcript holds enough turns, past turns are folded into a State
64
+ # Ledger and injected; savings are recorded incrementally to avoid
65
+ # double-counting the same history mass on every submit.
66
+ transcript_path = str(payload.get("transcript_path") or "")
67
+ if transcript_path:
68
+ try:
69
+ from src.history_compactor import HistoryCompactor
70
+ from src.metrics import MetricsTracker
71
+ turn = 0
72
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as tf:
73
+ turn = sum(1 for ln in tf if ln.strip())
74
+ if turn >= 3:
75
+ folded, orig_hist, folded_tok, stats = HistoryCompactor.fold_transcript(
76
+ transcript_path, turn
77
+ )
78
+ if folded and stats.get("saved_tokens", 0) > 0:
79
+ tracker = MetricsTracker()
80
+ prev_event = tracker.get_last_event(session_id, "HISTORY_FOLD")
81
+ prev_orig = 0
82
+ if prev_event and isinstance(prev_event.get("details"), dict):
83
+ prev_orig = prev_event["details"].get("total_accum_orig", 0) or prev_event.get("original_tokens", 0)
84
+ delta_orig = max(0, orig_hist - prev_orig)
85
+ if prev_event is None or delta_orig >= 1500:
86
+ inc_orig = orig_hist if prev_event is None else delta_orig
87
+ inc_saved = max(0, inc_orig - folded_tok)
88
+ tracker.record_event(
89
+ session_id=session_id,
90
+ event_type="HISTORY_FOLD",
91
+ original_tokens=inc_orig,
92
+ optimized_tokens=folded_tok,
93
+ details={"turns": turn, "total_accum_orig": orig_hist, "agent": AGENT},
94
+ )
95
+ parts.append(
96
+ f"{folded}\n"
97
+ f"(TokenSafe History Compactor: stabilized {orig_hist:,} tokens "
98
+ f"of previous turns — saved {stats['saved_tokens']:,}. "
99
+ f"Estimated per METRICS.md.)"
100
+ )
101
+ except Exception:
102
+ pass
103
+
104
+ if parts:
49
105
  return {
50
106
  "hookSpecificOutput": {
51
107
  "hookEventName": "UserPromptSubmit",
52
- "additionalContext": (
53
- f"{context}\n"
54
- f"(TokenSafe: compacted ~{meta['saved_tokens']} prompt tokens, "
55
- f"-{meta.get('reduction_pct', 0)}% — original intent preserved.)"
56
- ),
108
+ "additionalContext": "\n\n".join(parts),
57
109
  }
58
110
  }
59
111
  return {}
@@ -25,6 +25,7 @@ from src.history_compactor import HistoryCompactor
25
25
  from src.metrics import MetricsTracker
26
26
  from src.governor import ContextBudget
27
27
  from src.license_manager import LicenseManager
28
+ from src.adapter_core import TOKENSAFE_DIRECTIVES as PROTOCOL_DIRECTIVES
28
29
  from src.paths import resolve_data_dir
29
30
 
30
31
  def _model_name(payload: dict) -> str:
@@ -175,46 +176,57 @@ def main():
175
176
  }
176
177
  })
177
178
 
179
+ # 3b. Real history mass for the Context Budget HUD: the fold already
180
+ # measured it when active; on early turns probe the transcript lightly
181
+ # so the estimate reflects the history that genuinely sits in context.
182
+ history_mass = 0
183
+ if folded_text is not None:
184
+ history_mass = orig_hist_tokens
185
+ elif transcript_path:
186
+ try:
187
+ history_mass = HistoryCompactor.measure_transcript(transcript_path)
188
+ except Exception:
189
+ history_mass = 0
190
+
178
191
  # 4. Adaptive Protocol Enforcement Reminder (Guard-triggered only).
179
192
  # Full directives are injected once per session by session_start.py as a
180
193
  # persistent systemMessage; here they are re-shown only when the guard
181
194
  # just fired or fresh history was folded.
182
195
  recent_guard = tracker.get_last_event(conversation_id, "GUARD_RAW_CODE_SEARCH")
183
196
  if folded_text is not None or recent_guard is not None:
184
- protocol_reminder = (
185
- "[TokenSafe Mandatory Directives]:\n"
186
- "• Terminal code searches (grep/rg/find on source files) are BLOCKED by TokenSafe Guard.\n"
187
- "• To search keywords, symbols, or configs: call 'tokensafe:scoped_search(query, scope)'.\n"
188
- "• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)'.\n"
189
- "• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
190
- "• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
191
- "• Prefer 'edit_file' over 'write_file' for existing files."
192
- )
193
197
  # systemMessage nested form (hooks.md contract): ephemeralMessage is
194
198
  # deprecated and is converted to a hidden system message anyway. This
195
199
  # reminder only fires on guard violations / fresh history folds, so
196
200
  # persistence here is intentional reinforcement, not per-turn bloat.
197
201
  inject_steps.append({
198
202
  "systemMessage": {
199
- "systemMessage": protocol_reminder,
203
+ "systemMessage": PROTOCOL_DIRECTIVES,
200
204
  "metadata": {}
201
205
  }
202
206
  })
203
207
 
204
208
  # 5. Context Budget HUD warning: inject once per session when the
205
- # instrumented context crosses 80% of the estimated window.
209
+ # context crosses 80% of the estimated window. history_mass upgrades
210
+ # the instrumented floor to a semi-real estimate, so the threshold is
211
+ # actually reachable; the warning carries a ready-to-run compact command.
206
212
  try:
207
213
  budget = ContextBudget.estimate(
208
214
  tracker, session_id=conversation_id,
209
- model=_model_name(payload)
215
+ model=_model_name(payload),
216
+ history_tokens=history_mass,
217
+ transcript_path=transcript_path
210
218
  )
211
219
  if budget["used_pct"] >= 80 and budget["instrumented_events"] >= 3:
212
220
  already = tracker.get_last_event(conversation_id, "BUDGET_WARNING")
213
221
  if not already:
222
+ if transcript_path:
223
+ action = (f"Call tokensafe:compact_conversation(transcript_path='{transcript_path}') "
224
+ f"now to fold past turns before continuing.")
225
+ else:
226
+ action = budget["recommendation"]
214
227
  warn = (
215
228
  f"🧠 **Context Budget:** ~{budget['used_pct']}% of the estimated window used "
216
- f"({budget['used_estimated']:,}/{budget['window_tokens']:,} tokens, instrumented floor). "
217
- f"{budget['recommendation']}"
229
+ f"({budget['used_estimated']:,}/{budget['window_tokens']:,} tokens). {action}"
218
230
  )
219
231
  inject_steps.append({
220
232
  "systemMessage": {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "mcpName": "dev.tokensafe/tokensafe",
4
- "version": "2.4.0",
4
+ "version": "2.4.2",
5
5
  "description": "Local-first AI coding guardrails, context slicing, and team ROI telemetry for AI coding agents",
6
6
  "main": "bin/tokensafe.js",
7
7
  "bin": {
package/plugin.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "tokensafe",
3
3
  "displayName": "TokenSafe",
4
- "version": "2.4.0",
5
- "description": "Zero-Loss Token Economy & Context Optimizer for AI Agents. Compresses prompts, slices AST/tool outputs, and prevents stuck loops.",
4
+ "version": "2.4.2",
5
+ "description": "Local-first guardrails, focused context & auditable team ROI for AI coding agents. Agents read only the code they need, secrets get blocked before commit.",
6
6
  "logo": "assets/logo.svg",
7
7
  "author": {
8
8
  "name": "Oleg Savelev",
package/rules/AGENTS.md CHANGED
@@ -33,6 +33,7 @@ Execute the specified action directly based on these extracted parameters.
33
33
  5. **Bounded Reads**: Never call `read_file` without `StartLine`/`EndLine` on files > 100 lines unless inspecting a skeleton.
34
34
  6. **Directory Navigation**: Never run verbose `ls -la` or `ls -l`; use `tokensafe:list_dir(path, depth=2)` to inspect directory trees without permissions, timestamps, or lockfiles (-90% tokens).
35
35
  7. **Style & Design Tokens**: When inspecting CSS/SCSS/LESS/Tailwind, `tokensafe:smart_read_file` automatically preserves all design tokens (`:root`, `@theme`, CSS variables) in full while folding component selectors.
36
+ 8. **Context Budget & Smart Compaction**: Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check window usage (tools/history/prompts breakdown, 50/80/95% thresholds). When it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a State Ledger instead of letting code quality degrade.
36
37
 
37
38
  ### 4. Turn Token Savings Footer (Proof-of-Savings — always in English)
38
39
  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:
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": "2.4.0",
6
+ "version": "2.4.2",
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.4.0",
33
+ "version": "2.4.2",
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.4.0",
49
+ "version": "2.4.2",
50
50
  "runtimeHint": "uvx",
51
51
  "transport": {
52
52
  "type": "stdio"
@@ -40,6 +40,10 @@ folds multi-turn conversation history, slices verbose tool outputs, and guards a
40
40
  6. **SECRET LEAK PREVENTION (ZERO HARDCODED FALLBACKS)**:
41
41
  - Never provide real private keys, API secrets, or credentials as fallback values in `os.environ.get()` or `process.env`. Real credentials must exist strictly in environment variables.
42
42
 
43
+ 7. **CONTEXT BUDGET BEFORE HEAVY WORK (`context_budget` → `compact_conversation`)**:
44
+ - Before large multi-step tasks, call `tokensafe:context_budget(model=...)` to check the window budget (tools/history/prompts breakdown, 50/80/95% thresholds).
45
+ - When it reports `warning` or `critical`, call `tokensafe:compact_conversation(transcript_path=...)` to fold past turns into a State Ledger before continuing — do not let context exhaustion degrade code quality mid-task.
46
+
43
47
  ---
44
48
 
45
49
  ## Core MCP Tools (`tokensafe`)
@@ -99,3 +99,27 @@ All tools are exposed via Model Context Protocol (stdio JSON-RPC 2.0).
99
99
  }
100
100
  ```
101
101
  *Validates commands and code snippets before execution; returns structured pass/block verdict with check_name.*
102
+
103
+ ### 5. Context Budget → Smart Compact Workflow
104
+ ```json
105
+ {
106
+ "ServerName": "tokensafe",
107
+ "ToolName": "context_budget",
108
+ "Arguments": {
109
+ "model": "claude-x"
110
+ }
111
+ }
112
+ ```
113
+ *Run before large multi-step tasks. When the response reports `threshold: "warning"` or `"critical"`, immediately chain the compact call:*
114
+
115
+ ```json
116
+ {
117
+ "ServerName": "tokensafe",
118
+ "ToolName": "compact_conversation",
119
+ "Arguments": {
120
+ "transcript_path": "/Users/.../.claude/projects/<session>/transcript.jsonl",
121
+ "invocation_num": 12
122
+ }
123
+ }
124
+ ```
125
+ *Folds past turns into a Consolidated State Ledger (-80% to -95% history tokens) so long sessions never degrade into context starvation. The transcript path is provided by the host session (hook payload `transcript_path` / session start context).*
@@ -32,6 +32,8 @@ TOKENSAFE_DIRECTIVES = (
32
32
  "• To inspect component or function definitions: call 'tokensafe:smart_read_file(path, symbol)'.\n"
33
33
  "• To locate dependencies & God Nodes: call 'tokensafe:get_architecture_graph(project_path)'.\n"
34
34
  "• To inspect all exported types/interfaces: call 'tokensafe:get_api_surface(project_path)'.\n"
35
+ "• Before large multi-step tasks: call 'tokensafe:context_budget(model=...)' to check the context window budget.\n"
36
+ "• When context_budget reports warning/critical: call 'tokensafe:compact_conversation(transcript_path=...)' to fold history before continuing.\n"
35
37
  "• Prefer 'edit_file' over 'write_file' for existing files."
36
38
  )
37
39
 
package/src/cli.py CHANGED
@@ -123,6 +123,15 @@ def main():
123
123
  except Exception:
124
124
  pass
125
125
  print(dashboard.render_terminal())
126
+ # Update banner in the most-reliable visibility channel: the stats
127
+ # output itself. Best-effort — never break the dashboard render.
128
+ try:
129
+ from src.version_checker import VersionChecker
130
+ banner = VersionChecker.get_banner()
131
+ if banner:
132
+ print(banner)
133
+ except Exception:
134
+ pass
126
135
 
127
136
  elif command in ("html", "web"):
128
137
  from src.paths import resolve_data_dir
package/src/governor.py CHANGED
@@ -214,7 +214,16 @@ class ContextBudget:
214
214
 
215
215
  @classmethod
216
216
  def estimate(cls, tracker: MetricsTracker, session_id: str = "mcp_session",
217
- model: str = "", window_tokens: Optional[int] = None) -> Dict[str, Any]:
217
+ model: str = "", window_tokens: Optional[int] = None,
218
+ history_tokens: int = 0, transcript_path: str = "") -> Dict[str, Any]:
219
+ """Estimate context-window usage for the session.
220
+
221
+ history_tokens / transcript_path upgrade the HUD from a pure
222
+ instrumented floor to a semi-real estimate: the REAL mass of past
223
+ conversation turns (measured from the transcript by the caller via
224
+ HistoryCompactor) is counted into the history bucket. Callers that
225
+ only know the transcript path can pass transcript_path instead; the
226
+ transcript is probed with HistoryCompactor.measure_transcript."""
218
227
  window = cls.resolve_window(model, window_tokens)
219
228
  breakdown = {"tools": 0, "history": 0, "prompts": 0, "other": 0}
220
229
  instrumented_events = 0
@@ -234,6 +243,19 @@ class ContextBudget:
234
243
  except Exception:
235
244
  pass
236
245
 
246
+ # Real history mass (estimated label per METRICS.md): the transcript
247
+ # content genuinely sits in the model context even though no TokenSafe
248
+ # instrument metered it.
249
+ transcript_mass = int(history_tokens or 0)
250
+ if transcript_mass <= 0 and transcript_path:
251
+ try:
252
+ from src.history_compactor import HistoryCompactor
253
+ transcript_mass = HistoryCompactor.measure_transcript(transcript_path)
254
+ except Exception:
255
+ transcript_mass = 0
256
+ if transcript_mass > breakdown["history"]:
257
+ breakdown["history"] = transcript_mass
258
+
237
259
  used = sum(breakdown.values())
238
260
  pct = round(used / window * 100.0, 1) if window > 0 else 0.0
239
261
  if pct >= 95:
@@ -250,6 +272,14 @@ class ContextBudget:
250
272
  else:
251
273
  threshold, recommendation = "healthy", "Context budget healthy."
252
274
 
275
+ if transcript_mass > 0:
276
+ caveat = ("Semi-real estimate: history mass is measured from the session "
277
+ "transcript; agent reasoning and output tokens stay invisible to "
278
+ "local hooks, so this remains a lower bound.")
279
+ else:
280
+ caveat = ("Floor estimate: only TokenSafe-instrumented flows are counted "
281
+ "(agent reasoning/output is invisible to local hooks).")
282
+
253
283
  return {
254
284
  "window_tokens": window,
255
285
  "used_estimated": used,
@@ -258,7 +288,6 @@ class ContextBudget:
258
288
  "instrumented_events": instrumented_events,
259
289
  "threshold": threshold,
260
290
  "recommendation": recommendation,
261
- "caveat": "Floor estimate: only TokenSafe-instrumented flows are counted "
262
- "(agent reasoning/output is invisible to local hooks).",
291
+ "caveat": caveat,
263
292
  "measurement": "estimated",
264
293
  }
@@ -9,9 +9,98 @@ import re
9
9
  from typing import Dict, Any, Optional, List, Tuple
10
10
  from src.tokenizer import count_tokens
11
11
 
12
+
13
+ def _extract_step_text(step: dict) -> str:
14
+ """Step text in any supported transcript format. Antigravity writes a
15
+ top-level `content` string; Claude Code writes `message.content` as a
16
+ string or a list of typed blocks (text / thinking)."""
17
+ if not isinstance(step, dict):
18
+ return ""
19
+ content = step.get("content")
20
+ if isinstance(content, str) and content:
21
+ return content
22
+ message = step.get("message")
23
+ if not isinstance(message, dict):
24
+ return ""
25
+ mc = message.get("content")
26
+ if isinstance(mc, str) and mc:
27
+ return mc
28
+ if isinstance(mc, list):
29
+ parts = []
30
+ for block in mc:
31
+ if isinstance(block, dict) and block.get("type") in ("text", "thinking"):
32
+ text = block.get("text")
33
+ if isinstance(text, str) and text:
34
+ parts.append(text)
35
+ return " ".join(parts)
36
+ return ""
37
+
38
+
39
+ _READ_TOOLS = {"read_file", "view_file", "Read"}
40
+ _EDIT_TOOLS = {"edit_file", "write_file", "Edit", "Write", "NotebookEdit"}
41
+ _COMMAND_TOOLS = {"run_command", "Bash"}
42
+ _PATH_KEYS = ("Path", "path", "FilePath", "file_path", "notebook_path")
43
+ _COMMAND_KEYS = ("CommandLine", "command")
44
+
45
+
46
+ def _arg_value(args: dict, keys) -> str:
47
+ if not isinstance(args, dict):
48
+ return ""
49
+ for key in keys:
50
+ value = args.get(key)
51
+ if isinstance(value, str) and value:
52
+ return value
53
+ return ""
54
+
55
+
56
+ def _extract_step_tool_calls(step: dict) -> List[Tuple[str, dict]]:
57
+ """Tool calls in any supported transcript format: Antigravity
58
+ `tool_calls: [{name, args}]` or Claude Code `message.content` blocks of
59
+ type `tool_use` with `name` / `input`. Returns (name, args) pairs."""
60
+ calls: List[Tuple[str, dict]] = []
61
+ if not isinstance(step, dict):
62
+ return calls
63
+ for tc in step.get("tool_calls") or []:
64
+ if isinstance(tc, dict):
65
+ calls.append((str(tc.get("name", "")), tc.get("args") or {}))
66
+ message = step.get("message")
67
+ if isinstance(message, dict):
68
+ mc = message.get("content")
69
+ if isinstance(mc, list):
70
+ for block in mc:
71
+ if isinstance(block, dict) and block.get("type") == "tool_use":
72
+ calls.append((str(block.get("name", "")), block.get("input") or {}))
73
+ return calls
74
+
12
75
  class HistoryCompactor:
13
76
  """Folds past conversation tool steps into a compact state ledger."""
14
77
 
78
+ @classmethod
79
+ def measure_transcript(cls, transcript_path: str) -> int:
80
+ """Lightweight transcript mass probe: returns the token count of all
81
+ step content without building a ledger. Used by the Context Budget HUD
82
+ to count REAL history mass on early turns where the full fold is not
83
+ yet active (< 3 turns) and by hooks that only need the estimate."""
84
+ if not transcript_path or not os.path.exists(transcript_path):
85
+ return 0
86
+ total = 0
87
+ try:
88
+ with open(transcript_path, "r", encoding="utf-8", errors="replace") as f:
89
+ for line in f:
90
+ line = line.strip()
91
+ if not line:
92
+ continue
93
+ try:
94
+ step = json.loads(line)
95
+ except Exception:
96
+ continue
97
+ text = _extract_step_text(step)
98
+ if text:
99
+ total += count_tokens(text)
100
+ except Exception:
101
+ return 0
102
+ return total
103
+
15
104
  @classmethod
16
105
  def fold_transcript(cls, transcript_path: str, invocation_num: int) -> Tuple[Optional[str], int, int, Dict[str, Any]]:
17
106
  """
@@ -43,34 +132,28 @@ class HistoryCompactor:
43
132
  raw_text_accum = []
44
133
 
45
134
  for step in steps:
46
- # Accumulate content for token counting
47
- content = step.get("content", "")
48
- if content:
49
- raw_text_accum.append(str(content))
50
-
51
- # Inspect tool calls
52
- tool_calls = step.get("tool_calls", [])
53
- if isinstance(tool_calls, list):
54
- for tc in tool_calls:
55
- name = tc.get("name", "")
56
- args = tc.get("args", {})
57
- if name in ("read_file", "view_file"):
58
- # 'view_file' is the IDE-surface name for read_file;
59
- # arg keys keep proto casing but tolerate lowercase.
60
- p = args.get("Path") or args.get("path") or args.get("FilePath") or ""
61
- if p:
62
- read_files.add(os.path.basename(p))
63
- elif name in ("edit_file", "write_file"):
64
- p = args.get("Path") or args.get("path") or args.get("FilePath") or ""
65
- if p:
66
- edited_files.add(os.path.basename(p))
67
- elif name == "run_command":
68
- cmd = args.get("CommandLine", "")
69
- if cmd:
70
- # Keep short representation
71
- clean_cmd = cmd.split()[0] if cmd.split() else cmd
72
- if clean_cmd not in executed_commands:
73
- executed_commands.append(clean_cmd)
135
+ # Accumulate content for token counting (any supported format)
136
+ text = _extract_step_text(step)
137
+ if text:
138
+ raw_text_accum.append(text)
139
+
140
+ # Inspect tool calls (Antigravity tool_calls / Claude Code tool_use)
141
+ for name, args in _extract_step_tool_calls(step):
142
+ if name in _READ_TOOLS:
143
+ p = _arg_value(args, _PATH_KEYS)
144
+ if p:
145
+ read_files.add(os.path.basename(p))
146
+ elif name in _EDIT_TOOLS:
147
+ p = _arg_value(args, _PATH_KEYS)
148
+ if p:
149
+ edited_files.add(os.path.basename(p))
150
+ elif name in _COMMAND_TOOLS:
151
+ cmd = _arg_value(args, _COMMAND_KEYS)
152
+ if cmd:
153
+ # Keep short representation
154
+ clean_cmd = cmd.split()[0] if cmd.split() else cmd
155
+ if clean_cmd not in executed_commands:
156
+ executed_commands.append(clean_cmd)
74
157
 
75
158
  raw_history_str = " ".join(raw_text_accum)
76
159
  orig_tokens = count_tokens(raw_history_str)
package/src/mcp_server.py CHANGED
@@ -39,7 +39,7 @@ from src.scoped_search import ScopedSearch
39
39
 
40
40
  SERVER_INFO = {
41
41
  "name": "tokensafe-mcp",
42
- "version": "2.4.0"
42
+ "version": "2.4.2"
43
43
  }
44
44
 
45
45
  # MCP client attribution: the initialize handshake carries clientInfo, which
@@ -104,19 +104,20 @@ TOOLS = [
104
104
  },
105
105
  {
106
106
  "name": "context_budget",
107
- "description": "Context Budget HUD: estimates how much of the model's context window this session has consumed (tools/history/prompts breakdown, 50/80/95% thresholds). Call when deciding whether to compact or start fresh.",
107
+ "description": "Context Budget HUD: estimates how much of the model's context window this session has consumed (tools/history/prompts breakdown, 50/80/95% thresholds). Call before large multi-step tasks. When the threshold is warning or critical, immediately call tokensafe:compact_conversation on the session transcript.",
108
108
  "inputSchema": {
109
109
  "type": "object",
110
110
  "properties": {
111
111
  "model": {"type": "string", "description": "Optional: model name to resolve window size (default: env TOKENSAFE_CONTEXT_WINDOW or 200k)"},
112
112
  "window_tokens": {"type": "integer", "description": "Optional: explicit context window size in tokens"},
113
- "session_id": {"type": "string", "description": "Optional: session identifier (default: mcp_session)"}
113
+ "session_id": {"type": "string", "description": "Optional: session identifier (default: mcp_session)"},
114
+ "transcript_path": {"type": "string", "description": "Optional: path to the session JSONL transcript; when provided, REAL history mass is measured instead of the instrumented floor (recommended)"}
114
115
  }
115
116
  }
116
117
  },
117
118
  {
118
119
  "name": "compact_conversation",
119
- "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.",
120
+ "description": "On-demand context compaction: folds a long agent conversation transcript into a compact Consolidated State Ledger. Use when tokensafe:context_budget reports warning/critical, when the context window feels heavy, or before starting a new subtask inside the same session. The transcript path comes from your host session (hook payload transcript_path / session start context).",
120
121
  "inputSchema": {
121
122
  "type": "object",
122
123
  "properties": {
@@ -609,12 +610,16 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
609
610
  model = str(args.get("model") or "")
610
611
  window_tokens = args.get("window_tokens")
611
612
  session_id = str(args.get("session_id") or _mcp_session_id())
613
+ transcript_path = str(args.get("transcript_path") or "")
612
614
  try:
613
615
  if window_tokens is not None:
614
616
  window_tokens = int(window_tokens)
615
617
  except (TypeError, ValueError):
616
618
  window_tokens = None
617
- budget = ContextBudget.estimate(tracker, session_id=session_id, model=model, window_tokens=window_tokens)
619
+ budget = ContextBudget.estimate(
620
+ tracker, session_id=session_id, model=model, window_tokens=window_tokens,
621
+ transcript_path=transcript_path
622
+ )
618
623
  return {"content": [{"type": "text", "text": json.dumps(budget, indent=2, ensure_ascii=False)}]}
619
624
 
620
625
  elif name == "compact_conversation":
@@ -632,13 +637,26 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
632
637
  "reason": "Transcript too short to fold (needs >= 4 steps and >= 1000 history tokens)"
633
638
  }, indent=2)}]}
634
639
  saved = max(0, orig_t - folded_t)
635
- tracker.record_event(
636
- session_id=_mcp_session_id(),
637
- event_type="HISTORY_FOLD",
638
- original_tokens=orig_t,
639
- optimized_tokens=folded_t,
640
- details={"mode": "manual_compact_conversation", "turns": invocation_num, **stats}
640
+ # Incremental metrics guard (same policy as the PreInvocation hook):
641
+ # repeated compaction of the SAME transcript must not re-record the
642
+ # full history mass — count only the delta since the last fold.
643
+ prev_event = tracker.get_last_event(_mcp_session_id(), "HISTORY_FOLD")
644
+ prev_same_path = bool(
645
+ prev_event and isinstance(prev_event.get("details"), dict)
646
+ and prev_event["details"].get("transcript_path") == transcript_path
641
647
  )
648
+ prev_orig = prev_event["details"].get("total_accum_orig", 0) if prev_same_path else 0
649
+ delta_orig = max(0, orig_t - prev_orig)
650
+ if not prev_same_path or delta_orig >= 1500:
651
+ inc_orig = orig_t if not prev_same_path else delta_orig
652
+ tracker.record_event(
653
+ session_id=_mcp_session_id(),
654
+ event_type="HISTORY_FOLD",
655
+ original_tokens=inc_orig,
656
+ optimized_tokens=folded_t,
657
+ details={"mode": "manual_compact_conversation", "turns": invocation_num,
658
+ "transcript_path": transcript_path, "total_accum_orig": orig_t, **stats}
659
+ )
642
660
  return {"content": [{"type": "text", "text": json.dumps({
643
661
  "compactable": True,
644
662
  "ledger": ledger,
@@ -266,7 +266,7 @@ class TelemetrySync:
266
266
  rollup_synced = bool(state.get("lifetime_rollup_synced", False))
267
267
  headers = {
268
268
  "Content-Type": "application/json",
269
- "User-Agent": "TokenSafe-Sync/2.4.0"
269
+ "User-Agent": "TokenSafe-Sync/2.4.2"
270
270
  }
271
271
  if active_key:
272
272
  headers["Authorization"] = f"Bearer {active_key}"