tokensafe 4.16.3 → 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 +1 -1
- 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 -2487
- package/src/mcp_server.py +11 -5437
- package/src/proxy.py +11 -1834
- 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 +21 -18
- 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 +51 -10
- 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 +729 -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/{src → tokensafe}/ingress_staging.py +9 -9
- 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/{src → tokensafe}/read_baseline.py +1 -1
- package/{src → tokensafe}/repo_compute.py +1 -1
- 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
|
@@ -22,7 +22,7 @@ from collections import OrderedDict
|
|
|
22
22
|
from dataclasses import dataclass, field
|
|
23
23
|
from typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple
|
|
24
24
|
|
|
25
|
-
from
|
|
25
|
+
from tokensafe.format_parsers.i18n_strings import (
|
|
26
26
|
CatalogEntry,
|
|
27
27
|
StringCatalogReducer,
|
|
28
28
|
locale_namespace_from_path,
|
|
@@ -154,34 +154,46 @@ def list_locales(messages_dir: str) -> List[str]:
|
|
|
154
154
|
return []
|
|
155
155
|
|
|
156
156
|
|
|
157
|
-
_LOCALE_CACHE: "OrderedDict[Tuple[str, str,
|
|
157
|
+
_LOCALE_CACHE: "OrderedDict[Tuple[str, str, Tuple], LocaleCatalog]" = OrderedDict()
|
|
158
158
|
_LOCALE_CACHE_MAX = 24
|
|
159
159
|
|
|
160
160
|
|
|
161
161
|
def load_locale(messages_dir: str, locale: str) -> LocaleCatalog:
|
|
162
|
-
"""Parses every catalog file of a locale.
|
|
162
|
+
"""Parses every catalog file of a locale.
|
|
163
|
+
|
|
164
|
+
Cached by each file's (name, mtime_ns, size). A directory mtime only
|
|
165
|
+
changes when files are added or removed, so an edit made in place (an
|
|
166
|
+
editor save, git checkout) kept serving the old text and `dict apply`
|
|
167
|
+
wrote that stale text back over the fresh edit.
|
|
168
|
+
"""
|
|
163
169
|
messages_dir = os.path.abspath(messages_dir)
|
|
164
170
|
locale_dir = os.path.join(messages_dir, locale)
|
|
165
171
|
try:
|
|
166
|
-
|
|
172
|
+
names = sorted(
|
|
173
|
+
(d for d in os.scandir(locale_dir)
|
|
174
|
+
if d.is_file() and d.name.lower().endswith(CATALOG_EXTS)),
|
|
175
|
+
key=lambda d: d.name,
|
|
176
|
+
)
|
|
167
177
|
except OSError:
|
|
168
|
-
|
|
169
|
-
|
|
178
|
+
names = []
|
|
179
|
+
signature = []
|
|
180
|
+
for dirent in names:
|
|
181
|
+
try:
|
|
182
|
+
st = dirent.stat()
|
|
183
|
+
except OSError:
|
|
184
|
+
continue
|
|
185
|
+
signature.append((dirent.name, st.st_mtime_ns, st.st_size))
|
|
186
|
+
key = (messages_dir, locale, tuple(signature))
|
|
170
187
|
cached = _LOCALE_CACHE.get(key)
|
|
171
188
|
if cached is not None:
|
|
172
189
|
_LOCALE_CACHE.move_to_end(key)
|
|
173
190
|
return cached
|
|
174
191
|
|
|
175
192
|
catalog = LocaleCatalog(messages_dir=messages_dir, locale=locale)
|
|
176
|
-
try:
|
|
177
|
-
names = sorted(os.scandir(locale_dir), key=lambda d: d.name)
|
|
178
|
-
except OSError:
|
|
179
|
-
names = []
|
|
180
193
|
for dirent in names:
|
|
181
|
-
if not dirent.is_file() or not dirent.name.lower().endswith(CATALOG_EXTS):
|
|
182
|
-
continue
|
|
183
194
|
try:
|
|
184
|
-
|
|
195
|
+
# newline="" keeps CRLF catalogs CRLF when apply writes them back.
|
|
196
|
+
with open(dirent.path, "r", encoding="utf-8", errors="replace", newline="") as handle:
|
|
185
197
|
text = handle.read()
|
|
186
198
|
except OSError:
|
|
187
199
|
continue
|
|
@@ -546,8 +558,21 @@ def apply(
|
|
|
546
558
|
diffs.extend(diff)
|
|
547
559
|
if not dry_run:
|
|
548
560
|
abspath = os.path.join(catalog.messages_dir, relpath)
|
|
561
|
+
try:
|
|
562
|
+
with open(abspath, "r", encoding="utf-8", errors="replace", newline="") as handle:
|
|
563
|
+
on_disk = handle.read()
|
|
564
|
+
except OSError:
|
|
565
|
+
on_disk = None
|
|
566
|
+
if on_disk != text:
|
|
567
|
+
# Changed since it was parsed: writing would revert that edit.
|
|
568
|
+
for c in changed:
|
|
569
|
+
if c["file"] == relpath:
|
|
570
|
+
refused[c["path"]] = "refused: file changed on disk since it was read; re-run"
|
|
571
|
+
changed = [c for c in changed if c["file"] != relpath]
|
|
572
|
+
del diffs[len(diffs) - len(diff):]
|
|
573
|
+
continue
|
|
549
574
|
tmp = abspath + ".tokensafe.tmp"
|
|
550
|
-
with open(tmp, "w", encoding="utf-8") as handle:
|
|
575
|
+
with open(tmp, "w", encoding="utf-8", newline="") as handle:
|
|
551
576
|
handle.write(new_text)
|
|
552
577
|
os.replace(tmp, abspath)
|
|
553
578
|
written.append(relpath)
|
|
@@ -16,7 +16,7 @@ import shutil
|
|
|
16
16
|
import hashlib
|
|
17
17
|
import subprocess
|
|
18
18
|
from typing import Dict, Any, Tuple, Optional
|
|
19
|
-
from
|
|
19
|
+
from tokensafe.paths import resolve_data_dir
|
|
20
20
|
|
|
21
21
|
# Supported extensions
|
|
22
22
|
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif"}
|
|
@@ -50,14 +50,14 @@ def threshold() -> int:
|
|
|
50
50
|
|
|
51
51
|
|
|
52
52
|
def _count(text: str) -> int:
|
|
53
|
-
from
|
|
53
|
+
from tokensafe.tokenizer import count_tokens
|
|
54
54
|
|
|
55
55
|
return count_tokens(text)
|
|
56
56
|
|
|
57
57
|
|
|
58
58
|
def _redact(text: str) -> str:
|
|
59
59
|
try:
|
|
60
|
-
from
|
|
60
|
+
from tokensafe.compactor import SecretRedactor
|
|
61
61
|
|
|
62
62
|
result = SecretRedactor.redact_text(text)
|
|
63
63
|
if isinstance(result, tuple):
|
|
@@ -192,7 +192,7 @@ def stage(prompt: str, agent: str = "", session_id: str = "") -> Optional[Dict[s
|
|
|
192
192
|
return None
|
|
193
193
|
redacted = _redact(prompt)
|
|
194
194
|
try:
|
|
195
|
-
from
|
|
195
|
+
from tokensafe.stash import stash_block
|
|
196
196
|
|
|
197
197
|
hash8, _marker = stash_block(redacted, source="ingress")
|
|
198
198
|
except Exception:
|
|
@@ -202,7 +202,7 @@ def stage(prompt: str, agent: str = "", session_id: str = "") -> Optional[Dict[s
|
|
|
202
202
|
sections = split_sections(redacted)
|
|
203
203
|
summary = ""
|
|
204
204
|
try:
|
|
205
|
-
from
|
|
205
|
+
from tokensafe.compactor import PromptCompactor
|
|
206
206
|
|
|
207
207
|
compaction = PromptCompactor.compact(redacted, enable_distill=False)
|
|
208
208
|
if compaction.get("saved_tokens", 0) >= 5:
|
|
@@ -213,7 +213,7 @@ def stage(prompt: str, agent: str = "", session_id: str = "") -> Optional[Dict[s
|
|
|
213
213
|
context_text = f"{summary}\n{handle}" if summary else handle
|
|
214
214
|
injected_tokens = _count(context_text)
|
|
215
215
|
try:
|
|
216
|
-
from
|
|
216
|
+
from tokensafe.metrics import MetricsTracker
|
|
217
217
|
|
|
218
218
|
MetricsTracker().record_event(
|
|
219
219
|
session_id=session_id or f"ingress:{agent or 'unknown'}",
|
|
@@ -250,7 +250,7 @@ def append_handle(compacted_text: str, staged: Optional[Dict[str, Any]]) -> str:
|
|
|
250
250
|
|
|
251
251
|
|
|
252
252
|
def _rank_sections(query: str, sections: List[Section]) -> List[Section]:
|
|
253
|
-
from
|
|
253
|
+
from tokensafe.transcript_recall import tokenize
|
|
254
254
|
|
|
255
255
|
query_terms = set(tokenize(query))
|
|
256
256
|
if not query_terms:
|
|
@@ -285,7 +285,7 @@ def show(
|
|
|
285
285
|
session_id: str = "",
|
|
286
286
|
) -> Dict[str, Any]:
|
|
287
287
|
"""Return a section (or the index) from a staged prompt."""
|
|
288
|
-
from
|
|
288
|
+
from tokensafe.stash import retrieve_block
|
|
289
289
|
|
|
290
290
|
content = retrieve_block(str(hash_or_ref or ""))
|
|
291
291
|
if content is None:
|
|
@@ -335,7 +335,7 @@ def show(
|
|
|
335
335
|
"truncated": truncated,
|
|
336
336
|
}
|
|
337
337
|
try:
|
|
338
|
-
from
|
|
338
|
+
from tokensafe.metrics import MetricsTracker
|
|
339
339
|
|
|
340
340
|
MetricsTracker().record_event(
|
|
341
341
|
session_id=session_id or "ingress",
|
|
@@ -354,7 +354,7 @@ def stats() -> Dict[str, Any]:
|
|
|
354
354
|
staged: set = set()
|
|
355
355
|
fetched: set = set()
|
|
356
356
|
try:
|
|
357
|
-
from
|
|
357
|
+
from tokensafe.metrics import MetricsTracker
|
|
358
358
|
|
|
359
359
|
tracker = MetricsTracker()
|
|
360
360
|
with tracker._get_connection() as conn:
|
|
@@ -17,7 +17,7 @@ import hashlib
|
|
|
17
17
|
import shutil
|
|
18
18
|
import re
|
|
19
19
|
import shlex
|
|
20
|
-
from
|
|
20
|
+
from tokensafe.win_paths import quote_hook_command
|
|
21
21
|
import signal
|
|
22
22
|
import subprocess
|
|
23
23
|
import time
|
|
@@ -33,7 +33,7 @@ DIM = "\033[2m"
|
|
|
33
33
|
|
|
34
34
|
HOME = os.path.expanduser("~")
|
|
35
35
|
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
|
36
|
-
MCP_SERVER_PATH = os.path.join(PROJECT_ROOT, "
|
|
36
|
+
MCP_SERVER_PATH = os.path.join(PROJECT_ROOT, "tokensafe", "mcp_server.py")
|
|
37
37
|
PYTHON_BIN = sys.executable
|
|
38
38
|
|
|
39
39
|
def _app_data_dir(*parts: str) -> str:
|
|
@@ -184,8 +184,18 @@ def _has_vscode_extension(prefixes: Tuple[str, ...]) -> bool:
|
|
|
184
184
|
class AgentInstaller:
|
|
185
185
|
"""Manages multi-agent detection and configuration injection."""
|
|
186
186
|
|
|
187
|
+
# The tokensafe section ends at the next TOML table header: dotted bare or
|
|
188
|
+
# quoted keys, where a quoted key may hold any character. The old character
|
|
189
|
+
# class had no '/', so `[projects."/Users/me/repo"]` (Codex trust tables) was
|
|
190
|
+
# not seen as a header and every table after the section was deleted. A line
|
|
191
|
+
# whose FIRST key is a quoted path (`["/path/mcp_server.py"]`) is still an
|
|
192
|
+
# item of a multi-line array, not a header.
|
|
193
|
+
_TOML_KEY = r'(?:[A-Za-z0-9_-]+|"[^"\n]*"|\'[^\'\n]*\')'
|
|
187
194
|
_CODEX_SECTION_RE = re.compile(
|
|
188
|
-
r'(?ms)^\[mcp_servers\.tokensafe\]\s*\n
|
|
195
|
+
r'(?ms)^\[mcp_servers\.tokensafe\]\s*\n'
|
|
196
|
+
r'(?:(?!^\[{1,2}[ \t]*(?!["\']?(?:/|[A-Za-z]:\\))'
|
|
197
|
+
+ _TOML_KEY + r'(?:[ \t]*\.[ \t]*' + _TOML_KEY + r')*'
|
|
198
|
+
r'[ \t]*\]{1,2}[ \t]*(?:#[^\n]*)?$).)*'
|
|
189
199
|
)
|
|
190
200
|
_CODEX_ORPHAN_LINE_RE = re.compile(r'(?m)^\s*\["[^"\n]*(?:mcp_server\.py|tokensafe[^"\n]*)"\]\s*\n?')
|
|
191
201
|
|
|
@@ -361,16 +371,44 @@ class AgentInstaller:
|
|
|
361
371
|
script = os.path.join(PROJECT_ROOT, "hooks", script_name)
|
|
362
372
|
return quote_hook_command([PYTHON_BIN, script])
|
|
363
373
|
|
|
374
|
+
BACKUP_KEEP = 5
|
|
375
|
+
|
|
376
|
+
@classmethod
|
|
377
|
+
def _backup_config(cls, config_file: str) -> None:
|
|
378
|
+
"""Keeps the last BACKUP_KEEP distinct copies (.backup, .backup.1 ...).
|
|
379
|
+
|
|
380
|
+
A single .backup overwritten on every run lost the user's original
|
|
381
|
+
config after the second install. Identical content is not rotated, so
|
|
382
|
+
repeated runs never push the pre-TokenSafe copy out.
|
|
383
|
+
"""
|
|
384
|
+
try:
|
|
385
|
+
with open(config_file, "rb") as f:
|
|
386
|
+
current = f.read()
|
|
387
|
+
except OSError:
|
|
388
|
+
return
|
|
389
|
+
first = f"{config_file}.backup"
|
|
390
|
+
try:
|
|
391
|
+
with open(first, "rb") as f:
|
|
392
|
+
if f.read() == current:
|
|
393
|
+
return
|
|
394
|
+
except OSError:
|
|
395
|
+
pass
|
|
396
|
+
try:
|
|
397
|
+
for i in range(cls.BACKUP_KEEP - 1, 0, -1):
|
|
398
|
+
src = first if i == 1 else f"{first}.{i - 1}"
|
|
399
|
+
if os.path.exists(src):
|
|
400
|
+
os.replace(src, f"{first}.{i}")
|
|
401
|
+
shutil.copy2(config_file, first)
|
|
402
|
+
except OSError:
|
|
403
|
+
pass
|
|
404
|
+
|
|
364
405
|
@staticmethod
|
|
365
406
|
def _load_json_with_backup(config_file: str) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
|
366
407
|
"""Reads a JSON config file after creating a .backup copy.
|
|
367
408
|
If parsing fails or root is non-dict, refuses to overwrite existing data."""
|
|
368
409
|
if not os.path.exists(config_file):
|
|
369
410
|
return {}, None
|
|
370
|
-
|
|
371
|
-
shutil.copy2(config_file, f"{config_file}.backup")
|
|
372
|
-
except Exception:
|
|
373
|
-
pass
|
|
411
|
+
AgentInstaller._backup_config(config_file)
|
|
374
412
|
try:
|
|
375
413
|
with open(config_file, "r", encoding="utf-8") as f:
|
|
376
414
|
data = json.load(f)
|
|
@@ -390,6 +428,17 @@ class AgentInstaller:
|
|
|
390
428
|
json.dump(data, f, indent=2)
|
|
391
429
|
os.replace(tmp, config_file)
|
|
392
430
|
|
|
431
|
+
@staticmethod
|
|
432
|
+
def _atomic_write_text(config_file: str, content: str) -> None:
|
|
433
|
+
"""Write via a temp file + rename so a crash never leaves a truncated config."""
|
|
434
|
+
parent = os.path.dirname(config_file)
|
|
435
|
+
if parent:
|
|
436
|
+
os.makedirs(parent, exist_ok=True)
|
|
437
|
+
tmp = f"{config_file}.tmp.{os.getpid()}"
|
|
438
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
439
|
+
f.write(content)
|
|
440
|
+
os.replace(tmp, config_file)
|
|
441
|
+
|
|
393
442
|
@classmethod
|
|
394
443
|
def install_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
395
444
|
"""Registers TokenSafe lifecycle-hook adapters with agents that support them.
|
|
@@ -399,7 +448,7 @@ class AgentInstaller:
|
|
|
399
448
|
Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
|
|
400
449
|
if agent_key == "codex":
|
|
401
450
|
return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
|
|
402
|
-
from
|
|
451
|
+
from tokensafe.host_capabilities import supports
|
|
403
452
|
if not supports(agent_key, "hooks"):
|
|
404
453
|
return False, "hooks not applicable for this agent"
|
|
405
454
|
|
|
@@ -412,15 +461,13 @@ class AgentInstaller:
|
|
|
412
461
|
os.makedirs(os.path.dirname(config_file), exist_ok=True)
|
|
413
462
|
content = ""
|
|
414
463
|
if os.path.exists(config_file):
|
|
415
|
-
|
|
416
|
-
shutil.copy2(config_file, f"{config_file}.backup")
|
|
417
|
-
except Exception:
|
|
418
|
-
pass
|
|
464
|
+
cls._backup_config(config_file)
|
|
419
465
|
try:
|
|
420
466
|
with open(config_file, "r", encoding="utf-8") as f:
|
|
421
467
|
content = f.read()
|
|
422
|
-
except Exception:
|
|
423
|
-
|
|
468
|
+
except Exception as e:
|
|
469
|
+
# Writing after a failed read would replace the user's config.
|
|
470
|
+
return False, f"Could not read {config_file} ({e}); left untouched"
|
|
424
471
|
|
|
425
472
|
toml_hook_cmd = json.dumps(kimi_cmd)
|
|
426
473
|
|
|
@@ -665,6 +712,27 @@ class AgentInstaller:
|
|
|
665
712
|
cls._atomic_write_json(config_file, data)
|
|
666
713
|
return True, "guards registered (shell + junk-read + prompt pipeline)"
|
|
667
714
|
|
|
715
|
+
# Any TOML table header: [table], [[array]], dotted/quoted keys included.
|
|
716
|
+
_TOML_HEADER_RE = re.compile(r'(?m)^(?=[ \t]*\[)')
|
|
717
|
+
|
|
718
|
+
@classmethod
|
|
719
|
+
def _strip_kimi_hook_tables(cls, content: str) -> Tuple[str, bool]:
|
|
720
|
+
"""Drops only the [[hooks]] tables whose command runs kimi_hook.py.
|
|
721
|
+
|
|
722
|
+
Splitting on ``[[hooks]]`` alone glued every following table (``[mcp]``,
|
|
723
|
+
the user's own settings) onto the last TokenSafe hook, so uninstall
|
|
724
|
+
deleted them too.
|
|
725
|
+
"""
|
|
726
|
+
keep = []
|
|
727
|
+
removed = False
|
|
728
|
+
for chunk in cls._TOML_HEADER_RE.split(content):
|
|
729
|
+
header = chunk.lstrip().split("\n", 1)[0].strip()
|
|
730
|
+
if re.match(r'\[\[\s*hooks\s*\]\]', header) and "kimi_hook.py" in chunk:
|
|
731
|
+
removed = True
|
|
732
|
+
continue
|
|
733
|
+
keep.append(chunk)
|
|
734
|
+
return "".join(keep), removed
|
|
735
|
+
|
|
668
736
|
@classmethod
|
|
669
737
|
def uninstall_hooks_config(cls, agent_key: str) -> Tuple[bool, str]:
|
|
670
738
|
"""Removes TokenSafe lifecycle hooks from agents that support them."""
|
|
@@ -675,26 +743,14 @@ class AgentInstaller:
|
|
|
675
743
|
config_file = os.path.join(HOME, ".kimi-code", "config.toml")
|
|
676
744
|
if not os.path.exists(config_file):
|
|
677
745
|
return True, "Kimi Code config.toml not found"
|
|
678
|
-
|
|
679
|
-
shutil.copy2(config_file, f"{config_file}.backup")
|
|
680
|
-
except Exception:
|
|
681
|
-
pass
|
|
746
|
+
cls._backup_config(config_file)
|
|
682
747
|
try:
|
|
683
748
|
with open(config_file, "r", encoding="utf-8") as f:
|
|
684
749
|
content = f.read()
|
|
685
750
|
except Exception:
|
|
686
751
|
return False, f"Could not read {config_file}"
|
|
687
752
|
|
|
688
|
-
|
|
689
|
-
keep = []
|
|
690
|
-
removed = False
|
|
691
|
-
for s in sections:
|
|
692
|
-
if "kimi_hook.py" in s:
|
|
693
|
-
removed = True
|
|
694
|
-
continue
|
|
695
|
-
keep.append(s)
|
|
696
|
-
|
|
697
|
-
new_content = "".join(keep)
|
|
753
|
+
new_content, removed = cls._strip_kimi_hook_tables(content)
|
|
698
754
|
new_content = re.sub(r'(?m)^[ \t]*#[ \t]*TokenSafe[^\n]*\n?', '', new_content)
|
|
699
755
|
cleaned = new_content.strip()
|
|
700
756
|
if not cleaned:
|
|
@@ -704,8 +760,9 @@ class AgentInstaller:
|
|
|
704
760
|
except Exception:
|
|
705
761
|
pass
|
|
706
762
|
|
|
707
|
-
|
|
708
|
-
|
|
763
|
+
if not removed:
|
|
764
|
+
return True, "No TokenSafe hooks in config.toml"
|
|
765
|
+
cls._atomic_write_text(config_file, cleaned + "\n")
|
|
709
766
|
return True, "Removed TokenSafe hooks from ~/.kimi-code/config.toml" if removed else "No TokenSafe hooks in config.toml"
|
|
710
767
|
|
|
711
768
|
if agent_key == "claude_code":
|
|
@@ -967,7 +1024,7 @@ class AgentInstaller:
|
|
|
967
1024
|
@staticmethod
|
|
968
1025
|
def _proxy_routes_path() -> str:
|
|
969
1026
|
try:
|
|
970
|
-
from
|
|
1027
|
+
from tokensafe.paths import resolve_data_dir
|
|
971
1028
|
return os.path.join(resolve_data_dir(), "proxy_routes.json")
|
|
972
1029
|
except Exception:
|
|
973
1030
|
return os.path.join(HOME, ".tokensafe", "data", "proxy_routes.json")
|
|
@@ -1144,7 +1201,7 @@ class AgentInstaller:
|
|
|
1144
1201
|
<array>
|
|
1145
1202
|
<string>{python_bin}</string>
|
|
1146
1203
|
<string>-m</string>
|
|
1147
|
-
<string>
|
|
1204
|
+
<string>tokensafe.proxy</string>
|
|
1148
1205
|
<string>{cls.PROXY_PORT}</string>
|
|
1149
1206
|
</array>
|
|
1150
1207
|
<key>WorkingDirectory</key><string>{PROJECT_ROOT}</string>
|
|
@@ -1171,7 +1228,7 @@ Description=TokenSafe Local AI Proxy
|
|
|
1171
1228
|
After=network.target
|
|
1172
1229
|
|
|
1173
1230
|
[Service]
|
|
1174
|
-
ExecStart={python_bin} -m
|
|
1231
|
+
ExecStart={python_bin} -m tokensafe.proxy {cls.PROXY_PORT}
|
|
1175
1232
|
WorkingDirectory={PROJECT_ROOT}
|
|
1176
1233
|
Restart=always
|
|
1177
1234
|
RestartSec=3
|
|
@@ -1260,7 +1317,7 @@ WantedBy=default.target
|
|
|
1260
1317
|
pass
|
|
1261
1318
|
heartbeat_age = None
|
|
1262
1319
|
try:
|
|
1263
|
-
from
|
|
1320
|
+
from tokensafe.paths import resolve_data_dir
|
|
1264
1321
|
marker = os.path.join(resolve_data_dir(), ".proxy_active")
|
|
1265
1322
|
if os.path.exists(marker):
|
|
1266
1323
|
with open(marker, "r", encoding="utf-8") as f:
|
|
@@ -1327,7 +1384,7 @@ WantedBy=default.target
|
|
|
1327
1384
|
Fail-open: skips quietly on non-interactive environments (CI, scripts).
|
|
1328
1385
|
"""
|
|
1329
1386
|
try:
|
|
1330
|
-
from
|
|
1387
|
+
from tokensafe.license_manager import LicenseManager
|
|
1331
1388
|
tier, lic = LicenseManager.get_active_license()
|
|
1332
1389
|
email = lic.get("email", "")
|
|
1333
1390
|
|
|
@@ -1358,14 +1415,14 @@ WantedBy=default.target
|
|
|
1358
1415
|
if context == "update":
|
|
1359
1416
|
used_tokens = 0
|
|
1360
1417
|
try:
|
|
1361
|
-
from
|
|
1418
|
+
from tokensafe.metrics import MetricsTracker
|
|
1362
1419
|
quota = LicenseManager.check_quota(MetricsTracker())
|
|
1363
1420
|
used_tokens = int(quota.get("monthly_saved", 0))
|
|
1364
1421
|
except Exception:
|
|
1365
1422
|
used_tokens = 0
|
|
1366
1423
|
pct = min(100.0, (used_tokens / 50_000) * 100) if 50_000 > 0 else 0.0
|
|
1367
1424
|
try:
|
|
1368
|
-
from
|
|
1425
|
+
from tokensafe.version_checker import CURRENT_VERSION
|
|
1369
1426
|
ver_label = f"v{CURRENT_VERSION}"
|
|
1370
1427
|
except Exception:
|
|
1371
1428
|
ver_label = ""
|
|
@@ -1383,7 +1440,7 @@ WantedBy=default.target
|
|
|
1383
1440
|
|
|
1384
1441
|
answer = _read_input(f" {CYAN}→ Activate your free 500k Community license now? [{GREEN}Y{RESET}/n]: {RESET}").lower()
|
|
1385
1442
|
if answer in ("", "y", "yes"):
|
|
1386
|
-
from
|
|
1443
|
+
from tokensafe.cli import main as cli_main
|
|
1387
1444
|
cli_main(["login"])
|
|
1388
1445
|
else:
|
|
1389
1446
|
# Strict 1-step polite decline (no nagging on update)
|
|
@@ -1403,14 +1460,14 @@ WantedBy=default.target
|
|
|
1403
1460
|
|
|
1404
1461
|
answer = _read_input(f" {CYAN}→ Activate your free 500k Community license now? [{GREEN}Y{RESET}/n]: {RESET}").lower()
|
|
1405
1462
|
if answer in ("", "y", "yes"):
|
|
1406
|
-
from
|
|
1463
|
+
from tokensafe.cli import main as cli_main
|
|
1407
1464
|
cli_main(["login"])
|
|
1408
1465
|
else:
|
|
1409
1466
|
# Intelligent One-More-Chance nudge highlighting quick exhaustion of guest quota
|
|
1410
1467
|
print(f"\n {YELLOW}⚠️ Are you sure?{RESET} In Guest mode, optimizations pause after only 50,000 tokens (~1-2 days of coding).")
|
|
1411
1468
|
second_chance = _read_input(f" {CYAN}→ Connect your free account now for 500,000 tokens/month? [{GREEN}y{RESET}/N]: {RESET}").lower()
|
|
1412
1469
|
if second_chance in ("y", "yes"):
|
|
1413
|
-
from
|
|
1470
|
+
from tokensafe.cli import main as cli_main
|
|
1414
1471
|
cli_main(["login"])
|
|
1415
1472
|
else:
|
|
1416
1473
|
print(f"\n {CYAN}ℹ{RESET} Continuing in Guest Mode (50,000 tokens/mo limit).")
|
|
@@ -1534,15 +1591,13 @@ WantedBy=default.target
|
|
|
1534
1591
|
|
|
1535
1592
|
content = ""
|
|
1536
1593
|
if os.path.exists(config_file):
|
|
1537
|
-
|
|
1538
|
-
shutil.copy2(config_file, f"{config_file}.backup")
|
|
1539
|
-
except Exception:
|
|
1540
|
-
pass
|
|
1594
|
+
cls._backup_config(config_file)
|
|
1541
1595
|
try:
|
|
1542
1596
|
with open(config_file, "r", encoding="utf-8") as f:
|
|
1543
1597
|
content = f.read()
|
|
1544
|
-
except Exception:
|
|
1545
|
-
|
|
1598
|
+
except Exception as e:
|
|
1599
|
+
# Writing after a failed read would replace the user's config.
|
|
1600
|
+
return False, f"Could not read {config_file} ({e}); left untouched"
|
|
1546
1601
|
|
|
1547
1602
|
toml_cmd = json.dumps(PYTHON_BIN)
|
|
1548
1603
|
toml_srv = json.dumps(MCP_SERVER_PATH)
|
|
@@ -1559,8 +1614,7 @@ WantedBy=default.target
|
|
|
1559
1614
|
else:
|
|
1560
1615
|
content = (content.rstrip() + "\n\n" + server_section) if content.strip() else server_section
|
|
1561
1616
|
|
|
1562
|
-
|
|
1563
|
-
f.write(content)
|
|
1617
|
+
cls._atomic_write_text(config_file, content)
|
|
1564
1618
|
|
|
1565
1619
|
if "skills_path" in info:
|
|
1566
1620
|
cls._symlink_skill(info["skills_path"])
|
|
@@ -1652,7 +1706,7 @@ WantedBy=default.target
|
|
|
1652
1706
|
os.makedirs(os.path.dirname(mcp_file), exist_ok=True)
|
|
1653
1707
|
data, err = cls._load_json_with_backup(mcp_file)
|
|
1654
1708
|
if err or data is None:
|
|
1655
|
-
|
|
1709
|
+
return False, err or f"Failed to parse {mcp_file}"
|
|
1656
1710
|
if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
|
|
1657
1711
|
data["mcpServers"] = {}
|
|
1658
1712
|
data["mcpServers"]["tokensafe"] = {
|
|
@@ -1671,7 +1725,7 @@ WantedBy=default.target
|
|
|
1671
1725
|
os.makedirs(os.path.dirname(installed_json), exist_ok=True)
|
|
1672
1726
|
inst_data, err = cls._load_json_with_backup(installed_json)
|
|
1673
1727
|
if err or inst_data is None:
|
|
1674
|
-
|
|
1728
|
+
return False, err or f"Failed to parse {installed_json}"
|
|
1675
1729
|
if "plugins" not in inst_data or not isinstance(inst_data["plugins"], list):
|
|
1676
1730
|
inst_data["plugins"] = []
|
|
1677
1731
|
|
|
@@ -1806,11 +1860,10 @@ WantedBy=default.target
|
|
|
1806
1860
|
with open(config_file, "r", encoding="utf-8") as f:
|
|
1807
1861
|
content = f.read()
|
|
1808
1862
|
if re.search(r'(?m)^\[mcp_servers\.tokensafe\]\s*$', content) or cls._CODEX_ORPHAN_LINE_RE.search(content):
|
|
1809
|
-
|
|
1863
|
+
cls._backup_config(config_file)
|
|
1810
1864
|
content = cls._clean_codex_orphans(content)
|
|
1811
1865
|
content = cls._CODEX_SECTION_RE.sub("", content)
|
|
1812
|
-
|
|
1813
|
-
f.write(content.strip() + "\n" if content.strip() else "")
|
|
1866
|
+
cls._atomic_write_text(config_file, content.strip() + "\n" if content.strip() else "")
|
|
1814
1867
|
except Exception:
|
|
1815
1868
|
pass
|
|
1816
1869
|
|
|
@@ -1947,7 +2000,7 @@ WantedBy=default.target
|
|
|
1947
2000
|
data = json.load(f)
|
|
1948
2001
|
servers = data.get("mcpServers")
|
|
1949
2002
|
if isinstance(servers, dict) and "tokensafe" in servers:
|
|
1950
|
-
|
|
2003
|
+
AgentInstaller._backup_config(config_path)
|
|
1951
2004
|
servers.pop("tokensafe")
|
|
1952
2005
|
with open(config_path, "w", encoding="utf-8") as f:
|
|
1953
2006
|
json.dump(data, f, indent=2)
|
|
@@ -2214,7 +2267,7 @@ WantedBy=default.target
|
|
|
2214
2267
|
created.append(".agents/plugins.json")
|
|
2215
2268
|
|
|
2216
2269
|
try:
|
|
2217
|
-
from
|
|
2270
|
+
from tokensafe.paths import ensure_tokensafe_gitignore
|
|
2218
2271
|
if ensure_tokensafe_gitignore(project_dir):
|
|
2219
2272
|
created.append(".gitignore (.tokensafe/ registered)")
|
|
2220
2273
|
except Exception:
|
|
@@ -2447,7 +2500,7 @@ WantedBy=default.target
|
|
|
2447
2500
|
purged = False
|
|
2448
2501
|
if purge:
|
|
2449
2502
|
try:
|
|
2450
|
-
from
|
|
2503
|
+
from tokensafe.paths import resolve_data_dir
|
|
2451
2504
|
d_dir = resolve_data_dir()
|
|
2452
2505
|
if os.path.isdir(d_dir):
|
|
2453
2506
|
shutil.rmtree(d_dir, ignore_errors=True)
|
|
@@ -2532,7 +2585,7 @@ WantedBy=default.target
|
|
|
2532
2585
|
|
|
2533
2586
|
if purge:
|
|
2534
2587
|
try:
|
|
2535
|
-
from
|
|
2588
|
+
from tokensafe.paths import resolve_data_dir
|
|
2536
2589
|
d_dir = resolve_data_dir()
|
|
2537
2590
|
if os.path.isdir(d_dir):
|
|
2538
2591
|
shutil.rmtree(d_dir, ignore_errors=True)
|
|
@@ -2567,7 +2620,11 @@ WantedBy=default.target
|
|
|
2567
2620
|
|
|
2568
2621
|
for idx, tok in enumerate(tokens):
|
|
2569
2622
|
base = os.path.basename(tok).lower()
|
|
2570
|
-
|
|
2623
|
+
# `src/mcp_server.py` is the location before the package rename;
|
|
2624
|
+
# configs written by older installs still launch it.
|
|
2625
|
+
norm = tok.replace("\\", "/")
|
|
2626
|
+
if base == "mcp_server.py" and ("tokensafe" in tok.lower() or "agy-token-optimizer" in tok.lower()
|
|
2627
|
+
or "src/mcp_server.py" in norm or "tokensafe/mcp_server.py" in norm):
|
|
2571
2628
|
return True
|
|
2572
2629
|
if base in ("tokensafe", "tokensafe.js", "agy-tokens"):
|
|
2573
2630
|
rest = tokens[idx + 1:]
|
|
@@ -2593,7 +2650,7 @@ WantedBy=default.target
|
|
|
2593
2650
|
# Data-dir resolution is context-independent (canonical
|
|
2594
2651
|
# ~/.tokensafe/data unless TOKENSAFE_DATA_DIR overrides), so one
|
|
2595
2652
|
# marker location covers every launch context.
|
|
2596
|
-
from
|
|
2653
|
+
from tokensafe.paths import resolve_data_dir
|
|
2597
2654
|
data_dir = resolve_data_dir()
|
|
2598
2655
|
os.makedirs(data_dir, exist_ok=True)
|
|
2599
2656
|
reload_marker = os.path.join(data_dir, ".mcp_reload")
|
|
@@ -2994,7 +3051,7 @@ WantedBy=default.target
|
|
|
2994
3051
|
|
|
2995
3052
|
# 5. Refresh local version cache and report the newly installed version in a fresh process
|
|
2996
3053
|
try:
|
|
2997
|
-
from
|
|
3054
|
+
from tokensafe.paths import resolve_data_dir
|
|
2998
3055
|
cache_file = os.path.join(resolve_data_dir(), "version_cache.json")
|
|
2999
3056
|
if os.path.exists(cache_file):
|
|
3000
3057
|
os.remove(cache_file)
|
|
@@ -3002,7 +3059,7 @@ WantedBy=default.target
|
|
|
3002
3059
|
pass
|
|
3003
3060
|
try:
|
|
3004
3061
|
tokensafe_bin = fresh_bin or shutil.which("tokensafe")
|
|
3005
|
-
sync_cmd = [tokensafe_bin, "version", "--check"] if tokensafe_bin else [sys.executable, os.path.join(PROJECT_ROOT, "
|
|
3062
|
+
sync_cmd = [tokensafe_bin, "version", "--check"] if tokensafe_bin else [sys.executable, os.path.join(PROJECT_ROOT, "tokensafe", "cli.py"), "version", "--check"]
|
|
3006
3063
|
sync_env = cls._npm_subprocess_env(tokensafe_bin) if tokensafe_bin else None
|
|
3007
3064
|
subprocess.run(sync_cmd, env=sync_env, capture_output=True, text=True, timeout=5)
|
|
3008
3065
|
except Exception:
|