tokensafe 4.16.2 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +8 -3
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2429
  26. package/src/mcp_server.py +11 -5024
  27. package/src/proxy.py +11 -1803
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +42 -17
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +68 -9
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +769 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/tokensafe/ingress_staging.py +384 -0
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5664 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/tokensafe/read_baseline.py +192 -0
  100. package/tokensafe/repo_compute.py +332 -0
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
package/src/cli.py CHANGED
@@ -1,2432 +1,14 @@
1
- #!/usr/bin/env python3
2
- """
3
- TokenSafe Unified CLI Dispatcher.
4
- Used by:
5
- - npm CLI (`bin/tokensafe.js`)
6
- - standalone executable (`bin/tokensafe`)
7
- - PyPI console script entrypoint (`tokensafe` via `pyproject.toml`)
8
- """
9
-
10
- import sys
1
+ """Legacy launcher: forwards to ``tokensafe.cli`` (see src/__init__.py)."""
11
2
  import os
12
- import shutil
13
- import subprocess
14
- from typing import Optional, List, Dict, Any
15
-
16
- SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
17
- PROJECT_ROOT = os.path.dirname(SCRIPT_DIR)
18
- if PROJECT_ROOT not in sys.path:
19
- sys.path.insert(0, PROJECT_ROOT)
20
-
21
- from src.metrics import MetricsTracker
22
- from src.dashboard import Dashboard, render_bar
23
- from src.compactor import PromptCompactor
24
- from src.tokenizer import count_tokens
25
- from src import oumv_policy
26
-
27
- def summarize_unittest_output(raw: str, full_traceback: bool = False) -> str:
28
- """Compacts `python3 -m unittest discover` output to what a developer
29
- actually needs: one green line, or per-failure test name + root cause.
30
- Keeps the suite run out of the context window (the raw output of a
31
- 300+ test run with tracebacks is thousands of tokens)."""
32
- lines = raw.splitlines()
33
- ran = status = ""
34
- for ln in lines:
35
- s = ln.strip()
36
- if s.startswith("Ran ") and " test" in s:
37
- ran = s
38
- elif s.startswith("OK") or s.startswith("FAILED"):
39
- # "OK (skipped=N)" must count as success too, not just bare "OK".
40
- status = s
41
- # Failure blocks: one '=' * 70 line PER failure, then the title line,
42
- # a '-' * 70 rule and the traceback — each block is self-contained.
43
- blocks, cur = [], None
44
- for ln in lines:
45
- if len(ln) >= 10 and set(ln) == {"="}:
46
- if cur is not None:
47
- blocks.append(cur)
48
- cur = []
49
- continue
50
- if cur is not None:
51
- cur.append(ln)
52
- if cur is not None:
53
- blocks.append(cur)
54
-
55
- failures = []
56
- for block in blocks:
57
- title_idx = next((j for j, l in enumerate(block) if l.startswith(("FAIL: ", "ERROR: "))), None)
58
- if title_idx is None:
59
- continue
60
- title = block[title_idx]
61
- body = [l for l in block[title_idx + 1:]
62
- if not (len(l) >= 10 and set(l) == {"-"})
63
- and not l.strip().startswith(("Ran ", "FAILED", "OK"))]
64
- kind, name = title.split(" ", 1)
65
- if full_traceback:
66
- detail = [l.rstrip() for l in body if l.strip()]
67
- else:
68
- loc = next((l.strip() for l in reversed(body) if l.strip().startswith('File "')), "")
69
- cause_lines = [l.strip() for l in reversed(body)
70
- if l.strip() and not l.strip().startswith('File "')
71
- and not l.strip().startswith(("self.", "assert", "raise"))]
72
- # assertEqual-style failures end with a diff block ('- a' / '+ b');
73
- # the actual AssertionError line sits above it.
74
- cause = next((l for l in cause_lines if not l.startswith(("+", "-", "?", "!"))),
75
- cause_lines[0] if cause_lines else "")
76
- if len(cause) > 200:
77
- cause = cause[:200] + " …"
78
- detail = [l for l in (loc, cause) if l]
79
- failures.append((kind.rstrip(": "), name, detail))
80
-
81
- if not ran and not failures:
82
- # Crash before unittest could report (import error, bad path):
83
- # fall back to the tail, which carries the exception.
84
- tail = [l for l in lines if l.strip()][-15:]
85
- return "\n".join(tail) if tail else "(no unittest output captured)"
86
-
87
- if status.startswith("OK"):
88
- return f"\033[32m✓ {ran} — all tests passed\033[0m"
89
-
90
- out = [f"\033[31m✗ {ran} — {status}\033[0m"]
91
- for kind, name, detail in failures:
92
- out.append(f" \033[31m{kind}\033[0m {name}")
93
- for d in detail:
94
- out.append(f" {d}")
95
- out.append("Full output: python3 -m unittest discover tests (or: tokensafe tests --traceback)")
96
- return "\n".join(out)
97
-
98
-
99
- def _print_help():
100
- print("TokenSafe CLI — usage: tokensafe <command> [args]\n")
101
- print("Commands:")
102
- print(" dev [dir] [--port N] [--host H] [--open] Start Vite+React DevServer with OUMV (zero repo footprint)")
103
- print(" integrate [--dry-run] Retrofit OUMV into existing project (React, Vue, FastAPI, Go)")
104
- print(" inject [status|apply|revert] Auto-wire adapters with zero repo footprint (add --dry-run)")
105
- print(" adapters [list] Catalog of frontend/backend OUMV runtime adapters")
106
- print(" oumv doctor / status Diagnose OUMV configuration, ports, and permissions")
107
- print(" oumv doctor --prune Remove descriptors with no live OUMV runtime")
108
- print(" create <name> [--template ...] Greenfield project scaffolder (tokensafe-ui + tokensafe-backend)")
109
- print(" init [--template ...] Initialize TokenSafe stack in current directory")
110
- print(" stats / markdown / html Savings analytics (terminal / .md report / dashboard)")
111
- print(" savings [--json] Canonical totals + last event (cite these numbers, never guess)")
112
- print(" usage [--json] [--session ID] Per-session context report: peak, host compactions, cache-miss events")
113
- print(" recall <query> [--sessions this|project|all] [--json] [--id S:N] BM25 search over prior session transcripts")
114
- print(" statusline Zero-token savings line for the host status bar")
115
- print(" bench-oumv [--target go|react] [--tasks all] [--arms baseline,oumv] [--runs N] [--budget USD] Measured agent benchmark")
116
- print(" dict lint|coverage|show|apply String catalogs: suspect keys only, byte-preserving write-back")
117
- print(" status One-screen health check: hooks, weekly savings, tier, sync")
118
- print(" budget [--transcript=...] Context Window Budget HUD & Context Quality Score (Grade S-F)")
119
- print(" compact <transcript.jsonl> Fold conversation transcript into Consolidated State Ledger")
120
- print(" transcripts [--recent N] Analyze agent transcripts (Antigravity/Claude/Codex)")
121
- print(" [--compare A B] A/B comparison of two session transcripts")
122
- print(" benchmark Zero-context-loss benchmark suite (simulated SWE-bench harness)")
123
- print(" bench --real [--repo=key|--here] Measured benchmark on real repos (zero-loss gates)")
124
- print(" graph / map / skeleton Architecture graph / API surface / AST skeleton of a file")
125
- print(" test <prompt> Preview TOCP S-expression prompt compaction")
126
- print(" guard <command> Pre-flight safety check for a shell command")
127
- print(" expand-ref <hash> Restore folded tool/command/file result by its 8-char hash")
128
- print(" wrap <command> Run command with compact output folding (e.g. tests/logs)")
129
- print(" web <url> Fetch web page/docs and print clean compact Markdown")
130
- print(" doctor [--fix | --cleanup] Audit MCP/skill overhead, repair configs & consolidate ghost rules")
131
- print(" skills [list|disable|enable] Inspect and toggle active skills to cut turn context tax")
132
- print(" tests [pytest] [--traceback] Run the unit test suite (compact failure report)")
133
- print(" prune [--days N | --max N] Compact metrics database (roll old events)")
134
- print(" vacuum Reclaim SQLite disk space")
135
- print(" reset Reset all local token metrics")
136
- print(" install | setup [--all] Configure detected agent environments")
137
- print(" uninstall [--all | --project] Remove TokenSafe from agent environments & unwire proxy")
138
- print(" update | upgrade Self-update npm/PyPI package and re-sync agents")
139
- print(" check-update Check for a newer published version")
140
- print(" activate / license License activation and status")
141
- print(" booster on|off|status Cloud Prompt Booster control (paid tiers)")
142
- print(" login / auth Authorize this device via browser login")
143
- print(" logout / unlink Unlink this device and remove local license")
144
- print(" sync Sync telemetry with the cloud backend")
145
- print(" providers / proxy / mcp Providers info / proxy server / MCP stdio server")
146
- print(" agent [--model M] [-C dir] <prompt> One agent turn in this workspace (streaming tool use)")
147
- print(" acp ACP agent server over stdio (Zed, JetBrains, Neovim, Emacs)")
148
- print(" --version Print version and exit")
149
-
150
-
151
- def _booster_consent_prompt() -> None:
152
- """One-time Cloud Prompt Booster consent after a PAID license activation.
153
-
154
- Asks [Y/n] with an honest data-flow disclosure (default Y). Non-TTY runs
155
- keep the legacy default (on) and print a disable hint instead of blocking.
156
- Users who already chose (config/env) are never re-asked. Fail-open: a
157
- broken TTY never blocks activation.
158
- """
159
- try:
160
- from src.distiller import UniversalDistiller
161
- if UniversalDistiller.is_self_hosted():
162
- return # BYOK self-hosted: own keys are their own explicit opt-in
163
- _enabled, explicitly_set = UniversalDistiller.cloud_booster_enabled()
164
- if explicitly_set:
165
- return
166
- interactive = sys.stdin.isatty() and sys.stdout.isatty()
167
- if interactive:
168
- print("\n \033[1m⚡ Cloud Prompt Booster\033[0m — distills long prompts (100+ tokens) cloud-side,")
169
- print(" ~5x deeper compression than the local engine (measured median 71% vs 14%).")
170
- print(" \033[2mWhat leaves this machine:\033[0m the prompt text (may include code snippets or stack")
171
- print(" \033[2mtraces) with secrets automatically scrubbed. Processed transiently via TokenSafe")
172
- print(" \033[2mCloud (Google Gemini Flash-Lite); raw text is never stored and not used for training.\033[0m")
173
- try:
174
- answer = input(" Enable Cloud Prompt Booster? [Y/n]: ").strip().lower()
175
- except (EOFError, KeyboardInterrupt):
176
- answer = ""
177
- print()
178
- chosen = answer in ("", "y", "yes")
179
- else:
180
- chosen = True # non-interactive: keep the legacy default + hint
181
- UniversalDistiller.write_config_value("cloud_distill", chosen)
182
- if chosen:
183
- suffix = "" if interactive else " \033[2m(default — run \033[36mtokensafe booster off\033[0m \033[2mto disable)\033[0m"
184
- print(f" \033[32m✔ Cloud Prompt Booster enabled.\033[0m{suffix}")
185
- else:
186
- print(" \033[33m○ Cloud Prompt Booster off — all prompt processing stays 100% local.\033[0m")
187
- except Exception:
188
- pass
189
-
190
-
191
- def main(argv: Optional[List[str]] = None):
192
- args = sys.argv[1:] if argv is None else list(argv)
193
- command = args[0] if args else "stats"
194
-
195
- if command in ("--help", "-h", "help"):
196
- _print_help()
197
- return
198
-
199
- # Fast path: version queries must not construct MetricsTracker (which creates
200
- # the data dir and SQLite database). `tokensafe --version` may run in read-only
201
- # or foreign directories and must stay side-effect free.
202
- if command in ("version", "--version", "-v"):
203
- from src.version_checker import CURRENT_VERSION, VersionChecker
204
- print(f"TokenSafe v{CURRENT_VERSION}")
205
- if "--check" in args or "-c" in args:
206
- banner = VersionChecker.get_banner()
207
- if banner:
208
- print(banner)
209
- else:
210
- print("\033[32m✔ TokenSafe is up to date.\033[0m")
211
- if "--notify" in args or "--prompt" in args:
212
- VersionChecker.notify_os_update(force=True)
213
- return
214
-
215
- if command in ("status", "health"):
216
- from src.installer import AgentInstaller
217
- from src.license_manager import LicenseManager
218
- from src.telemetry_sync import TelemetrySync
219
- tracker = MetricsTracker()
220
- print("\n\033[1m\033[36m⚡ TOKENSAFE STATUS ⚡\033[0m\n")
221
- # Hooks wiring (best-effort scan of agent config files and plugin dirs)
222
- active_agents = []
223
- for key, info in AgentInstaller.detect_available_agents().items():
224
- hit = any(info.get(pk) and os.path.exists(info[pk]) for pk in
225
- ("target_path", "plugin_path", "skills_path", "agents_md_path", "rules_path", "extension_path"))
226
- cfg = info.get("config_path")
227
- if not hit and cfg and os.path.exists(cfg):
228
- try:
229
- with open(cfg, "r", encoding="utf-8", errors="replace") as f:
230
- hit = "tokensafe" in f.read().lower()
231
- except Exception:
232
- pass
233
- if hit:
234
- active_agents.append(key)
235
- if active_agents:
236
- print(f" Hooks: \033[32m✔ active\033[0m in {len(active_agents)} agent(s): {', '.join(active_agents)}")
237
- else:
238
- print(" Hooks: \033[33m○ not detected\033[0m — run \033[1mtokensafe install\033[0m to configure your agents")
239
- # Context Quality Health Indicator (S/A/B/C/F)
240
- try:
241
- from src.quality_score import ContextQualityScore
242
- q_score = ContextQualityScore.evaluate(tracker)
243
- color = "\033[32m" if q_score["grade"] in ("S", "A") else ("\033[33m" if q_score["grade"] == "B" else "\033[31m")
244
- tax_str = f"~{q_score['static_tax_tokens']:,} tok/turn" if q_score['static_tax_tokens'] else "0 tok/turn"
245
- print(f" Context: {color}\033[1mGrade {q_score['grade']} ({q_score['label']})\033[0m — {q_score['headroom_pct']:.0f}% headroom (static tax: {tax_str})")
246
- except Exception:
247
- pass
248
- # The value moment: recent measured savings
249
- weekly = tracker.get_weekly_saved()
250
- print(f" This Week: \033[32m\033[1m{weekly['saved_tokens']:,} tokens saved\033[0m across {weekly['events']:,} events (≈${weekly['usd_saved']:.2f})")
251
- # Tier + quota state
252
- tier, payload = LicenseManager.get_active_license()
253
- quota = LicenseManager.check_quota(tracker)
254
- if tier == "guest":
255
- q_saved = int(quota.get("monthly_saved", 0))
256
- q_limit = int(quota.get("monthly_limit") or 50_000)
257
- q_pct = min(100, int(q_saved / q_limit * 100)) if q_limit else 0
258
- q_state = "\033[31mQUOTA REACHED (Optimizers paused)\033[0m" if quota.get("is_quota_exceeded") else f"{q_pct}% of monthly guest limit"
259
- print(f" Tier: \033[33mGUEST (Offline)\033[0m — {q_saved:,} / {q_limit:,} tokens ({q_state})")
260
- print(" Unlock 500k: Run \033[36mtokensafe login\033[0m for free Community account & Web Dashboard")
261
- elif tier == "free":
262
- q_saved = int(quota.get("monthly_saved", 0))
263
- q_limit = int(quota.get("monthly_limit") or 500_000)
264
- q_pct = min(100, int(q_saved / q_limit * 100)) if q_limit else 0
265
- q_state = "\033[31mQUOTA REACHED — Pro optimizations paused\033[0m" if quota.get("is_quota_exceeded") else f"{q_pct}% of monthly measured quota"
266
- print(f" Tier: \033[33mCOMMUNITY (Free Account)\033[0m — {q_saved:,} / {q_limit:,} tokens ({q_state})")
267
- print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo · 7-Day Team Trial)")
268
- else:
269
- print(f" Tier: \033[32m{tier.upper()}\033[0m (Unlimited)")
270
- try:
271
- from src.distiller import UniversalDistiller
272
- enabled, explicitly_set = UniversalDistiller.cloud_booster_enabled(tier)
273
- state = "\033[32mon\033[0m" if enabled else "\033[33moff\033[0m"
274
- if not explicitly_set:
275
- state += " \033[2m(active by default — choose: \033[36mtokensafe booster on|off\033[0m\033[2m)\033[0m"
276
- print(f" Booster: Cloud Prompt Booster {state}")
277
- except Exception:
278
- pass
279
- profile, _sextant_tier = oumv_policy.current()
280
- if profile == oumv_policy.PROFILE_READ_ONLY:
281
- print(f" Sextant: \033[33mread-only\033[0m (observe everywhere; change/verify on Solo+)")
282
- else:
283
- print(f" Sextant: \033[32mfull\033[0m (change and verify the running app)")
284
- # Verifiable egress transparency: what left this machine today
285
- try:
286
- from src.egress_counter import today_counts
287
- _eg = today_counts()
288
- print(f" Egress: today — {_eg['booster']} booster · {_eg['telemetry']} telemetry outbound requests")
289
- except Exception:
290
- pass
291
- # Cloud heartbeat (non-blocking; keeps the machine visible server-side)
292
- try:
293
- TelemetrySync.sync_background()
294
- pending = int(TelemetrySync.get_sync_status().get("pending_events", 0) or 0)
295
- if pending:
296
- print(f" Cloud: {pending:,} events queued for telemetry sync (background)")
297
- else:
298
- print(" Cloud: \033[32m✔ telemetry up to date\033[0m")
299
- except Exception:
300
- pass
301
- # Distillation cache visibility (get_stats existed but was never surfaced anywhere)
302
- try:
303
- from src.distiller_cache import DistillationCache
304
- cstats = DistillationCache.get_stats()
305
- lookups = cstats["hits"] + cstats["misses"]
306
- if lookups:
307
- 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)")
308
- except Exception:
309
- pass
310
- print()
311
-
312
- elif command in ("budget", "quality", "score"):
313
- from src.governor import ContextBudget
314
- from src.quality_score import ContextQualityScore
315
- from src.environment_auditor import EnvironmentAuditor
316
- tracker = MetricsTracker()
317
- model = args[1] if len(args) > 1 and not args[1].startswith("-") else ""
318
- transcript = ""
319
- for a in args[1:]:
320
- if a.startswith("--transcript="):
321
- transcript = a.split("=", 1)[1]
322
- elif a.endswith(".jsonl"):
323
- transcript = a
324
- budget = ContextBudget.estimate(tracker, session_id="mcp_session", model=model, transcript_path=transcript)
325
- audit = EnvironmentAuditor.audit()
326
- q_score = ContextQualityScore.calculate(budget=budget, audit=audit)
327
-
328
- color = "\033[32m" if q_score["grade"] in ("S", "A") else ("\033[33m" if q_score["grade"] == "B" else "\033[31m")
329
- print("\n\033[1m\033[36m⚡ TOKENSAFE CONTEXT QUALITY & BUDGET HUD ⚡\033[0m\n")
330
- print(f" Health Grade: {color}\033[1mGrade {q_score['grade']} ({q_score['label']})\033[0m — {q_score['score']}/100 pts")
331
- print(f" Window Headroom: {color}{q_score['headroom_pct']:.1f}% free\033[0m ({budget['used_estimated']:,} / {budget['window_tokens']:,} tokens estimated)")
332
- print(f" Static Tax: ~{q_score['static_tax_tokens']:,} tokens on every API turn")
333
- print(f" Breakdown: tools: {budget['breakdown']['tools']:,} | history: {budget['breakdown']['history']:,} | prompts: {budget['breakdown']['prompts']:,}")
334
- if q_score["deductions"]:
335
- print(f" Deductions: {', '.join(q_score['deductions'])}")
336
- print(f" Recommendation: {budget['recommendation']}\n")
337
-
338
- elif command in ("compact", "fold"):
339
- if len(args) < 2:
340
- print("Usage: tokensafe compact <path_to_transcript.jsonl>")
341
- sys.exit(1)
342
- transcript_path = args[1].strip()
343
- from src.history_compactor import HistoryCompactor
344
- ledger, orig_t, fold_t, stats = HistoryCompactor.fold_transcript(transcript_path, invocation_num=3)
345
- if not ledger:
346
- print("\n\033[33m○ Transcript not compactable (requires >= 4 steps and >= 1,000 history tokens).\033[0m\n")
347
- sys.exit(0)
348
- print("\n\033[1m\033[36m⚡ TOKENSAFE COMPACT CONVERSATION ⚡\033[0m\n")
349
- print(f" Original history: {orig_t:,} tokens")
350
- print(f" Compacted ledger: {fold_t:,} tokens")
351
- print(f" Tokens saved: \033[32m\033[1m+{orig_t - fold_t:,} tokens\033[0m\n")
352
- print(ledger)
353
- print()
354
-
355
- elif command in ("savings", "saved"):
356
- # Canonical, machine-readable savings numbers. Agents must cite this
357
- # command instead of guessing (see the footer rule in AGENTS.md).
358
- from src.savings import build_savings_report
359
-
360
- report = build_savings_report()
361
- if "--json" in args:
362
- import json as _json
363
- print(_json.dumps(report, indent=2, ensure_ascii=False))
364
- else:
365
- last = report.get("last_event") or {}
366
- print("\n\033[1m\033[36m⚡ TOKENSAFE SAVINGS (canonical) ⚡\033[0m\n")
367
- print(f" Data dir: {report['data_dir']}")
368
- print(f" Events / sessions: {report['total_events']} / {report['sessions']}")
369
- print(f" Saved (live): {report['saved_tokens_live']:,} tokens")
370
- print(f" Synced to cloud: {report['pruned_synced_saved_tokens']:,} tokens (subset of live)")
371
- print(f" Cumulative: {report['cumulative_saved_tokens']:,} tokens")
372
- if last:
373
- print(f" Last event: {last.get('event_type')} — {last.get('saved_tokens'):,} tokens at {last.get('timestamp')}")
374
- print()
375
-
376
- elif command == "statusline":
377
- from src.statusline import render_statusline
378
- line = render_statusline()
379
- if line:
380
- print(line)
381
-
382
- elif command in ("recall", "transcript-recall"):
383
- query, scope, turn_id = "", "project", ""
384
- since = until = transcript_path = ""
385
- limit = 10
386
- as_json = "--json" in args
387
- idx = 1
388
- while idx < len(args):
389
- arg = args[idx]
390
- value = ""
391
- key = arg
392
- if arg.startswith("--") and "=" in arg:
393
- key, value = arg.split("=", 1)
394
- if key in ("--sessions", "--scope") and not value and idx + 1 < len(args):
395
- value = args[idx + 1]
396
- idx += 1
397
- if key in ("--limit",) and not value and idx + 1 < len(args):
398
- value = args[idx + 1]
399
- idx += 1
400
- if key in ("--since", "--until", "--transcript", "--id") and not value and idx + 1 < len(args):
401
- value = args[idx + 1]
402
- idx += 1
403
- if key in ("--sessions", "--scope"):
404
- scope = value or scope
405
- elif key == "--limit":
406
- try:
407
- limit = int(value)
408
- except ValueError:
409
- pass
410
- elif key == "--since":
411
- since = value
412
- elif key == "--until":
413
- until = value
414
- elif key == "--transcript":
415
- transcript_path = value
416
- elif key == "--id":
417
- turn_id = value
418
- elif not arg.startswith("-") and not query:
419
- query = arg
420
- idx += 1
421
- from src.transcript_recall import drill_down, search
422
- session_id = os.environ.get("TOKENSAFE_SESSION_ID", "")
423
- if turn_id:
424
- result = drill_down(
425
- turn_id,
426
- scope="all",
427
- cwd=os.getcwd(),
428
- session_id=session_id,
429
- transcript_path=transcript_path,
430
- )
431
- else:
432
- result = search(
433
- query=query,
434
- scope=scope,
435
- cwd=os.getcwd(),
436
- session_id=session_id,
437
- transcript_path=transcript_path,
438
- since=since,
439
- until=until,
440
- limit=limit,
441
- )
442
- if as_json:
443
- import json as _json
444
- print(_json.dumps(result, indent=2, ensure_ascii=False))
445
- else:
446
- print(result.get("text") or result.get("reason") or "(no results)")
447
-
448
- elif command in ("usage", "output"):
449
- # MetricsTracker is imported at module level on purpose: a function-local
450
- # import would shadow it for the whole main() and break earlier branches
451
- # (see the check-update note above).
452
- tracker = MetricsTracker()
453
- if "--backfill" in args:
454
- from src.usage_ledger import backfill_from_transcripts
455
- bf = backfill_from_transcripts(tracker=tracker)
456
- if "--json" not in args:
457
- print(f"\n Backfill: {bf['updated']} session(s) updated, {bf['skipped']} skipped · by agent {bf['by_agent']}")
458
- if "--calibrate" in args:
459
- from src.usage_ledger import compute_output_budgets, write_output_budgets
460
- cal = compute_output_budgets(tracker=tracker)
461
- written = write_output_budgets(cal) if "--write" in args else ""
462
- if "--json" in args:
463
- import json as _json
464
- print(_json.dumps({**cal, "written": written or None}, indent=2, ensure_ascii=False))
465
- else:
466
- print("\n\033[1m\033[36m⚡ OUTPUT BUDGET CALIBRATION (p90 output/call) ⚡\033[0m\n")
467
- for agent, stats in (cal.get("agents") or {}).items():
468
- print(f" {agent:<14} sessions={stats['sessions']:<4} p50={stats['p50']:<8} p90={stats['p90']:<8} budget={stats['budget']}")
469
- print(f"\n Default: {cal['default']}" + (f" · written: {written}" if written else "") + "\n")
470
- return
471
- session_filter = ""
472
- for i, a in enumerate(args):
473
- if a.startswith("--session="):
474
- session_filter = a.split("=", 1)[1]
475
- elif a == "--session" and i + 1 < len(args):
476
- session_filter = str(args[i + 1])
477
- if session_filter:
478
- row = tracker.get_usage_session(session_filter)
479
- if "--json" in args:
480
- import json as _json
481
- print(_json.dumps({"source": "transcript-ledger", "session": row}, indent=2, ensure_ascii=False))
482
- elif not row:
483
- print(f"\n\033[33m○ No usage recorded for session {session_filter}.\033[0m\n")
484
- sys.exit(0)
485
- else:
486
- out = int(row.get("output_tokens") or 0)
487
- turns = int(row.get("llm_turns") or 0)
488
- tools = int(row.get("tool_calls") or 0)
489
- reason = int(row.get("reasoning_chars") or 0)
490
- vis = int(row.get("visible_chars") or 0)
491
- share = round(reason / (reason + vis) * 100, 1) if (reason + vis) else None
492
- print("\n\033[1m\033[36m⚡ TOKENSAFE OUTPUT USAGE (measured) ⚡\033[0m\n")
493
- print(f" Session: {row['session_id']} ({row.get('source')})")
494
- print(f" Model: {row.get('model') or 'unknown'}")
495
- print(f" Output tokens: {out:,}")
496
- print(f" Model calls / tools: {turns:,} / {tools:,}")
497
- peak = int(row.get("peak_context_tokens") or 0)
498
- last_ctx = int(row.get("last_context_tokens") or 0)
499
- comps = int(row.get("compactions") or 0)
500
- miss = int(row.get("miss_tokens") or 0)
501
- miss_events = int(row.get("miss_events") or 0)
502
- cache_read = int(row.get("cache_read_tokens") or 0)
503
- total_in = int(row.get("input_tokens") or 0)
504
- cache_pct = round(cache_read / total_in * 100, 1) if total_in else None
505
- cache_label = f"{cache_pct}%" if cache_pct is not None else "unknown"
506
- print(f" Context: last {last_ctx:,} · peak {peak:,} · compactions {comps}")
507
- print(f" Cache: read {cache_read:,} ({cache_label}) · miss {miss:,} · miss events {miss_events}")
508
- print(f" Output / call: {round(out / turns, 1) if turns else 'unknown'}")
509
- print(f" Output / tool call: {round(out / tools, 1) if tools else 'unknown'}")
510
- print(f" Reasoning share: {f'{share}%' if share is not None else 'unknown'}\n")
511
- else:
512
- u = tracker.get_usage_summary()
513
- if "--json" in args:
514
- import json as _json
515
- print(_json.dumps({"source": "transcript-ledger", **u}, indent=2, ensure_ascii=False))
516
- else:
517
- print("\n\033[1m\033[36m⚡ TOKENSAFE OUTPUT USAGE (measured) ⚡\033[0m\n")
518
- print(f" Sessions: {u['sessions']} ({u['measured_sessions']} measured / {u['steps_only_sessions']} steps-only)")
519
- if u["measured_sessions"]:
520
- print(f" Output tokens: {u['output_tokens']:,}")
521
- print(f" Model calls: {u['llm_turns']:,}")
522
- print(f" Output / call: {u['output_per_call']}")
523
- print(f" Tool calls: {u['tool_calls']:,}")
524
- print(f" Output / tool call: {u['output_per_tool_call']}")
525
- print(f" Reasoning share: {u['reasoning_share_pct']}%")
526
- top = u.get("top") or []
527
- if top:
528
- print("\n Top sessions:")
529
- for r in top[:5]:
530
- print(f" • {r['session_id'][:18]:<18} {int(r.get('output_tokens') or 0):>12,} output")
531
- else:
532
- print(" No measured output yet — the Stop-hook ledger fills on the next session turn.")
533
- print()
534
-
535
- elif command in ("stats", "dashboard"):
536
- tracker = MetricsTracker()
537
- dashboard = Dashboard(tracker)
538
- try:
539
- from src.telemetry_sync import TelemetrySync
540
- TelemetrySync.sync_background()
541
- except Exception:
542
- pass
543
- print(dashboard.render_terminal())
544
-
545
- elif command in ("html", "dashboard-html"):
546
- from src.paths import resolve_data_dir
547
- tracker = MetricsTracker()
548
- dashboard = Dashboard(tracker)
549
- html_content = dashboard.render_html()
550
- out_path = os.path.join(resolve_data_dir(), "dashboard.html")
551
- os.makedirs(os.path.dirname(out_path), exist_ok=True)
552
- with open(out_path, "w", encoding="utf-8") as f:
553
- f.write(html_content)
554
- print(f"\n⚡ Interactive HTML Dashboard generated at: {out_path}")
555
- try:
556
- if sys.platform == "darwin":
557
- subprocess.run(["open", out_path], check=False)
558
- elif os.name == "nt":
559
- os.startfile(out_path) # type: ignore[attr-defined]
560
- else:
561
- subprocess.run(["xdg-open", out_path], check=False)
562
- print(" Opened in default browser.")
563
- except Exception:
564
- try:
565
- import webbrowser
566
- webbrowser.open(f"file://{os.path.abspath(out_path)}")
567
- except Exception:
568
- pass
569
-
570
- elif command in ("benchmark", "bench"):
571
- if "--real" in args:
572
- # Measured real-repo mode: pre-registered scenarios (src/bench_scenarios.json),
573
- # zero-loss gates, real clones — see src/benchmark_real.py methodology header.
574
- # --here: measure the CURRENT repository instead (god-node hot symbols,
575
- # suite as-is without mutation — self-measurement, not the published set).
576
- from src.benchmark_real import RealRepoBenchmark
577
- bench = RealRepoBenchmark()
578
- if "--here" in args:
579
- print("\n⚡ Running REAL-REPO benchmark on the CURRENT repository (measured, zero-loss gates)...")
580
- data = bench.run_local(os.getcwd())
581
- else:
582
- repo_keys = [a.split("=", 1)[1] for a in args if a.startswith("--repo=")]
583
- print("\n⚡ Running REAL-REPO benchmark (measured on live clones, pre-registered scenarios)...")
584
- data = bench.run_all(repo_keys or None)
585
- print()
586
- print(bench.render_markdown(data))
587
- out = bench.export(data)
588
- print(f"📊 JSON: {out['json']}")
589
- print(f"📊 MD: {out['md']}\n")
590
- sys.exit(0 if all(
591
- (s.get("status") in ("ok", "skipped"))
592
- for r in data["results"] for s in (r.get("symbol_read"), r.get("test_output"), r.get("multiturn"))
593
- if s
594
- ) else 1)
595
- from src.benchmark import BenchmarkSuite
596
- from src.paths import resolve_data_dir
597
- print("\n⚡ Running Zero-Loss SWE-bench Benchmark Suite across real-world scenarios...")
598
- data = BenchmarkSuite.run_all()
599
- print(BenchmarkSuite.render_report(data))
600
- out_md = os.path.join(resolve_data_dir(), "BENCHMARK_REPORT.md")
601
- BenchmarkSuite.export_markdown_report(data, out_md)
602
- print(f"📊 Publication-ready markdown report saved to: {out_md}\n")
603
-
604
- elif command in ("setup", "install"):
605
- from src.installer import AgentInstaller
606
- if "--all" in args or "-a" in args or "-y" in args or "--auto" in args:
607
- print("\n\033[1m\033[36m⚡ TOKENSAFE UNIVERSAL MULTI-AGENT INSTALLER (--all) ⚡\033[0m\n")
608
- res = AgentInstaller.install_all(force=True)
609
- print("Configured AI agent environments:")
610
- for k, r in res["agents"].items():
611
- status = "\033[32m✔\033[0m" if r["success"] else "\033[31m✖\033[0m"
612
- print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
613
- print(f"\n\033[32m✔ Universal project rules injected into: {', '.join(res['project_rules'])}\033[0m\n")
614
- # Proxy default-on is asserted INSIDE install_all (_ensure_proxy_default);
615
- # the retired interactive prompt must never be referenced here again.
616
- elif "--project" in args:
617
- agents_plugin = None
618
- if "--agents-plugin" in args:
619
- idx = args.index("--agents-plugin")
620
- if idx + 1 < len(args):
621
- agents_plugin = args[idx + 1]
622
- res = AgentInstaller.install_project(os.getcwd(), agents_plugin_path=agents_plugin)
623
- print(f"\n\033[32m✔ TokenSafe rules injected into project: {', '.join(res['created_rules'])}\033[0m\n")
624
- elif "--refresh" in args or "--sync-installed" in args:
625
- res = AgentInstaller.refresh_installed_agents()
626
- print(f"\n\033[32m✔ Synchronized {res['synced_count']} installed/configured agent environment(s).\033[0m\n")
627
- else:
628
- AgentInstaller.run_interactive()
629
-
630
- elif command in ("uninstall", "unistall", "remove", "unlink-all"):
631
- from src.installer import AgentInstaller
632
- purge = "--purge" in args
633
- if "--all" in args or "-a" in args or "-y" in args or "--auto" in args:
634
- print("\n\033[1m\033[36m⚡ TOKENSAFE UNIVERSAL MULTI-AGENT UNINSTALLER (--all) ⚡\033[0m\n")
635
- res = AgentInstaller.uninstall_all(force=True, purge=purge)
636
- print("Uninstalled AI agent configurations:")
637
- for k, r in res["agents"].items():
638
- status = "\033[32m✔\033[0m" if r["success"] else "\033[33m–\033[0m"
639
- print(f" {status} \033[1m{r['name']:<28}\033[0m: {r['message']}")
640
- if res.get("project_rules"):
641
- print(f"\n\033[32m✔ Project rules cleaned from: {', '.join(res['project_rules'])}\033[0m")
642
- if res.get("proxy"):
643
- print(f" \033[32m✔\033[0m Proxy daemon stopped and routing restored")
644
- if purge:
645
- print(f" \033[32m✔\033[0m Local data directory purged (~/.tokensafe)")
646
- print("\n\033[32m✔ TokenSafe uninstallation complete.\033[0m\n")
647
- elif "--project" in args:
648
- res = AgentInstaller.uninstall_project(os.getcwd())
649
- cleaned = res.get("cleaned_rules", [])
650
- msg = f"TokenSafe rules cleaned from project: {', '.join(cleaned)}" if cleaned else "No TokenSafe rules found in project workspace"
651
- print(f"\n\033[32m✔ {msg}\033[0m\n")
652
- else:
653
- AgentInstaller.run_interactive_uninstall()
654
-
655
- elif command in ("update", "upgrade"):
656
- from src.installer import AgentInstaller
657
- AgentInstaller.self_update()
658
-
659
- elif command in ("check-update", "check_update"):
660
- from src.version_checker import CURRENT_VERSION, VersionChecker
661
- print(f"\n\033[1m\033[36m⚡ CHECKING FOR TOKENSAFE UPDATES ⚡\033[0m\n")
662
- print(f" Current version: v{CURRENT_VERSION}")
663
- info = VersionChecker.check_version(force_fetch=True)
664
- latest = info.get("latest_version", CURRENT_VERSION)
665
- avail = info.get("update_available", False)
666
- print(f" Latest version: v{latest}")
667
- try:
668
- from src.license_manager import LicenseManager
669
- tier, lic = LicenseManager.get_active_license()
670
- if tier == "guest":
671
- # NOTE: no function-local MetricsTracker import here — it would
672
- # shadow the module-level import (L20) for the WHOLE main()
673
- # and crash `tokensafe status` with UnboundLocalError.
674
- quota = LicenseManager.check_quota(MetricsTracker())
675
- saved = int(quota.get("monthly_saved", 0))
676
- pct = min(100.0, (saved / 50_000) * 100) if 50_000 > 0 else 0.0
677
- print(f" \033[2mQuota:\033[0m \033[33mGuest Mode\033[0m ({saved:,} / 50,000 tokens used, {pct:.1f}%) • Run '\033[36mtokensafe login\033[0m' for 500k/mo.")
678
- except Exception:
679
- pass
680
- banner = VersionChecker.get_banner()
681
- if banner:
682
- print(banner)
683
- else:
684
- print("\n \033[32m✔ TokenSafe is up to date.\033[0m\n")
685
- if avail or "--notify" in args or "--prompt" in args or "-p" in args:
686
- print(" \033[36mTriggering native OS update dialog...\033[0m")
687
- VersionChecker.notify_os_update(force=True)
688
-
689
- elif command in ("guard", "security"):
690
- from src.guard import TokenSafeGuard
691
- sub = args[1] if len(args) > 1 else "help"
692
- if sub in ("audit", "scan"):
693
- target_path = args[2] if len(args) > 2 else os.getcwd()
694
- if not os.path.exists(target_path):
695
- print(f"\n\033[31m✖ Target path not found: {target_path}\033[0m\n")
696
- sys.exit(1)
697
- print(f"\n\033[1m\033[36m🛡️ TOKENSAFE SECURITY & HYGIENE AUDIT 🛡️\033[0m")
698
- print(f" Target: {target_path}\n")
699
- violations = []
700
- files_scanned = 0
701
- code_exts = (".py", ".ts", ".tsx", ".js", ".jsx", ".go", ".rs", ".java")
702
- if os.path.isfile(target_path):
703
- files_scanned = 1
704
- try:
705
- with open(target_path, "r", encoding="utf-8", errors="replace") as fp:
706
- content = fp.read()
707
- res = TokenSafeGuard.inspect_file_write(target_path, content)
708
- if res.blocked:
709
- violations.append((os.path.basename(target_path), res.check_name, res.reason))
710
- except Exception:
711
- pass
712
- else:
713
- for root, dirs, files in os.walk(target_path):
714
- dirs[:] = [d for d in dirs if d not in (".git", "node_modules", "dist", "build", ".next", ".venv", "venv", "__pycache__")]
715
- for f in files:
716
- if f.endswith(code_exts):
717
- files_scanned += 1
718
- full_p = os.path.join(root, f)
719
- try:
720
- with open(full_p, "r", encoding="utf-8", errors="replace") as fp:
721
- content = fp.read()
722
- res = TokenSafeGuard.inspect_file_write(full_p, content)
723
- if res.blocked:
724
- rel_p = os.path.relpath(full_p, target_path)
725
- violations.append((rel_p, res.check_name, res.reason))
726
- except Exception:
727
- pass
728
- if not violations:
729
- print(f" \033[32m✔ All {files_scanned} files passed TokenSafe Guard audit cleanly! Zero secret fallbacks or SQLi.\033[0m\n")
730
- else:
731
- print(f" \033[31m✖ Found {len(violations)} security violations in {files_scanned} files:\033[0m\n")
732
- for rel_p, check, reason in violations:
733
- print(f" \033[31m• [{check}]\033[0m {rel_p}: {reason}")
734
- print()
735
- elif sub in ("check", "test") and len(args) > 2:
736
- cmd_to_test = " ".join(args[2:])
737
- print(f"\n\033[1m\033[36m🛡️ TOKENSAFE COMMAND GUARD CHECK 🛡️\033[0m\n")
738
- print(f" Command: \033[1m{cmd_to_test}\033[0m")
739
- res = TokenSafeGuard.inspect_command(cmd_to_test)
740
- if res.blocked:
741
- print(f" Status: \033[31m\033[1mBLOCKED\033[0m [{res.check_name}]")
742
- print(f" Reason: {res.reason}\n")
743
- elif res.warning_only:
744
- print(f" Status: \033[33m\033[1mWARNING\033[0m [{res.check_name}]")
745
- print(f" Notice: {res.reason}\n")
746
- else:
747
- print(f" Status: \033[32m\033[1mALLOWED\033[0m (Command is safe and policy-compliant)\n")
748
- elif sub not in ("help", "--help", "-h", "check", "test") and len(args) > 1:
749
- cmd_to_test = " ".join(args[1:])
750
- print(f"\n\033[1m\033[36m🛡️ TOKENSAFE COMMAND GUARD CHECK 🛡️\033[0m\n")
751
- print(f" Command: \033[1m{cmd_to_test}\033[0m")
752
- res = TokenSafeGuard.inspect_command(cmd_to_test)
753
- if res.blocked:
754
- print(f" Status: \033[31m\033[1mBLOCKED\033[0m [{res.check_name}]")
755
- print(f" Reason: {res.reason}\n")
756
- elif res.warning_only:
757
- print(f" Status: \033[33m\033[1mWARNING\033[0m [{res.check_name}]")
758
- print(f" Notice: {res.reason}\n")
759
- else:
760
- print(f" Status: \033[32m\033[1mALLOWED\033[0m (Command is safe and policy-compliant)\n")
761
- else:
762
- print("\nUsage:")
763
- print(" tokensafe guard \"<command>\" Audit a terminal command line")
764
- print(" tokensafe guard check \"<command>\" Audit a terminal command line")
765
- print(" tokensafe guard audit [path] Recursively audit source files for secrets & vulnerabilities\n")
766
-
767
- elif command in ("create", "new"):
768
- from src.scaffold import ProjectScaffolder
769
- project_name = None
770
- template = "fullstack"
771
- force = False
772
-
773
- if "--list" in args:
774
- print("\nAvailable recipes:")
775
- print(" react-fastapi React 18 + Vite + FastAPI (recommended)")
776
- print(" react-go React 18 + Vite + Go/Gin")
777
- print(" vue-gin Vue 3 + Vite + Go/Gin")
778
- print(" react / vue frontend only (OUMV via `tokensafe dev`)")
779
- print(" fastapi / gin backend only (auto-mount)")
780
- print(" backend, ui, fullstack legacy TokenSafe-native templates\n")
781
- return
782
-
783
- i = 1
784
- while i < len(args):
785
- arg = args[i]
786
- if arg in ("--help", "-h"):
787
- print("\n⚡ TokenSafe Project Scaffolder\n")
788
- print("Usage:")
789
- print(" tokensafe create <project-name> [options]\n")
790
- print("Options:")
791
- print(" --template <type> recipe or stack:")
792
- print(" react-fastapi (recommended), react-go, vue-gin,")
793
- print(" react, vue, fastapi, gin, backend, ui, fullstack")
794
- print(" --force, -f Overwrite existing files")
795
- print(" --help, -h Show this help screen\n")
796
- print("Examples:")
797
- print(" tokensafe create my-app")
798
- print(" tokensafe create my-dashboard --template ui")
799
- print(" tokensafe create store-api --template fastapi")
800
- print(" tokensafe create shop --template react-fastapi")
801
- print(" tokensafe create edge-api --template gin\n")
802
- return
803
- elif arg in ("--template", "-t") and i + 1 < len(args):
804
- template = args[i + 1]
805
- i += 2
806
- continue
807
- elif arg.startswith("--template="):
808
- template = arg.split("=", 1)[1]
809
- elif arg in ("--force", "-f"):
810
- force = True
811
- elif not arg.startswith("-") and project_name is None:
812
- project_name = arg
813
- i += 1
814
-
815
- if not project_name:
816
- print("\n❌ Error: Project name is required.")
817
- print("Usage: tokensafe create <project-name> [--template fullstack|ui|backend]\n")
818
- return
819
-
820
- target_dir = os.path.abspath(project_name)
821
- try:
822
- res = ProjectScaffolder.scaffold(
823
- target_dir=target_dir,
824
- project_name=project_name,
825
- template=template,
826
- force=force,
827
- )
828
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE GREENFIELD SCAFFOLDER ⚡\033[0m\n")
829
- print(f" ✔ Created project: \033[1m{res['project_name']}\033[0m")
830
- print(f" ✔ Template: \033[32m{res['template']}\033[0m")
831
- print(f" ✔ Location: {res['target_dir']}")
832
- print(f" ✔ Files created: {len(res['created_files'])}\n")
833
- print("Next steps:")
834
- print(f" cd {project_name}")
835
- if template in ("fullstack", "ui"):
836
- sub = "frontend" if template == "fullstack" else "."
837
- print(f" cd {sub} && npm install && npm run dev")
838
- if template in ("fullstack", "backend", "python", "fastapi"):
839
- sub = "backend" if template == "fullstack" else "."
840
- print(f" cd {sub} && pip install -e . && python main.py")
841
- print("\n OUMV runtime and agent directives are pre-configured out-of-the-box.\n")
842
- except Exception as e:
843
- print(f"\n❌ Scaffolding failed: {e}\n")
844
-
845
- elif command == "init":
846
- from src.scaffold import ProjectScaffolder
847
- template = "fullstack"
848
- force = False
849
-
850
- i = 1
851
- while i < len(args):
852
- arg = args[i]
853
- if arg in ("--help", "-h"):
854
- print("\n⚡ TokenSafe Project Initializer\n")
855
- print("Usage:")
856
- print(" tokensafe init [options]\n")
857
- print("Options:")
858
- print(" --template <type> recipe or stack:")
859
- print(" react-fastapi (recommended), react-go, vue-gin,")
860
- print(" react, vue, fastapi, gin, backend, ui, fullstack")
861
- print(" --force, -f Overwrite existing files\n")
862
- return
863
- elif arg in ("--template", "-t") and i + 1 < len(args):
864
- template = args[i + 1]
865
- i += 2
866
- continue
867
- elif arg.startswith("--template="):
868
- template = arg.split("=", 1)[1]
869
- elif arg in ("--force", "-f"):
870
- force = True
871
- i += 1
872
-
873
- cwd = os.getcwd()
874
- project_name = os.path.basename(cwd)
875
- try:
876
- res = ProjectScaffolder.scaffold(
877
- target_dir=cwd,
878
- project_name=project_name,
879
- template=template,
880
- force=force,
881
- )
882
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE PROJECT INITIALIZED ⚡\033[0m\n")
883
- print(f" ✔ Initialized: \033[1m{res['project_name']}\033[0m")
884
- print(f" ✔ Template: \033[32m{res['template']}\033[0m")
885
- print(f" ✔ Files created: {len(res['created_files'])}\n")
886
- except Exception as e:
887
- print(f"\n❌ Initialization failed: {e}\n")
888
-
889
- elif command in ("integrate", "retrofit"):
890
- import json
891
- from src.retrofit import detect_project_stack, generate_config
892
- dry_run = "--dry-run" in args
893
- force = "--force" in args or "-f" in args
894
- cwd = os.getcwd()
895
-
896
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV RETROFIT INTEGRATION ⚡\033[0m\n")
897
- stack = detect_project_stack(cwd)
898
- fe = stack.get("frontend")
899
- be = stack.get("backend")
900
-
901
- print(f" Workspace: {cwd}")
902
- print(f" Frontend: \033[32m{fe['framework']} ({fe['provider']})\033[0m" if fe else " Frontend: \033[33mNone detected\033[0m")
903
- print(f" Backend: \033[32m{be['framework']} ({be['provider']})\033[0m" if be else " Backend: \033[33mNone detected\033[0m")
904
- print(f" Manifests: {', '.join(stack.get('detected_files', [])) or 'None'}\n")
905
-
906
- cfg, conf_file, created = generate_config(cwd, stack, dry_run=dry_run, force=force)
907
- if dry_run:
908
- print(f" \033[33m[DRY-RUN]\033[0m Proposed configuration (.tokensafe/oumv.json):")
909
- print(json.dumps(cfg, indent=4))
910
- elif not conf_file:
911
- print(" ○ No OUMV profile detected: nothing to configure (no .tokensafe/oumv.json written)\n")
912
- elif created:
913
- mutate_enabled = cfg.get("permissions", {}).get("mutate", True)
914
- policy = (
915
- "\033[32menabled out-of-the-box (OCC + syntax guard + backups)\033[0m"
916
- if mutate_enabled
917
- else "\033[33mread-only (mutate: false)\033[0m"
918
- )
919
- print(f" ✔ Generated OUMV config: \033[1m{conf_file}\033[0m")
920
- print(f" ✔ Mutation policy: {policy}")
921
- print(f" ✔ Profiles enabled: {', '.join(cfg.get('oumv', {}).get('profiles', []))}")
922
- print("\n Project is now retrofitted for OUMV. AI coding agents can inspect components and endpoints.\n")
923
- else:
924
- print(f" ✔ Existing configuration preserved: \033[1m{conf_file}\033[0m (use --force to overwrite)\n")
925
-
926
- elif command in ("run-backend", "run_backend"):
927
- # Executes the user's dev-server command. Python/uvicorn gets the OUMV
928
- # autoload hook from ~/.tokensafe; Java/PHP/Node sidecars run as-is (they
929
- # mount the runtime themselves and write their own descriptor).
930
- from src.auto_inject import backend_env, ensure_python_autoload
931
-
932
- argv_rest = [a for a in args[1:]]
933
- if not argv_rest:
934
- print(
935
- "usage: tokensafe run-backend <command...>\n"
936
- " tokensafe run-backend uvicorn app:app --reload\n"
937
- " tokensafe run-backend java OumvSpring.java --root . --port 7331\n"
938
- " tokensafe run-backend php -S 127.0.0.1:7332 oumv-php --root ."
939
- )
940
- return
941
- tool = argv_rest[0]
942
- resolved = shutil.which(tool)
943
- if not resolved:
944
- print(f"tokensafe run-backend: `{tool}` not found on PATH")
945
- return
946
- if os.path.basename(tool) in ("java", "php", "node", "npm", "npx"):
947
- print(f"⚡ Launching {os.path.basename(tool)} with the Sextant runtime")
948
- # Go/Node/.NET and the PHP sidecar read the env; Java takes the CLI
949
- # flag, which `sidecar_run_command` already appends.
950
- os.execvpe(resolved, argv_rest, oumv_policy.spawn_env())
951
- ensure_python_autoload()
952
- env = backend_env()
953
- os.execvpe(resolved, argv_rest, env)
954
-
955
- elif command in ("inject", "wire"):
956
- from src import auto_inject
957
-
958
- if "--status" in args:
959
- sub = "status"
960
- elif "--revert" in args:
961
- sub = "revert"
962
- else:
963
- positional = [a for a in args[1:] if not a.startswith("-")]
964
- sub = positional[0] if positional and positional[0] in ("status", "apply", "revert") else "apply"
965
- dry_run = "--dry-run" in args
966
- workspace = os.getcwd()
967
-
968
- if sub == "status":
969
- data = auto_inject.plan(workspace)
970
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV INJECT PLAN ⚡\033[0m\n")
971
- print(f" Profiles: {', '.join(data['profiles']) or 'none detected'}")
972
- for action in data["actions"]:
973
- writes = "writes repo" if action["writes_repo"] else "zero repo footprint"
974
- app = action.get("app")
975
- where = f" [{app}]" if app not in (None, ".", "") else ""
976
- status = f" ({action['status']})" if action.get("status") else ""
977
- print(f" - {action['kind']:<24} {action['profile']:<9}{where} {writes}{status}")
978
- if action.get("entrypoint"):
979
- print(f" entrypoint: {action['entrypoint']} (patched: {action.get('already_patched')})")
980
- if action.get("install"):
981
- print(f" install: {action['install']}")
982
- if action.get("run"):
983
- print(f" run: {action['run']}")
984
- middleware = action.get("middleware") or {}
985
- if middleware:
986
- files = ", ".join(middleware.get("files") or []) or "-"
987
- print(f" middleware: {middleware.get('status')} ({files})")
988
- if action.get("reason"):
989
- print(f" reason: {action['reason']}")
990
- if action.get("snippet"):
991
- print(" snippet:")
992
- for line in action["snippet"].splitlines():
993
- print(f" {line}")
994
- print(f" Python autoload: {'✔ installed' if data['python_autoload_present'] else '○ not installed'}")
995
- print(f" Revertable: {'✔ yes' if data['revertable'] else '○ no'}\n")
996
- elif sub == "revert":
997
- result = auto_inject.revert(workspace)
998
- for key, value in result.items():
999
- if key == "workspace" or not isinstance(value, dict):
1000
- continue
1001
- print(f" {key}: {value.get('status', '?')}")
1002
- if value.get("entrypoint"):
1003
- print(f" entrypoint: {value['entrypoint']}")
1004
- if value.get("removed"):
1005
- print(f" removed: {', '.join(value['removed'])}")
1006
- if value.get("restored"):
1007
- print(f" restored: {', '.join(value['restored'])}")
1008
- if value.get("modules"):
1009
- for module in value["modules"]:
1010
- print(f" module: {module.get('path')} ({module.get('status')})")
1011
- if value.get("project"):
1012
- print(f" project: {value['project']}")
1013
- if value.get("kept"):
1014
- for kept in value["kept"]:
1015
- print(f" kept: {kept.get('path')} ({kept.get('reason')})")
1016
- if value.get("reason"):
1017
- print(f" reason: {value['reason']}")
1018
- else:
1019
- result = auto_inject.apply(workspace, dry_run=dry_run, include_go=True)
1020
- prefix = "[DRY-RUN] " if dry_run else ""
1021
- cfg = result.get("config", {})
1022
- if cfg.get("skipped"):
1023
- print(f"\n{prefix}OUMV config: not written ({cfg['skipped']})")
1024
- else:
1025
- print(f"\n{prefix}OUMV config: {cfg.get('path')} ({'created' if cfg.get('created') else 'preserved'}), mutate={cfg.get('mutate')}")
1026
- for action in result.get("actions", []):
1027
- status = action.get("status", "?")
1028
- app = action.get("app")
1029
- where = f" [{app}]" if app not in (None, ".", "") else ""
1030
- print(f" {prefix}{action['kind']}{where}: {status}")
1031
- middleware = action.get("middleware") or {}
1032
- if middleware:
1033
- files = ", ".join(middleware.get("files") or []) or "-"
1034
- print(f" middleware: {middleware.get('status')} ({files})")
1035
- if action.get("run"):
1036
- print(f" run: {action['run']}")
1037
- if action.get("reason"):
1038
- print(f" reason: {action['reason']}")
1039
- if action.get("snippet"):
1040
- print(" snippet:")
1041
- for line in action["snippet"].splitlines():
1042
- print(f" {line}")
1043
- print()
1044
-
1045
- elif command in ("adapters", "adapter"):
1046
- from src.retrofit import get_adapters_catalog
1047
- catalog = get_adapters_catalog()
1048
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV ADAPTERS CATALOG ⚡\033[0m\n")
1049
- print(f" {'ADAPTER ID':<20} {'PROFILE':<10} {'REPO':<26} {'STATUS':<10}")
1050
- print(" " + "-" * 70)
1051
- for a in catalog:
1052
- color = "\033[32m" if a["status"] == "ready" else "\033[33m"
1053
- print(f" {a['id']:<20} {a['profile']:<10} {a['repo']:<26} {color}{a['status']:<10}\033[0m")
1054
- print("\n Run \033[1mtokensafe integrate\033[0m in any project to auto-detect and configure compatible adapters.\n")
1055
-
1056
- elif command == "oumv":
1057
- sub = args[1] if len(args) > 1 else "status"
1058
- # A session may hold several repos: `oumv status --workspace_dir <repo>`
1059
- # must answer for that repo, not for the process cwd. The routing brief
1060
- # and the apply_edits nudge both point at this form.
1061
- workspace_dir = ""
1062
- for i, arg in enumerate(args):
1063
- if arg in ("--workspace_dir", "--workspace-dir") and i + 1 < len(args):
1064
- workspace_dir = str(args[i + 1])
1065
- elif arg.startswith(("--workspace_dir=", "--workspace-dir=")):
1066
- workspace_dir = arg.split("=", 1)[1]
1067
- workspace = os.path.abspath(os.path.expanduser(workspace_dir)) if workspace_dir else os.getcwd()
1068
- if sub in ("doctor", "audit"):
1069
- from src.retrofit import run_doctor
1070
- if "--prune" in args[2:]:
1071
- from src.oumv_gateway import OUMVGateway
1072
- from src.context_index import ContextIndex
1073
- from src.skeletonizer import Skeletonizer
1074
- from src.result_ledger import prune_archives
1075
- removed = OUMVGateway.prune_stale_descriptors(os.getcwd())
1076
- if removed:
1077
- print("removed stale OUMV descriptors:")
1078
- for path in removed:
1079
- print(f" - {path}")
1080
- else:
1081
- print("no stale OUMV descriptors to remove")
1082
- index_stats = ContextIndex.prune()
1083
- print(
1084
- f"pruned context indexes: {index_stats['removed']} "
1085
- f"({index_stats['freed_bytes'] // 1024} KB freed); "
1086
- f"skeletons: {Skeletonizer.prune()}; "
1087
- f"ledger archives: {prune_archives()}"
1088
- )
1089
- return
1090
- doc = run_doctor(workspace)
1091
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV DOCTOR ⚡\033[0m\n")
1092
- print(f" Config (.tokensafe/oumv.json): {'✔ Present' if doc['config_present'] else '○ Not found (run tokensafe integrate)'}")
1093
- print(f" Runtime Beacon (.tokensafe/...): {'✔ Active' if doc['runtime_beacon_present'] else '○ Offline (DevServer not running)'}")
1094
- fe = doc['detected_stack'].get('frontend')
1095
- be = doc['detected_stack'].get('backend')
1096
- print(f" Detected Frontend: {fe['framework'] if fe else 'None'}")
1097
- print(f" Detected Backend: {be['framework'] if be else 'None'}")
1098
- mut = doc['permissions'].get('mutate', True)
1099
- print(f" Mutation Permission: {'✔ Enabled (out-of-the-box, guarded)' if mut else '○ Read-only (mutate: false)'}")
1100
- for profile, item in (doc.get('adapter_readiness') or {}).items():
1101
- state = "✔ ready" if item["ready"] else "○ not ready"
1102
- live = " (live)" if item["live"] else ""
1103
- print(f" Adapter {profile:<10} {state}{live}: {item['provider']}/{item['framework']} — {item['evidence']}")
1104
- print(f" Ready for agent: {'✔ yes' if doc.get('ready_for_agent') else '○ no'}")
1105
- for reason in doc.get('blocking') or []:
1106
- print(f" - {reason}")
1107
- print()
1108
- else:
1109
- from src.oumv_gateway import OUMVGateway
1110
- status = OUMVGateway.status(workspace_dir=workspace)
1111
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE OUMV RUNTIME STATUS ⚡\033[0m\n")
1112
- print(f" Frontend Runtime: {status['frontend'].get('status', 'OK')} ({status['frontend'].get('name', 'N/A')})")
1113
- print(f" Backend Runtime: {status['backend'].get('status', 'OK')} ({status['backend'].get('name', 'N/A')})")
1114
- print(f" Workspace: {status.get('workspace')}\n")
1115
-
1116
- elif command == "dev":
1117
- from src.retrofit import detect_project_stack, resolve_zero_footprint_vite_command
1118
-
1119
- if "--help" in args or "-h" in args:
1120
- print(
1121
- "\n tokensafe dev [path] [--port N] [--host H] [--open]\n"
1122
- " [--framework react|vue|solid|angular]\n"
1123
- "\n Starts the app's own Vite dev server with the tokensafe-ui OUMV bridge and\n"
1124
- " leaves the repository untouched. Needs a Vite frontend: React, Vue, Solid,\n"
1125
- " or Angular through @analogjs/vite-plugin-angular. Run it in the app directory.\n"
1126
- )
1127
- return
1128
- target_dir = os.getcwd()
1129
- port_val: Optional[int] = None
1130
- host_val: Optional[str] = None
1131
- framework_val: Optional[str] = None
1132
- open_browser = False
1133
- unknown_flags: List[str] = []
1134
- i = 1
1135
- while i < len(args):
1136
- a = args[i]
1137
- nxt = args[i + 1] if i + 1 < len(args) else None
1138
- if a.startswith("--port="):
1139
- try:
1140
- port_val = int(a.split("=", 1)[1])
1141
- except ValueError:
1142
- pass
1143
- elif a == "--port":
1144
- if nxt is not None:
1145
- try:
1146
- port_val = int(nxt)
1147
- i += 1
1148
- except ValueError:
1149
- unknown_flags.append(a)
1150
- else:
1151
- unknown_flags.append(a)
1152
- elif a.startswith("--host="):
1153
- host_val = a.split("=", 1)[1]
1154
- elif a == "--host":
1155
- if nxt is not None and not nxt.startswith("-"):
1156
- host_val = nxt
1157
- i += 1
1158
- else:
1159
- host_val = "true"
1160
- elif a == "--open":
1161
- open_browser = True
1162
- elif a.startswith("--framework="):
1163
- framework_val = a.split("=", 1)[1].strip().lower()
1164
- elif a == "--framework":
1165
- if nxt is not None and not nxt.startswith("-"):
1166
- framework_val = nxt.strip().lower()
1167
- i += 1
1168
- else:
1169
- unknown_flags.append(a)
1170
- elif a.startswith("-"):
1171
- unknown_flags.append(a)
1172
- else:
1173
- target_dir = os.path.abspath(a)
1174
- i += 1
1175
- if unknown_flags:
1176
- print(f"⚠ Ignoring unsupported 'tokensafe dev' flag(s): {' '.join(unknown_flags)}")
1177
- supported_frameworks = ("react", "vue", "solid", "angular")
1178
- if framework_val is not None and framework_val not in supported_frameworks:
1179
- print(
1180
- f"✗ --framework {framework_val} is not served by `tokensafe dev`: "
1181
- f"choose one of {', '.join(supported_frameworks)}."
1182
- )
1183
- sys.exit(2)
1184
- # `tokensafe dev` cannot invent a frontend: without a Vite app the server
1185
- # would serve an empty directory. Refuse with the reason and the nearest
1186
- # frontend path instead of failing inside Vite.
1187
- stack = detect_project_stack(target_dir)
1188
- frontend = stack.get("frontend") or {}
1189
- if not frontend:
1190
- nested = [
1191
- pkg.get("path")
1192
- for pkg in (stack.get("packages") or [])
1193
- if pkg.get("vite") and pkg.get("path") not in (None, ".")
1194
- ]
1195
- hint = f"\n A Vite frontend lives in {nested[0]} — run `tokensafe dev` there." if nested else ""
1196
- print(
1197
- f"✗ No Vite frontend in {target_dir}. `tokensafe dev` starts the app's own Vite\n"
1198
- f" dev server (React, Vue, Solid, or Angular with @analogjs/vite-plugin-angular).{hint}"
1199
- )
1200
- sys.exit(1)
1201
- if frontend.get("vite") and not frontend.get("oumv_supported", True):
1202
- note = frontend.get("note") or f"status: {frontend.get('status')}"
1203
- print(f"✗ {frontend.get('framework')} detected, but the OUMV dev bridge is not available: {note}")
1204
- sys.exit(1)
1205
- if framework_val is not None:
1206
- detected_framework = str(frontend.get("framework") or "")
1207
- if detected_framework and detected_framework != framework_val:
1208
- print(
1209
- f"✗ --framework {framework_val} does not match the detected frontend "
1210
- f"({detected_framework}). `tokensafe dev` serves the app's own Vite frontend;\n"
1211
- " run it without --framework."
1212
- )
1213
- sys.exit(2)
1214
- # In a monorepo the frontend is a nested package: run the server there,
1215
- # not at the root that has no index.html.
1216
- frontend_root = frontend.get("root")
1217
- if frontend_root and frontend_root != ".":
1218
- nested_dir = os.path.abspath(os.path.join(target_dir, frontend_root))
1219
- if os.path.isdir(nested_dir):
1220
- print(f"⚡ Using the {frontend.get('framework')} Vite frontend at {frontend_root}")
1221
- target_dir = nested_dir
1222
- cmd, source = resolve_zero_footprint_vite_command(
1223
- target_dir, port=port_val, host=host_val, open_browser=open_browser
1224
- )
1225
- print(f"⚡ Launching Zero-Footprint Vite OUMV server ({source})...")
1226
- # The Vite bridge is a process-start profile: a free license must never
1227
- # advertise write methods the engine would refuse anyway.
1228
- proc = subprocess.run(cmd, cwd=target_dir, env=oumv_policy.spawn_env())
1229
- sys.exit(proc.returncode)
1230
-
1231
- elif command in ("dict", "i18n"):
1232
- # Deterministic string-catalog audit: lint suspects only, write back
1233
- # without reformatting. Replaces "read 18 catalog files per locale".
1234
- from src import i18n_catalog as _dict
1235
-
1236
- def _dflag(name: str, default: str = "") -> str:
1237
- for i, arg in enumerate(args):
1238
- if arg == name and i + 1 < len(args):
1239
- return args[i + 1]
1240
- if arg.startswith(name + "="):
1241
- return arg.split("=", 1)[1]
1242
- return default
1243
-
1244
- sub = args[1] if len(args) > 1 and not args[1].startswith("-") else ""
1245
- if not sub or sub in ("help", "--help", "-h"):
1246
- print(
1247
- "\n tokensafe dict lint --locale ru [--base en] [--severity high|all] [--limit N] [--json]"
1248
- "\n tokensafe dict coverage [--base en] [--json]"
1249
- "\n tokensafe dict show --locale ru --keys a.b,c.d [--json]"
1250
- "\n tokensafe dict apply --locale ru --patch patch.json [--dry-run]"
1251
- "\n"
1252
- "\n Lint lists only suspect keys — untranslated, missing, orphan, placeholder"
1253
- "\n drift, English leakage, brand loss, length outliers, calque smells."
1254
- "\n apply writes values back in place: formatting, comments and key order"
1255
- "\n are preserved byte-for-byte. --root picks the project (default: cwd).\n"
1256
- )
1257
- return
1258
-
1259
- root = _dflag("--root") or os.getcwd()
1260
- messages_dir = _dict.resolve_messages_dir(root)
1261
- if not messages_dir:
1262
- print(f"\n no message catalog found under {root}\n pass --root <project>\n")
1263
- sys.exit(1)
1264
- flags = {
1265
- "locale": _dflag("--locale") or _dflag("--l"),
1266
- "base": _dflag("--base", "en"),
1267
- "keys": _dflag("--keys"),
1268
- "patch": _dflag("--patch"),
1269
- "severity": _dflag("--severity", "all"),
1270
- "limit": _dflag("--limit", "0"),
1271
- "dry_run": "1" if "--dry-run" in args else _dflag("--dry-run"),
1272
- }
1273
- try:
1274
- text, payload = _dict.run_command(messages_dir, sub, flags)
1275
- except (ValueError, json.JSONDecodeError) as exc:
1276
- print(f"\n dict {sub}: {exc}\n")
1277
- sys.exit(1)
1278
- if "--json" in args:
1279
- print(json.dumps(payload, indent=2, ensure_ascii=False))
1280
- else:
1281
- print(text)
1282
-
1283
- elif command in ("bench-oumv", "bench_oumv"):
1284
- # Measured, agent-driven benchmark (DeepSeek by default): real oracle,
1285
- # provider-side token accounting, hard budget cap.
1286
- from src.bench import go_target, react_target
1287
- from src.bench.runner import render_markdown, run_matrix, run_react_matrix, write_artifacts
1288
-
1289
- def _flag(name: str, default: str) -> str:
1290
- for i, arg in enumerate(args):
1291
- if arg == name and i + 1 < len(args):
1292
- return args[i + 1]
1293
- if arg.startswith(name + "="):
1294
- return arg.split("=", 1)[1]
1295
- return default
1296
-
1297
- if "--help" in args or "-h" in args:
1298
- print(
1299
- "\n tokensafe bench-oumv [--target go|react] [--tasks all|id,id] [--arms baseline,oumv] "
1300
- "[--runs N] [--budget USD] [--model NAME] [--max-steps N] [--dry-run] [--mechanics] [--json]\n"
1301
- "\n Measured agent run against DeepSeek with a hard USD cap. --dry-run prints the\n"
1302
- " matrix and the pricing without calling the provider. --mechanics measures the\n"
1303
- " runtime itself (payload sizes, verification latency, guard rejections), no model.\n"
1304
- )
1305
- return
1306
-
1307
- if "--mechanics" in args:
1308
- # Deterministic runtime measurements: no provider call, no API key.
1309
- from src.bench import mechanics
1310
-
1311
- results = mechanics.run()
1312
- if "--json" in args:
1313
- import json as _json
1314
- print(_json.dumps(results, indent=2, ensure_ascii=False))
1315
- else:
1316
- print(mechanics.render_markdown(results))
1317
- return
1318
-
1319
- target = _flag("--target", "go")
1320
- catalogue = react_target.TASKS if target == "react" else go_target.TASKS
1321
- tasks_arg = _flag("--tasks", "all")
1322
- task_ids = list(catalogue) if tasks_arg == "all" else [t.strip() for t in tasks_arg.split(",") if t.strip()]
1323
- arms = [a.strip() for a in _flag("--arms", "baseline,oumv").split(",") if a.strip()]
1324
- runs = int(_flag("--runs", "1"))
1325
- budget = float(_flag("--budget", "1.0"))
1326
- model = _flag("--model", "deepseek-chat")
1327
- max_steps = int(_flag("--max-steps", "14"))
1328
- files = int(_flag("--files", "0"))
1329
-
1330
- if "--dry-run" in args:
1331
- from src.bench.driver import PRICES
1332
-
1333
- sessions = len(task_ids) * len(arms) * runs
1334
- print(f"\n dry run: {target} · tasks={task_ids} · arms={arms} · runs={runs} → {sessions} sessions"
1335
- + (f" · sandbox_files={files} (generated)" if files and target == "go" else ""))
1336
- print(f" model={model} prices={PRICES.get(model)} budget=${budget}")
1337
- print(" no provider call was made\n")
1338
- return
1339
-
1340
- print(f"\n⚡ OUMV bench ({target}): tasks={task_ids} runs={runs} model={model} budget=${budget}"
1341
- + (f" sandbox_files={files}" if files and target == "go" else "") + "\n")
1342
- if target == "react":
1343
- report = run_react_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget)
1344
- else:
1345
- report = run_matrix(task_ids, arms, runs=runs, model=model, max_steps=max_steps, budget_usd=budget,
1346
- files=files)
1347
- paths = write_artifacts(report)
1348
- if "--json" in args:
1349
- import json as _json
1350
- print(_json.dumps(report, indent=2, ensure_ascii=False))
1351
- else:
1352
- print(render_markdown(report))
1353
- print(f"artifacts: {paths['markdown']}\n {paths['json']}\n")
1354
-
1355
- elif command in ("burn", "burn-monitor"):
1356
- from src.burn_monitor import collect_live_burn_snapshot, evaluate_burn_warnings, is_zai_peak_hour
1357
- from src.transcript_analyzer import discover_transcript_paths, analyze_transcript, render_transcripts_report
1358
- agent_filter = "auto"
1359
- for i, a in enumerate(args):
1360
- if a.startswith("--agent="):
1361
- agent_filter = a.split("=", 1)[1]
1362
- elif a in ("--agent", "-a") and i + 1 < len(args):
1363
- agent_filter = args[i + 1]
1364
- print("\n\033[1m\033[36m🔥 TOKENSAFE MULTI-AGENT LIVE BURN MONITOR 🔥\033[0m\n")
1365
- print(f" Z.ai Peak Hours (Mon-Fri 14:00-18:00 SST): {'ACTIVE (1.0x = 2x off-peak)' if is_zai_peak_hour() else 'OFF-PEAK (0.5x rate)'}")
1366
- found = discover_transcript_paths(agent=agent_filter, limit=8)
1367
- if not found:
1368
- print(" No active session transcripts/rollouts found.\n")
1369
- sys.exit(0)
1370
- analyzed = [analyze_transcript(fp, agent_type=ag_type) for ag_type, fp, _ in found]
1371
- print(render_transcripts_report(analyzed))
1372
- for ag in ("zcode", "claude_code", "antigravity"):
1373
- if agent_filter not in ("auto", ag):
1374
- continue
1375
- snap = collect_live_burn_snapshot(agent=ag)
1376
- if snap:
1377
- warns = evaluate_burn_warnings(snap)
1378
- if warns:
1379
- print(f" [{ag}] Active session alerts:")
1380
- for w in warns:
1381
- print(f" • {w['message']}")
1382
- sys.exit(0)
1383
-
1384
- elif command in ("transcripts", "transcript"):
1385
- from src.transcript_analyzer import (
1386
- discover_transcript_paths,
1387
- analyze_transcript,
1388
- compare_transcripts,
1389
- render_transcripts_report,
1390
- render_comparison_report
1391
- )
1392
- if "--compare" in args:
1393
- c_idx = args.index("--compare")
1394
- if len(args) < c_idx + 3:
1395
- print("Usage: tokensafe transcripts --compare <before.jsonl> <after.jsonl>")
1396
- sys.exit(1)
1397
- before_f = args[c_idx + 1]
1398
- after_f = args[c_idx + 2]
1399
- res = compare_transcripts(before_f, after_f)
1400
- print(render_comparison_report(res))
1401
- sys.exit(0)
1402
-
1403
- agent_type = "auto"
1404
- explicit_path = None
1405
- limit = 10
1406
- for i, a in enumerate(args):
1407
- if a in ("--recent", "-n") and i + 1 < len(args):
1408
- try:
1409
- limit = int(args[i + 1])
1410
- except ValueError:
1411
- pass
1412
- elif a.startswith("--agent="):
1413
- agent_type = a.split("=", 1)[1]
1414
- elif a in ("--agent", "-a") and i + 1 < len(args):
1415
- agent_type = args[i + 1]
1416
- elif a.startswith("--path="):
1417
- explicit_path = a.split("=", 1)[1]
1418
- elif a in ("--path", "-p") and i + 1 < len(args):
1419
- explicit_path = args[i + 1]
1420
-
1421
- found = discover_transcript_paths(agent=agent_type, explicit_path=explicit_path, limit=limit)
1422
- if not found:
1423
- print("No transcripts found. Specify path via --path <path_or_dir> or --agent <antigravity|claude|codex>.")
1424
- sys.exit(0)
1425
-
1426
- analyzed = []
1427
- for ag_type, fp, _ in found:
1428
- analyzed.append(analyze_transcript(fp, agent_type=ag_type))
1429
-
1430
- print(render_transcripts_report(analyzed))
1431
- sys.exit(0)
1432
-
1433
- elif command == "proxy":
1434
- from src.proxy import run_proxy
1435
- sub = args[1] if len(args) > 1 else ""
1436
- if sub in ("--help", "-h", "help"):
1437
- print("Usage: tokensafe proxy [port] Run in foreground (default: 8765)")
1438
- print(" tokensafe proxy on Install daemon + wire agents (one command)")
1439
- print(" tokensafe proxy off Unwire agents + remove daemon (rollback)")
1440
- print(" tokensafe proxy status Health, wiring state, heartbeat")
1441
- return
1442
- if sub == "on":
1443
- from src.installer import AgentInstaller
1444
- report = AgentInstaller.proxy_on()
1445
- d, w = report["daemon"], report["wiring"]
1446
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE PROXY SETUP ⚡\033[0m\n")
1447
- print(f" Daemon: {'✔ ' + d['message'] if d['ok'] else '✖ ' + d['message']}")
1448
- print(f" Health: {'✔ proxy answering on 127.0.0.1:8765' if report['health'] else '✖ not reachable'}")
1449
- print(f" Wiring: {'✔ ' + w['message'] if w['ok'] else '✖ ' + w['message']}")
1450
- if report["manual_steps"]:
1451
- print(" Manual (not auto-wirable):")
1452
- for step in report["manual_steps"]:
1453
- print(f" • {step}")
1454
- print(f"\n Rollback anytime: \033[1mtokensafe proxy off\033[0m\n")
1455
- return
1456
- if sub == "off":
1457
- from src.installer import AgentInstaller
1458
- report = AgentInstaller.proxy_off()
1459
- u, d = report["unwired"], report["daemon"]
1460
- print(f"\n Unwired: {'✔ ' + u['message'] if u['ok'] else '✖ ' + u['message']}")
1461
- print(f" Daemon: {'✔ ' + d['message'] if d['ok'] else '✖ ' + d['message']}\n")
1462
- return
1463
- if sub == "status":
1464
- from src.installer import AgentInstaller
1465
- st = AgentInstaller.proxy_status()
1466
- print(f"\n Health: {'✔ running on 127.0.0.1:8765' if st['health'] else '✖ not running'}")
1467
- print(f" Claude Code wired: {'✔ ' + str(st['claude_code_env_value']) if st['claude_code_wired'] else '○ not wired'}")
1468
- hb = st.get("heartbeat_age_seconds")
1469
- print(f" Last traffic: {f'{hb}s ago' if hb is not None else 'no heartbeat yet'}\n")
1470
- return
1471
- port = 8765
1472
- if len(args) > 1:
1473
- try:
1474
- port = int(args[1])
1475
- if not (1 <= port <= 65535):
1476
- raise ValueError("port out of range")
1477
- except ValueError:
1478
- print(f"Invalid port '{args[1]}'. Expected integer 1..65535 (default: 8765).")
1479
- sys.exit(1)
1480
- run_proxy(port)
1481
-
1482
- elif command == "mcp":
1483
- subcmd = args[1] if len(args) > 1 else "serve"
1484
- if subcmd in ("disable", "off", "rm"):
1485
- if len(args) < 3:
1486
- print("Usage: tokensafe mcp disable <server_name>")
1487
- sys.exit(1)
1488
- target = args[2].strip()
1489
- from src.environment_auditor import EnvironmentAuditor
1490
- res = EnvironmentAuditor.disable_mcp(target)
1491
- if res["success"]:
1492
- print(f"\n\033[32m✔ MCP server '{target}' disabled successfully. Removed from active turn overhead.\033[0m\n")
1493
- else:
1494
- print(f"\n\033[31m✖ Server '{target}' not found or already disabled.\033[0m\n")
1495
- elif subcmd in ("enable", "on", "add"):
1496
- if len(args) < 3:
1497
- print("Usage: tokensafe mcp enable <server_name>")
1498
- sys.exit(1)
1499
- target = args[2].strip()
1500
- from src.environment_auditor import EnvironmentAuditor
1501
- res = EnvironmentAuditor.enable_mcp(target)
1502
- if res["success"]:
1503
- print(f"\n\033[32m✔ MCP server '{target}' re-enabled successfully.\033[0m\n")
1504
- else:
1505
- print(f"\n\033[31m✖ Server '{target}' not found in disabled servers.\033[0m\n")
1506
- elif subcmd in ("wrap", "proxy-wrap"):
1507
- from src.mcp_config_manager import MCPConfigManager
1508
- target = args[2].strip() if len(args) > 2 else "--all"
1509
- if target in ("--all", "-a", "all"):
1510
- count = MCPConfigManager.wrap_all()
1511
- print(f"\n\033[32m✔ Wrapped {count} third-party MCP server(s) behind tokensafe mcp-proxy.\033[0m\n")
1512
- else:
1513
- servers = MCPConfigManager.list_servers()
1514
- matched = [s for s in servers if s["server_name"] == target]
1515
- if not matched:
1516
- print(f"\n\033[31m✖ Server '{target}' not found in active agent MCP configs.\033[0m\n")
1517
- else:
1518
- for s in matched:
1519
- MCPConfigManager.wrap_server(s["config_path"], s["server_name"])
1520
- print(f"\n\033[32m✔ Server '{target}' wrapped behind tokensafe mcp-proxy.\033[0m\n")
1521
- elif subcmd in ("unwrap", "restore"):
1522
- from src.mcp_config_manager import MCPConfigManager
1523
- target = args[2].strip() if len(args) > 2 else "--all"
1524
- if target in ("--all", "-a", "all"):
1525
- count = MCPConfigManager.unwrap_all()
1526
- print(f"\n\033[32m✔ Unwrapped {count} MCP server(s) back to direct execution.\033[0m\n")
1527
- else:
1528
- servers = MCPConfigManager.list_servers()
1529
- matched = [s for s in servers if s["server_name"] == target]
1530
- if not matched:
1531
- print(f"\n\033[31m✖ Server '{target}' not found in active agent MCP configs.\033[0m\n")
1532
- else:
1533
- for s in matched:
1534
- MCPConfigManager.unwrap_server(s["config_path"], s["server_name"])
1535
- print(f"\n\033[32m✔ Server '{target}' restored to original command.\033[0m\n")
1536
- elif subcmd in ("list", "ls", "status"):
1537
- from src.environment_auditor import EnvironmentAuditor
1538
- print(EnvironmentAuditor.format_cli_report())
1539
- else:
1540
- from src.mcp_server import run_mcp_server
1541
- run_mcp_server()
1542
-
1543
- elif command in ("acp",):
1544
- if any(arg in ("--print-command", "--print_command") for arg in args[1:]):
1545
- import shutil as _shutil
1546
- import sys as _sys
1547
- node = _shutil.which("node") or "node"
1548
- shim = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "bin", "tokensafe-acp.js")
1549
- print(f'{node} "{shim}"')
1550
- _sys.exit(0)
1551
- from src.acp.server import run_acp_server
1552
- run_acp_server()
1553
-
1554
- elif command in ("agent", "run-agent", "run_agent"):
1555
- opts = {"model": "", "provider": "", "base_url": "", "root": "", "max_steps": 16, "budget": 1.0}
1556
- prompt_parts: List[str] = []
1557
- index = 1
1558
- while index < len(args):
1559
- arg = args[index]
1560
- if arg in ("--model", "-m") and index + 1 < len(args):
1561
- opts["model"] = args[index + 1]
1562
- index += 2
1563
- elif arg == "--provider" and index + 1 < len(args):
1564
- opts["provider"] = args[index + 1]
1565
- index += 2
1566
- elif arg in ("--base-url", "--base_url") and index + 1 < len(args):
1567
- opts["base_url"] = args[index + 1]
1568
- index += 2
1569
- elif arg in ("--root", "-C") and index + 1 < len(args):
1570
- opts["root"] = args[index + 1]
1571
- index += 2
1572
- elif arg == "--max-steps" and index + 1 < len(args):
1573
- try:
1574
- opts["max_steps"] = int(args[index + 1])
1575
- except ValueError:
1576
- pass
1577
- index += 2
1578
- elif arg == "--budget" and index + 1 < len(args):
1579
- try:
1580
- opts["budget"] = float(args[index + 1])
1581
- except ValueError:
1582
- pass
1583
- index += 2
1584
- else:
1585
- prompt_parts.append(arg)
1586
- index += 1
1587
- prompt = " ".join(prompt_parts).strip()
1588
- if not prompt:
1589
- print("Usage: tokensafe agent [--model M] [--provider P] [--base-url U] [-C dir] "
1590
- "[--max-steps N] [--budget USD] <prompt>")
1591
- sys.exit(1)
1592
- from src.agent.loop import AgentConfig, AgentLoop
1593
- from src.agent.providers import ProviderError
1594
- import json as _json
1595
-
1596
- def _sink(event):
1597
- kind = event.get("type")
1598
- if kind == "text":
1599
- sys.stdout.write(event.get("text") or "")
1600
- sys.stdout.flush()
1601
- elif kind == "tool_call":
1602
- rendered = _json.dumps(event.get("arguments"), ensure_ascii=False)[:160]
1603
- print(f"\n\033[2m→ {event.get('name')} {rendered}\033[0m")
1604
- elif kind == "tool_result":
1605
- state = "ok" if event.get("ok") else "error"
1606
- print(f"\033[2m← {event.get('name')}: {state} ({len(event.get('text') or '')} chars)\033[0m")
1607
- elif kind == "compaction":
1608
- print(f"\033[2m[context compacted: {event.get('before')} → {event.get('after')} tokens]\033[0m")
1609
-
1610
- loop = AgentLoop(
1611
- root=opts["root"] or None,
1612
- session_id="cli:agent",
1613
- config=AgentConfig(
1614
- model=opts["model"],
1615
- provider=opts["provider"],
1616
- base_url=opts["base_url"],
1617
- max_steps=opts["max_steps"],
1618
- budget_usd=opts["budget"],
1619
- ),
1620
- event_sink=_sink,
1621
- )
1622
- try:
1623
- result = loop.run(prompt)
1624
- except ProviderError as exc:
1625
- print(f"\n\033[31mError:\033[0m {exc}")
1626
- sys.exit(2)
1627
- usage = result.usage
1628
- priced = "" if usage.get("priced") else " · unpriced model"
1629
- print(
1630
- f"\n\033[2m[{result.stop_reason} · {result.steps} step(s) · "
1631
- f"{usage.get('input_tokens', 0)} in / {usage.get('output_tokens', 0)} out · "
1632
- f"${usage.get('usd', 0.0):.4f}{priced}]\033[0m"
1633
- )
1634
-
1635
- elif command in ("mcp-proxy", "mcp_proxy"):
1636
- target_args = list(args[1:])
1637
- if target_args and target_args[0] == "--":
1638
- target_args.pop(0)
1639
- from src.mcp_proxy import run_proxy
1640
- run_proxy(target_args)
1641
-
1642
- elif command in ("doctor", "audit", "tax"):
1643
- from src.environment_auditor import EnvironmentAuditor
1644
- from src.competitors import CompetitorAuditor
1645
-
1646
- if "--fix" in args:
1647
- print("\n\033[1m\033[36m🔧 TOKENSAFE ENVIRONMENT AUTO-FIX 🔧\033[0m\n")
1648
- fix_res = EnvironmentAuditor.auto_fix()
1649
- for item in fix_res.get("fixed", []):
1650
- print(f" \033[32m✔\033[0m {item}")
1651
- for item in fix_res.get("skipped", []):
1652
- print(f" \033[33m⚠\033[0m {item}")
1653
- if not fix_res.get("fixed") and not fix_res.get("skipped"):
1654
- print(" \033[32m✔\033[0m No auto-fixable config or ghost-token issues found.")
1655
- print()
1656
-
1657
- print(EnvironmentAuditor.format_cli_report())
1658
-
1659
- # Honest per-host feature matrix: what is enforced vs merely available.
1660
- try:
1661
- from src.host_capabilities import matrix_rows
1662
- print("\n\033[1m\033[36m⚡ HOST CAPABILITIES ⚡\033[0m")
1663
- for row in matrix_rows():
1664
- flags = []
1665
- for key, label in (
1666
- ("hooks", "hooks"),
1667
- ("precompact", "pre-compact"),
1668
- ("postcompact", "post-compact"),
1669
- ("session_injection", "session-inject"),
1670
- ("prompt_injection", "prompt-inject"),
1671
- ("statusline", "statusline"),
1672
- ("transcript", "transcript"),
1673
- ):
1674
- if row.get(key):
1675
- flags.append(label)
1676
- print(f" {row['host']:<15} {' · '.join(flags) if flags else 'MCP/rules only'}")
1677
- print()
1678
- except Exception:
1679
- pass
1680
-
1681
- conflicts = CompetitorAuditor.audit()
1682
- if conflicts:
1683
- print("\n\033[1m\033[33m⚡ DETECTED CONFLICTING OR STALE TOOLS ⚡\033[0m")
1684
- for c in conflicts:
1685
- print(f" • \033[1m{c['name']}\033[0m [{c['class']}]: {c['description']}")
1686
- for tr in c['traces']:
1687
- loc = tr.get('path') or tr.get('file') or tr.get('config')
1688
- print(f" - {tr['kind']}: {loc}")
1689
- print("\n 💡 Tip: Run 'tokensafe doctor --cleanup' (or '--fix') to remove conflicting orphan hooks/rules.\n")
1690
-
1691
- if "--cleanup" in args:
1692
- for c in conflicts:
1693
- res = CompetitorAuditor.cleanup(c["id"])
1694
- print(f" \033[32m✔ Cleaned {c['name']}: {', '.join(res.get('removed', []))}\033[0m")
1695
-
1696
- elif command in ("skills", "skill"):
1697
- from src.environment_auditor import EnvironmentAuditor
1698
- sub = args[1] if len(args) > 1 else "list"
1699
- if sub in ("disable", "off", "rm"):
1700
- if len(args) < 3:
1701
- print("Usage: tokensafe skills disable <skill_name>")
1702
- sys.exit(1)
1703
- target = args[2].strip()
1704
- res = EnvironmentAuditor.disable_skill(target)
1705
- if res.get("success"):
1706
- print(f"\n\033[32m✔ Skill '{res['skill']}' disabled ({res['path']}).\033[0m\n")
1707
- else:
1708
- print(f"\n\033[31m✖ {res.get('error', 'Failed to disable skill')}\033[0m\n")
1709
- sys.exit(1)
1710
- elif sub in ("enable", "on", "add"):
1711
- if len(args) < 3:
1712
- print("Usage: tokensafe skills enable <skill_name>")
1713
- sys.exit(1)
1714
- target = args[2].strip()
1715
- res = EnvironmentAuditor.enable_skill(target)
1716
- if res.get("success"):
1717
- print(f"\n\033[32m✔ Skill '{res['skill']}' re-enabled ({res['path']}).\033[0m\n")
1718
- else:
1719
- print(f"\n\033[31m✖ {res.get('error', 'Failed to enable skill')}\033[0m\n")
1720
- sys.exit(1)
1721
- else:
1722
- print(EnvironmentAuditor.format_skills_report())
1723
-
1724
- elif command in ("web", "fetch", "url"):
1725
- if len(args) < 2:
1726
- print("Usage: tokensafe web <url>")
1727
- sys.exit(1)
1728
- url = args[1].strip()
1729
- from src.web_reader import WebReader
1730
- md, ok, err = WebReader.fetch_url(url)
1731
- if not ok:
1732
- print(f"\033[31mError: {err}\033[0m")
1733
- sys.exit(1)
1734
- print(md)
1735
-
1736
- elif command in ("search", "find", "fts"):
1737
- if len(args) < 2:
1738
- print("Usage: tokensafe search <query> [--limit 25] [--path <dir>]")
1739
- sys.exit(1)
1740
- query = args[1]
1741
- limit = 25
1742
- target_dir = os.getcwd()
1743
- if "--limit" in args:
1744
- idx = args.index("--limit")
1745
- if idx + 1 < len(args):
1746
- try:
1747
- limit = int(args[idx + 1])
1748
- except ValueError:
1749
- pass
1750
- if "--path" in args:
1751
- idx = args.index("--path")
1752
- if idx + 1 < len(args):
1753
- target_dir = os.path.abspath(args[idx + 1])
1754
-
1755
- from src.fts_index import CodeFTSIndex
1756
- idx_engine = CodeFTSIndex(target_dir)
1757
- idx_engine.index_files()
1758
- results = idx_engine.search(query, limit=limit)
1759
- if not results:
1760
- print(f"No matches found for '{query}'.")
1761
- else:
1762
- print(f"\n\033[1m\033[36m⚡ SQLite FTS5 BM25 Search ({len(results)} matches for '{query}'):\033[0m\n")
1763
- for r in results:
1764
- print(f" \033[32m{r['file']}:{r['line']}\033[0m: {r['content']}")
1765
- print()
1766
-
1767
- elif command in ("index", "fts-index"):
1768
- target_dir = os.getcwd()
1769
- if len(args) > 1 and not args[1].startswith("-"):
1770
- target_dir = os.path.abspath(args[1])
1771
- from src.fts_index import CodeFTSIndex
1772
- idx_engine = CodeFTSIndex(target_dir)
1773
- if "--clear" in args or "--reset" in args:
1774
- idx_engine.clear()
1775
- print(f"\033[32m✔ Cleared FTS index database for {target_dir}.\033[0m")
1776
- else:
1777
- stats = idx_engine.index_files()
1778
- print(f"\n\033[1m\033[36m⚡ SQLite FTS5 Full-Text Indexer ⚡\033[0m")
1779
- print(f" Scanned files: {stats['scanned_files']}")
1780
- print(f" Updated files: {stats['updated_files']}")
1781
- print(f" Indexed lines: {stats['indexed_lines']:,}")
1782
- print(f" Duration: {stats['duration_ms']:.2f} ms")
1783
- print(f" Index path: {idx_engine.db_path}\n")
1784
-
1785
- elif command in ("graph", "nodes"):
1786
- from src.graph_engine import GraphEngine
1787
- target_dir = args[1] if len(args) > 1 else os.getcwd()
1788
- graph = GraphEngine.get_instance(target_dir)
1789
- print(f"\n🔍 TokenSafe Graph Engine — Knowledge Graph & Centrality Analysis")
1790
- print(f" Indexed: {len(graph.file_symbols)} code files, {len(graph.symbols)} symbols\n")
1791
- god_nodes = graph.get_god_nodes(top_n=7)
1792
- print("⚡ Architectural Hubs (God Nodes):")
1793
- for idx, g in enumerate(god_nodes, 1):
1794
- print(f" {idx}. {g['file']}")
1795
- print(f" Degree Centrality: {g['centrality']} | Dependents: {g['dependents']} | Dependencies: {g['dependencies']} | Symbols: {g['symbols_count']}")
1796
- print(f"\n💡 Tip: Run 'tokensafe map' to generate tokensafe-out/API_SURFACE.md\n")
1797
-
1798
- elif command in ("map", "surface"):
1799
- from src.graph_engine import GraphEngine
1800
- target_dir = args[1] if len(args) > 1 else os.getcwd()
1801
- if not os.path.isdir(target_dir):
1802
- print(f"\n\033[31m✖ Directory not found: {target_dir}\033[0m\n")
1803
- sys.exit(1)
1804
- graph = GraphEngine.get_instance(target_dir)
1805
- out_file = os.path.join(os.path.abspath(target_dir), "tokensafe-out", "API_SURFACE.md")
1806
- graph.generate_api_surface(out_file)
1807
- if not os.path.exists(out_file):
1808
- print(f"\n\033[31m✖ Could not write API Surface Map to: {out_file}\033[0m\n")
1809
- sys.exit(1)
1810
- print(f"\n✓ Generated API Surface Map: {out_file} ({os.path.getsize(out_file):,} bytes)")
1811
- print(f" AI agents can read this file in ~1.5k tokens instead of reading the entire repo.\n")
1812
-
1813
- elif command == "skeleton":
1814
- from src.graph_engine import GraphEngine
1815
- if len(args) < 2:
1816
- print("Usage: tokensafe skeleton <file_path> [target_symbol]")
1817
- sys.exit(1)
1818
- file_path = os.path.abspath(args[1])
1819
- target_symbol = args[2] if len(args) > 2 else None
1820
- graph, _ = GraphEngine.for_file(file_path)
1821
- res = graph.graph_guided_skeletonize(file_path, target_symbol)
1822
- print(res)
1823
-
1824
- elif command in ("login", "auth", "connect"):
1825
- from src.license_manager import LicenseManager
1826
- import json
1827
- import time
1828
- import urllib.request
1829
- import webbrowser
1830
- import platform
1831
-
1832
- cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
1833
- active_tier, active_lic = LicenseManager.get_active_license()
1834
- active_email = active_lic.get("email", "")
1835
-
1836
- print("\n\033[1m\033[36m╔════════════════════════════════════════════════════════════════════╗\033[0m")
1837
- print("\033[1m\033[36m║ ⚡ TOKENSAFE ACCOUNT AUTHORIZATION ⚡ ║\033[0m")
1838
- print("\033[1m\033[36m╚════════════════════════════════════════════════════════════════════╝\033[0m\n")
1839
-
1840
- if active_email and active_email != "community@tokensafe.dev":
1841
- print(f" Currently logged in as: \033[32m{active_email}\033[0m (Tier: {active_tier.upper()})")
1842
- if sys.stdin.isatty():
1843
- ans = input(" Do you want to re-authenticate or switch accounts? [y/N]: ").strip().lower()
1844
- if ans not in ("y", "yes"):
1845
- print(" Keeping current authorization.\n")
1846
- sys.exit(0)
1847
-
1848
- # 1. Request device code
1849
- from src.version_checker import CURRENT_VERSION
1850
- machine_fp = LicenseManager.get_machine_fingerprint()
1851
- payload = {
1852
- "machine_fp": machine_fp,
1853
- "platform": platform.system()[:32],
1854
- "arch": platform.machine()[:32],
1855
- "agent": str(LicenseManager.detect_agent())[:32],
1856
- "version": CURRENT_VERSION[:32],
1857
- "hostname": platform.node()[:64]
1858
- }
1859
- try:
1860
- req = urllib.request.Request(
1861
- f"{cloud_url}/api/auth/device/code",
1862
- data=json.dumps(payload).encode("utf-8"),
1863
- headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Login"},
1864
- method="POST"
1865
- )
1866
- with urllib.request.urlopen(req, timeout=5.0) as resp:
1867
- init_data = json.loads(resp.read().decode("utf-8") or "{}")
1868
- except Exception as exc:
1869
- print(f"\033[31m✖ Could not connect to {cloud_url}: {exc}\033[0m")
1870
- print(" Check your internet connection and try again.\n")
1871
- sys.exit(1)
1872
-
1873
- if not (init_data.get("success") or init_data.get("ok")):
1874
- print(f"\033[31m✖ Authorization initiation failed: {init_data.get('error')}\033[0m\n")
1875
- sys.exit(1)
1876
-
1877
- user_code = init_data["user_code"]
1878
- device_code = init_data["device_code"]
1879
- verif_url = init_data.get("verification_uri_complete") or f"{init_data['verification_uri']}?code={user_code}"
1880
- interval = init_data.get("interval", 3)
1881
-
1882
- print(" To authorize this device and connect your account:")
1883
- print(f" 1. Confirm code: \033[1m\033[33m{user_code}\033[0m")
1884
- print(f" 2. In browser at: {verif_url}\n")
1885
-
1886
- # Attempt to open browser automatically
1887
- try:
1888
- webbrowser.open(verif_url)
1889
- print(" \033[2m(Opened verification page in your default browser)\033[0m")
1890
- except Exception:
1891
- pass
1892
-
1893
- print(" Waiting for authorization in browser (Ctrl+C to abort)...", end="", flush=True)
1894
-
1895
- # 2. Polling loop
1896
- spinner = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
1897
- spin_idx = 0
1898
- approved_data = None
1899
-
1900
- try:
1901
- start_time = time.time()
1902
- while time.time() - start_time < 600:
1903
- time.sleep(interval)
1904
- spin_char = spinner[spin_idx % len(spinner)]
1905
- spin_idx += 1
1906
- print(f"\r {spin_char} Waiting for authorization in browser (Ctrl+C to abort)...", end="", flush=True)
1907
-
1908
- try:
1909
- poll_req = urllib.request.Request(
1910
- f"{cloud_url}/api/auth/device/poll",
1911
- data=json.dumps({"device_code": device_code}).encode("utf-8"),
1912
- headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Login"},
1913
- method="POST"
1914
- )
1915
- with urllib.request.urlopen(poll_req, timeout=4.0) as resp:
1916
- poll_data = json.loads(resp.read().decode("utf-8") or "{}")
1917
- except Exception:
1918
- continue
1919
-
1920
- status = poll_data.get("status")
1921
- if status == "approved":
1922
- approved_data = poll_data
1923
- break
1924
- elif status == "quota_exhausted":
1925
- print(f"\n\n\033[31m✖ {poll_data.get('error')}\033[0m\n")
1926
- sys.exit(1)
1927
- elif status in ("expired", "denied"):
1928
- print(f"\n\n\033[31m✖ Authorization {status}.\033[0m\n")
1929
- sys.exit(1)
1930
-
1931
- except KeyboardInterrupt:
1932
- print("\n\n\033[33m Authorization cancelled by user.\033[0m")
1933
- print(" Run 'tokensafe login' whenever you are ready.\n")
1934
- sys.exit(130)
1935
-
1936
- if not approved_data:
1937
- print("\n\n\033[31m✖ Authorization timed out. Please try again.\033[0m\n")
1938
- sys.exit(1)
1939
-
1940
- # 3. Save license and device token
1941
- lic_key = approved_data.get("license_key", "")
1942
- dev_tok = approved_data.get("device_token", "")
1943
- auth_email = approved_data.get("email") or approved_data.get("user_email") or ""
1944
-
1945
- ok, msg = LicenseManager.save_license(lic_key, device_token=dev_tok)
1946
- if ok:
1947
- valid, lic_meta, _ = LicenseManager.validate_license(lic_key)
1948
- detected_tier = (lic_meta.get("tier") or approved_data.get("tier") or "free").lower()
1949
- org_id = lic_meta.get("org")
1950
-
1951
- print(f"\r\033[K \033[32m\033[1m✔ Successfully authenticated as {auth_email}!\033[0m")
1952
- if detected_tier == "solo":
1953
- print(" \033[32m✔ Solo Pro license activated (Unlimited tokens).\033[0m")
1954
- elif detected_tier in ("team", "enterprise"):
1955
- org_msg = f" [{org_id}]" if org_id else ""
1956
- print(f" \033[32m✔ Team license activated (Unlimited tokens, organization workspace{org_msg}).\033[0m")
1957
- else:
1958
- print(" \033[32m✔ Community Edition license activated (500,000 free tokens/month).\033[0m")
1959
- print(f" \033[36m✔ Web dashboard unlocked at:\033[0m https://tokensafe.dev/dashboard\n")
1960
-
1961
- # Cloud Prompt Booster consent (paid tiers only; already-chosen users skipped)
1962
- if detected_tier in ("solo", "team", "enterprise"):
1963
- _booster_consent_prompt()
1964
-
1965
- # Sync local token metrics
1966
- try:
1967
- from src.telemetry_sync import TelemetrySync
1968
- sync_res = TelemetrySync.sync(license_key=lic_key, timeout=3.0)
1969
- if sync_res.get("success") and sync_res.get("synced_events", 0) > 0:
1970
- print(f" \033[36m✔ Synced {sync_res['synced_events']:,} optimization events to your cloud dashboard.\033[0m\n")
1971
- except Exception:
1972
- pass
1973
- else:
1974
- print(f"\n\033[31m✖ Failed to save license: {msg}\033[0m\n")
1975
- sys.exit(1)
1976
-
1977
- elif command in ("logout", "unlink", "disconnect"):
1978
- from src.license_manager import LicenseManager, LICENSE_FILE, GLOBAL_LICENSE_FILE
1979
- import json
1980
- import urllib.request
1981
-
1982
- cloud_url = os.environ.get("TOKENSAFE_CLOUD_URL", "https://api.tokensafe.dev").rstrip("/")
1983
- machine_fp = LicenseManager.get_machine_fingerprint()
1984
- _, active_lic = LicenseManager.get_active_license()
1985
- active_email = active_lic.get("email", "")
1986
-
1987
- # 1. Unlink on server to free up device slot
1988
- if active_email and machine_fp and active_email != "community@tokensafe.dev":
1989
- try:
1990
- req = urllib.request.Request(
1991
- f"{cloud_url}/api/auth/device/unlink",
1992
- data=json.dumps({"email": active_email, "machine_fp": machine_fp}).encode("utf-8"),
1993
- headers={"Content-Type": "application/json", "User-Agent": "TokenSafe/CLI-Logout"},
1994
- method="POST"
1995
- )
1996
- with urllib.request.urlopen(req, timeout=4.0):
1997
- pass
1998
- except Exception:
1999
- pass
2000
-
2001
- # 2. Remove local license files
2002
- for p in LicenseManager._candidate_license_files():
2003
- try:
2004
- if os.path.exists(p):
2005
- os.remove(p)
2006
- except Exception:
2007
- pass
2008
-
2009
- print("\n\033[32m✔ Successfully unlinked this device and logged out.\033[0m")
2010
- if active_email and active_email != "community@tokensafe.dev":
2011
- print(f" Disconnected account: {active_email}")
2012
- print(" Your device slot has been freed.")
2013
- print(" Run \033[36mtokensafe login\033[0m anytime to connect again.\n")
2014
-
2015
- elif command == "activate":
2016
- from src.license_manager import LicenseManager
2017
- if len(args) < 2:
2018
- print("Usage: tokensafe activate <LICENSE_KEY>")
2019
- sys.exit(1)
2020
- key = args[1].strip()
2021
- ok, msg = LicenseManager.save_license(key)
2022
- if ok:
2023
- print(f"\n\033[32m\033[1m✔ {msg}\033[0m")
2024
- # Cloud Prompt Booster consent (paid tiers only; already-chosen users skipped)
2025
- try:
2026
- valid, lic_meta, _ = LicenseManager.validate_license(key)
2027
- if valid and str(lic_meta.get("tier", "")).lower() in ("solo", "team", "enterprise"):
2028
- _booster_consent_prompt()
2029
- except Exception:
2030
- pass
2031
- # Automatically report version and seat activation to cloud
2032
- try:
2033
- from src.version_checker import VersionChecker
2034
- VersionChecker.check_version(license_key=key, force_fetch=True)
2035
- except Exception:
2036
- pass
2037
- # Automatically sync existing local token metrics to newly activated license
2038
- try:
2039
- from src.telemetry_sync import TelemetrySync
2040
- sync_res = TelemetrySync.sync(license_key=key, timeout=3.0)
2041
- if sync_res.get("success") and sync_res.get("synced_events", 0) > 0:
2042
- print(f" \033[36m✔ Synced {sync_res['synced_events']:,} past optimization events to cloud dashboard.\033[0m")
2043
- except Exception:
2044
- pass
2045
- print()
2046
- else:
2047
- print(f"\n\033[31m\033[1m✖ {msg}\033[0m\n")
2048
- sys.exit(1)
2049
-
2050
- elif command in ("sync", "push"):
2051
- from src.telemetry_sync import TelemetrySync
2052
- print("\n\033[1m\033[36m⚡ SYNCHRONIZING TOKEN METRICS WITH DASHBOARD ⚡\033[0m\n")
2053
- force_sync = "--force" in args or "-f" in args
2054
- status_before = TelemetrySync.get_sync_status()
2055
- print(f" Local recorded events: {status_before['total_local_events']:,}")
2056
- print(f" Pending sync: {status_before['pending_events']:,}\n")
2057
- res = TelemetrySync.sync(force=force_sync, verbose=True)
2058
- if res.get("success"):
2059
- print(f" \033[32m✔ {res.get('message', 'Synchronized successfully.')}\033[0m")
2060
- status_after = TelemetrySync.get_sync_status()
2061
- print(f" Total synced events: {status_after['total_synced_events']:,}\n")
2062
- else:
2063
- print(f" \033[31m✖ Sync failed: {res.get('error', 'Unknown error')}\033[0m\n")
2064
-
2065
- elif command in ("license", "tier"):
2066
- from src.license_manager import LicenseManager
2067
- tier, payload = LicenseManager.get_active_license()
2068
- print("\n\033[1m\033[36m⚡ TOKENSAFE LICENSE STATUS ⚡\033[0m\n")
2069
- print(f" Tier: \033[32m\033[1m{tier.upper()}\033[0m")
2070
- if tier == "guest":
2071
- quota = LicenseManager.check_quota()
2072
- q_saved = int(quota.get("monthly_saved", 0))
2073
- q_limit = int(quota.get("monthly_limit") or 50_000)
2074
- q_state = "\033[31mQUOTA REACHED (Optimizers paused)\033[0m" if quota.get("is_quota_exceeded") else "\033[32mActive\033[0m"
2075
- print(f" Status: Guest Mode ({q_saved:,} / {q_limit:,} tokens this month · {q_state})")
2076
- print(" Mode: Local Offline (No account connected)")
2077
- print(" Unlock 500k: \033[36mtokensafe login\033[0m (Free Community license + Web Dashboard)")
2078
- print(" Solo Pro: https://tokensafe.dev/signup (Unlimited tokens)\n")
2079
- elif tier == "free":
2080
- quota = LicenseManager.check_quota()
2081
- q_saved = int(quota.get("monthly_saved", 0))
2082
- q_limit = int(quota.get("monthly_limit") or 500_000)
2083
- q_state = "\033[31mQUOTA REACHED (Pro optimizations paused)\033[0m" if quota.get("is_quota_exceeded") else "\033[32mActive\033[0m"
2084
- print(f" Email: {payload.get('email', 'community@tokensafe.dev')}")
2085
- print(f" Status: Community Account ({q_saved:,} / {q_limit:,} measured tokens this month · {q_state})")
2086
- print(" Upgrade: https://tokensafe.dev/signup ($9/mo Solo with 7-Day Free Trial)\n")
2087
- else:
2088
- print(f" Email: {payload.get('email', 'N/A')}")
2089
- if payload.get("trial"):
2090
- print(f" Mode: \033[33m7-Day Free Trial\033[0m")
2091
- exp = payload.get("expires_at", 0)
2092
- if exp > 0:
2093
- import datetime
2094
- dt = datetime.datetime.fromtimestamp(exp).strftime('%Y-%m-%d %H:%M:%S')
2095
- print(f" Expires: {dt}")
2096
- else:
2097
- print(f" Expires: Never (Lifetime)")
2098
- profile, _sextant_tier = oumv_policy.current()
2099
- if profile == oumv_policy.PROFILE_READ_ONLY:
2100
- print(" Sextant: read-only (observe everywhere; change/verify on Solo+)")
2101
- else:
2102
- print(" Sextant: full (change and verify the running app)")
2103
- print()
2104
-
2105
- elif command in ("booster",):
2106
- from src.license_manager import LicenseManager
2107
- from src.distiller import UniversalDistiller
2108
- from src.egress_counter import today_counts
2109
- sub = args[1].strip().lower() if len(args) > 1 else "status"
2110
- tier, _ = LicenseManager.get_active_license()
2111
- print("\n\033[1m\033[36m⚡ CLOUD PROMPT BOOSTER ⚡\033[0m\n")
2112
- if tier not in UniversalDistiller.PAID_TIERS:
2113
- print(" Cloud Prompt Booster distills long prompts (100+ tokens) cloud-side with")
2114
- print(" ~5x deeper compression than the local engine. Available on Solo, Team, and Enterprise.")
2115
- print(" Guest and Community tiers keep all prompt processing 100% local by design.\n")
2116
- elif sub in ("on", "enable", "off", "disable"):
2117
- value = sub in ("on", "enable")
2118
- if UniversalDistiller.write_config_value("cloud_distill", value):
2119
- if value:
2120
- print(" \033[32m✔ Booster enabled\033[0m — long prompts are distilled via TokenSafe Cloud")
2121
- print(" (secrets scrubbed before egress; raw text never stored; not used for training).")
2122
- else:
2123
- print(" \033[33m○ Booster disabled\033[0m — all prompt processing stays 100% local.")
2124
- else:
2125
- print(" \033[31m✖ Failed to write data/config.json — check permissions.\033[0m")
2126
- print()
2127
- else:
2128
- enabled, explicitly_set = UniversalDistiller.cloud_booster_enabled(tier)
2129
- eg = today_counts()
2130
- state = "\033[32mon\033[0m" if enabled else "\033[33moff\033[0m"
2131
- if not explicitly_set:
2132
- state += " \033[2m(active by default — make an explicit choice below)\033[0m"
2133
- print(f" Status: {state}")
2134
- print(f" Egress: today — {eg['booster']} booster · {eg['telemetry']} telemetry outbound requests")
2135
- print(" What it sends when on: prompt text (code snippets/stack traces possible) with secrets")
2136
- print(" scrubbed → TokenSafe Cloud → Google Gemini Flash-Lite. Transient processing;")
2137
- print(" raw text never stored, not used for training.")
2138
- print(" Toggle: \033[36mtokensafe booster on|off\033[0m\n")
2139
-
2140
- elif command in ("providers", "models", "keys"):
2141
- from src.license_manager import LicenseManager
2142
- from src.distiller import UniversalDistiller
2143
- tier, _ = LicenseManager.get_active_license()
2144
- print("\n\033[1m\033[36m⚡ TOKENSAFE LLM DISTILLATION PROVIDERS ⚡\033[0m\n")
2145
- if tier not in UniversalDistiller.PAID_TIERS:
2146
- tier_label = "Guest (Offline)" if tier == "guest" else "Free Community Edition"
2147
- print(f" \033[33mTier: {tier_label}\033[0m")
2148
- print(" Cloud Prompt Booster (managed distillation, zero API keys) is reserved for Solo, Team, and Enterprise tiers.")
2149
- print(" Guest and Community Editions operate with the zero-latency, zero-cost Local Regex Compactor.\n")
2150
- print(" \033[1mTo unlock the Cloud Prompt Booster:\033[0m")
2151
- print(" 1. Start 7-day free trial or upgrade at: https://tokensafe.dev")
2152
- print(" 2. Activate your key: \033[32mtokensafe activate <KEY>\033[0m\n")
2153
- elif not UniversalDistiller.is_self_hosted():
2154
- enabled, explicitly_set = UniversalDistiller.cloud_booster_enabled(tier)
2155
- if enabled:
2156
- print(f" \033[32m✔\033[0m \033[1mCloud Prompt Booster\033[0m [Active: gemini-flash-lite-latest via TokenSafe Cloud]")
2157
- print(" Long prompts (100+ tokens) are distilled cloud-side. Secrets are scrubbed before")
2158
- print(" egress; raw text is never stored and is not used for training. Zero API keys required.")
2159
- if not explicitly_set:
2160
- print(" \033[2mActive by default for your plan — make an explicit choice: tokensafe booster on|off\033[0m")
2161
- else:
2162
- print(" \033[33m○ Cloud Prompt Booster: off\033[0m — long prompts stay on the local regex compactor.")
2163
- print(" Enable anytime: \033[36mtokensafe booster on\033[0m")
2164
- print()
2165
- print(" \033[2m💡 Tip: To run self-hosted with custom BYOK keys in Docker, export TOKENSAFE_SELF_HOSTED=1.\033[0m\n")
2166
- else:
2167
- print(" \033[36mMode: Self-Hosted Docker (Custom BYOK Keys)\033[0m\n")
2168
- configured = UniversalDistiller.get_configured_providers()
2169
- all_p = UniversalDistiller.PROVIDERS
2170
- for key, p in all_p.items():
2171
- if key in configured:
2172
- c = configured[key]
2173
- print(f" \033[32m✔\033[0m \033[1m{p['name']:<18}\033[0m [Active: {c['model']}]")
2174
- else:
2175
- print(f" \033[2m○ {p['name']:<18} [Set {p['env_key']} to activate]\033[0m")
2176
- print("\nSet environment variable or add to data/config.json to activate.\n")
2177
-
2178
- elif command in ("markdown", "md", "export"):
2179
- print(Dashboard(MetricsTracker()).render_markdown())
2180
-
2181
- elif command == "test":
2182
- if len(args) < 2:
2183
- print("Usage: tokensafe test \"<prompt text>\"")
2184
- sys.exit(1)
2185
- raw_prompt = " ".join(args[1:])
2186
- res = PromptCompactor.compact(raw_prompt)
2187
-
2188
- print("\n\033[1m\033[36m⚡ TOKEN COMPRESSION TEST ⚡\033[0m\n")
2189
- print(f"\033[1mOriginal Input:\033[0m {res['original_text']}")
2190
- print(f"\033[1mCompacted DSL:\033[0m \033[32m\033[1m{res['compact_text']}\033[0m\n")
2191
- print(f"\033[1mRouting Tier:\033[0m \033[33m{res.get('tier', 'REGEX')}\033[0m")
2192
- print(f"\033[1mExtracted Action:\033[0m {res['action']}")
2193
- print(f"\033[1mTarget File:\033[0m {res['target_file'] or 'None'}")
2194
- print(f"\033[1mScope Symbol:\033[0m {res['symbol'] or 'None'}")
2195
- print(f"\033[1mTraits / Tags:\033[0m {res['traits']}\n")
2196
- print(f"\033[1mOriginal Tokens:\033[0m {res['original_tokens']}")
2197
- print(f"\033[1mCompacted Tokens:\033[0m {res['compact_tokens']}")
2198
- print(f"\033[1mTokens Saved:\033[0m \033[32m\033[1m+{res['saved_tokens']} tokens\033[0m ({render_bar(res['reduction_pct'])})\n")
2199
-
2200
- elif command == "wrap":
2201
- if len(args) < 2:
2202
- print("Usage: tokensafe wrap <command>")
2203
- sys.exit(1)
2204
- sub_cmd = " ".join(args[1:])
2205
- try:
2206
- proc = subprocess.run(sub_cmd, shell=True, capture_output=True, text=True)
2207
- raw = (proc.stdout or "") + (proc.stderr or "")
2208
- except Exception as e:
2209
- print(f"Error running command: {e}")
2210
- sys.exit(1)
2211
-
2212
- from src.format_parsers.ansi import strip_ansi
2213
- from src.test_parsers import TestOutputParser
2214
- from src.build_parsers import BuildOutputParser
2215
- from src.stash import stash_block
2216
-
2217
- raw = strip_ansi(raw)
2218
- compacted, was_test = TestOutputParser.compact(raw)
2219
- if was_test:
2220
- print(compacted)
2221
- sys.exit(proc.returncode)
2222
-
2223
- compacted_build, was_build = BuildOutputParser.compact(raw, exit_code=proc.returncode, cmd=sub_cmd)
2224
- if was_build:
2225
- print(compacted_build)
2226
- sys.exit(proc.returncode)
2227
-
2228
- # Container build reducer (docker build, docker compose build)
2229
- try:
2230
- from src.format_parsers.docker_k8s import ContainerAndK8sReducer
2231
- compacted_docker, was_docker = ContainerAndK8sReducer.reduce_docker_build(raw)
2232
- if was_docker:
2233
- print(compacted_docker)
2234
- sys.exit(proc.returncode)
2235
- except Exception:
2236
- pass
2237
-
2238
- # Structured NDJSON / JSON log reducer
2239
- try:
2240
- from src.format_parsers.json_log import JSONLogReducer
2241
- if JSONLogReducer.is_ndjson_log(raw):
2242
- compacted_logs, was_logs = JSONLogReducer.reduce(raw)
2243
- if was_logs:
2244
- print(compacted_logs)
2245
- sys.exit(proc.returncode)
2246
- except Exception:
2247
- pass
2248
-
2249
- lines = raw.splitlines()
2250
- if len(lines) > 40:
2251
- head = lines[:15]
2252
- tail = lines[-15:]
2253
- omitted = len(lines) - 30
2254
- _, marker = stash_block(raw, source="wrap")
2255
- folded = "\n".join(head + [f"... [{omitted} lines omitted by TokenSafe] ..."] + tail + [marker])
2256
- print(folded)
2257
- else:
2258
- print(raw)
2259
- sys.exit(proc.returncode)
2260
-
2261
- elif command in ("tests", "testsuite", "unittest"):
2262
- tests_dir = os.path.join(PROJECT_ROOT, "tests")
2263
- if not os.path.isdir(tests_dir):
2264
- print("No tests/ directory found — run from a repository checkout "
2265
- "(installed packages do not ship the unit-test suite).")
2266
- sys.exit(1)
2267
- verbose = "--verbose" in args or "-v" in args
2268
- full_tb = "--traceback" in args or "-tb" in args
2269
- launcher = next((a for a in args[1:] if not a.startswith("-")), "unittest")
2270
- if launcher == "unittest":
2271
- cmd = [sys.executable, "-m", "unittest", "discover", "tests"]
2272
- elif launcher == "pytest":
2273
- # pytest is natively compact with quiet flags; the wrapper
2274
- # guarantees them instead of trusting the caller.
2275
- cmd = [sys.executable, "-m", "pytest", "-q", "--tb=short"]
2276
- else:
2277
- print(f"Unknown test launcher '{launcher}' — supported: unittest (default), pytest.")
2278
- sys.exit(1)
2279
- print(f"\n⚡ Running the unit test suite ({launcher})...")
2280
- try:
2281
- proc = subprocess.run(cmd, cwd=PROJECT_ROOT, capture_output=True, text=True)
2282
- except FileNotFoundError:
2283
- print(f"Launcher '{launcher}' is not available — install it (e.g. pip install pytest) and retry.")
2284
- sys.exit(1)
2285
- raw = (proc.stdout or "") + (proc.stderr or "")
2286
- if verbose:
2287
- print(raw)
2288
- elif launcher == "pytest":
2289
- print(raw.rstrip() or "(no output)")
2290
- else:
2291
- print(summarize_unittest_output(raw, full_traceback=full_tb))
2292
- sys.exit(proc.returncode)
2293
-
2294
- elif command in ("prune", "cleanup"):
2295
- days = None
2296
- max_events = None
2297
- i = 1
2298
- while i < len(args):
2299
- if args[i] == "--days" and i + 1 < len(args):
2300
- try:
2301
- days = int(args[i + 1])
2302
- except ValueError:
2303
- pass
2304
- i += 2
2305
- elif args[i] in ("--max", "--max-events") and i + 1 < len(args):
2306
- try:
2307
- max_events = int(args[i + 1])
2308
- except ValueError:
2309
- pass
2310
- i += 2
2311
- else:
2312
- i += 1
2313
-
2314
- if days is None and max_events is None:
2315
- days = 30
2316
- max_events = 5000
2317
-
2318
- print(f"\n\033[1m\033[36m⚡ DATA RETENTION PRUNE ⚡\033[0m")
2319
- print(f"Policy: retain events < {days or 'any'} days old, max {max_events or 'unlimited'} entries.")
2320
- res = MetricsTracker().prune(days=days, max_events=max_events, vacuum=True)
2321
- b_before = res.get("db_size_before", 0) / 1024.0
2322
- b_after = res.get("db_size_after", 0) / 1024.0
2323
- print(f"\033[32m✔ Pruned {res['pruned_events']} granular events into lifetime rollup table.\033[0m")
2324
- print(f" DB Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\n")
2325
-
2326
- elif command == "vacuum":
2327
- print("\n\033[1m\033[36m⚡ VACUUMING METRICS DATABASE ⚡\033[0m")
2328
- t = MetricsTracker()
2329
- b_before = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
2330
- t.vacuum()
2331
- # Repair pass: rebuild session aggregates straight from events (guards
2332
- # against sessions/events drift after crashes or manual DB edits).
2333
- t.recalculate_sessions()
2334
- b_after = (os.path.getsize(t.db_path) if os.path.exists(t.db_path) else 0) / 1024.0
2335
- print(f"\033[32m✔ Database compacted + session aggregates rebuilt. Size: {b_before:.1f} KB ➔ {b_after:.1f} KB\033[0m\n")
2336
-
2337
- elif command in ("expand-ref", "expand_ref", "expand"):
2338
- if len(args) < 2:
2339
- print("Usage: tokensafe expand-ref <hash8>")
2340
- sys.exit(1)
2341
- ref_hash = args[1].strip()
2342
- from src.stash import retrieve_block
2343
- content = retrieve_block(ref_hash)
2344
- if content is None:
2345
- print(f"\033[31mError: Stashed reference '{ref_hash}' not found or expired.\033[0m")
2346
- sys.exit(1)
2347
- print(content)
2348
-
2349
- elif command in ("optimize-image", "image-opt", "image"):
2350
- if len(args) < 2:
2351
- print("Usage: tokensafe optimize-image <image_path> [--max-edge 1024]")
2352
- sys.exit(1)
2353
- img_path = args[1]
2354
- max_edge = 1024
2355
- if "--max-edge" in args:
2356
- idx = args.index("--max-edge")
2357
- if idx + 1 < len(args):
2358
- try:
2359
- max_edge = int(args[idx + 1])
2360
- except ValueError:
2361
- pass
2362
- from src.image_downscale import ImageDownscaler
2363
- res = ImageDownscaler.optimize(img_path, max_edge=max_edge)
2364
- if not res.get("success"):
2365
- print(f"\033[31mError: {res.get('error')}\033[0m")
2366
- sys.exit(1)
2367
- if res.get("was_downscaled"):
2368
- print(f"\033[32m✔ Downscaled image using {res.get('engine')}:\033[0m {res['orig_dimensions']} ➔ {res['new_dimensions']}")
2369
- print(f" Saved vision tokens: ~{res['saved_tokens']} tokens")
2370
- print(f" Optimized image: {res['optimized_path']}")
2371
- else:
2372
- print(f"Image within bounds ({res.get('dimensions', 'N/A')} <= {max_edge}px). Using original file.")
2373
-
2374
- elif command in ("prune-superseded", "prune_superseded"):
2375
- if len(args) < 2:
2376
- print("Usage: tokensafe prune-superseded <transcript_path>")
2377
- sys.exit(1)
2378
- t_path = args[1]
2379
- from src.superseded import SupersededPruner
2380
- res = SupersededPruner.prune_transcript(t_path)
2381
- if not res.get("success"):
2382
- print(f"\033[31mError: {res.get('error')}\033[0m")
2383
- sys.exit(1)
2384
- print(f"\033[32m✔ Pruned {res['pruned_count']} superseded tool read(s) from transcript.\033[0m")
2385
- print(f" Saved context: ~{res['saved_tokens']} tokens")
2386
-
2387
- elif command in ("mistakes", "deadends"):
2388
- from src.mistakes import MistakesLedger
2389
- sub = args[1] if len(args) > 1 else "list"
2390
- if sub in ("clear", "reset"):
2391
- c = MistakesLedger.clear_mistakes(os.getcwd())
2392
- print(f"\033[32m✔ Cleared {c} mistake record(s).\033[0m")
2393
- elif sub in ("record", "add"):
2394
- reason = "Failed hypothesis"
2395
- f_path = None
2396
- if "--reason" in args:
2397
- idx = args.index("--reason")
2398
- if idx + 1 < len(args):
2399
- reason = args[idx + 1]
2400
- if "--file" in args:
2401
- idx = args.index("--file")
2402
- if idx + 1 < len(args):
2403
- f_path = args[idx + 1]
2404
- entry = MistakesLedger.record_revert(f_path or "project", reason, project_root=os.getcwd())
2405
- print(f"\033[32m✔ Recorded mistake: {entry['summary']}\033[0m")
2406
- else:
2407
- entries = MistakesLedger.list_mistakes(project_root=os.getcwd())
2408
- if not entries:
2409
- print("No recorded dead-ends or reverts for this project.")
2410
- else:
2411
- print(f"\n\033[1m\033[36m⚡ TOKENSAFE ANTI-STUCK DEAD-ENDS LEDGER ({len(entries)}) ⚡\033[0m\n")
2412
- for e in entries:
2413
- print(f" • \033[1m{e.get('file') or 'project'}\033[0m: {e.get('summary')} [{e.get('source')}]")
2414
- guard = MistakesLedger.get_guard_prompt(project_root=os.getcwd())
2415
- if guard:
2416
- print(f"\n\033[33mActive prompt guard:\033[0m\n{guard}\n")
2417
-
2418
- elif command == "reset":
2419
- confirm = input("Are you sure you want to reset all token metrics? [y/N]: ").strip().lower()
2420
- if confirm == "y":
2421
- MetricsTracker().reset()
2422
- print("Metrics database reset successfully.")
2423
- else:
2424
- print("Reset cancelled.")
2425
-
2426
- else:
2427
- print(f"Unknown command: {command}")
2428
- print("Available commands: init, login, logout, stats, status, sync, html, test, tests, expand-ref, wrap, web, doctor, skills, providers, mcp, benchmark, proxy, graph, map, skeleton, guard, mistakes, vacuum, prune, digest, activate, license, markdown, install, uninstall, setup, update, check-update, reset. Run 'tokensafe help' for details.")
2429
- sys.exit(1)
3
+ import runpy
4
+ import sys
2430
5
 
2431
6
  if __name__ == "__main__":
2432
- main()
7
+ _here = os.path.dirname(os.path.realpath(__file__))
8
+ _root = os.path.dirname(_here)
9
+ # As a script, sys.path[0] is this directory: drop it so nothing here
10
+ # shadows a real module, and make the install root importable.
11
+ sys.path[:] = [p for p in sys.path if os.path.realpath(p or os.curdir) != _here]
12
+ if _root not in sys.path:
13
+ sys.path.insert(0, _root)
14
+ runpy.run_module("tokensafe.cli", run_name="__main__", alter_sys=True)