tokensafe 4.2.1 → 4.2.3
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/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 +23 -2
- package/src/installer.py +61 -35
- package/src/license_manager.py +23 -4
- package/src/mcp_server.py +1 -1
- package/src/proxy.py +22 -2
- package/src/stash.py +8 -2
- package/src/superseded.py +70 -10
- package/src/telemetry_sync.py +1 -1
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +30 -3
package/kimi.plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tokensafe",
|
|
3
|
-
"version": "4.2.
|
|
3
|
+
"version": "4.2.3",
|
|
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.3",
|
|
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.3",
|
|
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.3",
|
|
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.3",
|
|
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.3",
|
|
50
50
|
"runtimeHint": "uvx",
|
|
51
51
|
"transport": {
|
|
52
52
|
"type": "stdio"
|
package/src/fts_index.py
CHANGED
|
@@ -179,9 +179,13 @@ class CodeFTSIndex:
|
|
|
179
179
|
continue # File unchanged
|
|
180
180
|
|
|
181
181
|
files_to_index.append((rel_path, full_path, f_mtime, f_size))
|
|
182
|
-
|
|
182
|
+
# Cap the INDEXING work per run, never the walk: files
|
|
183
|
+
# beyond the cap must still enter found_paths, or the
|
|
184
|
+
# prune step below would treat them as deleted on every
|
|
185
|
+
# run (repos > max_files lost their tail permanently).
|
|
186
|
+
if len(files_to_index) >= max_files:
|
|
183
187
|
break
|
|
184
|
-
if
|
|
188
|
+
if len(files_to_index) >= max_files:
|
|
185
189
|
break
|
|
186
190
|
|
|
187
191
|
# Index modified/new files in batches
|
|
@@ -283,6 +287,23 @@ class CodeFTSIndex:
|
|
|
283
287
|
"content": row[2].strip(),
|
|
284
288
|
"bm25_rank": row[3]
|
|
285
289
|
})
|
|
290
|
+
|
|
291
|
+
# Phrase search can miss when the user types several loose words.
|
|
292
|
+
# Strictly additive retry: AND of individually quoted terms —
|
|
293
|
+
# only runs when the exact-phrase pass returned nothing.
|
|
294
|
+
if not results and " " in clean_q.strip():
|
|
295
|
+
and_query = " AND ".join(
|
|
296
|
+
f'"{term.replace(chr(34), chr(34) * 2)}"' for term in clean_q.split()
|
|
297
|
+
)
|
|
298
|
+
params2 = ([f"%{path_filter}%"] if path_filter else []) + [limit]
|
|
299
|
+
cur = con.execute(sql, (and_query, *params2))
|
|
300
|
+
for row in cur.fetchall():
|
|
301
|
+
results.append({
|
|
302
|
+
"file": row[0],
|
|
303
|
+
"line": row[1],
|
|
304
|
+
"content": row[2].strip(),
|
|
305
|
+
"bm25_rank": row[3]
|
|
306
|
+
})
|
|
286
307
|
except sqlite3.OperationalError:
|
|
287
308
|
# If trigram MATCH fails (e.g. query < 3 chars), fallback to LIKE
|
|
288
309
|
like_sql = """
|
package/src/installer.py
CHANGED
|
@@ -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")
|
|
@@ -560,8 +555,12 @@ class AgentInstaller:
|
|
|
560
555
|
if not isinstance(routes, dict):
|
|
561
556
|
routes = {}
|
|
562
557
|
routes[fp] = {"upstream_url": upstream_url, "label": label, "added_at": int(time.time())}
|
|
563
|
-
|
|
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:
|
|
564
562
|
json.dump(routes, f, indent=2)
|
|
563
|
+
os.replace(tmp_path, path)
|
|
565
564
|
return True
|
|
566
565
|
except Exception as e:
|
|
567
566
|
try:
|
|
@@ -629,10 +628,15 @@ class AgentInstaller:
|
|
|
629
628
|
if not api_key or not base_url:
|
|
630
629
|
return (False, f"enabled provider '{enabled_key}' lacks apiKey/baseURL")
|
|
631
630
|
clone_key = f"{enabled_key}{cls._ZCODE_CLONE_SUFFIX}"
|
|
632
|
-
# 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.
|
|
633
634
|
upstream = base_url
|
|
634
|
-
if str(src.get("kind") or "").lower() == "anthropic" and
|
|
635
|
-
|
|
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"
|
|
636
640
|
route_ok = cls._register_proxy_route(f"zcode:{enabled_key}", upstream, api_key)
|
|
637
641
|
clone = json.loads(json.dumps(src))
|
|
638
642
|
clone["enabled"] = True
|
|
@@ -670,10 +674,18 @@ class AgentInstaller:
|
|
|
670
674
|
origin_key = ck[: -len(cls._ZCODE_CLONE_SUFFIX)]
|
|
671
675
|
del providers[ck]
|
|
672
676
|
origin = providers.get(origin_key)
|
|
673
|
-
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:
|
|
674
686
|
origin["enabled"] = True
|
|
675
687
|
cls._atomic_write_json(cls.ZCODE_V2_CONFIG, data)
|
|
676
|
-
return (True, "ZCode unwired: clone removed
|
|
688
|
+
return (True, "ZCode unwired: clone removed (restart the app)")
|
|
677
689
|
|
|
678
690
|
@classmethod
|
|
679
691
|
def install_proxy_daemon(cls) -> Tuple[bool, str]:
|
|
@@ -839,14 +851,28 @@ WantedBy=default.target
|
|
|
839
851
|
if fresh_bin:
|
|
840
852
|
# Re-assert via the freshly upgraded binary so the daemon plist
|
|
841
853
|
# points at the new engine path, not this (old) process.
|
|
842
|
-
subprocess.run(
|
|
854
|
+
proc = subprocess.run(
|
|
843
855
|
[fresh_bin, "proxy", "on"],
|
|
844
856
|
env=cls._npm_subprocess_env(fresh_bin), capture_output=True, text=True, timeout=30,
|
|
845
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}")
|
|
846
867
|
else:
|
|
847
868
|
cls.proxy_on()
|
|
869
|
+
wired_ok = cls.wire_proxy_config()[0]
|
|
870
|
+
zcode_ok = cls._wire_zcode_provider()[0]
|
|
848
871
|
if cls.proxy_health(timeout=3.0):
|
|
849
|
-
|
|
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.")
|
|
850
876
|
print(f" {DIM}Rollback: tokensafe proxy off{RESET}")
|
|
851
877
|
else:
|
|
852
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
package/src/proxy.py
CHANGED
|
@@ -887,7 +887,17 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
887
887
|
sys.stderr.write(f"[TokenSafe] {self.command} {self.path} -> {status_code}: {message}\n")
|
|
888
888
|
except Exception:
|
|
889
889
|
pass
|
|
890
|
-
|
|
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")
|
|
891
901
|
self.send_response(status_code)
|
|
892
902
|
self.send_header("Content-Type", "application/json")
|
|
893
903
|
self.send_header("Content-Length", str(len(err_bytes)))
|
|
@@ -1002,6 +1012,14 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
1002
1012
|
# Client shape: "anthropic" when the request arrived on /v1/messages
|
|
1003
1013
|
# (Claude Code via ANTHROPIC_BASE_URL), else OpenAI-native.
|
|
1004
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"
|
|
1005
1023
|
# Optional upstream model mapping: route client model names (e.g. claude-*)
|
|
1006
1024
|
# to the model the upstream account actually serves.
|
|
1007
1025
|
upstream_model = os.environ.get("TOKENSAFE_UPSTREAM_MODEL", "").strip()
|
|
@@ -1237,7 +1255,9 @@ class TokenSafeProxyHandler(BaseHTTPRequestHandler):
|
|
|
1237
1255
|
return "anthropic"
|
|
1238
1256
|
# Anthropic-compatible mirrors (e.g. Z.ai /api/anthropic[/v1/messages]
|
|
1239
1257
|
# coding-plan endpoint): same wire dialect, client x-api-key is forwarded as-is.
|
|
1240
|
-
|
|
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):
|
|
1241
1261
|
return "anthropic"
|
|
1242
1262
|
if "openai.com" in url:
|
|
1243
1263
|
return "openai"
|
package/src/stash.py
CHANGED
|
@@ -58,8 +58,14 @@ def stash_block(content: str, source: str = "tool") -> Tuple[str, str]:
|
|
|
58
58
|
)
|
|
59
59
|
|
|
60
60
|
if chars_count > MAX_STASH_CHARS:
|
|
61
|
-
# Don't exhaust local disk on massive blobs > 5MB
|
|
62
|
-
|
|
61
|
+
# Don't exhaust local disk on massive blobs > 5MB — and don't advertise
|
|
62
|
+
# a restore path that would dead-end: without the stored file,
|
|
63
|
+
# expand_ref would return None ("not found or expired").
|
|
64
|
+
honest_marker = (
|
|
65
|
+
f"[TokenSafe folded: #{hash8} ({lines_count} lines / {chars_count} chars omitted) "
|
|
66
|
+
f"— content exceeds the 5 MB stash cap and was not archived]"
|
|
67
|
+
)
|
|
68
|
+
return hash8, honest_marker
|
|
63
69
|
|
|
64
70
|
try:
|
|
65
71
|
stash_dir = get_stash_dir()
|
package/src/superseded.py
CHANGED
|
@@ -50,6 +50,8 @@ class SupersededPruner:
|
|
|
50
50
|
# action_type: "READ" or "EDIT"
|
|
51
51
|
file_actions: Dict[str, List[Tuple[int, str]]] = {}
|
|
52
52
|
step_read_files: Dict[int, str] = {}
|
|
53
|
+
# Claude Code: tool_use ids map reads to their (later) result step
|
|
54
|
+
read_tool_ids: Dict[str, int] = {}
|
|
53
55
|
|
|
54
56
|
for idx, step in enumerate(steps):
|
|
55
57
|
if not isinstance(step, dict):
|
|
@@ -87,6 +89,9 @@ class SupersededPruner:
|
|
|
87
89
|
if tname in _READ_TOOLS:
|
|
88
90
|
file_actions.setdefault(fpath, []).append((idx, "READ"))
|
|
89
91
|
step_read_files[idx] = fpath
|
|
92
|
+
tool_use_id = str(b.get("id") or "")
|
|
93
|
+
if tool_use_id:
|
|
94
|
+
read_tool_ids[tool_use_id] = idx
|
|
90
95
|
elif tname in _EDIT_TOOLS:
|
|
91
96
|
file_actions.setdefault(fpath, []).append((idx, "EDIT"))
|
|
92
97
|
|
|
@@ -107,25 +112,52 @@ class SupersededPruner:
|
|
|
107
112
|
if not superseded_map:
|
|
108
113
|
return steps, 0, 0, {"pruned_count": 0, "saved_tokens": 0}
|
|
109
114
|
|
|
115
|
+
# Claude Code transcripts: the tool RESULT for a read lives in a LATER
|
|
116
|
+
# step's tool_result block (matched by tool_use_id), so the tombstone
|
|
117
|
+
# must land there, not in the read's own (tool_use-only) step.
|
|
118
|
+
superseded_ids: Dict[str, Tuple[int, str, str]] = {}
|
|
119
|
+
for tid, step_idx in read_tool_ids.items():
|
|
120
|
+
if step_idx in superseded_map:
|
|
121
|
+
superseded_ids[tid] = superseded_map[step_idx]
|
|
122
|
+
|
|
110
123
|
# Apply tombstoning to the tool results of the superseded steps
|
|
111
124
|
pruned_steps: List[dict] = []
|
|
112
125
|
orig_tokens_total = 0
|
|
113
126
|
pruned_tokens_total = 0
|
|
114
127
|
pruned_count = 0
|
|
115
128
|
|
|
129
|
+
def _carries_super_result(s: dict) -> bool:
|
|
130
|
+
"""True when this step holds a tool_result whose tool_use_id is superseded."""
|
|
131
|
+
msg = s.get("message") if isinstance(s, dict) else None
|
|
132
|
+
mc = msg.get("content") if isinstance(msg, dict) else None
|
|
133
|
+
if not isinstance(mc, list):
|
|
134
|
+
return False
|
|
135
|
+
return any(
|
|
136
|
+
isinstance(b, dict) and str(b.get("tool_use_id") or "") in superseded_ids
|
|
137
|
+
for b in mc
|
|
138
|
+
)
|
|
139
|
+
|
|
116
140
|
for idx, step in enumerate(steps):
|
|
117
|
-
if idx not in superseded_map
|
|
141
|
+
if idx not in superseded_map and not (
|
|
142
|
+
superseded_ids and isinstance(step, dict) and _carries_super_result(step)
|
|
143
|
+
):
|
|
118
144
|
pruned_steps.append(step)
|
|
119
145
|
continue
|
|
120
146
|
|
|
121
|
-
|
|
122
|
-
|
|
147
|
+
same_step = superseded_map.get(idx)
|
|
148
|
+
if same_step:
|
|
149
|
+
by_step, by_action, fpath = same_step
|
|
150
|
+
else:
|
|
151
|
+
# Result-only step (Claude Code): tombstones are chosen per
|
|
152
|
+
# tool_use_id below; the step-level fields stay unused.
|
|
153
|
+
by_step, by_action, fpath = None, None, None
|
|
154
|
+
fname = os.path.basename(fpath) if fpath else ""
|
|
123
155
|
new_step = json.loads(json.dumps(step)) # deep copy
|
|
124
156
|
modified = False
|
|
125
157
|
|
|
126
158
|
# Check Antigravity output/content in this step or subsequent tool response step
|
|
127
159
|
content = new_step.get("content")
|
|
128
|
-
if isinstance(content, str) and len(content) > 150:
|
|
160
|
+
if same_step and isinstance(content, str) and len(content) > 150:
|
|
129
161
|
orig_t = count_tokens(content)
|
|
130
162
|
_, marker = stash_block(content, source="superseded_read")
|
|
131
163
|
tombstone = (
|
|
@@ -137,17 +169,45 @@ class SupersededPruner:
|
|
|
137
169
|
pruned_tokens_total += pruned_t
|
|
138
170
|
modified = True
|
|
139
171
|
|
|
140
|
-
# Claude Code message content tool_result blocks
|
|
172
|
+
# Claude Code message content tool_result blocks. Priority: match by
|
|
173
|
+
# tool_use_id (result trails the tool_use across steps); fall back to
|
|
174
|
+
# the same-step rule only for id-less formats (Antigravity exports).
|
|
141
175
|
msg = new_step.get("message")
|
|
142
176
|
if isinstance(msg, dict):
|
|
143
177
|
mc = msg.get("content")
|
|
144
178
|
if isinstance(mc, list):
|
|
145
179
|
for block in mc:
|
|
146
|
-
if isinstance(block, dict)
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
180
|
+
if not isinstance(block, dict) or block.get("type") != "tool_result":
|
|
181
|
+
continue
|
|
182
|
+
tid = str(block.get("tool_use_id") or "")
|
|
183
|
+
mapping = superseded_ids.get(tid) if tid else None
|
|
184
|
+
if mapping is None and not tid:
|
|
185
|
+
mapping = superseded_map.get(idx)
|
|
186
|
+
if mapping is None:
|
|
187
|
+
continue
|
|
188
|
+
by_step, by_action, fpath = mapping
|
|
189
|
+
fname = os.path.basename(fpath)
|
|
190
|
+
tc = block.get("content")
|
|
191
|
+
if isinstance(tc, str) and len(tc) > 150:
|
|
192
|
+
orig_t = count_tokens(tc)
|
|
193
|
+
_, marker = stash_block(tc, source="superseded_read")
|
|
194
|
+
tombstone = (
|
|
195
|
+
f"[TokenSafe: Output superseded by step #{by_step + 1} ({by_action.lower()} {fname}) — {marker}]"
|
|
196
|
+
)
|
|
197
|
+
block["content"] = tombstone
|
|
198
|
+
pruned_t = count_tokens(tombstone)
|
|
199
|
+
orig_tokens_total += orig_t
|
|
200
|
+
pruned_tokens_total += pruned_t
|
|
201
|
+
modified = True
|
|
202
|
+
elif isinstance(tc, list) and tc:
|
|
203
|
+
# tool_result content can be a list of text blocks
|
|
204
|
+
text = "\n".join(
|
|
205
|
+
(b.get("text", "") if isinstance(b, dict) else str(b))
|
|
206
|
+
for b in tc
|
|
207
|
+
)
|
|
208
|
+
if len(text) > 150:
|
|
209
|
+
orig_t = count_tokens(text)
|
|
210
|
+
_, marker = stash_block(text, source="superseded_read")
|
|
151
211
|
tombstone = (
|
|
152
212
|
f"[TokenSafe: Output superseded by step #{by_step + 1} ({by_action.lower()} {fname}) — {marker}]"
|
|
153
213
|
)
|
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.3"
|
|
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.3"
|
|
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}"
|