tokensafe 2.9.0 → 3.0.1
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 +57 -1
- package/hooks/claude_code_hook.py +24 -1
- package/hooks/pre_tool_use.py +7 -32
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/adapter_core.py +71 -0
- package/src/benchmark_real.py +562 -0
- package/src/cli.py +129 -6
- package/src/command_sanitizer.py +0 -26
- package/src/dashboard.py +26 -4
- package/src/distiller.py +41 -2
- package/src/governor.py +1 -0
- package/src/guard.py +0 -5
- package/src/installer.py +279 -1
- package/src/license_manager.py +31 -4
- package/src/mcp_server.py +1 -1
- package/src/metrics.py +25 -0
- package/src/proxy.py +455 -5
- package/src/result_ledger.py +314 -0
- package/src/slicer.py +0 -39
- package/src/telemetry_sync.py +1 -1
- package/src/tool_pruner.py +244 -0
- package/src/version_checker.py +1 -15
package/src/cli.py
CHANGED
|
@@ -97,7 +97,9 @@ def _print_help():
|
|
|
97
97
|
print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
|
|
98
98
|
print("Commands:")
|
|
99
99
|
print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
|
|
100
|
+
print(" status One-screen health check: hooks, weekly savings, tier, sync")
|
|
100
101
|
print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
|
|
102
|
+
print(" bench --real [--repo=key|--here] Measured benchmark on real repos (zero-loss gates)")
|
|
101
103
|
print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
|
|
102
104
|
print(" test <prompt> Preview TOCP S-expression prompt compaction")
|
|
103
105
|
print(" digest [--send] [--email=...] Compile (and optionally dispatch) the weekly team digest")
|
|
@@ -140,7 +142,67 @@ def main():
|
|
|
140
142
|
VersionChecker.notify_os_update(force=True)
|
|
141
143
|
return
|
|
142
144
|
|
|
143
|
-
if command in ("
|
|
145
|
+
if command in ("status", "health"):
|
|
146
|
+
from src.installer import AgentInstaller
|
|
147
|
+
from src.license_manager import LicenseManager
|
|
148
|
+
from src.telemetry_sync import TelemetrySync
|
|
149
|
+
tracker = MetricsTracker()
|
|
150
|
+
print("\n\033[1m\033[36m⚡ TOKENSAFE STATUS ⚡\033[0m\n")
|
|
151
|
+
# Hooks wiring (best-effort scan of agent config files and plugin dirs)
|
|
152
|
+
active_agents = []
|
|
153
|
+
for key, info in AgentInstaller.detect_available_agents().items():
|
|
154
|
+
hit = any(info.get(pk) and os.path.exists(info[pk]) for pk in
|
|
155
|
+
("target_path", "plugin_path", "skills_path", "agents_md_path", "rules_path", "extension_path"))
|
|
156
|
+
cfg = info.get("config_path")
|
|
157
|
+
if not hit and cfg and os.path.exists(cfg):
|
|
158
|
+
try:
|
|
159
|
+
with open(cfg, "r", encoding="utf-8", errors="replace") as f:
|
|
160
|
+
hit = "tokensafe" in f.read().lower()
|
|
161
|
+
except Exception:
|
|
162
|
+
pass
|
|
163
|
+
if hit:
|
|
164
|
+
active_agents.append(key)
|
|
165
|
+
if active_agents:
|
|
166
|
+
print(f" Hooks: \033[32m✔ active\033[0m in {len(active_agents)} agent(s): {', '.join(active_agents)}")
|
|
167
|
+
else:
|
|
168
|
+
print(" Hooks: \033[33m○ not detected\033[0m — run \033[1mtokensafe install\033[0m to configure your agents")
|
|
169
|
+
# The value moment: recent measured savings
|
|
170
|
+
weekly = tracker.get_weekly_saved()
|
|
171
|
+
print(f" This Week: \033[32m\033[1m{weekly['saved_tokens']:,} tokens saved\033[0m across {weekly['events']:,} events (≈${weekly['usd_saved']:.2f})")
|
|
172
|
+
# Tier + quota state
|
|
173
|
+
tier, payload = LicenseManager.get_active_license()
|
|
174
|
+
quota = LicenseManager.check_quota(tracker)
|
|
175
|
+
if tier == "free":
|
|
176
|
+
q_saved = int(quota.get("monthly_saved", 0))
|
|
177
|
+
q_limit = int(quota.get("monthly_limit") or 500_000)
|
|
178
|
+
q_pct = min(100, int(q_saved / q_limit * 100)) if q_limit else 0
|
|
179
|
+
q_state = "\033[31mQUOTA REACHED — Pro optimizations paused\033[0m" if quota.get("is_quota_exceeded") else f"{q_pct}% of monthly measured quota"
|
|
180
|
+
print(f" Tier: \033[33mCOMMUNITY (Free)\033[0m — {q_saved:,} / {q_limit:,} tokens ({q_state})")
|
|
181
|
+
print(" Upgrade: \033[36mhttps://tokensafe.dev/signup\033[0m ($9/mo Solo · 7-Day Team Trial)")
|
|
182
|
+
else:
|
|
183
|
+
print(f" Tier: \033[32m{tier.upper()}\033[0m (Unlimited)")
|
|
184
|
+
# Cloud heartbeat (non-blocking; keeps the machine visible server-side)
|
|
185
|
+
try:
|
|
186
|
+
TelemetrySync.sync_background()
|
|
187
|
+
pending = int(TelemetrySync.get_sync_status().get("pending_events", 0) or 0)
|
|
188
|
+
if pending:
|
|
189
|
+
print(f" Cloud: {pending:,} events queued for telemetry sync (background)")
|
|
190
|
+
else:
|
|
191
|
+
print(" Cloud: \033[32m✔ telemetry up to date\033[0m")
|
|
192
|
+
except Exception:
|
|
193
|
+
pass
|
|
194
|
+
# Distillation cache visibility (get_stats existed but was never surfaced anywhere)
|
|
195
|
+
try:
|
|
196
|
+
from src.distiller_cache import DistillationCache
|
|
197
|
+
cstats = DistillationCache.get_stats()
|
|
198
|
+
lookups = cstats["hits"] + cstats["misses"]
|
|
199
|
+
if lookups:
|
|
200
|
+
print(f" Cache: \033[32m{cstats['hit_ratio_pct']}% distillation cache hit ratio\033[0m ({cstats['hits']:,}/{lookups:,} lookups · {cstats['persistent_entries']:,} entries on disk)")
|
|
201
|
+
except Exception:
|
|
202
|
+
pass
|
|
203
|
+
print()
|
|
204
|
+
|
|
205
|
+
elif command in ("stats", "dashboard"):
|
|
144
206
|
tracker = MetricsTracker()
|
|
145
207
|
dashboard = Dashboard(tracker)
|
|
146
208
|
try:
|
|
@@ -176,6 +238,30 @@ def main():
|
|
|
176
238
|
pass
|
|
177
239
|
|
|
178
240
|
elif command in ("benchmark", "bench"):
|
|
241
|
+
if "--real" in args:
|
|
242
|
+
# Measured real-repo mode: pre-registered scenarios (src/bench_scenarios.json),
|
|
243
|
+
# zero-loss gates, real clones — see src/benchmark_real.py methodology header.
|
|
244
|
+
# --here: measure the CURRENT repository instead (god-node hot symbols,
|
|
245
|
+
# suite as-is without mutation — self-measurement, not the published set).
|
|
246
|
+
from src.benchmark_real import RealRepoBenchmark
|
|
247
|
+
bench = RealRepoBenchmark()
|
|
248
|
+
if "--here" in args:
|
|
249
|
+
print("\n⚡ Running REAL-REPO benchmark on the CURRENT repository (measured, zero-loss gates)...")
|
|
250
|
+
data = bench.run_local(os.getcwd())
|
|
251
|
+
else:
|
|
252
|
+
repo_keys = [a.split("=", 1)[1] for a in args if a.startswith("--repo=")]
|
|
253
|
+
print("\n⚡ Running REAL-REPO benchmark (measured on live clones, pre-registered scenarios)...")
|
|
254
|
+
data = bench.run_all(repo_keys or None)
|
|
255
|
+
print()
|
|
256
|
+
print(bench.render_markdown(data))
|
|
257
|
+
out = bench.export(data)
|
|
258
|
+
print(f"📊 JSON: {out['json']}")
|
|
259
|
+
print(f"📊 MD: {out['md']}\n")
|
|
260
|
+
sys.exit(0 if all(
|
|
261
|
+
(s.get("status") == "ok")
|
|
262
|
+
for r in data["results"] for s in (r.get("symbol_read"), r.get("test_output"), r.get("multiturn"))
|
|
263
|
+
if s
|
|
264
|
+
) else 1)
|
|
179
265
|
from src.benchmark import BenchmarkSuite
|
|
180
266
|
from src.paths import resolve_data_dir
|
|
181
267
|
print("\n⚡ Running Zero-Loss SWE-bench Benchmark Suite across real-world scenarios...")
|
|
@@ -195,6 +281,7 @@ def main():
|
|
|
195
281
|
status = "\033[32m✔\033[0m" if r["success"] else "\033[31m✖\033[0m"
|
|
196
282
|
print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
|
|
197
283
|
print(f"\n\033[32m✔ Universal project rules injected into: {', '.join(res['project_rules'])}\033[0m\n")
|
|
284
|
+
AgentInstaller.maybe_prompt_proxy_enable(context="install")
|
|
198
285
|
elif "--project" in args:
|
|
199
286
|
agents_plugin = None
|
|
200
287
|
if "--agents-plugin" in args:
|
|
@@ -307,8 +394,41 @@ def main():
|
|
|
307
394
|
|
|
308
395
|
elif command == "proxy":
|
|
309
396
|
from src.proxy import run_proxy
|
|
310
|
-
if len(args) > 1
|
|
311
|
-
|
|
397
|
+
sub = args[1] if len(args) > 1 else ""
|
|
398
|
+
if sub in ("--help", "-h", "help"):
|
|
399
|
+
print("Usage: tokensafe proxy [port] Run in foreground (default: 8765)")
|
|
400
|
+
print(" tokensafe proxy on Install daemon + wire agents (one command)")
|
|
401
|
+
print(" tokensafe proxy off Unwire agents + remove daemon (rollback)")
|
|
402
|
+
print(" tokensafe proxy status Health, wiring state, heartbeat")
|
|
403
|
+
return
|
|
404
|
+
if sub == "on":
|
|
405
|
+
from src.installer import AgentInstaller
|
|
406
|
+
report = AgentInstaller.proxy_on()
|
|
407
|
+
d, w = report["daemon"], report["wiring"]
|
|
408
|
+
print(f"\n\033[1m\033[36m⚡ TOKENSAFE PROXY SETUP ⚡\033[0m\n")
|
|
409
|
+
print(f" Daemon: {'✔ ' + d['message'] if d['ok'] else '✖ ' + d['message']}")
|
|
410
|
+
print(f" Health: {'✔ proxy answering on 127.0.0.1:8765' if report['health'] else '✖ not reachable'}")
|
|
411
|
+
print(f" Wiring: {'✔ ' + w['message'] if w['ok'] else '✖ ' + w['message']}")
|
|
412
|
+
if report["manual_steps"]:
|
|
413
|
+
print(" Manual (not auto-wirable):")
|
|
414
|
+
for step in report["manual_steps"]:
|
|
415
|
+
print(f" • {step}")
|
|
416
|
+
print(f"\n Rollback anytime: \033[1mtokensafe proxy off\033[0m\n")
|
|
417
|
+
return
|
|
418
|
+
if sub == "off":
|
|
419
|
+
from src.installer import AgentInstaller
|
|
420
|
+
report = AgentInstaller.proxy_off()
|
|
421
|
+
u, d = report["unwired"], report["daemon"]
|
|
422
|
+
print(f"\n Unwired: {'✔ ' + u['message'] if u['ok'] else '✖ ' + u['message']}")
|
|
423
|
+
print(f" Daemon: {'✔ ' + d['message'] if d['ok'] else '✖ ' + d['message']}\n")
|
|
424
|
+
return
|
|
425
|
+
if sub == "status":
|
|
426
|
+
from src.installer import AgentInstaller
|
|
427
|
+
st = AgentInstaller.proxy_status()
|
|
428
|
+
print(f"\n Health: {'✔ running on 127.0.0.1:8765' if st['health'] else '✖ not running'}")
|
|
429
|
+
print(f" Claude Code wired: {'✔ ' + str(st['claude_code_env_value']) if st['claude_code_wired'] else '○ not wired'}")
|
|
430
|
+
hb = st.get("heartbeat_age_seconds")
|
|
431
|
+
print(f" Last traffic: {f'{hb}s ago' if hb is not None else 'no heartbeat yet'}\n")
|
|
312
432
|
return
|
|
313
433
|
port = 8765
|
|
314
434
|
if len(args) > 1:
|
|
@@ -460,7 +580,7 @@ def main():
|
|
|
460
580
|
q_limit = int(quota.get("monthly_limit") or 500_000)
|
|
461
581
|
q_state = "\033[31mQUOTA REACHED (Pro optimizations paused)\033[0m" if quota.get("is_quota_exceeded") else "\033[32mActive\033[0m"
|
|
462
582
|
print(f" Status: Free Tier ({q_saved:,} / {q_limit:,} measured tokens this month · {q_state})")
|
|
463
|
-
print(" Upgrade: https://tokensafe.dev
|
|
583
|
+
print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo with 7-Day Free Trial)\n")
|
|
464
584
|
print()
|
|
465
585
|
|
|
466
586
|
elif command in ("providers", "models", "keys"):
|
|
@@ -584,8 +704,11 @@ def main():
|
|
|
584
704
|
t = MetricsTracker()
|
|
585
705
|
b_before = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
|
|
586
706
|
t.vacuum()
|
|
707
|
+
# Repair pass: rebuild session aggregates straight from events (guards
|
|
708
|
+
# against sessions/events drift after crashes or manual DB edits).
|
|
709
|
+
t.recalculate_sessions()
|
|
587
710
|
b_after = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
|
|
588
|
-
print(f"\033[32m✔ Database compacted. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
|
|
711
|
+
print(f"\033[32m✔ Database compacted + session aggregates rebuilt. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
|
|
589
712
|
|
|
590
713
|
elif command in ("digest", "weekly-digest"):
|
|
591
714
|
from src.weekly_digest import WeeklyDigestGenerator
|
|
@@ -660,7 +783,7 @@ def main():
|
|
|
660
783
|
|
|
661
784
|
else:
|
|
662
785
|
print(f"Unknown command: {command}")
|
|
663
|
-
print("Available commands: stats, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
786
|
+
print("Available commands: stats, status, sync, html, test, tests, doctor, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, vacuum, prune, digest, activate, license, markdown, install, setup, update, check-update, reset. Run 'tokensafe help' for details.")
|
|
664
787
|
sys.exit(1)
|
|
665
788
|
|
|
666
789
|
if __name__ == "__main__":
|
package/src/command_sanitizer.py
CHANGED
|
@@ -190,32 +190,6 @@ class CommandSanitizer:
|
|
|
190
190
|
out += f" {op} {stage}"
|
|
191
191
|
return out
|
|
192
192
|
|
|
193
|
-
@staticmethod
|
|
194
|
-
def _split_pipeline_stages(cmd: str) -> List[str]:
|
|
195
|
-
"""
|
|
196
|
-
Splits a shell command on single '|' pipe operators while respecting
|
|
197
|
-
quoting ('...', "...", `...`) and '||' logical OR, so regex patterns like
|
|
198
|
-
grep "foo|bar" are never torn apart mid-string.
|
|
199
|
-
"""
|
|
200
|
-
pairs = CommandSanitizer.split_stages(cmd)
|
|
201
|
-
# Legacy contract: only pipe boundaries split; '&&'/';'/'||' stay inside stages.
|
|
202
|
-
stages: List[str] = []
|
|
203
|
-
pipe_open = False
|
|
204
|
-
for op, stage in pairs:
|
|
205
|
-
if op in ("", "|"):
|
|
206
|
-
if pipe_open and stages:
|
|
207
|
-
stages[-1] = f"{stages[-1]} | {stage}"
|
|
208
|
-
else:
|
|
209
|
-
stages.append(stage)
|
|
210
|
-
pipe_open = op == "|"
|
|
211
|
-
else:
|
|
212
|
-
# Non-pipe operator: glue operator + stage back into current stage
|
|
213
|
-
if stages:
|
|
214
|
-
stages[-1] = f"{stages[-1]} {op} {stage}"
|
|
215
|
-
else:
|
|
216
|
-
stages.append(stage)
|
|
217
|
-
return [s for s in (st.strip() for st in stages) if s]
|
|
218
|
-
|
|
219
193
|
@classmethod
|
|
220
194
|
def _has_redirect(cls, stage: str) -> bool:
|
|
221
195
|
"""True if the stage redirects stdout to a file/stream (ignoring 2>&1 merges and quoted '>')."""
|
package/src/dashboard.py
CHANGED
|
@@ -48,7 +48,12 @@ EVENT_NAMES = {
|
|
|
48
48
|
"OUTPUT_GUARD": "Output Token Guard (write_file)",
|
|
49
49
|
"LOOP_GUARD": "Anti-Stuck Loop Guard",
|
|
50
50
|
"HISTORY_FOLD": "Multi-turn History Fold",
|
|
51
|
-
"COMMAND_OUTPUT": "Terminal Log Sanitizer"
|
|
51
|
+
"COMMAND_OUTPUT": "Terminal Log Sanitizer",
|
|
52
|
+
"TOOL_OUTPUT_COMPACT": "PostToolUse Stdout Compact",
|
|
53
|
+
"TOOL_LEDGER": "Tool Result Ledger (proxy)",
|
|
54
|
+
"TOOL_PRUNE": "Cold Tool Pruning (proxy)",
|
|
55
|
+
"TOOL_PRUNE_MISS": "Tool Prune Miss (quality watch)",
|
|
56
|
+
"EPOCH_ROLLOVER": "Epoch Rollover (80% window)"
|
|
52
57
|
}
|
|
53
58
|
|
|
54
59
|
class Dashboard:
|
|
@@ -83,10 +88,10 @@ class Dashboard:
|
|
|
83
88
|
q_pct = min(100.0, (monthly_saved / limit * 100.0))
|
|
84
89
|
if monthly_saved >= limit:
|
|
85
90
|
out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {RED}{BOLD}500k Monthly Measured Quota Reached ({monthly_saved:,}/{limit:,}){RESET}")
|
|
86
|
-
out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Pro optimizations paused · Upgrade: tokensafe activate <key> | {CYAN}https://tokensafe.dev
|
|
91
|
+
out.append(f" {BOLD}Quota Usage:{RESET} {RED}{render_bar(q_pct)}{RESET} (Pro optimizations paused · Upgrade: tokensafe activate <key> | {CYAN}https://tokensafe.dev/signup{RESET})")
|
|
87
92
|
else:
|
|
88
93
|
out.append(f" {BOLD}Subscription Tier:{RESET} {YELLOW}COMMUNITY (Free){RESET} • {monthly_saved:,} / {limit:,} measured tokens this month")
|
|
89
|
-
out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited)")
|
|
94
|
+
out.append(f" {BOLD}Quota Usage:{RESET} {YELLOW}{render_bar(q_pct)}{RESET} (Upgrade to Solo for Unlimited · {CYAN}https://tokensafe.dev/signup{RESET})")
|
|
90
95
|
else:
|
|
91
96
|
email_info = f" ({payload.get('email', '')})" if payload.get('email') else ""
|
|
92
97
|
out.append(f" {BOLD}Subscription Tier:{RESET} {GREEN}{BOLD}{tier_upper} (Unlimited){RESET}{email_info}")
|
|
@@ -95,6 +100,8 @@ class Dashboard:
|
|
|
95
100
|
out.append(f" {BOLD}Total Tokens Saved:{RESET} {GREEN}{BOLD}{total_saved:,}{RESET} tokens")
|
|
96
101
|
out.append(f" {BOLD}Efficiency Gain:{RESET} {YELLOW}{BOLD}{render_bar(pct)}{RESET}")
|
|
97
102
|
out.append(f" {BOLD}Estimated Savings:{RESET} {GREEN}≈${usd:.4f} USD{RESET} {DIM}(derived: tokens × $1.5/M — approximation, not a bill){RESET}")
|
|
103
|
+
weekly = self.tracker.get_weekly_saved()
|
|
104
|
+
out.append(f" {BOLD}This Week:{RESET} {GREEN}{BOLD}{weekly['saved_tokens']:,}{RESET} tokens saved across {weekly['events']:,} events (≈${weekly['usd_saved']:.2f})")
|
|
98
105
|
|
|
99
106
|
# Per-agent breakdown (honest Cumulative Total across ALL agents)
|
|
100
107
|
by_agent = summary.get("by_agent") or {}
|
|
@@ -109,6 +116,21 @@ class Dashboard:
|
|
|
109
116
|
out.append("")
|
|
110
117
|
out.append(f" {BOLD}Context Traffic:{RESET} {orig:,} raw ➔ {opt:,} optimized ({events_count} events)\n")
|
|
111
118
|
|
|
119
|
+
# Egress economy (v3.0.0): output tokens cost ~4x input — surfaced apart
|
|
120
|
+
breakdown_early = summary.get("breakdown", {})
|
|
121
|
+
og = breakdown_early.get("OUTPUT_GUARD") or {}
|
|
122
|
+
tl = breakdown_early.get("TOOL_LEDGER") or {}
|
|
123
|
+
tp = breakdown_early.get("TOOL_PRUNE") or {}
|
|
124
|
+
if og.get("count") or tl.get("count") or tp.get("count"):
|
|
125
|
+
out.append(f"{BOLD}── Egress Economy (output ≈4× input price) ──────────────────────────{RESET}")
|
|
126
|
+
if og.get("count"):
|
|
127
|
+
out.append(f" • {BOLD}{'Full-file writes steered to Edit':<34}{RESET} : {GREEN}{og['saved']:,} output tokens{RESET} ({og['count']} events)")
|
|
128
|
+
if tl.get("count"):
|
|
129
|
+
out.append(f" • {BOLD}{'Aged tool results folded (proxy)':<34}{RESET} : {GREEN}{tl['saved']:,} input tokens{RESET} ({tl['count']} events)")
|
|
130
|
+
if tp.get("count"):
|
|
131
|
+
out.append(f" • {BOLD}{'Cold MCP tools pruned (proxy)':<34}{RESET} : {GREEN}{tp['saved']:,} floor tokens{RESET} ({tp['count']} events)")
|
|
132
|
+
out.append("")
|
|
133
|
+
|
|
112
134
|
# Breakdown by category
|
|
113
135
|
out.append(f"{BOLD}── Breakdown by Source ──────────────────────────────────────────────{RESET}")
|
|
114
136
|
breakdown = summary.get("breakdown", {})
|
|
@@ -255,7 +277,7 @@ class Dashboard:
|
|
|
255
277
|
<div>
|
|
256
278
|
<strong style="color: #eab308;">⚡ Community Edition:</strong> {monthly_saved:,} / {limit:,} free measured tokens saved this month ({q_pct}%).
|
|
257
279
|
</div>
|
|
258
|
-
<a href="https://tokensafe.dev
|
|
280
|
+
<a href="https://tokensafe.dev/signup" target="_blank" style="background: #10b981; color: #090a0f; font-weight: 700; padding: 6px 14px; border-radius: 8px; text-decoration: none; font-size: 12px;">Upgrade to Solo (Unlimited)</a>
|
|
259
281
|
</div>
|
|
260
282
|
"""
|
|
261
283
|
else:
|
package/src/distiller.py
CHANGED
|
@@ -109,10 +109,13 @@ Rules:
|
|
|
109
109
|
return os.environ.get("TOKENSAFE_SELF_HOSTED", "").lower() in ("1", "true", "yes")
|
|
110
110
|
|
|
111
111
|
@classmethod
|
|
112
|
-
def _call_cloud_distill(cls, raw_text: str, lic_key: str) -> Optional[str]:
|
|
112
|
+
def _call_cloud_distill(cls, raw_text: str, lic_key: str, mode: str = "") -> Optional[str]:
|
|
113
113
|
cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
|
|
114
114
|
endpoint = f"{cloud_url}/api/distill"
|
|
115
115
|
payload = {"prompt": raw_text.strip()}
|
|
116
|
+
if mode:
|
|
117
|
+
payload["mode"] = mode
|
|
118
|
+
timeout = cls.HISTORY_DISTILL_TIMEOUT if mode == "history" else cls.DEFAULT_TIMEOUT
|
|
116
119
|
req = urllib.request.Request(
|
|
117
120
|
endpoint,
|
|
118
121
|
data=json.dumps(payload).encode("utf-8"),
|
|
@@ -123,7 +126,7 @@ Rules:
|
|
|
123
126
|
}
|
|
124
127
|
)
|
|
125
128
|
try:
|
|
126
|
-
with urllib.request.urlopen(req, timeout=
|
|
129
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
127
130
|
if resp.status == 200:
|
|
128
131
|
data = json.loads(resp.read().decode("utf-8"))
|
|
129
132
|
if data.get("success") and data.get("distilled"):
|
|
@@ -132,6 +135,42 @@ Rules:
|
|
|
132
135
|
return None
|
|
133
136
|
return None
|
|
134
137
|
|
|
138
|
+
HISTORY_DISTILL_TIMEOUT = 8.0
|
|
139
|
+
|
|
140
|
+
@classmethod
|
|
141
|
+
def distill_history(cls, raw_text: str) -> Optional[str]:
|
|
142
|
+
"""
|
|
143
|
+
Managed-cloud history summarization for the Tool Result Ledger (v3.0.0):
|
|
144
|
+
compresses an aged tool-result segment into a terse state ledger.
|
|
145
|
+
Paid license required (free tier = hard-off per the distiller contract);
|
|
146
|
+
managed cloud only — self-hosted BYOK keeps the mechanical fold.
|
|
147
|
+
Shares the failure-cooldown breaker with prompt distillation.
|
|
148
|
+
"""
|
|
149
|
+
if not raw_text or len(raw_text.strip()) < 50:
|
|
150
|
+
return None
|
|
151
|
+
if cls._cooldown_active():
|
|
152
|
+
return None
|
|
153
|
+
cache_key_text = "HIST:" + raw_text[:4000]
|
|
154
|
+
cached = DistillationCache.get(cache_key_text)
|
|
155
|
+
if cached:
|
|
156
|
+
return cached
|
|
157
|
+
tier, _ = LicenseManager.get_active_license()
|
|
158
|
+
if tier == "free":
|
|
159
|
+
return None
|
|
160
|
+
providers = cls.get_configured_providers()
|
|
161
|
+
if "cloud" not in providers:
|
|
162
|
+
return None # self-hosted BYOK: mechanical fold stays the contract
|
|
163
|
+
lic_key = LicenseManager.get_active_license_key()
|
|
164
|
+
if not lic_key:
|
|
165
|
+
return None
|
|
166
|
+
cloud_res = cls._call_cloud_distill(raw_text, lic_key, mode="history")
|
|
167
|
+
if cloud_res:
|
|
168
|
+
DistillationCache.set(cache_key_text, cloud_res, provider="cloud-managed")
|
|
169
|
+
cls._clear_failure()
|
|
170
|
+
return cloud_res
|
|
171
|
+
cls._record_failure()
|
|
172
|
+
return None
|
|
173
|
+
|
|
135
174
|
@classmethod
|
|
136
175
|
def get_configured_providers(cls) -> Dict[str, Dict[str, Any]]:
|
|
137
176
|
"""Scans environment and data/config.json for configured LLM distillation keys."""
|
package/src/governor.py
CHANGED
package/src/guard.py
CHANGED
|
@@ -603,8 +603,3 @@ class TokenSafeGuard:
|
|
|
603
603
|
if "/" not in clean_pattern and rel_path.startswith(clean_pattern + "/"):
|
|
604
604
|
return True
|
|
605
605
|
return False
|
|
606
|
-
|
|
607
|
-
@classmethod
|
|
608
|
-
def _is_git_ignored(cls, file_path: str, repo_root: str) -> bool:
|
|
609
|
-
"""Checks if a file is covered by .gitignore in the repository."""
|
|
610
|
-
return cls._matches_gitignore(file_path, repo_root, cls._load_gitignore_patterns(repo_root))
|