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