tokensafe 4.16.2 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (151) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +1 -1
  4. package/README.md +8 -3
  5. package/bin/agy-tokens +1 -1
  6. package/bin/tokensafe +1 -1
  7. package/bin/tokensafe-acp.js +1 -1
  8. package/bin/tokensafe-mcp +1 -1
  9. package/bin/tokensafe.js +1 -1
  10. package/hooks/claude_code_hook.py +49 -45
  11. package/hooks/cursor_hook.py +8 -8
  12. package/hooks/kimi_hook.py +23 -23
  13. package/hooks/post_tool_use.py +6 -6
  14. package/hooks/pre_invocation.py +21 -17
  15. package/hooks/pre_tool_use.py +27 -27
  16. package/hooks/session_start.py +17 -17
  17. package/hooks/stop_hook.py +3 -3
  18. package/hooks/zcode_hook.py +2 -2
  19. package/kimi.plugin.json +2 -2
  20. package/mcp_config.json +1 -1
  21. package/package.json +5 -4
  22. package/plugin.json +1 -1
  23. package/server.json +3 -3
  24. package/src/__init__.py +9 -5
  25. package/src/cli.py +11 -2429
  26. package/src/mcp_server.py +11 -5024
  27. package/src/proxy.py +11 -1803
  28. package/tokensafe/__init__.py +6 -0
  29. package/{src → tokensafe}/acp/__init__.py +2 -2
  30. package/{src → tokensafe}/acp/server.py +5 -5
  31. package/{src → tokensafe}/adapter_core.py +42 -17
  32. package/{src → tokensafe}/agent/__init__.py +1 -1
  33. package/{src → tokensafe}/agent/context.py +4 -4
  34. package/{src → tokensafe}/agent/loop.py +4 -4
  35. package/{src → tokensafe}/agent/providers.py +2 -2
  36. package/{src → tokensafe}/agent/tools.py +2 -2
  37. package/{src → tokensafe}/agent_firewall.py +68 -9
  38. package/{src → tokensafe}/angular_cli.py +4 -4
  39. package/{src → tokensafe}/auto_inject.py +37 -5
  40. package/{src → tokensafe}/batch_editor.py +185 -28
  41. package/tokensafe/batch_search.py +1191 -0
  42. package/{src → tokensafe}/bench/go_target.py +1 -1
  43. package/{src → tokensafe}/bench/mechanics.py +1 -1
  44. package/{src → tokensafe}/bench/react_target.py +1 -1
  45. package/{src → tokensafe}/bench/runner.py +4 -4
  46. package/{src → tokensafe}/benchmark.py +12 -12
  47. package/{src → tokensafe}/benchmark_real.py +18 -18
  48. package/{src → tokensafe}/build_parsers.py +3 -3
  49. package/{src → tokensafe}/bundle_probe.py +1 -1
  50. package/{src → tokensafe}/burn_monitor.py +3 -3
  51. package/{src → tokensafe}/cache_normalizer.py +1 -1
  52. package/tokensafe/cli.py +2490 -0
  53. package/{src → tokensafe}/command_sanitizer.py +94 -26
  54. package/{src → tokensafe}/compaction_recovery.py +5 -5
  55. package/{src → tokensafe}/compactor.py +148 -95
  56. package/{src → tokensafe}/context_index.py +194 -28
  57. package/{src → tokensafe}/cross_stack.py +2 -2
  58. package/{src → tokensafe}/dashboard.py +3 -3
  59. package/{src → tokensafe}/delegation.py +4 -4
  60. package/{src → tokensafe}/dependency_prefetcher.py +1 -1
  61. package/{src → tokensafe}/diff_slicer.py +2 -2
  62. package/{src → tokensafe}/distiller.py +7 -7
  63. package/{src → tokensafe}/distiller_cache.py +3 -3
  64. package/{src → tokensafe}/egress_counter.py +1 -1
  65. package/{src → tokensafe}/environment_auditor.py +7 -7
  66. package/{src → tokensafe}/file_state.py +2 -2
  67. package/{src → tokensafe}/format_invariants.py +1 -1
  68. package/tokensafe/format_parsers/__init__.py +20 -0
  69. package/{src → tokensafe}/format_parsers/compiler_errors.py +2 -2
  70. package/{src → tokensafe}/format_parsers/docker_k8s.py +1 -1
  71. package/{src → tokensafe}/format_parsers/i18n_strings.py +19 -9
  72. package/{src → tokensafe}/format_parsers/json_log.py +1 -1
  73. package/{src → tokensafe}/format_parsers/lockfiles.py +4 -4
  74. package/{src → tokensafe}/format_parsers/tabular.py +1 -1
  75. package/{src → tokensafe}/fts_index.py +20 -11
  76. package/{src → tokensafe}/governor.py +143 -31
  77. package/{src → tokensafe}/graph_engine.py +769 -126
  78. package/{src → tokensafe}/guard.py +80 -25
  79. package/{src → tokensafe}/history_compactor.py +407 -133
  80. package/{src → tokensafe}/i18n_catalog.py +39 -14
  81. package/{src → tokensafe}/image_downscale.py +1 -1
  82. package/tokensafe/ingress_staging.py +384 -0
  83. package/{src → tokensafe}/installer.py +118 -61
  84. package/{src → tokensafe}/license_manager.py +9 -67
  85. package/{src → tokensafe}/live_relay.py +2 -2
  86. package/{src → tokensafe}/loop_detector.py +2 -2
  87. package/{src → tokensafe}/mcp_config_manager.py +2 -2
  88. package/{src → tokensafe}/mcp_proxy.py +4 -4
  89. package/tokensafe/mcp_server.py +5664 -0
  90. package/{src → tokensafe}/metrics.py +56 -21
  91. package/{src → tokensafe}/mistakes.py +4 -4
  92. package/{src → tokensafe}/oumv_brief.py +21 -3
  93. package/{src → tokensafe}/oumv_gateway.py +146 -49
  94. package/{src → tokensafe}/oumv_policy.py +1 -1
  95. package/{src → tokensafe}/paths.py +1 -1
  96. package/{src → tokensafe}/project_memory.py +4 -4
  97. package/tokensafe/proxy.py +2075 -0
  98. package/{src → tokensafe}/quality_score.py +4 -4
  99. package/tokensafe/read_baseline.py +192 -0
  100. package/tokensafe/repo_compute.py +332 -0
  101. package/{src → tokensafe}/result_ledger.py +19 -19
  102. package/{src → tokensafe}/retrofit.py +6 -6
  103. package/{src → tokensafe}/savings.py +3 -3
  104. package/tokensafe/schema_slicer.py +1087 -0
  105. package/{src → tokensafe}/scoped_search.py +144 -6
  106. package/{src → tokensafe}/secret_redactor.py +22 -0
  107. package/{src → tokensafe}/session_brief.py +8 -8
  108. package/{src → tokensafe}/skeletonizer.py +89 -26
  109. package/{src → tokensafe}/slicer.py +3 -2
  110. package/{src → tokensafe}/snapshot.py +1 -1
  111. package/{src → tokensafe}/stash.py +1 -1
  112. package/{src → tokensafe}/statusline.py +1 -1
  113. package/{src → tokensafe}/superseded.py +22 -4
  114. package/{src → tokensafe}/team_cache.py +3 -3
  115. package/{src → tokensafe}/telemetry_sync.py +63 -11
  116. package/{src → tokensafe}/test_parsers.py +3 -3
  117. package/{src → tokensafe}/thinking_fold.py +3 -3
  118. package/{src → tokensafe}/tokenizer.py +37 -1
  119. package/{src → tokensafe}/tool_pruner.py +3 -3
  120. package/{src → tokensafe}/transcript_analyzer.py +1 -1
  121. package/{src → tokensafe}/transcript_recall.py +8 -8
  122. package/{src → tokensafe}/type_slicer.py +3 -3
  123. package/{src → tokensafe}/usage_ledger.py +4 -4
  124. package/{src → tokensafe}/version_checker.py +6 -6
  125. package/{src → tokensafe}/web_reader.py +86 -8
  126. package/{src → tokensafe}/workspace_roots.py +2 -2
  127. package/src/batch_search.py +0 -589
  128. package/src/format_parsers/__init__.py +0 -20
  129. package/src/schema_slicer.py +0 -578
  130. /package/{src → tokensafe}/agent/pricing.py +0 -0
  131. /package/{src → tokensafe}/atomic_io.py +0 -0
  132. /package/{src → tokensafe}/backend_release.py +0 -0
  133. /package/{src → tokensafe}/bench/__init__.py +0 -0
  134. /package/{src → tokensafe}/bench/driver.py +0 -0
  135. /package/{src → tokensafe}/bench/tokensafe_mcp.py +0 -0
  136. /package/{src → tokensafe}/bench_scenarios.json +0 -0
  137. /package/{src → tokensafe}/competitors.py +0 -0
  138. /package/{src → tokensafe}/format_parsers/ansi.py +0 -0
  139. /package/{src → tokensafe}/format_parsers/game_assets.py +0 -0
  140. /package/{src → tokensafe}/globmatch.py +0 -0
  141. /package/{src → tokensafe}/host_capabilities.py +0 -0
  142. /package/{src → tokensafe}/json_repair.py +0 -0
  143. /package/{src → tokensafe}/route_index.py +0 -0
  144. /package/{src → tokensafe}/scaffold.py +0 -0
  145. /package/{src → tokensafe}/session_context.py +0 -0
  146. /package/{src → tokensafe}/ssl_context.py +0 -0
  147. /package/{src → tokensafe}/stdio_io.py +0 -0
  148. /package/{src → tokensafe}/syntax_guard.py +0 -0
  149. /package/{src → tokensafe}/toml_mcp_config.py +0 -0
  150. /package/{src → tokensafe}/treesitter_backend.py +0 -0
  151. /package/{src → tokensafe}/win_paths.py +0 -0
@@ -14,6 +14,7 @@ Features:
14
14
  import os
15
15
  import sys
16
16
  import json
17
+ import uuid
17
18
  import time
18
19
  import secrets
19
20
  import sqlite3
@@ -30,11 +31,11 @@ PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30
31
  if PROJECT_ROOT not in sys.path:
31
32
  sys.path.insert(0, PROJECT_ROOT)
32
33
 
33
- from src.license_manager import LicenseManager
34
- from src.metrics import resolve_measurement
35
- from src.ssl_context import shared_ssl_context
34
+ from tokensafe.license_manager import LicenseManager
35
+ from tokensafe.metrics import resolve_measurement
36
+ from tokensafe.ssl_context import shared_ssl_context
36
37
 
37
- from src.paths import resolve_data_dir
38
+ from tokensafe.paths import resolve_data_dir
38
39
 
39
40
  DATA_DIR = resolve_data_dir()
40
41
  METRICS_DB_PATH = os.environ.get("TOKENSAFE_DB_PATH") or os.path.join(DATA_DIR, "metrics.db")
@@ -179,6 +180,17 @@ class TelemetrySync:
179
180
  state[key] = durable
180
181
  if durable_rollup:
181
182
  state["lifetime_rollup_synced"] = True
183
+ # Durable event cursor: a lost sync_state.json must not replay every event.
184
+ raw_cursor = _sync_meta_read(db_path, "last_synced_event_id")
185
+ try:
186
+ durable_cursor = int(raw_cursor) if raw_cursor is not None else 0
187
+ except (TypeError, ValueError):
188
+ durable_cursor = 0
189
+ try:
190
+ json_cursor = int(state.get("last_synced_event_id", 0) or 0)
191
+ except (TypeError, ValueError):
192
+ json_cursor = 0
193
+ state["last_synced_event_id"] = max(json_cursor, durable_cursor)
182
194
  return state
183
195
 
184
196
  @classmethod
@@ -289,10 +301,28 @@ class TelemetrySync:
289
301
  }
290
302
 
291
303
  state = cls.get_state()
292
- last_id = 0 if force else state.get("last_synced_event_id", 0)
304
+ prev_last_id = int(state.get("last_synced_event_id", 0) or 0)
305
+ # Every event carries an idempotency key (ev:<install>:<id>) that the
306
+ # server deduplicates on, so a re-send is harmless. Events synced
307
+ # before keys existed were stored unkeyed: `force` therefore rewinds
308
+ # only to the first keyed event, never to 0 (that duplicated the
309
+ # whole history server-side).
310
+ install_id = _sync_meta_read(db_path, "install_id") or ""
311
+ if not install_id:
312
+ install_id = uuid.uuid4().hex
313
+ _sync_meta_write(db_path, {"install_id": install_id})
314
+ keyed_from_raw = _sync_meta_read(db_path, "keyed_from_event_id")
315
+ try:
316
+ keyed_from = int(keyed_from_raw) if keyed_from_raw is not None else None
317
+ except (TypeError, ValueError):
318
+ keyed_from = None
319
+ if keyed_from is None:
320
+ keyed_from = prev_last_id
321
+ _sync_meta_write(db_path, {"keyed_from_event_id": keyed_from})
322
+ last_id = min(prev_last_id, keyed_from) if force else prev_last_id
293
323
 
294
324
  try:
295
- from src.metrics import MetricsTracker
325
+ from tokensafe.metrics import MetricsTracker
296
326
  local_monthly_measured = MetricsTracker(db_path=db_path).get_monthly_saved_tokens(measured_only=True)
297
327
  except Exception:
298
328
  local_monthly_measured = 0
@@ -311,7 +341,7 @@ class TelemetrySync:
311
341
  current_last_id = last_id
312
342
  headers = {
313
343
  "Content-Type": "application/json",
314
- "User-Agent": "TokenSafe-Sync/4.16.2"
344
+ "User-Agent": "TokenSafe-Sync/5.0.0"
315
345
  }
316
346
  if active_key:
317
347
  headers["Authorization"] = f"Bearer {active_key}"
@@ -487,7 +517,8 @@ class TelemetrySync:
487
517
  "model": model_name,
488
518
  "agent": agent_name,
489
519
  "timestamp": ts_int,
490
- "measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"])
520
+ "measurement": resolve_measurement(str(r["event_type"] or "PROMPT"), r["measurement"]),
521
+ "client_event_id": f"ev:{install_id}:{ev_id}",
491
522
  }))
492
523
 
493
524
  for i in range(0, len(formatted_items), batch_size):
@@ -507,7 +538,7 @@ class TelemetrySync:
507
538
 
508
539
  req = urllib.request.Request(target_url, data=body_bytes, headers=headers, method="POST")
509
540
  try:
510
- from src.egress_counter import increment as _egress_increment
541
+ from tokensafe.egress_counter import increment as _egress_increment
511
542
  _egress_increment("telemetry")
512
543
  with urllib.request.urlopen(req, timeout=timeout, context=shared_ssl_context()) as resp:
513
544
  if resp.status == 200:
@@ -518,14 +549,18 @@ class TelemetrySync:
518
549
  processed_n = max(0, min(len(chunk), int(resp_body["processed"])))
519
550
  srv_measured = int(resp_body.get("server_monthly_measured_saved") or 0)
520
551
  if srv_measured > 0:
521
- from src.metrics import MetricsTracker
552
+ from tokensafe.metrics import MetricsTracker
522
553
  MetricsTracker(db_path=db_path).record_server_quota_floor(srv_measured)
523
554
  except Exception:
524
555
  pass
525
556
  acked_count = processed_n if chunk else 0
526
557
  total_sent += acked_count
527
- cumulative_synced += acked_count
528
558
  committed_items = batch_items[:processed_n] if chunk else batch_items
559
+ # A forced re-send of already-synced events is not new.
560
+ cumulative_synced += sum(
561
+ 1 for ev_id, ev_payload in committed_items
562
+ if ev_payload is not None and (ev_id is None or ev_id > prev_last_id)
563
+ )
529
564
  for ev_id, ev_payload in committed_items:
530
565
  if ev_id is not None and ev_id > current_last_id:
531
566
  current_last_id = ev_id
@@ -552,6 +587,23 @@ class TelemetrySync:
552
587
  "last_synced_rollup_orig": last_synced_rollup_orig,
553
588
  "last_synced_rollup_usd": last_synced_rollup_usd,
554
589
  })
590
+ if current_last_id > prev_last_id:
591
+ _sync_meta_write(db_path, {"last_synced_event_id": current_last_id})
592
+ if chunk and processed_n < len(chunk):
593
+ # The server accepted only a prefix. Sending the
594
+ # next batch would move the cursor past the
595
+ # rejected events and lose them: stop here and
596
+ # resume from the last acknowledged event.
597
+ return {
598
+ "success": True,
599
+ "partial": True,
600
+ "synced_events": total_sent,
601
+ "total_synced": cumulative_synced,
602
+ "message": (
603
+ f"Server accepted {processed_n} of {len(chunk)} events; "
604
+ "the rest will be sent on the next sync."
605
+ ),
606
+ }
555
607
  else:
556
608
  return _record_failure(f"Server returned HTTP {resp.status}")
557
609
  except urllib.error.HTTPError as he:
@@ -15,7 +15,7 @@ the raw traceback to the reversible local stash with a hash anchor.
15
15
 
16
16
  import re
17
17
  from typing import Dict, Any, List, Optional, Tuple
18
- from src.stash import stash_block
18
+ from tokensafe.stash import stash_block
19
19
 
20
20
  # Runner signatures
21
21
  _PYTEST_SUMMARY_RE = re.compile(
@@ -118,10 +118,10 @@ class TestOutputParser:
118
118
  elif detected == "go test":
119
119
  return cls._compact_go_test(raw)
120
120
  elif detected == "tsc":
121
- from src.format_parsers.compiler_errors import CompilerErrorCompactor
121
+ from tokensafe.format_parsers.compiler_errors import CompilerErrorCompactor
122
122
  return CompilerErrorCompactor.compact_tsc(raw)
123
123
  elif detected == "stacktrace":
124
- from src.format_parsers.compiler_errors import CompilerErrorCompactor
124
+ from tokensafe.format_parsers.compiler_errors import CompilerErrorCompactor
125
125
  return CompilerErrorCompactor.compact_stacktrace(raw)
126
126
 
127
127
  return raw, False
@@ -15,7 +15,7 @@ history if ``suffix_tokens * (M_in - M_cache) >= expected_savings``.
15
15
  import os
16
16
  from typing import Any, Dict, List, Optional, Tuple
17
17
 
18
- from src.tokenizer import count_tokens
18
+ from tokensafe.tokenizer import count_tokens
19
19
 
20
20
  THINKING_FOLD_MARKER = "[TokenSafe: aged thinking folded"
21
21
  DEFAULT_KEEP_RECENT = 6
@@ -103,7 +103,7 @@ def fold_aged_thinking(
103
103
 
104
104
  total_saved = sum(max(0, orig_t - new_t) for _, _, orig_t, _, new_t in pending)
105
105
  earliest_idx = pending[0][0]
106
- from src.burn_monitor import evaluate_fold_roi
106
+ from tokensafe.burn_monitor import evaluate_fold_roi
107
107
  roi = evaluate_fold_roi(
108
108
  messages,
109
109
  earliest_fold_idx=earliest_idx,
@@ -128,7 +128,7 @@ def fold_aged_thinking(
128
128
 
129
129
  if stats["folded"] and record:
130
130
  try:
131
- from src.metrics import MetricsTracker
131
+ from tokensafe.metrics import MetricsTracker
132
132
  MetricsTracker().record_event(
133
133
  session_id=session_id,
134
134
  event_type="THINKING_FOLD",
@@ -4,10 +4,19 @@ Optimized for Gemini, Claude, and OpenAI tokenization patterns.
4
4
  Supports English, Cyrillic, CJK, and code-heavy payloads.
5
5
  """
6
6
 
7
+ import hashlib
7
8
  import re
9
+ import threading
10
+ from collections import OrderedDict
8
11
  from typing import Optional
9
12
 
10
13
  _TIKTOKEN_ENCODING = None
14
+
15
+ # Content-digest memo for count(): bounded LRU of (backend, blake2b) -> tokens.
16
+ _MEMO_MIN_CHARS = 256
17
+ _MEMO_MAX = 8192
18
+ _MEMO: "OrderedDict[tuple, int]" = OrderedDict()
19
+ _MEMO_LOCK = threading.Lock()
11
20
  _TIKTOKEN_PROBED = False
12
21
 
13
22
 
@@ -49,8 +58,35 @@ class TokenCounter:
49
58
  if not text:
50
59
  return 0
51
60
 
52
- # If tiktoken is installed, use exact OpenAI BPE cl100k (allowing literal special tokens)
53
61
  enc = _get_tiktoken_encoding()
62
+ # Callers re-count the same history on every request (each turn
63
+ # re-sends every earlier message). Hashing is far cheaper than
64
+ # tokenizing, so long texts are memoized by content digest.
65
+ key = None
66
+ if len(text) >= _MEMO_MIN_CHARS:
67
+ try:
68
+ digest = hashlib.blake2b(text.encode("utf-8", "surrogatepass"), digest_size=16).digest()
69
+ key = (enc is not None, digest)
70
+ except Exception:
71
+ key = None
72
+ if key is not None:
73
+ with _MEMO_LOCK:
74
+ hit = _MEMO.get(key)
75
+ if hit is not None:
76
+ _MEMO.move_to_end(key)
77
+ return hit
78
+
79
+ n = cls._count_uncached(text, enc)
80
+ if key is not None:
81
+ with _MEMO_LOCK:
82
+ _MEMO[key] = n
83
+ if len(_MEMO) > _MEMO_MAX:
84
+ _MEMO.popitem(last=False)
85
+ return n
86
+
87
+ @classmethod
88
+ def _count_uncached(cls, text: str, enc) -> int:
89
+ # If tiktoken is installed, use exact OpenAI BPE cl100k (allowing literal special tokens)
54
90
  if enc is not None:
55
91
  try:
56
92
  return len(enc.encode(text, disallowed_special=()))
@@ -29,7 +29,7 @@ import re
29
29
  import time
30
30
  from typing import Any, Dict, List, Optional, Tuple
31
31
 
32
- from src.tokenizer import count_tokens
32
+ from tokensafe.tokenizer import count_tokens
33
33
 
34
34
  STATE_FILENAME = "proxy_tool_subsets.json"
35
35
  STATE_TTL_SECONDS = 24 * 3600
@@ -84,7 +84,7 @@ def _allowlist() -> List[str]:
84
84
 
85
85
 
86
86
  def _state_path() -> str:
87
- from src.paths import resolve_data_dir
87
+ from tokensafe.paths import resolve_data_dir
88
88
  return os.path.join(resolve_data_dir(), STATE_FILENAME)
89
89
 
90
90
 
@@ -213,7 +213,7 @@ def apply_subset(
213
213
  meta["saved_tokens"] = max(0, count_tokens(json.dumps(tools, ensure_ascii=False)) - count_tokens(json.dumps(pruned, ensure_ascii=False)))
214
214
  if record_metrics and meta.get("saved_tokens"):
215
215
  try:
216
- from src.metrics import MetricsTracker
216
+ from tokensafe.metrics import MetricsTracker
217
217
  MetricsTracker().record_event(
218
218
  session_id=f"prune_{meta.get('session_key', 'sess')}",
219
219
  event_type="TOOL_PRUNE",
@@ -19,7 +19,7 @@ import json
19
19
  import datetime
20
20
  from typing import Dict, Any, List, Optional, Tuple
21
21
 
22
- from src.burn_monitor import estimate_zai_credits, evaluate_burn_warnings
22
+ from tokensafe.burn_monitor import estimate_zai_credits, evaluate_burn_warnings
23
23
 
24
24
 
25
25
  def _parse_iso_ts(ts_str: Optional[str]) -> Optional[datetime.datetime]:
@@ -20,7 +20,7 @@ import time
20
20
  from dataclasses import dataclass, field
21
21
  from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple
22
22
 
23
- from src.paths import resolve_data_dir
23
+ from tokensafe.paths import resolve_data_dir
24
24
 
25
25
  MAX_FILES = 24
26
26
  MAX_FILE_BYTES = 8 * 1024 * 1024
@@ -92,7 +92,7 @@ def remember_session(session_id: str, transcript_path: str, agent: str = "", cwd
92
92
  if not sid or not path:
93
93
  return
94
94
  try:
95
- from src.atomic_io import write_text_atomic
95
+ from tokensafe.atomic_io import write_text_atomic
96
96
 
97
97
  state = _load_state()
98
98
  state[sid] = {
@@ -223,11 +223,11 @@ def _role(rec: Dict[str, Any]) -> str:
223
223
 
224
224
  def _record_text(rec: Dict[str, Any]) -> Tuple[str, List[Tuple[str, Dict[str, Any]]], str]:
225
225
  """(text, tool_calls, user_prompt) for every supported transcript schema."""
226
- from src.history_compactor import _extract_step_text, _extract_step_tool_calls
226
+ from tokensafe.history_compactor import _extract_step_text, _extract_step_tool_calls
227
227
 
228
228
  if rec.get("type") == "model_io":
229
229
  try:
230
- from src.history_compactor import _model_io_parts
230
+ from tokensafe.history_compactor import _model_io_parts
231
231
 
232
232
  text, calls, prompt = _model_io_parts(rec)
233
233
  return text, calls, prompt
@@ -253,7 +253,7 @@ def turns_from_records(
253
253
  max_turns: int = MAX_TURNS,
254
254
  ) -> Iterator[Turn]:
255
255
  """Yield normalized turns from already-parsed JSONL records."""
256
- from src.history_compactor import _is_injected_prompt
256
+ from tokensafe.history_compactor import _is_injected_prompt
257
257
 
258
258
  session = os.path.splitext(os.path.basename(path))[0] or "session"
259
259
  produced = 0
@@ -392,7 +392,7 @@ def discover(scope: str, cwd: str, session_id: str, transcript_path: str) -> Lis
392
392
  """Resolve the (agent, path) list a scope refers to."""
393
393
  scope = (scope or "project").lower()
394
394
  if transcript_path and os.path.exists(transcript_path):
395
- from src.transcript_analyzer import _detect_agent_from_path
395
+ from tokensafe.transcript_analyzer import _detect_agent_from_path
396
396
 
397
397
  return [(_detect_agent_from_path(transcript_path), transcript_path)]
398
398
  if scope == "this":
@@ -400,7 +400,7 @@ def discover(scope: str, cwd: str, session_id: str, transcript_path: str) -> Lis
400
400
  if info:
401
401
  return [(str(info.get("agent") or ""), str(info.get("path") or ""))]
402
402
  return []
403
- from src.transcript_analyzer import discover_transcript_paths
403
+ from tokensafe.transcript_analyzer import discover_transcript_paths
404
404
 
405
405
  entries = discover_transcript_paths(limit=MAX_FILES)
406
406
  if scope == "all":
@@ -419,7 +419,7 @@ def discover(scope: str, cwd: str, session_id: str, transcript_path: str) -> Lis
419
419
 
420
420
  def _redact(text: str) -> str:
421
421
  try:
422
- from src.project_memory import _redact as redact
422
+ from tokensafe.project_memory import _redact as redact
423
423
 
424
424
  return redact(text)
425
425
  except Exception:
@@ -21,7 +21,7 @@ import threading
21
21
  from collections import OrderedDict
22
22
  from typing import Dict, Any, List, Optional, Tuple
23
23
 
24
- from src.paths import resolve_data_dir
24
+ from tokensafe.paths import resolve_data_dir
25
25
 
26
26
 
27
27
  class TypeSlicer:
@@ -381,7 +381,7 @@ class TypeSlicer:
381
381
 
382
382
  # 3. Check L3 Team Sync
383
383
  try:
384
- from src.team_cache import TeamCache
384
+ from tokensafe.team_cache import TeamCache
385
385
  team_val = TeamCache.get("3RD_PARTY_DTS", type_key, timeout=0.5)
386
386
  if team_val:
387
387
  code_block = team_val
@@ -478,7 +478,7 @@ class TypeSlicer:
478
478
  pass
479
479
 
480
480
  try:
481
- from src.team_cache import TeamCache
481
+ from tokensafe.team_cache import TeamCache
482
482
  payload = json.dumps({"code": code_block, "dts_bytes": dts_bytes}, ensure_ascii=False)
483
483
  tokens_saved = max(30, (dts_bytes // 4) if dts_bytes else len(code_block) // 4)
484
484
  TeamCache.put("3RD_PARTY_DTS", type_key, payload, tokens_saved=tokens_saved)
@@ -18,7 +18,7 @@ import os
18
18
  from datetime import datetime
19
19
  from typing import Any, Dict, List, Optional
20
20
 
21
- from src.metrics import MetricsTracker
21
+ from tokensafe.metrics import MetricsTracker
22
22
 
23
23
  _CLAUDE_LIKE = frozenset({"claude", "claude_code", "claude-code", "kimi", "kimi_code"})
24
24
 
@@ -202,7 +202,7 @@ def update_from_transcript(
202
202
  # event here. Arm a one-shot recovery digest for the next
203
203
  # session-start/prompt injection.
204
204
  try:
205
- from src.compaction_recovery import mark_pending
205
+ from tokensafe.compaction_recovery import mark_pending
206
206
  mark_pending(
207
207
  session_id,
208
208
  transcript_path=transcript_path,
@@ -256,7 +256,7 @@ def backfill_from_transcripts(limit: int = 50, tracker: Optional[MetricsTracker]
256
256
  accumulate history: the same incremental reader is applied to the newest
257
257
  host transcripts, and re-running it is a no-op (offsets are stored).
258
258
  """
259
- from src.transcript_analyzer import discover_transcript_paths
259
+ from tokensafe.transcript_analyzer import discover_transcript_paths
260
260
 
261
261
  tracker = tracker or MetricsTracker()
262
262
  updated = 0
@@ -335,7 +335,7 @@ def compute_output_budgets(
335
335
 
336
336
  def write_output_budgets(calibration: Dict[str, Any], path: str = "") -> str:
337
337
  """Atomically writes the calibration file burn_monitor reads per agent."""
338
- from src.paths import resolve_data_dir
338
+ from tokensafe.paths import resolve_data_dir
339
339
 
340
340
  target = path or os.path.join(resolve_data_dir(), "output_budget.json")
341
341
  os.makedirs(os.path.dirname(target) or ".", exist_ok=True)
@@ -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.16.2"
20
+ CURRENT_VERSION = "5.0.0"
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
@@ -27,15 +27,15 @@ FALLBACK_CACHE_TTL = 900 # 15 minutes
27
27
 
28
28
  PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29
29
  # Script-mode guard: notify_os_update_background spawns this file directly
30
- # (`python3 src/version_checker.py --check-bg`), which sets sys.path[0] to the
31
- # src/ directory — `import src.*` fails unless PROJECT_ROOT is on the path
30
+ # (`python3 tokensafe/version_checker.py --check-bg`), which sets sys.path[0] to the
31
+ # tokensafe/ directory — `import tokensafe.*` fails unless PROJECT_ROOT is on the path
32
32
  # FIRST. The old ordering (import before path setup) made every background
33
33
  # update check die silently in the bare except of __main__, so version_cache.json
34
34
  # was never written and the update dialog never appeared.
35
35
  if PROJECT_ROOT not in sys.path:
36
36
  sys.path.insert(0, PROJECT_ROOT)
37
37
 
38
- from src.paths import resolve_data_dir
38
+ from tokensafe.paths import resolve_data_dir
39
39
 
40
40
  DATA_DIR = resolve_data_dir()
41
41
  CACHE_FILE = os.path.join(DATA_DIR, "version_cache.json")
@@ -134,7 +134,7 @@ class VersionChecker:
134
134
  now = int(time.time())
135
135
  if not license_key:
136
136
  try:
137
- from src.license_manager import LicenseManager
137
+ from tokensafe.license_manager import LicenseManager
138
138
  license_key = LicenseManager.get_active_license_key()
139
139
  except Exception:
140
140
  license_key = ""
@@ -186,7 +186,7 @@ class VersionChecker:
186
186
  reissued = data.pop("reissued_license_key", "")
187
187
  if reissued and reissued.startswith("TS2."):
188
188
  try:
189
- from src.license_manager import LicenseManager
189
+ from tokensafe.license_manager import LicenseManager
190
190
  LicenseManager.save_license(reissued)
191
191
  except Exception:
192
192
  pass
@@ -15,6 +15,7 @@ import ipaddress
15
15
  import urllib.request
16
16
  import urllib.parse
17
17
  import urllib.error
18
+ import http.client
18
19
  import sqlite3
19
20
  import time
20
21
  import hashlib
@@ -23,8 +24,8 @@ from collections import OrderedDict
23
24
  from html.parser import HTMLParser
24
25
  from typing import Tuple, Optional, Dict, Any, List
25
26
 
26
- from src.stash import stash_block
27
- from src.paths import resolve_data_dir
27
+ from tokensafe.stash import stash_block
28
+ from tokensafe.paths import resolve_data_dir
28
29
 
29
30
 
30
31
  class _HTMLToMarkdownParser(HTMLParser):
@@ -146,6 +147,72 @@ class _HTMLToMarkdownParser(HTMLParser):
146
147
  return cleaned
147
148
 
148
149
 
150
+ def _guarded_create_connection(address, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, source_address=None, *args, **kwargs):
151
+ """socket.create_connection that refuses non-public addresses at connect time.
152
+
153
+ is_safe_url resolves the name once and urllib resolves it again to connect;
154
+ a DNS-rebinding host answers public the first time and 127.0.0.1 / 169.254.x
155
+ the second. Resolving here and connecting to the checked IP closes that gap.
156
+ TLS still verifies the certificate against the hostname (server_hostname is
157
+ the connection's host, not the IP).
158
+ """
159
+ host, port = address[0], address[1]
160
+ infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
161
+ checked = []
162
+ for family, socktype, proto, _canon, sockaddr in infos:
163
+ ip = ipaddress.ip_address(str(sockaddr[0]).split("%", 1)[0])
164
+ if not WebReader._is_public_ip(ip):
165
+ raise OSError(f"TokenSafe: connection to non-public address {ip} ({host}) blocked")
166
+ checked.append(sockaddr)
167
+ last_err: Optional[BaseException] = None
168
+ for sockaddr in checked:
169
+ try:
170
+ return socket.create_connection((sockaddr[0], port), timeout, source_address)
171
+ except OSError as exc:
172
+ last_err = exc
173
+ raise last_err or OSError(f"TokenSafe: no address for {host}")
174
+
175
+
176
+ def _is_direct_request(req) -> bool:
177
+ """True unless urllib routed the request through a configured proxy."""
178
+ if getattr(req, "_tunnel_host", None):
179
+ return False
180
+ try:
181
+ return (req.host or "").lower() == (urllib.parse.urlsplit(req.full_url).netloc or "").lower()
182
+ except Exception:
183
+ return True
184
+
185
+
186
+ class _GuardedHTTPConnection(http.client.HTTPConnection):
187
+ def __init__(self, *args, **kwargs):
188
+ super().__init__(*args, **kwargs)
189
+ self._create_connection = _guarded_create_connection
190
+
191
+
192
+ class _GuardedHTTPSConnection(http.client.HTTPSConnection):
193
+ def __init__(self, *args, **kwargs):
194
+ super().__init__(*args, **kwargs)
195
+ self._create_connection = _guarded_create_connection
196
+
197
+
198
+ class _SafeHTTPHandler(urllib.request.HTTPHandler):
199
+ def http_open(self, req):
200
+ if not _is_direct_request(req):
201
+ return super().http_open(req)
202
+ return self.do_open(_GuardedHTTPConnection, req)
203
+
204
+
205
+ class _SafeHTTPSHandler(urllib.request.HTTPSHandler):
206
+ def https_open(self, req):
207
+ if not _is_direct_request(req):
208
+ return super().https_open(req)
209
+ return self.do_open(_GuardedHTTPSConnection, req, context=self._context)
210
+
211
+
212
+ def _safe_opener():
213
+ return urllib.request.build_opener(_SafeRedirectHandler, _SafeHTTPHandler, _SafeHTTPSHandler)
214
+
215
+
149
216
  class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
150
217
  """Blocks redirect hops that leave the safe-URL zone (public → localhost/DMZ)."""
151
218
 
@@ -212,8 +279,16 @@ class WebReader:
212
279
  parsed = urllib.parse.urlparse(url.strip())
213
280
  if parsed.username or parsed.password or "@" in parsed.netloc:
214
281
  return True
282
+ # A credential in the query string (?token=…, presigned S3 URLs) makes
283
+ # the page private. sanitize_url strips it from the cache key, so
284
+ # caching it published the private page under the public URL to the
285
+ # local and team caches, for anyone asking with another or no token.
286
+ for key, _value in urllib.parse.parse_qsl(parsed.query, keep_blank_values=True):
287
+ low = key.lower()
288
+ if low in cls._SENSITIVE_QUERY_PARAMS or low.startswith("x-amz-"):
289
+ return True
215
290
  except Exception:
216
- pass
291
+ return True
217
292
  return False
218
293
 
219
294
  @classmethod
@@ -319,7 +394,7 @@ class WebReader:
319
394
  has_auth = cls.has_auth_or_userinfo(url, custom_headers=custom_headers)
320
395
  if not has_auth:
321
396
  try:
322
- from src.team_cache import TeamCache
397
+ from tokensafe.team_cache import TeamCache
323
398
  team_val = TeamCache.get("WEB_DOCS", clean_url, timeout=0.6)
324
399
  if team_val:
325
400
  cls.set_cached(url, team_val, sync_team=False)
@@ -373,7 +448,7 @@ class WebReader:
373
448
  has_auth = cls.has_auth_or_userinfo(url, custom_headers=custom_headers)
374
449
  if sync_team and not has_auth:
375
450
  try:
376
- from src.team_cache import TeamCache
451
+ from tokensafe.team_cache import TeamCache
377
452
  est_saved = max(50, len(markdown) // 4)
378
453
  TeamCache.put("WEB_DOCS", clean_url, markdown, tokens_saved=est_saved)
379
454
  except Exception:
@@ -417,7 +492,10 @@ class WebReader:
417
492
  if not cls._is_public_ip(ip):
418
493
  return False
419
494
  except socket.gaierror:
420
- pass # Allow offline mocked unit tests where DNS isn't reachable
495
+ # Fail closed: an unresolvable host is not proven public. The
496
+ # connection itself is re-checked at connect time anyway
497
+ # (_guarded_create_connection), which also defeats DNS rebinding.
498
+ return False
421
499
  return True
422
500
  except Exception:
423
501
  return False
@@ -475,7 +553,7 @@ class WebReader:
475
553
  req = urllib.request.Request(url, headers=headers)
476
554
 
477
555
  try:
478
- _opener = urllib.request.build_opener(_SafeRedirectHandler)
556
+ _opener = _safe_opener()
479
557
  with _opener.open(req, timeout=timeout) as resp:
480
558
  status = resp.status
481
559
  if status >= 400:
@@ -524,7 +602,7 @@ class WebReader:
524
602
  }
525
603
  req = urllib.request.Request(url, headers=headers)
526
604
  try:
527
- opener = urllib.request.build_opener(_SafeRedirectHandler)
605
+ opener = _safe_opener()
528
606
  with opener.open(req, timeout=timeout) as resp:
529
607
  status = int(getattr(resp, "status", 0) or 0)
530
608
  raw = resp.read(max_bytes + 1)
@@ -13,8 +13,8 @@ import os
13
13
  import threading
14
14
  from typing import Any, Dict, Iterable, List, Optional, Tuple
15
15
 
16
- from src.paths import is_plugin_or_system_dir
17
- from src.win_paths import is_within
16
+ from tokensafe.paths import is_plugin_or_system_dir
17
+ from tokensafe.win_paths import is_within
18
18
 
19
19
  _LOCK = threading.Lock()
20
20
  _ROOTS: List[str] = []