tokensafe 2.4.1 → 2.4.3
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 +2 -1
- package/hooks/claude_code_hook.py +57 -5
- package/hooks/pre_invocation.py +26 -14
- package/package.json +2 -2
- package/plugin.json +2 -2
- package/rules/AGENTS.md +1 -0
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +4 -0
- package/skills/token-optimizer/references/mcp-tools.md +24 -0
- package/src/adapter_core.py +2 -0
- package/src/cli.py +9 -0
- package/src/distiller.py +1 -10
- package/src/governor.py +32 -3
- package/src/history_compactor.py +111 -28
- package/src/installer.py +7 -1
- package/src/license_manager.py +72 -27
- package/src/mcp_server.py +29 -11
- package/src/team_cache.py +1 -19
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +37 -15
package/README.md
CHANGED
|
@@ -7,7 +7,8 @@
|
|
|
7
7
|
|
|
8
8
|
<p align="center">
|
|
9
9
|
<b>Local-First AI Guardrails, Focused Context & Auditable Team ROI</b><br>
|
|
10
|
-
|
|
10
|
+
Reduce your AI bills by up to 90%. Let your team ship clean code faster and cheaper.<br>
|
|
11
|
+
TokenSafe runs locally between your agents and your repos: agents read only the code they need (context spend 60-90% lower, measured / estimated) and secrets get blocked before commit.<br>
|
|
11
12
|
Built for teams using <b>Cursor, Claude Code, Codex, Windsurf, Google Antigravity, Gemini CLI, and ChatGPT</b>.
|
|
12
13
|
</p>
|
|
13
14
|
|
|
@@ -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 {}
|
package/hooks/pre_invocation.py
CHANGED
|
@@ -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":
|
|
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
|
-
#
|
|
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
|
|
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,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "2.4.
|
|
5
|
-
"description": "Local-first AI
|
|
4
|
+
"version": "2.4.3",
|
|
5
|
+
"description": "Local-first AI guardrails: reduce AI bills by up to 90%, focused context, zero leaked secrets.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
|
8
8
|
"tokensafe": "bin/tokensafe.js"
|
package/plugin.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "2.4.
|
|
5
|
-
"description": "Local-first guardrails
|
|
4
|
+
"version": "2.4.3",
|
|
5
|
+
"description": "Local-first AI guardrails: reduce AI bills by up to 90%, focused context, zero leaked secrets.",
|
|
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.
|
|
6
|
+
"version": "2.4.3",
|
|
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.
|
|
33
|
+
"version": "2.4.3",
|
|
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.
|
|
49
|
+
"version": "2.4.3",
|
|
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).*
|
package/src/adapter_core.py
CHANGED
|
@@ -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/distiller.py
CHANGED
|
@@ -213,16 +213,7 @@ Rules:
|
|
|
213
213
|
|
|
214
214
|
# 1. Managed Cloud Distillation (Default for Solo/Team SaaS)
|
|
215
215
|
if "cloud" in providers:
|
|
216
|
-
lic_key =
|
|
217
|
-
if not lic_key:
|
|
218
|
-
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
219
|
-
lic_file = os.path.join(base_dir, "data", "license.json")
|
|
220
|
-
if os.path.exists(lic_file):
|
|
221
|
-
try:
|
|
222
|
-
with open(lic_file, "r", encoding="utf-8") as f:
|
|
223
|
-
lic_key = json.load(f).get("license_key", "").strip()
|
|
224
|
-
except Exception:
|
|
225
|
-
pass
|
|
216
|
+
lic_key = LicenseManager.get_active_license_key()
|
|
226
217
|
|
|
227
218
|
if lic_key:
|
|
228
219
|
cloud_res = cls._call_cloud_distill(raw_text, lic_key)
|
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
|
|
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":
|
|
262
|
-
"(agent reasoning/output is invisible to local hooks).",
|
|
291
|
+
"caveat": caveat,
|
|
263
292
|
"measurement": "estimated",
|
|
264
293
|
}
|
package/src/history_compactor.py
CHANGED
|
@@ -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
|
-
|
|
48
|
-
if
|
|
49
|
-
raw_text_accum.append(
|
|
50
|
-
|
|
51
|
-
# Inspect tool calls
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
if
|
|
66
|
-
|
|
67
|
-
|
|
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/installer.py
CHANGED
|
@@ -922,7 +922,7 @@ class AgentInstaller:
|
|
|
922
922
|
else:
|
|
923
923
|
print(f" {YELLOW}⚠{RESET} {info['name']}: {msg}")
|
|
924
924
|
|
|
925
|
-
# 5. Refresh local version cache
|
|
925
|
+
# 5. Refresh local version cache and report the newly installed version in a fresh process
|
|
926
926
|
try:
|
|
927
927
|
from src.paths import resolve_data_dir
|
|
928
928
|
cache_file = os.path.join(resolve_data_dir(), "version_cache.json")
|
|
@@ -930,6 +930,12 @@ class AgentInstaller:
|
|
|
930
930
|
os.remove(cache_file)
|
|
931
931
|
except Exception:
|
|
932
932
|
pass
|
|
933
|
+
try:
|
|
934
|
+
tokensafe_bin = shutil.which("tokensafe")
|
|
935
|
+
sync_cmd = [tokensafe_bin, "version", "--check"] if tokensafe_bin else [sys.executable, os.path.join(PROJECT_ROOT, "src", "cli.py"), "version", "--check"]
|
|
936
|
+
subprocess.run(sync_cmd, capture_output=True, text=True, timeout=5)
|
|
937
|
+
except Exception:
|
|
938
|
+
pass
|
|
933
939
|
|
|
934
940
|
# 6. Restart running MCP server daemons so IDEs load the new version
|
|
935
941
|
restarted_count = cls.restart_mcp_daemons()
|
package/src/license_manager.py
CHANGED
|
@@ -12,7 +12,7 @@ import hmac
|
|
|
12
12
|
import hashlib
|
|
13
13
|
import base64
|
|
14
14
|
import threading
|
|
15
|
-
from typing import Dict, Any, Tuple, Optional
|
|
15
|
+
from typing import Dict, Any, Tuple, Optional, List
|
|
16
16
|
|
|
17
17
|
from src.paths import resolve_data_dir
|
|
18
18
|
|
|
@@ -21,6 +21,8 @@ DATA_DIR = resolve_data_dir()
|
|
|
21
21
|
LICENSE_FILE = os.path.join(DATA_DIR, "license.json")
|
|
22
22
|
GLOBAL_DATA_DIR = os.path.expanduser("~/.tokensafe")
|
|
23
23
|
GLOBAL_LICENSE_FILE = os.path.join(GLOBAL_DATA_DIR, "license.json")
|
|
24
|
+
_DEFAULT_LICENSE_FILE = LICENSE_FILE
|
|
25
|
+
_DEFAULT_GLOBAL_LICENSE_FILE = GLOBAL_LICENSE_FILE
|
|
24
26
|
|
|
25
27
|
# Master Public Key for client-side offline verification (RFC 8032 Ed25519)
|
|
26
28
|
DEFAULT_ED25519_PUBLIC_KEY = os.environ.get("TOKENSAFE_PUBLIC_KEY", "3911e2ffe5ad07ee23be392b88f238af302f9d3a0bf51881de8b5e0e6af71430")
|
|
@@ -297,40 +299,81 @@ class LicenseManager:
|
|
|
297
299
|
return True, payload, "License is active and valid"
|
|
298
300
|
|
|
299
301
|
@classmethod
|
|
300
|
-
def
|
|
301
|
-
"""
|
|
302
|
-
|
|
303
|
-
if
|
|
302
|
+
def _candidate_license_files(cls) -> List[str]:
|
|
303
|
+
"""Returns license.json paths to inspect, honoring explicit TOKENSAFE_DATA_DIR and test patches."""
|
|
304
|
+
explicit_dir = os.environ.get("TOKENSAFE_DATA_DIR", "").strip()
|
|
305
|
+
if LICENSE_FILE != _DEFAULT_LICENSE_FILE:
|
|
306
|
+
paths = [LICENSE_FILE]
|
|
307
|
+
if GLOBAL_LICENSE_FILE != _DEFAULT_GLOBAL_LICENSE_FILE:
|
|
308
|
+
paths.append(GLOBAL_LICENSE_FILE)
|
|
309
|
+
elif explicit_dir:
|
|
310
|
+
paths = [os.path.join(explicit_dir, "license.json")]
|
|
311
|
+
else:
|
|
312
|
+
paths = [LICENSE_FILE, GLOBAL_LICENSE_FILE]
|
|
313
|
+
|
|
314
|
+
seen = set()
|
|
315
|
+
unique: List[str] = []
|
|
316
|
+
for p in paths:
|
|
317
|
+
ap = os.path.abspath(p)
|
|
318
|
+
if ap not in seen:
|
|
319
|
+
seen.add(ap)
|
|
320
|
+
unique.append(p)
|
|
321
|
+
return unique
|
|
322
|
+
|
|
323
|
+
@classmethod
|
|
324
|
+
def _resolve_active_license_record(cls) -> Tuple[Optional[Tuple[str, Dict[str, Any]]], str]:
|
|
325
|
+
"""Selects the freshest valid license across env and candidate files."""
|
|
326
|
+
env_key = os.environ.get("TOKENSAFE_LICENSE_KEY", "").strip()
|
|
327
|
+
if env_key:
|
|
328
|
+
valid, payload, _ = cls.validate_license(env_key)
|
|
329
|
+
return ((env_key, payload) if valid else None), env_key
|
|
330
|
+
|
|
331
|
+
best_valid: Optional[Tuple[Tuple[int, int, float], str, Dict[str, Any]]] = None
|
|
332
|
+
best_raw: Optional[Tuple[Tuple[int, float], str]] = None
|
|
333
|
+
|
|
334
|
+
for path in cls._candidate_license_files():
|
|
335
|
+
if not os.path.exists(path):
|
|
336
|
+
continue
|
|
304
337
|
try:
|
|
305
|
-
with open(
|
|
338
|
+
with open(path, "r", encoding="utf-8") as f:
|
|
306
339
|
data = json.load(f)
|
|
307
|
-
|
|
340
|
+
candidate = str(data.get("license_key", "")).strip()
|
|
341
|
+
if not candidate:
|
|
342
|
+
continue
|
|
343
|
+
saved_at = int(data.get("saved_at") or 0)
|
|
344
|
+
mtime = os.path.getmtime(path)
|
|
308
345
|
except Exception:
|
|
309
|
-
|
|
346
|
+
continue
|
|
310
347
|
|
|
311
|
-
|
|
312
|
-
|
|
348
|
+
raw_rank = (saved_at, mtime)
|
|
349
|
+
if best_raw is None or raw_rank > best_raw[0]:
|
|
350
|
+
best_raw = (raw_rank, candidate)
|
|
351
|
+
|
|
352
|
+
valid, payload, _ = cls.validate_license(candidate)
|
|
313
353
|
if valid:
|
|
314
|
-
|
|
354
|
+
issued_at = int(payload.get("issued_at") or 0)
|
|
355
|
+
valid_rank = (saved_at, issued_at, mtime)
|
|
356
|
+
if best_valid is None or valid_rank > best_valid[0]:
|
|
357
|
+
best_valid = (valid_rank, candidate, payload)
|
|
358
|
+
|
|
359
|
+
if best_valid is not None:
|
|
360
|
+
return (best_valid[1], best_valid[2]), best_valid[1]
|
|
361
|
+
return None, (best_raw[1] if best_raw is not None else "")
|
|
362
|
+
|
|
363
|
+
@classmethod
|
|
364
|
+
def get_active_license(cls) -> Tuple[str, Dict[str, Any]]:
|
|
365
|
+
"""Retrieves active license from env or persistent license.json files, falling back to free tier."""
|
|
366
|
+
resolved, _ = cls._resolve_active_license_record()
|
|
367
|
+
if resolved is not None:
|
|
368
|
+
_, payload = resolved
|
|
369
|
+
return payload.get("tier", "solo"), payload
|
|
315
370
|
|
|
316
371
|
return "free", {"tier": "free", "max_tokens_monthly": 500_000}
|
|
317
372
|
|
|
318
373
|
@classmethod
|
|
319
374
|
def get_active_license_key(cls) -> str:
|
|
320
|
-
"""Retrieves active raw license key string from env or persistent license.json files."""
|
|
321
|
-
key =
|
|
322
|
-
if not key:
|
|
323
|
-
for p in (LICENSE_FILE, GLOBAL_LICENSE_FILE):
|
|
324
|
-
if os.path.exists(p):
|
|
325
|
-
try:
|
|
326
|
-
with open(p, "r", encoding="utf-8") as f:
|
|
327
|
-
data = json.load(f)
|
|
328
|
-
candidate = data.get("license_key", "").strip()
|
|
329
|
-
if candidate:
|
|
330
|
-
key = candidate
|
|
331
|
-
break
|
|
332
|
-
except Exception:
|
|
333
|
-
pass
|
|
375
|
+
"""Retrieves the freshest active raw license key string from env or persistent license.json files."""
|
|
376
|
+
_, key = cls._resolve_active_license_record()
|
|
334
377
|
return key
|
|
335
378
|
|
|
336
379
|
@classmethod
|
|
@@ -349,9 +392,11 @@ class LicenseManager:
|
|
|
349
392
|
"saved_at": int(time.time())
|
|
350
393
|
}
|
|
351
394
|
|
|
352
|
-
for
|
|
395
|
+
for target_file in cls._candidate_license_files():
|
|
396
|
+
target_dir = os.path.dirname(target_file)
|
|
353
397
|
try:
|
|
354
|
-
|
|
398
|
+
if target_dir:
|
|
399
|
+
os.makedirs(target_dir, exist_ok=True)
|
|
355
400
|
with open(target_file, "w", encoding="utf-8") as f:
|
|
356
401
|
json.dump(record, f, indent=2)
|
|
357
402
|
except Exception:
|
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.
|
|
42
|
+
"version": "2.4.3"
|
|
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
|
|
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(
|
|
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
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
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,
|
package/src/team_cache.py
CHANGED
|
@@ -26,25 +26,7 @@ class TeamCache:
|
|
|
26
26
|
@classmethod
|
|
27
27
|
def _is_team_tier(cls) -> Tuple[bool, str]:
|
|
28
28
|
"""Checks if current active license belongs to a Team tier subscription."""
|
|
29
|
-
key =
|
|
30
|
-
if not key:
|
|
31
|
-
from src.paths import resolve_data_dir
|
|
32
|
-
candidate_paths = [
|
|
33
|
-
os.path.join(resolve_data_dir(), "license.json"),
|
|
34
|
-
os.path.join(os.getcwd(), "data", "license.json"),
|
|
35
|
-
os.path.expanduser("~/.tokensafe/license.json")
|
|
36
|
-
]
|
|
37
|
-
for lic_file in candidate_paths:
|
|
38
|
-
if os.path.exists(lic_file):
|
|
39
|
-
try:
|
|
40
|
-
with open(lic_file, "r", encoding="utf-8") as f:
|
|
41
|
-
data = json.load(f)
|
|
42
|
-
key = data.get("license_key", "").strip()
|
|
43
|
-
if key:
|
|
44
|
-
break
|
|
45
|
-
except Exception:
|
|
46
|
-
pass
|
|
47
|
-
|
|
29
|
+
key = LicenseManager.get_active_license_key()
|
|
48
30
|
if not key:
|
|
49
31
|
return False, ""
|
|
50
32
|
|
package/src/telemetry_sync.py
CHANGED
|
@@ -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.
|
|
269
|
+
"User-Agent": "TokenSafe-Sync/2.4.3"
|
|
270
270
|
}
|
|
271
271
|
if active_key:
|
|
272
272
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -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 = "2.4.
|
|
19
|
+
CURRENT_VERSION = "2.4.3"
|
|
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
|
|
@@ -24,9 +24,18 @@ CACHE_TTL = 86400 # 24 hours
|
|
|
24
24
|
# "broken" while the backend was redeploying).
|
|
25
25
|
FALLBACK_CACHE_TTL = 900 # 15 minutes
|
|
26
26
|
|
|
27
|
+
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
28
|
+
# Script-mode guard: notify_os_update_background spawns this file directly
|
|
29
|
+
# (`python3 src/version_checker.py --check-bg`), which sets sys.path[0] to the
|
|
30
|
+
# src/ directory — `import src.*` fails unless PROJECT_ROOT is on the path
|
|
31
|
+
# FIRST. The old ordering (import before path setup) made every background
|
|
32
|
+
# update check die silently in the bare except of __main__, so version_cache.json
|
|
33
|
+
# was never written and the update dialog never appeared.
|
|
34
|
+
if PROJECT_ROOT not in sys.path:
|
|
35
|
+
sys.path.insert(0, PROJECT_ROOT)
|
|
36
|
+
|
|
27
37
|
from src.paths import resolve_data_dir
|
|
28
38
|
|
|
29
|
-
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
30
39
|
DATA_DIR = resolve_data_dir()
|
|
31
40
|
CACHE_FILE = os.path.join(DATA_DIR, "version_cache.json")
|
|
32
41
|
CLOUD_CHECK_URL = os.environ.get("TOKENSAFE_VERSION_URL", "https://api.tokensafe.dev/api/version/check")
|
|
@@ -82,6 +91,15 @@ class VersionChecker:
|
|
|
82
91
|
except Exception:
|
|
83
92
|
pass
|
|
84
93
|
|
|
94
|
+
@staticmethod
|
|
95
|
+
def _cache_matches_version(cached: Optional[Dict[str, Any]], current_version: str) -> bool:
|
|
96
|
+
"""True when cached payload was recorded for `current_version` (invalidates cache on upgrade)."""
|
|
97
|
+
if not cached:
|
|
98
|
+
return False
|
|
99
|
+
cached_ver = str(cached.get("client_version") or "").strip().lstrip("v")
|
|
100
|
+
curr_ver = str(current_version or "").strip().lstrip("v")
|
|
101
|
+
return bool(cached_ver) and cached_ver == curr_ver
|
|
102
|
+
|
|
85
103
|
@classmethod
|
|
86
104
|
def check_version(
|
|
87
105
|
cls,
|
|
@@ -91,8 +109,8 @@ class VersionChecker:
|
|
|
91
109
|
timeout: float = 1.5
|
|
92
110
|
) -> Dict[str, Any]:
|
|
93
111
|
"""
|
|
94
|
-
Retrieves version status. Returns cached result if within TTL
|
|
95
|
-
otherwise makes a fast network request (< 1.5s timeout).
|
|
112
|
+
Retrieves version status. Returns cached result if within TTL and matching
|
|
113
|
+
`current_version`, otherwise makes a fast network request (< 1.5s timeout).
|
|
96
114
|
Falls back gracefully on network or offline scenarios.
|
|
97
115
|
"""
|
|
98
116
|
now = int(time.time())
|
|
@@ -104,8 +122,9 @@ class VersionChecker:
|
|
|
104
122
|
license_key = ""
|
|
105
123
|
|
|
106
124
|
cached = cls.load_cache()
|
|
125
|
+
cache_matches = cls._cache_matches_version(cached, current_version)
|
|
107
126
|
|
|
108
|
-
if not force_fetch and
|
|
127
|
+
if not force_fetch and cache_matches:
|
|
109
128
|
checked_at = cached.get("checked_at", 0)
|
|
110
129
|
ttl = int(cached.get("ttl", CACHE_TTL))
|
|
111
130
|
if now - checked_at < ttl:
|
|
@@ -152,8 +171,8 @@ class VersionChecker:
|
|
|
152
171
|
except Exception:
|
|
153
172
|
pass
|
|
154
173
|
|
|
155
|
-
# Stale cache fallback if available
|
|
156
|
-
if
|
|
174
|
+
# Stale cache fallback if available for the same installed version
|
|
175
|
+
if cache_matches:
|
|
157
176
|
return cached
|
|
158
177
|
cls.save_cache(payload)
|
|
159
178
|
return payload
|
|
@@ -351,19 +370,22 @@ class VersionChecker:
|
|
|
351
370
|
except OSError:
|
|
352
371
|
pass # claim is best-effort; never block the dialog entirely on fs errors
|
|
353
372
|
|
|
354
|
-
try:
|
|
355
|
-
cached["last_os_notify_version"] = latest
|
|
356
|
-
cached["last_os_notify_at"] = now
|
|
357
|
-
cls.save_cache(cached)
|
|
358
|
-
except Exception:
|
|
359
|
-
pass
|
|
360
|
-
|
|
361
373
|
try:
|
|
362
374
|
dispatched = cls.show_os_dialog(
|
|
363
375
|
current_version=current_version,
|
|
364
376
|
latest_version=latest,
|
|
365
377
|
update_command=cmd
|
|
366
378
|
)
|
|
379
|
+
if dispatched:
|
|
380
|
+
# Mark "notified" only after the dialog actually dispatched.
|
|
381
|
+
# Writing it earlier let a silently TCC-blocked osascript buy
|
|
382
|
+
# 24h of dialog silence without the user ever seeing anything.
|
|
383
|
+
try:
|
|
384
|
+
cached["last_os_notify_version"] = latest
|
|
385
|
+
cached["last_os_notify_at"] = now
|
|
386
|
+
cls.save_cache(cached)
|
|
387
|
+
except Exception:
|
|
388
|
+
pass
|
|
367
389
|
return dispatched
|
|
368
390
|
finally:
|
|
369
391
|
# Release the dialog claim so a future version can notify again.
|
|
@@ -385,7 +407,7 @@ class VersionChecker:
|
|
|
385
407
|
"""
|
|
386
408
|
now = int(time.time())
|
|
387
409
|
cached = cls.load_cache()
|
|
388
|
-
if not force and cached:
|
|
410
|
+
if not force and cls._cache_matches_version(cached, current_version):
|
|
389
411
|
checked_at = cached.get("checked_at", 0)
|
|
390
412
|
update_available = cached.get("update_available", False)
|
|
391
413
|
latest = cached.get("latest_version", current_version)
|