tokensafe 4.2.0 → 4.2.2
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/.codex-plugin/plugin.json +1 -1
- package/hooks.json +7 -0
- package/kimi.plugin.json +1 -1
- package/package.json +1 -1
- package/plugin.json +1 -1
- package/server.json +3 -3
- package/src/fts_index.py +17 -0
- package/src/installer.py +127 -37
- package/src/license_manager.py +23 -4
- package/src/mcp_server.py +42 -3
- package/src/proxy.py +30 -2
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +30 -3
package/hooks.json
CHANGED
|
@@ -15,6 +15,13 @@
|
|
|
15
15
|
"timeout": 10
|
|
16
16
|
}
|
|
17
17
|
],
|
|
18
|
+
"UserPromptSubmit": [
|
|
19
|
+
{
|
|
20
|
+
"type": "command",
|
|
21
|
+
"command": "python3 hooks/pre_invocation.py",
|
|
22
|
+
"timeout": 10
|
|
23
|
+
}
|
|
24
|
+
],
|
|
18
25
|
"PreToolUse": [
|
|
19
26
|
{
|
|
20
27
|
"matcher": "read_file|view_file|run_command|write_file|edit_file",
|
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.2.
|
|
3
|
+
"version": "4.2.2",
|
|
4
4
|
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
|
|
5
5
|
"homepage": "https://tokensafe.dev",
|
|
6
6
|
"license": "MIT",
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"mcpName": "dev.tokensafe/tokensafe",
|
|
4
|
-
"version": "4.2.
|
|
4
|
+
"version": "4.2.2",
|
|
5
5
|
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
|
|
6
6
|
"main": "bin/tokensafe.js",
|
|
7
7
|
"bin": {
|
package/plugin.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
3
|
"displayName": "TokenSafe",
|
|
4
|
-
"version": "4.2.
|
|
4
|
+
"version": "4.2.2",
|
|
5
5
|
"description": "Your coding agent isn't getting dumber. Your context is just full of trash. Local context firewall & zero-loss runtime for Cursor, Claude Code, and autonomous agents.",
|
|
6
6
|
"logo": "https://tokensafe.dev/logo.png",
|
|
7
7
|
"developerName": "TokenSafe",
|
package/server.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"name": "dev.tokensafe/tokensafe",
|
|
4
4
|
"title": "TokenSafe",
|
|
5
5
|
"description": "Your agent isn't getting dumber, your context is full of trash. Local firewall & zero-loss runtime.",
|
|
6
|
-
"version": "4.2.
|
|
6
|
+
"version": "4.2.2",
|
|
7
7
|
"websiteUrl": "https://tokensafe.dev",
|
|
8
8
|
"repository": {
|
|
9
9
|
"url": "https://github.com/tokensafe-dev/tokensafe",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"registryType": "npm",
|
|
31
31
|
"registryBaseUrl": "https://registry.npmjs.org",
|
|
32
32
|
"identifier": "tokensafe",
|
|
33
|
-
"version": "4.2.
|
|
33
|
+
"version": "4.2.2",
|
|
34
34
|
"runtimeHint": "npx",
|
|
35
35
|
"transport": {
|
|
36
36
|
"type": "stdio"
|
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
"registryType": "pypi",
|
|
47
47
|
"registryBaseUrl": "https://pypi.org",
|
|
48
48
|
"identifier": "tokensafe",
|
|
49
|
-
"version": "4.2.
|
|
49
|
+
"version": "4.2.2",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
package/src/fts_index.py
CHANGED
|
@@ -283,6 +283,23 @@ class CodeFTSIndex:
|
|
|
283
283
|
"content": row[2].strip(),
|
|
284
284
|
"bm25_rank": row[3]
|
|
285
285
|
})
|
|
286
|
+
|
|
287
|
+
# Phrase search can miss when the user types several loose words.
|
|
288
|
+
# Strictly additive retry: AND of individually quoted terms —
|
|
289
|
+
# only runs when the exact-phrase pass returned nothing.
|
|
290
|
+
if not results and " " in clean_q.strip():
|
|
291
|
+
and_query = " AND ".join(
|
|
292
|
+
f'"{term.replace(chr(34), chr(34) * 2)}"' for term in clean_q.split()
|
|
293
|
+
)
|
|
294
|
+
params2 = ([f"%{path_filter}%"] if path_filter else []) + [limit]
|
|
295
|
+
cur = con.execute(sql, (and_query, *params2))
|
|
296
|
+
for row in cur.fetchall():
|
|
297
|
+
results.append({
|
|
298
|
+
"file": row[0],
|
|
299
|
+
"line": row[1],
|
|
300
|
+
"content": row[2].strip(),
|
|
301
|
+
"bm25_rank": row[3]
|
|
302
|
+
})
|
|
286
303
|
except sqlite3.OperationalError:
|
|
287
304
|
# If trigram MATCH fails (e.g. query < 3 chars), fallback to LIKE
|
|
288
305
|
like_sql = """
|
package/src/installer.py
CHANGED
|
@@ -228,7 +228,7 @@ class AgentInstaller:
|
|
|
228
228
|
Codex has no lifecycle hooks (MCP + AGENTS.md remain the integration)."""
|
|
229
229
|
if agent_key == "codex":
|
|
230
230
|
return False, "Codex CLI has no lifecycle hooks — MCP + AGENTS.md stay the integration"
|
|
231
|
-
if agent_key not in ("claude_code", "cursor", "kimi"):
|
|
231
|
+
if agent_key not in ("claude_code", "cursor", "kimi", "zcode"):
|
|
232
232
|
return False, "hooks not applicable for this agent"
|
|
233
233
|
|
|
234
234
|
claude_cmd = cls._tokensafe_hook_command("claude_code_hook.py")
|
|
@@ -250,40 +250,35 @@ class AgentInstaller:
|
|
|
250
250
|
except Exception:
|
|
251
251
|
pass
|
|
252
252
|
|
|
253
|
+
toml_hook_cmd = json.dumps(kimi_cmd)
|
|
254
|
+
|
|
255
|
+
def _kimi_section(event: str, matcher: str = "") -> str:
|
|
256
|
+
m = f'matcher = "{matcher}"\n' if matcher else ""
|
|
257
|
+
return f'[[hooks]]\nevent = "{event}"\n{m}command = {toml_hook_cmd}\ntimeout = 10\n'
|
|
258
|
+
|
|
253
259
|
if "kimi_hook.py" in content:
|
|
254
|
-
|
|
260
|
+
# Migration: older installs lack the PostToolUse output-compaction hook.
|
|
261
|
+
if 'event = "PostToolUse"' in content:
|
|
262
|
+
return True, "TokenSafe Kimi Code hooks already registered in config.toml"
|
|
263
|
+
post_section = "\n# TokenSafe PostToolUse stdout compaction (migration)\n" + _kimi_section("PostToolUse")
|
|
264
|
+
content = content.rstrip() + "\n" + post_section
|
|
265
|
+
with open(config_file, "w", encoding="utf-8") as f:
|
|
266
|
+
f.write(content)
|
|
267
|
+
return True, "PostToolUse hook migrated in ~/.kimi-code/config.toml (stdout compaction)"
|
|
255
268
|
|
|
256
|
-
toml_hook_cmd = json.dumps(kimi_cmd)
|
|
257
269
|
hook_sections = (
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
f'command = {toml_hook_cmd}\n'
|
|
266
|
-
f'timeout = 10\n\n'
|
|
267
|
-
f'[[hooks]]\n'
|
|
268
|
-
f'event = "PreToolUse"\n'
|
|
269
|
-
f'matcher = "Bash"\n'
|
|
270
|
-
f'command = {toml_hook_cmd}\n'
|
|
271
|
-
f'timeout = 10\n\n'
|
|
272
|
-
f'[[hooks]]\n'
|
|
273
|
-
f'event = "PreToolUse"\n'
|
|
274
|
-
f'matcher = "Write"\n'
|
|
275
|
-
f'command = {toml_hook_cmd}\n'
|
|
276
|
-
f'timeout = 10\n\n'
|
|
277
|
-
f'[[hooks]]\n'
|
|
278
|
-
f'event = "PreToolUse"\n'
|
|
279
|
-
f'matcher = "Read"\n'
|
|
280
|
-
f'command = {toml_hook_cmd}\n'
|
|
281
|
-
f'timeout = 10\n'
|
|
270
|
+
'\n# TokenSafe Lifecycle Hooks\n'
|
|
271
|
+
+ _kimi_section("SessionStart") + "\n"
|
|
272
|
+
+ _kimi_section("UserPromptSubmit") + "\n"
|
|
273
|
+
+ _kimi_section("PreToolUse", "Bash") + "\n"
|
|
274
|
+
+ _kimi_section("PreToolUse", "Write") + "\n"
|
|
275
|
+
+ _kimi_section("PreToolUse", "Read") + "\n"
|
|
276
|
+
+ _kimi_section("PostToolUse")
|
|
282
277
|
)
|
|
283
278
|
content = (content.rstrip() + "\n" + hook_sections) if content.strip() else hook_sections.lstrip()
|
|
284
279
|
with open(config_file, "w", encoding="utf-8") as f:
|
|
285
280
|
f.write(content)
|
|
286
|
-
return True, "hooks registered in ~/.kimi-code/config.toml (SessionStart + UserPromptSubmit + PreToolUse Bash/Write/Read)"
|
|
281
|
+
return True, "hooks registered in ~/.kimi-code/config.toml (SessionStart + UserPromptSubmit + PreToolUse Bash/Write/Read + PostToolUse compact)"
|
|
287
282
|
|
|
288
283
|
if agent_key == "claude_code":
|
|
289
284
|
config_file = os.path.join(HOME, ".claude", "settings.json")
|
|
@@ -331,6 +326,66 @@ class AgentInstaller:
|
|
|
331
326
|
cls._atomic_write_json(config_file, data)
|
|
332
327
|
return True, "hooks registered (SessionStart + UserPromptSubmit + PreToolUse guard/write + PostToolUse stdout compact)"
|
|
333
328
|
|
|
329
|
+
if agent_key == "zcode":
|
|
330
|
+
config_file = os.path.join(HOME, ".zcode", "cli", "config.json")
|
|
331
|
+
data, err = cls._load_json_with_backup(config_file)
|
|
332
|
+
if err or data is None:
|
|
333
|
+
return False, err or f"Failed to parse {config_file}"
|
|
334
|
+
# ZCode configuration-file hooks are disabled by default and only run
|
|
335
|
+
# with enabled=true. The bundled hook scripts already speak the ZCode
|
|
336
|
+
# contract (injectSteps/systemMessage outputs + decision/reason), so
|
|
337
|
+
# registration is pure plumbing — no adapter shim needed.
|
|
338
|
+
hooks_block = data.get("hooks") if isinstance(data.get("hooks"), dict) else {}
|
|
339
|
+
hooks_block["enabled"] = True
|
|
340
|
+
events = hooks_block.get("events") if isinstance(hooks_block.get("events"), dict) else {}
|
|
341
|
+
|
|
342
|
+
def _zcode_entry(script_name: str) -> dict:
|
|
343
|
+
return {"hooks": [{
|
|
344
|
+
"type": "process",
|
|
345
|
+
"command": PYTHON_BIN,
|
|
346
|
+
"args": [os.path.join(PROJECT_ROOT, "hooks", script_name)],
|
|
347
|
+
"timeoutMs": 10000,
|
|
348
|
+
}]}
|
|
349
|
+
|
|
350
|
+
def _sync_zcode_event(event_name: str, script_name: str) -> bool:
|
|
351
|
+
entry = _zcode_entry(script_name)
|
|
352
|
+
expected = os.path.join(PROJECT_ROOT, "hooks", script_name)
|
|
353
|
+
entries = events.get(event_name)
|
|
354
|
+
if not isinstance(entries, list):
|
|
355
|
+
events[event_name] = [entry]
|
|
356
|
+
return True
|
|
357
|
+
seen = False
|
|
358
|
+
dirty = False
|
|
359
|
+
for e in entries:
|
|
360
|
+
if isinstance(e, dict) and isinstance(e.get("hooks"), list):
|
|
361
|
+
for h in e["hooks"]:
|
|
362
|
+
args = h.get("args") if isinstance(h, dict) else None
|
|
363
|
+
if not isinstance(args, list):
|
|
364
|
+
continue
|
|
365
|
+
if any(isinstance(a, str) and a.endswith(script_name) for a in args):
|
|
366
|
+
seen = True
|
|
367
|
+
if args[-1] != expected:
|
|
368
|
+
args[-1] = expected
|
|
369
|
+
dirty = True
|
|
370
|
+
if not seen:
|
|
371
|
+
entries.append(entry)
|
|
372
|
+
dirty = True
|
|
373
|
+
return dirty
|
|
374
|
+
|
|
375
|
+
changed = any([
|
|
376
|
+
_sync_zcode_event("SessionStart", "session_start.py"),
|
|
377
|
+
_sync_zcode_event("UserPromptSubmit", "pre_invocation.py"),
|
|
378
|
+
_sync_zcode_event("PreToolUse", "pre_tool_use.py"),
|
|
379
|
+
_sync_zcode_event("PostToolUse", "post_tool_use.py"),
|
|
380
|
+
_sync_zcode_event("Stop", "stop_hook.py"),
|
|
381
|
+
])
|
|
382
|
+
if changed:
|
|
383
|
+
hooks_block["events"] = events
|
|
384
|
+
data["hooks"] = hooks_block
|
|
385
|
+
cls._atomic_write_json(config_file, data)
|
|
386
|
+
return True, "ZCode hooks registered in ~/.zcode/cli/config.json (SessionStart + UserPromptSubmit + PreToolUse guard + PostToolUse compact + Stop) — restart the app to take effect"
|
|
387
|
+
return True, "TokenSafe ZCode hooks already registered"
|
|
388
|
+
|
|
334
389
|
# cursor
|
|
335
390
|
config_file = os.path.join(HOME, ".cursor", "hooks.json")
|
|
336
391
|
os.makedirs(os.path.dirname(config_file), exist_ok=True)
|
|
@@ -500,10 +555,18 @@ class AgentInstaller:
|
|
|
500
555
|
if not isinstance(routes, dict):
|
|
501
556
|
routes = {}
|
|
502
557
|
routes[fp] = {"upstream_url": upstream_url, "label": label, "added_at": int(time.time())}
|
|
503
|
-
|
|
558
|
+
# Atomic write: a truncated routes file makes the proxy silently fall
|
|
559
|
+
# back to its default upstream (the live 400-incident class).
|
|
560
|
+
tmp_path = f"{path}.tmp.{os.getpid()}"
|
|
561
|
+
with open(tmp_path, "w", encoding="utf-8") as f:
|
|
504
562
|
json.dump(routes, f, indent=2)
|
|
563
|
+
os.replace(tmp_path, path)
|
|
505
564
|
return True
|
|
506
|
-
except Exception:
|
|
565
|
+
except Exception as e:
|
|
566
|
+
try:
|
|
567
|
+
sys.stderr.write(f"[TokenSafe] WARN: proxy route registration failed ({label}): {e}\n")
|
|
568
|
+
except Exception:
|
|
569
|
+
pass
|
|
507
570
|
return False
|
|
508
571
|
|
|
509
572
|
@classmethod
|
|
@@ -565,10 +628,15 @@ class AgentInstaller:
|
|
|
565
628
|
if not api_key or not base_url:
|
|
566
629
|
return (False, f"enabled provider '{enabled_key}' lacks apiKey/baseURL")
|
|
567
630
|
clone_key = f"{enabled_key}{cls._ZCODE_CLONE_SUFFIX}"
|
|
568
|
-
# Anthropic-kind
|
|
631
|
+
# Anthropic-kind upstreams need the full messages endpoint on the route.
|
|
632
|
+
# Append for a bare host (https://api.anthropic.com) or an /anthropic
|
|
633
|
+
# mirror base (https://api.z.ai/api/anthropic); leave other paths alone.
|
|
569
634
|
upstream = base_url
|
|
570
|
-
if str(src.get("kind") or "").lower() == "anthropic" and
|
|
571
|
-
|
|
635
|
+
if str(src.get("kind") or "").lower() == "anthropic" and not upstream.endswith("/v1/messages"):
|
|
636
|
+
after_host = upstream.split("://", 1)[-1]
|
|
637
|
+
path = "/" + after_host.split("/", 1)[1] if "/" in after_host else ""
|
|
638
|
+
if not path or path.rstrip("/").endswith("/anthropic"):
|
|
639
|
+
upstream = f"{upstream.rstrip('/')}/v1/messages"
|
|
572
640
|
route_ok = cls._register_proxy_route(f"zcode:{enabled_key}", upstream, api_key)
|
|
573
641
|
clone = json.loads(json.dumps(src))
|
|
574
642
|
clone["enabled"] = True
|
|
@@ -606,10 +674,18 @@ class AgentInstaller:
|
|
|
606
674
|
origin_key = ck[: -len(cls._ZCODE_CLONE_SUFFIX)]
|
|
607
675
|
del providers[ck]
|
|
608
676
|
origin = providers.get(origin_key)
|
|
609
|
-
if
|
|
677
|
+
# Only re-enable the original when nothing else is enabled — if the
|
|
678
|
+
# user deliberately switched to another provider while wired, we must
|
|
679
|
+
# not end up with two enabled providers after `proxy off`.
|
|
680
|
+
other_enabled = any(
|
|
681
|
+
k
|
|
682
|
+
for k, v in providers.items()
|
|
683
|
+
if isinstance(v, dict) and v.get("enabled") is True and k != origin_key
|
|
684
|
+
)
|
|
685
|
+
if isinstance(origin, dict) and origin.get("enabled") is not True and not other_enabled:
|
|
610
686
|
origin["enabled"] = True
|
|
611
687
|
cls._atomic_write_json(cls.ZCODE_V2_CONFIG, data)
|
|
612
|
-
return (True, "ZCode unwired: clone removed
|
|
688
|
+
return (True, "ZCode unwired: clone removed (restart the app)")
|
|
613
689
|
|
|
614
690
|
@classmethod
|
|
615
691
|
def install_proxy_daemon(cls) -> Tuple[bool, str]:
|
|
@@ -775,14 +851,28 @@ WantedBy=default.target
|
|
|
775
851
|
if fresh_bin:
|
|
776
852
|
# Re-assert via the freshly upgraded binary so the daemon plist
|
|
777
853
|
# points at the new engine path, not this (old) process.
|
|
778
|
-
subprocess.run(
|
|
854
|
+
proc = subprocess.run(
|
|
779
855
|
[fresh_bin, "proxy", "on"],
|
|
780
856
|
env=cls._npm_subprocess_env(fresh_bin), capture_output=True, text=True, timeout=30,
|
|
781
857
|
)
|
|
858
|
+
# Surface the subreport: swallowed wiring/route WARNs previously
|
|
859
|
+
# made a failed wire look like a success on the update path.
|
|
860
|
+
out = (proc.stdout or "").strip()
|
|
861
|
+
if out:
|
|
862
|
+
print(out)
|
|
863
|
+
if proc.returncode != 0:
|
|
864
|
+
err = (proc.stderr or "").strip()[:300]
|
|
865
|
+
if err:
|
|
866
|
+
print(f" {YELLOW}⚠{RESET} proxy on reported a problem: {err}")
|
|
782
867
|
else:
|
|
783
868
|
cls.proxy_on()
|
|
869
|
+
wired_ok = cls.wire_proxy_config()[0]
|
|
870
|
+
zcode_ok = cls._wire_zcode_provider()[0]
|
|
784
871
|
if cls.proxy_health(timeout=3.0):
|
|
785
|
-
|
|
872
|
+
if wired_ok and zcode_ok:
|
|
873
|
+
print(f" {GREEN}✔{RESET} TokenSafe proxy daemon active — Claude Code / ZCode routed through the local optimizer.")
|
|
874
|
+
else:
|
|
875
|
+
print(f" {YELLOW}⚠{RESET} TokenSafe proxy daemon active, but agent wiring is incomplete — run {BOLD}tokensafe proxy on{RESET} for details.")
|
|
786
876
|
print(f" {DIM}Rollback: tokensafe proxy off{RESET}")
|
|
787
877
|
else:
|
|
788
878
|
print(f" {YELLOW}⚠{RESET} TokenSafe proxy did not answer — run {BOLD}tokensafe proxy on{RESET} to retry.")
|
package/src/license_manager.py
CHANGED
|
@@ -482,7 +482,11 @@ class LicenseManager:
|
|
|
482
482
|
"""
|
|
483
483
|
Retrieves active license from env or persistent license.json files.
|
|
484
484
|
Falls back to 'guest' tier (50,000 tokens/month) if no license is present.
|
|
485
|
-
Legacy anonymous licenses (email == 'community@tokensafe.dev') are mapped to 'guest'
|
|
485
|
+
Legacy anonymous licenses (email == 'community@tokensafe.dev') are mapped to 'guest',
|
|
486
|
+
keeping the server-SIGNED monthly quota (grandfathered machines stay at 500k; fresh
|
|
487
|
+
machines are signed at the 50k guest quota). Keys issued before the signed-quota
|
|
488
|
+
field existed carry no quota and default to the legacy community 500k — they are
|
|
489
|
+
exactly the pre-cutoff (grandfathered) population.
|
|
486
490
|
Verified personal licenses (tier == 'free' with user email) get 'free' (500,000 tokens/month).
|
|
487
491
|
"""
|
|
488
492
|
resolved, _ = cls._resolve_active_license_record()
|
|
@@ -493,7 +497,13 @@ class LicenseManager:
|
|
|
493
497
|
if tier == "free" and email == "community@tokensafe.dev":
|
|
494
498
|
guest_payload = dict(payload)
|
|
495
499
|
guest_payload["tier"] = "guest"
|
|
496
|
-
|
|
500
|
+
try:
|
|
501
|
+
signed_quota = int(guest_payload.get("max_tokens_monthly") or 0)
|
|
502
|
+
except (TypeError, ValueError):
|
|
503
|
+
signed_quota = 0
|
|
504
|
+
if signed_quota <= 0:
|
|
505
|
+
signed_quota = cls.TIERS["free"]["max_tokens_monthly"] or 500_000
|
|
506
|
+
guest_payload["max_tokens_monthly"] = signed_quota
|
|
497
507
|
guest_payload["is_legacy_community"] = True
|
|
498
508
|
return "guest", guest_payload
|
|
499
509
|
return tier, payload
|
|
@@ -639,10 +649,19 @@ class LicenseManager:
|
|
|
639
649
|
tier_cfg = cls.TIERS.get(tier, cls.TIERS["guest"] if tier == "guest" else cls.TIERS["free"])
|
|
640
650
|
max_tokens = tier_cfg.get("max_tokens_monthly")
|
|
641
651
|
|
|
642
|
-
# Server-issued quota (community license payload) overrides embedded
|
|
643
|
-
#
|
|
652
|
+
# Server-issued quota (community license payload) overrides embedded defaults.
|
|
653
|
+
# Anonymous/guest tier honors the SIGNED quota: fresh machines 50k, grandfathered
|
|
654
|
+
# machines keep their 500k community quota (variant D). Unsigned/absent quota
|
|
655
|
+
# falls back to the strict guest limit (50,000).
|
|
644
656
|
if tier == "guest":
|
|
645
657
|
max_tokens = 50_000
|
|
658
|
+
if isinstance(payload, dict):
|
|
659
|
+
try:
|
|
660
|
+
signed_quota = int(payload.get("max_tokens_monthly") or 0)
|
|
661
|
+
if signed_quota > 0:
|
|
662
|
+
max_tokens = signed_quota
|
|
663
|
+
except (TypeError, ValueError):
|
|
664
|
+
pass
|
|
646
665
|
elif max_tokens is not None and isinstance(payload, dict):
|
|
647
666
|
try:
|
|
648
667
|
server_quota = int(payload.get("max_tokens_monthly") or 0)
|
package/src/mcp_server.py
CHANGED
|
@@ -42,7 +42,7 @@ from src.paths import get_active_workspace, is_plugin_or_system_dir
|
|
|
42
42
|
|
|
43
43
|
SERVER_INFO = {
|
|
44
44
|
"name": "tokensafe-mcp",
|
|
45
|
-
"version": "4.2.
|
|
45
|
+
"version": "4.2.2"
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
# MCP client attribution: the initialize handshake carries clientInfo, which
|
|
@@ -1864,6 +1864,45 @@ def _dispatch_tool_call(name: str, args: dict) -> dict:
|
|
|
1864
1864
|
return _fallback_error(name, f"unknown tool '{name}'")
|
|
1865
1865
|
|
|
1866
1866
|
|
|
1867
|
+
def _redact_result_secrets(result):
|
|
1868
|
+
"""Egress guard at the MCP boundary: strips recognized secret patterns from
|
|
1869
|
+
tool results BEFORE they enter any agent's context. Covers every MCP-connected
|
|
1870
|
+
agent (CC, Cursor, Cline, Windsurf, Copilot, Kimi, Codex, Antigravity, ZCode)
|
|
1871
|
+
even when the proxy is not on the path. Same redactor the proxy pipeline uses.
|
|
1872
|
+
Fail-open: any internal problem returns the result untouched."""
|
|
1873
|
+
try:
|
|
1874
|
+
if result is None:
|
|
1875
|
+
return result
|
|
1876
|
+
from src.secret_redactor import SecretRedactor
|
|
1877
|
+
except Exception:
|
|
1878
|
+
return result
|
|
1879
|
+
total = 0
|
|
1880
|
+
|
|
1881
|
+
def _walk(node):
|
|
1882
|
+
nonlocal total
|
|
1883
|
+
if isinstance(node, str):
|
|
1884
|
+
red, n, _ = SecretRedactor.redact_text(node)
|
|
1885
|
+
if n:
|
|
1886
|
+
total += n
|
|
1887
|
+
return red
|
|
1888
|
+
if isinstance(node, dict):
|
|
1889
|
+
return {k: _walk(v) for k, v in node.items()}
|
|
1890
|
+
if isinstance(node, list):
|
|
1891
|
+
return [_walk(v) for v in node]
|
|
1892
|
+
return node
|
|
1893
|
+
|
|
1894
|
+
try:
|
|
1895
|
+
redacted = _walk(result)
|
|
1896
|
+
except Exception:
|
|
1897
|
+
return result
|
|
1898
|
+
if total:
|
|
1899
|
+
try:
|
|
1900
|
+
sys.stderr.write(f"[TokenSafe] MCP egress redaction: {total} secret occurrence(s) stripped from tool result\n")
|
|
1901
|
+
except Exception:
|
|
1902
|
+
pass
|
|
1903
|
+
return redacted
|
|
1904
|
+
|
|
1905
|
+
|
|
1867
1906
|
def _execute_with_timeout(tool_name: str, tool_args: dict, timeout: float = MCP_TOOL_TIMEOUT) -> dict:
|
|
1868
1907
|
"""Runs handle_tool_call inside a daemon thread with hard timeout so stdio MCP never freezes."""
|
|
1869
1908
|
box = {"result": None, "error": None}
|
|
@@ -1977,9 +2016,9 @@ def run_mcp_server():
|
|
|
1977
2016
|
from src.json_repair import parse_tool_arguments
|
|
1978
2017
|
tool_args = parse_tool_arguments(raw_tool_args) or {}
|
|
1979
2018
|
try:
|
|
1980
|
-
response["result"] = _execute_with_timeout(tool_name, tool_args)
|
|
2019
|
+
response["result"] = _redact_result_secrets(_execute_with_timeout(tool_name, tool_args))
|
|
1981
2020
|
except Exception as e:
|
|
1982
|
-
response["result"] = _fallback_error(tool_name, f"{type(e).__name__}: {str(e)}")
|
|
2021
|
+
response["result"] = _redact_result_secrets(_fallback_error(tool_name, f"{type(e).__name__}: {str(e)}"))
|
|
1983
2022
|
finally:
|
|
1984
2023
|
try:
|
|
1985
2024
|
from src.telemetry_sync import TelemetrySync
|
package/src/proxy.py
CHANGED
|
@@ -834,6 +834,10 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
834
834
|
try:
|
|
835
835
|
openai_payload = _translate_anthropic_payload_to_openai(payload)
|
|
836
836
|
except Exception as e:
|
|
837
|
+
try:
|
|
838
|
+
sys.stderr.write(f"[TokenSafe][debug] translate fail body[:800]={json.dumps(payload)[:800]}\n")
|
|
839
|
+
except Exception:
|
|
840
|
+
pass
|
|
837
841
|
self._send_json_error(400, f"Failed to translate Anthropic payload: {e}")
|
|
838
842
|
return False
|
|
839
843
|
self._client_shape = "anthropic"
|
|
@@ -879,7 +883,21 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
879
883
|
return self.rfile.read(content_len)
|
|
880
884
|
|
|
881
885
|
def _send_json_error(self, status_code: int, message: str):
|
|
882
|
-
|
|
886
|
+
try:
|
|
887
|
+
sys.stderr.write(f"[TokenSafe] {self.command} {self.path} -> {status_code}: {message}\n")
|
|
888
|
+
except Exception:
|
|
889
|
+
pass
|
|
890
|
+
# Anthropic-dialect clients (ZCode /v1/messages) expect the Anthropic
|
|
891
|
+
# error envelope; OpenAI-shape clients keep the flat {"error": ...} form.
|
|
892
|
+
client_shape = getattr(self, "_client_shape", "") or (
|
|
893
|
+
"anthropic" if self.path.rstrip("/").endswith("/v1/messages") else ""
|
|
894
|
+
)
|
|
895
|
+
if client_shape == "anthropic":
|
|
896
|
+
err_type = "api_error" if status_code >= 500 else "invalid_request_error"
|
|
897
|
+
err_body: Dict[str, Any] = {"type": "error", "error": {"type": err_type, "message": message}}
|
|
898
|
+
else:
|
|
899
|
+
err_body = {"error": message}
|
|
900
|
+
err_bytes = json.dumps(err_body).encode("utf-8")
|
|
883
901
|
self.send_response(status_code)
|
|
884
902
|
self.send_header("Content-Type", "application/json")
|
|
885
903
|
self.send_header("Content-Length", str(len(err_bytes)))
|
|
@@ -994,6 +1012,14 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
994
1012
|
# Client shape: "anthropic" when the request arrived on /v1/messages
|
|
995
1013
|
# (Claude Code via ANTHROPIC_BASE_URL), else OpenAI-native.
|
|
996
1014
|
client_anthropic = getattr(self, "_client_shape", "") == "anthropic"
|
|
1015
|
+
# Defensive endpoint completion: an anthropic-dialect upstream registered
|
|
1016
|
+
# as a bare host (https://api.anthropic.com) or an /anthropic mirror base
|
|
1017
|
+
# must receive the payload on its /v1/messages endpoint, not on "/".
|
|
1018
|
+
if client_anthropic and provider == "anthropic" and not upstream_url.rstrip("/").endswith("/v1/messages"):
|
|
1019
|
+
after_host = upstream_url.split("://", 1)[-1]
|
|
1020
|
+
path = "/" + after_host.split("/", 1)[1] if "/" in after_host else ""
|
|
1021
|
+
if not path or path.rstrip("/").endswith("/anthropic"):
|
|
1022
|
+
upstream_url = f"{upstream_url.rstrip('/')}/v1/messages"
|
|
997
1023
|
# Optional upstream model mapping: route client model names (e.g. claude-*)
|
|
998
1024
|
# to the model the upstream account actually serves.
|
|
999
1025
|
upstream_model = os.environ.get("TOKENSAFE_UPSTREAM_MODEL", "").strip()
|
|
@@ -1229,7 +1255,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
1229
1255
|
return "anthropic"
|
|
1230
1256
|
# Anthropic-compatible mirrors (e.g. Z.ai /api/anthropic[/v1/messages]
|
|
1231
1257
|
# coding-plan endpoint): same wire dialect, client x-api-key is forwarded as-is.
|
|
1232
|
-
|
|
1258
|
+
# Match "/anthropic" as a path SEGMENT, not a substring — a URL like
|
|
1259
|
+
# ".../my-anthropic-proxy/v1/chat/completions" is an OpenAI-dialect host.
|
|
1260
|
+
if re.search(r"/anthropic(/|$)", url):
|
|
1233
1261
|
return "anthropic"
|
|
1234
1262
|
if "openai.com" in url:
|
|
1235
1263
|
return "openai"
|
package/src/telemetry_sync.py
CHANGED
|
@@ -241,7 +241,7 @@ class TelemetrySync:
|
|
|
241
241
|
current_last_id = last_id
|
|
242
242
|
headers = {
|
|
243
243
|
"Content-Type": "application/json",
|
|
244
|
-
"User-Agent": "TokenSafe-Sync/4.2.
|
|
244
|
+
"User-Agent": "TokenSafe-Sync/4.2.2"
|
|
245
245
|
}
|
|
246
246
|
if active_key:
|
|
247
247
|
headers["Authorization"] = f"Bearer {active_key}"
|
package/src/version_checker.py
CHANGED
|
@@ -17,7 +17,7 @@ import urllib.request
|
|
|
17
17
|
import urllib.error
|
|
18
18
|
from typing import Dict, Any, Optional, Tuple
|
|
19
19
|
|
|
20
|
-
CURRENT_VERSION = "4.2.
|
|
20
|
+
CURRENT_VERSION = "4.2.2"
|
|
21
21
|
CACHE_TTL = 86400 # 24 hours
|
|
22
22
|
# When the cloud is unreachable we must NOT cache the synthesized "up to date"
|
|
23
23
|
# answer for a full day — otherwise an update released right after an outage
|
package/src/web_reader.py
CHANGED
|
@@ -9,8 +9,10 @@ Fetches web pages (documentation, API references, articles) and strips clutter:
|
|
|
9
9
|
"""
|
|
10
10
|
|
|
11
11
|
import re
|
|
12
|
+
import ipaddress
|
|
12
13
|
import urllib.request
|
|
13
14
|
import urllib.parse
|
|
15
|
+
import urllib.error
|
|
14
16
|
from html.parser import HTMLParser
|
|
15
17
|
from typing import Tuple, Optional, Dict, Any, List
|
|
16
18
|
|
|
@@ -125,6 +127,15 @@ class _HTMLToMarkdownParser(HTMLParser):
|
|
|
125
127
|
return cleaned
|
|
126
128
|
|
|
127
129
|
|
|
130
|
+
class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
131
|
+
"""Blocks redirect hops that leave the safe-URL zone (public → localhost/DMZ)."""
|
|
132
|
+
|
|
133
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
134
|
+
if not WebReader.is_safe_url(newurl):
|
|
135
|
+
raise urllib.error.HTTPError(newurl, code, "TokenSafe: redirect to a non-public URL blocked", headers, fp)
|
|
136
|
+
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
137
|
+
|
|
138
|
+
|
|
128
139
|
class WebReader:
|
|
129
140
|
"""Safely fetches web pages and returns clean Markdown."""
|
|
130
141
|
|
|
@@ -136,9 +147,24 @@ class WebReader:
|
|
|
136
147
|
parsed = urllib.parse.urlparse(url)
|
|
137
148
|
if parsed.scheme not in ("http", "https"):
|
|
138
149
|
return False
|
|
139
|
-
host = (parsed.hostname or "").lower()
|
|
140
|
-
if host in cls._BLOCKED_HOSTS or host.
|
|
150
|
+
host = (parsed.hostname or "").lower().rstrip(".")
|
|
151
|
+
if host in cls._BLOCKED_HOSTS or host.endswith(".local"):
|
|
141
152
|
return False
|
|
153
|
+
# Literal IPs (v4/v6) — exact range checks instead of string prefixes
|
|
154
|
+
# (the old prefix check missed 172.17-172.31 and all of IPv6).
|
|
155
|
+
try:
|
|
156
|
+
ip = ipaddress.ip_address(host)
|
|
157
|
+
if (
|
|
158
|
+
ip.is_private
|
|
159
|
+
or ip.is_loopback
|
|
160
|
+
or ip.is_link_local
|
|
161
|
+
or ip.is_reserved
|
|
162
|
+
or ip.is_unspecified
|
|
163
|
+
or ip.is_multicast
|
|
164
|
+
):
|
|
165
|
+
return False
|
|
166
|
+
except ValueError:
|
|
167
|
+
pass # hostname, not a literal IP
|
|
142
168
|
return True
|
|
143
169
|
except Exception:
|
|
144
170
|
return False
|
|
@@ -181,7 +207,8 @@ class WebReader:
|
|
|
181
207
|
)
|
|
182
208
|
|
|
183
209
|
try:
|
|
184
|
-
|
|
210
|
+
_opener = urllib.request.build_opener(_SafeRedirectHandler)
|
|
211
|
+
with _opener.open(req, timeout=timeout) as resp:
|
|
185
212
|
status = resp.status
|
|
186
213
|
if status >= 400:
|
|
187
214
|
return "", False, f"HTTP Error {status}"
|