tokensafe 3.1.5 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -58
- package/bin/tokensafe.js +25 -9
- package/hooks/claude_code_hook.py +7 -0
- package/hooks/pre_tool_use.py +24 -0
- package/hooks/session_start.py +8 -0
- package/package.json +3 -3
- package/plugin.json +1 -1
- package/rules/AGENTS.md +13 -7
- package/server.json +3 -3
- package/skills/token-optimizer/SKILL.md +7 -2
- package/skills/token-optimizer/references/cli-reference.md +11 -1
- package/skills/token-optimizer/references/mcp-tools.md +44 -2
- package/src/bench_scenarios.json +376 -0
- package/src/cache_normalizer.py +21 -0
- package/src/cli.py +425 -4
- package/src/command_sanitizer.py +2 -0
- package/src/compactor.py +1 -1
- package/src/competitors.py +179 -0
- package/src/environment_auditor.py +110 -1
- package/src/format_parsers/__init__.py +20 -0
- package/src/format_parsers/ansi.py +41 -0
- package/src/format_parsers/compiler_errors.py +159 -0
- package/src/format_parsers/docker_k8s.py +95 -0
- package/src/format_parsers/json_log.py +89 -0
- package/src/format_parsers/lockfiles.py +157 -0
- package/src/format_parsers/tabular.py +175 -0
- package/src/fts_index.py +296 -0
- package/src/graph_engine.py +395 -48
- package/src/image_downscale.py +228 -0
- package/src/installer.py +47 -1
- package/src/license_manager.py +103 -7
- package/src/loop_detector.py +5 -0
- package/src/mcp_config_manager.py +197 -0
- package/src/mcp_proxy.py +154 -0
- package/src/mcp_server.py +215 -1
- package/src/mistakes.py +203 -0
- package/src/result_ledger.py +8 -1
- package/src/scoped_search.py +32 -0
- package/src/stash.py +199 -0
- package/src/superseded.py +220 -0
- package/src/telemetry_sync.py +14 -1
- package/src/test_parsers.py +271 -0
- package/src/version_checker.py +1 -1
- package/src/web_reader.py +202 -0
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Universal Test Output Compactor (v3.3.0).
|
|
3
|
+
|
|
4
|
+
Parses verbose stdout/stderr of test frameworks:
|
|
5
|
+
- pytest (Python)
|
|
6
|
+
- unittest (Python)
|
|
7
|
+
- vitest / jest (JavaScript/TypeScript)
|
|
8
|
+
- cargo test (Rust)
|
|
9
|
+
- go test (Go)
|
|
10
|
+
|
|
11
|
+
Compacts passing suites to 1 line (-99% tokens).
|
|
12
|
+
For failing suites, preserves passing counts + exact failure blocks and stashes
|
|
13
|
+
the raw traceback to the reversible local stash with a hash anchor.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from typing import Dict, Any, List, Optional, Tuple
|
|
18
|
+
from src.stash import stash_block
|
|
19
|
+
|
|
20
|
+
# Runner signatures
|
|
21
|
+
_PYTEST_SUMMARY_RE = re.compile(
|
|
22
|
+
r"=+\s*(?:(?P<failed>\d+)\s+failed)?(?:,\s*)?(?P<passed>\d+)\s+passed(?:,\s*(?P<skipped>\d+)\s+skipped)?.*?\s+in\s+(?P<dur>[0-9.]+[ms]*)\s*=+",
|
|
23
|
+
re.IGNORECASE
|
|
24
|
+
)
|
|
25
|
+
_VITEST_FILES_RE = re.compile(
|
|
26
|
+
r"Test Files\s+(?:(?P<failed>\d+)\s+failed\s*\|\s*)?(?P<passed>\d+)\s+passed\s*\((?P<total>\d+)\)",
|
|
27
|
+
re.IGNORECASE
|
|
28
|
+
)
|
|
29
|
+
_VITEST_TESTS_RE = re.compile(
|
|
30
|
+
r"Tests\s+(?:(?P<failed>\d+)\s+failed\s*\|\s*)?(?P<passed>\d+)\s+passed\s*\((?P<total>\d+)\)",
|
|
31
|
+
re.IGNORECASE
|
|
32
|
+
)
|
|
33
|
+
_JEST_TESTS_RE = re.compile(
|
|
34
|
+
r"Tests:\s*(?:(?P<failed>\d+)\s+failed,\s*)?(?:(?P<passed>\d+)\s+passed,\s*)?(?P<total>\d+)\s+total",
|
|
35
|
+
re.IGNORECASE
|
|
36
|
+
)
|
|
37
|
+
_CARGO_TEST_RE = re.compile(
|
|
38
|
+
r"test result:\s*(?P<status>ok|FAILED)\.\s*(?P<passed>\d+)\s+passed;\s*(?P<failed>\d+)\s+failed;",
|
|
39
|
+
re.IGNORECASE
|
|
40
|
+
)
|
|
41
|
+
_CARGO_DUR_RE = re.compile(r"finished in\s+(?P<dur>[0-9.]+[a-zA-Z]*)", re.IGNORECASE)
|
|
42
|
+
_GO_TEST_OK_RE = re.compile(r"^ok\s+(\S+)\s+([0-9.]+[ms]+)", re.MULTILINE)
|
|
43
|
+
_GO_TEST_FAIL_RE = re.compile(r"^FAIL\s+(\S+)\s+([0-9.]+[ms]+)", re.MULTILINE)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class TestOutputParser:
|
|
47
|
+
"""Parses and folds test runner terminal outputs."""
|
|
48
|
+
|
|
49
|
+
@classmethod
|
|
50
|
+
def detect_runner(cls, cmd_or_output: str) -> Optional[str]:
|
|
51
|
+
s = cmd_or_output.lower()
|
|
52
|
+
if "pytest" in s:
|
|
53
|
+
return "pytest"
|
|
54
|
+
if "unittest" in s or ("ran " in s and " tests in " in s):
|
|
55
|
+
return "unittest"
|
|
56
|
+
if "vitest" in s:
|
|
57
|
+
return "vitest"
|
|
58
|
+
if "jest" in s:
|
|
59
|
+
return "jest"
|
|
60
|
+
if "cargo test" in s or "test result:" in s:
|
|
61
|
+
return "cargo test"
|
|
62
|
+
if "go test" in s or ("--- fail:" in s and "--- pass:" in s):
|
|
63
|
+
return "go test"
|
|
64
|
+
if "tsc" in s or "error ts" in s or ("found " in s and " error" in s):
|
|
65
|
+
return "tsc"
|
|
66
|
+
if "traceback (most recent call last):" in s or "recursionerror:" in s:
|
|
67
|
+
return "stacktrace"
|
|
68
|
+
return None
|
|
69
|
+
|
|
70
|
+
@classmethod
|
|
71
|
+
def compact(cls, raw: str, runner: Optional[str] = None) -> Tuple[str, bool]:
|
|
72
|
+
"""
|
|
73
|
+
Compacts test output.
|
|
74
|
+
Returns (compacted_text, was_compacted).
|
|
75
|
+
"""
|
|
76
|
+
if not raw or len(raw.splitlines()) <= 4:
|
|
77
|
+
return raw, False
|
|
78
|
+
|
|
79
|
+
detected = runner or cls.detect_runner(raw)
|
|
80
|
+
if not detected:
|
|
81
|
+
return raw, False
|
|
82
|
+
|
|
83
|
+
if detected == "pytest":
|
|
84
|
+
return cls._compact_pytest(raw)
|
|
85
|
+
elif detected == "unittest":
|
|
86
|
+
return cls._compact_unittest(raw)
|
|
87
|
+
elif detected in ("vitest", "jest"):
|
|
88
|
+
return cls._compact_js_tests(raw, detected)
|
|
89
|
+
elif detected == "cargo test":
|
|
90
|
+
return cls._compact_cargo_test(raw)
|
|
91
|
+
elif detected == "go test":
|
|
92
|
+
return cls._compact_go_test(raw)
|
|
93
|
+
elif detected == "tsc":
|
|
94
|
+
from src.format_parsers.compiler_errors import CompilerErrorCompactor
|
|
95
|
+
return CompilerErrorCompactor.compact_tsc(raw)
|
|
96
|
+
elif detected == "stacktrace":
|
|
97
|
+
from src.format_parsers.compiler_errors import CompilerErrorCompactor
|
|
98
|
+
return CompilerErrorCompactor.compact_stacktrace(raw)
|
|
99
|
+
|
|
100
|
+
return raw, False
|
|
101
|
+
|
|
102
|
+
@classmethod
|
|
103
|
+
def _compact_pytest(cls, raw: str) -> Tuple[str, bool]:
|
|
104
|
+
match = _PYTEST_SUMMARY_RE.search(raw)
|
|
105
|
+
if not match:
|
|
106
|
+
return raw, False
|
|
107
|
+
|
|
108
|
+
gd = match.groupdict()
|
|
109
|
+
passed = int(gd.get("passed") or 0)
|
|
110
|
+
failed = int(gd.get("failed") or 0)
|
|
111
|
+
skipped = int(gd.get("skipped") or 0)
|
|
112
|
+
dur = gd.get("dur") or ""
|
|
113
|
+
|
|
114
|
+
if failed == 0:
|
|
115
|
+
skip_str = f", {skipped} skipped" if skipped else ""
|
|
116
|
+
summary = f"✓ PASS: {passed} passed{skip_str} (pytest in {dur})"
|
|
117
|
+
return summary, True
|
|
118
|
+
|
|
119
|
+
# Extract failures section
|
|
120
|
+
failures_section = []
|
|
121
|
+
in_failures = False
|
|
122
|
+
lines = raw.splitlines()
|
|
123
|
+
for ln in lines:
|
|
124
|
+
if "=== FAILURES ===" in ln or "= FAILURES =" in ln:
|
|
125
|
+
in_failures = True
|
|
126
|
+
continue
|
|
127
|
+
if in_failures:
|
|
128
|
+
if ln.startswith("=== short test summary") or ln.startswith("=== 1 ") or _PYTEST_SUMMARY_RE.search(ln):
|
|
129
|
+
break
|
|
130
|
+
failures_section.append(ln)
|
|
131
|
+
|
|
132
|
+
fail_text = "\n".join(failures_section[:35]).strip()
|
|
133
|
+
_, marker = stash_block(raw, source="pytest")
|
|
134
|
+
res = [
|
|
135
|
+
f"✗ FAIL: {failed} failed, {passed} passed (pytest in {dur})",
|
|
136
|
+
"Failures excerpt:",
|
|
137
|
+
fail_text or " (see full traceback)",
|
|
138
|
+
marker
|
|
139
|
+
]
|
|
140
|
+
return "\n".join(res), True
|
|
141
|
+
|
|
142
|
+
@classmethod
|
|
143
|
+
def _compact_unittest(cls, raw: str) -> Tuple[str, bool]:
|
|
144
|
+
lines = raw.splitlines()
|
|
145
|
+
ran = status = ""
|
|
146
|
+
for ln in lines:
|
|
147
|
+
s = ln.strip()
|
|
148
|
+
if s.startswith("Ran ") and " test" in s:
|
|
149
|
+
ran = s
|
|
150
|
+
elif s.startswith("OK") or s.startswith("FAILED"):
|
|
151
|
+
status = s
|
|
152
|
+
|
|
153
|
+
if not ran:
|
|
154
|
+
return raw, False
|
|
155
|
+
|
|
156
|
+
if status.startswith("OK"):
|
|
157
|
+
return f"✓ {ran} — all tests passed", True
|
|
158
|
+
|
|
159
|
+
# Extract failure blocks
|
|
160
|
+
_, marker = stash_block(raw, source="unittest")
|
|
161
|
+
failures = []
|
|
162
|
+
cur_block = []
|
|
163
|
+
in_block = False
|
|
164
|
+
for ln in lines:
|
|
165
|
+
if ln.startswith("FAIL: ") or ln.startswith("ERROR: "):
|
|
166
|
+
if cur_block:
|
|
167
|
+
failures.append("\n".join(cur_block[:8]))
|
|
168
|
+
cur_block = []
|
|
169
|
+
in_block = True
|
|
170
|
+
if in_block:
|
|
171
|
+
cur_block.append(ln)
|
|
172
|
+
if len(failures) >= 5:
|
|
173
|
+
break
|
|
174
|
+
if cur_block and len(failures) < 5:
|
|
175
|
+
failures.append("\n".join(cur_block[:8]))
|
|
176
|
+
|
|
177
|
+
out = [
|
|
178
|
+
f"✗ {ran} — {status}",
|
|
179
|
+
"Failed tests summary:"
|
|
180
|
+
]
|
|
181
|
+
for fb in failures:
|
|
182
|
+
out.append(f" {fb}")
|
|
183
|
+
out.append(marker)
|
|
184
|
+
return "\n".join(out), True
|
|
185
|
+
|
|
186
|
+
@classmethod
|
|
187
|
+
def _compact_js_tests(cls, raw: str, runner: str) -> Tuple[str, bool]:
|
|
188
|
+
lines = raw.splitlines()
|
|
189
|
+
t_match = _VITEST_TESTS_RE.search(raw) or _JEST_TESTS_RE.search(raw)
|
|
190
|
+
if not t_match:
|
|
191
|
+
return raw, False
|
|
192
|
+
|
|
193
|
+
gd = t_match.groupdict()
|
|
194
|
+
failed = int(gd.get("failed") or 0)
|
|
195
|
+
passed = int(gd.get("passed") or 0)
|
|
196
|
+
total = int(gd.get("total") or (passed + failed))
|
|
197
|
+
|
|
198
|
+
if failed == 0:
|
|
199
|
+
return f"✓ PASS: {passed}/{total} tests passed ({runner})", True
|
|
200
|
+
|
|
201
|
+
_, marker = stash_block(raw, source=runner)
|
|
202
|
+
# Grab lines mentioning FAIL
|
|
203
|
+
fails = [ln.strip() for ln in lines if "FAIL " in ln or "● " in ln][:8]
|
|
204
|
+
out = [
|
|
205
|
+
f"✗ FAIL: {failed} failed, {passed} passed ({runner})",
|
|
206
|
+
"Failed tests:"
|
|
207
|
+
]
|
|
208
|
+
for f in fails:
|
|
209
|
+
out.append(f" {f}")
|
|
210
|
+
out.append(marker)
|
|
211
|
+
return "\n".join(out), True
|
|
212
|
+
|
|
213
|
+
@classmethod
|
|
214
|
+
def _compact_cargo_test(cls, raw: str) -> Tuple[str, bool]:
|
|
215
|
+
match = _CARGO_TEST_RE.search(raw)
|
|
216
|
+
if not match:
|
|
217
|
+
return raw, False
|
|
218
|
+
|
|
219
|
+
gd = match.groupdict()
|
|
220
|
+
status = gd.get("status", "")
|
|
221
|
+
passed = int(gd.get("passed") or 0)
|
|
222
|
+
failed = int(gd.get("failed") or 0)
|
|
223
|
+
dur_m = _CARGO_DUR_RE.search(raw)
|
|
224
|
+
dur = dur_m.group("dur") if dur_m else ""
|
|
225
|
+
|
|
226
|
+
dur_str = f" in {dur}" if dur else ""
|
|
227
|
+
if status.lower() == "ok" and failed == 0:
|
|
228
|
+
return f"✓ PASS: {passed} passed (cargo test{dur_str})", True
|
|
229
|
+
|
|
230
|
+
_, marker = stash_block(raw, source="cargo_test")
|
|
231
|
+
# Grab failure section
|
|
232
|
+
failures = []
|
|
233
|
+
in_failures = False
|
|
234
|
+
for ln in raw.splitlines():
|
|
235
|
+
if ln.strip() == "failures:":
|
|
236
|
+
in_failures = True
|
|
237
|
+
continue
|
|
238
|
+
if in_failures:
|
|
239
|
+
if ln.startswith("test result:") or not ln.strip():
|
|
240
|
+
if failures:
|
|
241
|
+
break
|
|
242
|
+
failures.append(ln.strip())
|
|
243
|
+
out = [
|
|
244
|
+
f"✗ FAIL: {failed} failed, {passed} passed (cargo test{dur_str})",
|
|
245
|
+
"Failures:"
|
|
246
|
+
]
|
|
247
|
+
for f in failures[:10]:
|
|
248
|
+
out.append(f" {f}")
|
|
249
|
+
out.append(marker)
|
|
250
|
+
return "\n".join(out), True
|
|
251
|
+
|
|
252
|
+
@classmethod
|
|
253
|
+
def _compact_go_test(cls, raw: str) -> Tuple[str, bool]:
|
|
254
|
+
fails = _GO_TEST_FAIL_RE.findall(raw)
|
|
255
|
+
oks = _GO_TEST_OK_RE.findall(raw)
|
|
256
|
+
if not fails and not oks:
|
|
257
|
+
return raw, False
|
|
258
|
+
|
|
259
|
+
if not fails:
|
|
260
|
+
pkgs = len(oks)
|
|
261
|
+
return f"✓ PASS: all {pkgs} packages passed (go test)", True
|
|
262
|
+
|
|
263
|
+
_, marker = stash_block(raw, source="go_test")
|
|
264
|
+
out = [
|
|
265
|
+
f"✗ FAIL: {len(fails)} package(s) failed, {len(oks)} passed (go test)",
|
|
266
|
+
"Failed packages:"
|
|
267
|
+
]
|
|
268
|
+
for pkg, dur in fails:
|
|
269
|
+
out.append(f" ✗ {pkg} ({dur})")
|
|
270
|
+
out.append(marker)
|
|
271
|
+
return "\n".join(out), True
|
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 = "
|
|
20
|
+
CURRENT_VERSION = "4.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
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""
|
|
2
|
+
TokenSafe Web Page Reader & HTML-to-Markdown Compactor (v3.3.0).
|
|
3
|
+
|
|
4
|
+
Fetches web pages (documentation, API references, articles) and strips clutter:
|
|
5
|
+
- Strips <script>, <style>, <nav>, <footer>, <header>, <aside>, <svg>, <form>, <noscript>
|
|
6
|
+
- Converts content into clean, readable Markdown
|
|
7
|
+
- Protects against SSRF / local address probing
|
|
8
|
+
- Stashes full raw HTML in TokenSafe reversible stash if content is large.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
import urllib.request
|
|
13
|
+
import urllib.parse
|
|
14
|
+
from html.parser import HTMLParser
|
|
15
|
+
from typing import Tuple, Optional, Dict, Any, List
|
|
16
|
+
|
|
17
|
+
from src.stash import stash_block
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class _HTMLToMarkdownParser(HTMLParser):
|
|
21
|
+
"""Pure-Python zero-dependency HTML to clean Markdown extractor."""
|
|
22
|
+
|
|
23
|
+
IGNORE_TAGS = {
|
|
24
|
+
"script", "style", "nav", "footer", "header", "aside",
|
|
25
|
+
"svg", "form", "noscript", "iframe", "object", "embed", "canvas"
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
BLOCK_TAGS = {"p", "div", "section", "article", "blockquote", "tr"}
|
|
29
|
+
HEADING_TAGS = {"h1": 1, "h2": 2, "h3": 3, "h4": 4, "h5": 5, "h6": 6}
|
|
30
|
+
|
|
31
|
+
def __init__(self):
|
|
32
|
+
super().__init__()
|
|
33
|
+
self._ignore_depth = 0
|
|
34
|
+
self._pieces: List[str] = []
|
|
35
|
+
self._in_pre = False
|
|
36
|
+
self._in_code = False
|
|
37
|
+
self._current_link: Optional[str] = None
|
|
38
|
+
self._link_text: List[str] = []
|
|
39
|
+
|
|
40
|
+
def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]):
|
|
41
|
+
tag_lower = tag.lower()
|
|
42
|
+
if tag_lower in self.IGNORE_TAGS:
|
|
43
|
+
self._ignore_depth += 1
|
|
44
|
+
return
|
|
45
|
+
if self._ignore_depth > 0:
|
|
46
|
+
return
|
|
47
|
+
|
|
48
|
+
attr_dict = {k.lower(): (v or "") for k, v in attrs}
|
|
49
|
+
|
|
50
|
+
# Filter out common ad/nav/cookie banner classes/ids
|
|
51
|
+
cls_and_id = (attr_dict.get("class", "") + " " + attr_dict.get("id", "")).lower()
|
|
52
|
+
if any(w in cls_and_id for w in ("cookie", "banner", "advertisement", "sidebar", "nav-menu")):
|
|
53
|
+
self._ignore_depth += 1
|
|
54
|
+
return
|
|
55
|
+
|
|
56
|
+
if tag_lower in self.HEADING_TAGS:
|
|
57
|
+
level = self.HEADING_TAGS[tag_lower]
|
|
58
|
+
self._pieces.append(f"\n\n{'#' * level} ")
|
|
59
|
+
elif tag_lower in self.BLOCK_TAGS:
|
|
60
|
+
self._pieces.append("\n")
|
|
61
|
+
elif tag_lower == "br":
|
|
62
|
+
self._pieces.append("\n")
|
|
63
|
+
elif tag_lower == "hr":
|
|
64
|
+
self._pieces.append("\n\n---\n\n")
|
|
65
|
+
elif tag_lower in ("pre",):
|
|
66
|
+
self._in_pre = True
|
|
67
|
+
self._pieces.append("\n```\n")
|
|
68
|
+
elif tag_lower in ("code",):
|
|
69
|
+
if not self._in_pre:
|
|
70
|
+
self._in_code = True
|
|
71
|
+
self._pieces.append("`")
|
|
72
|
+
elif tag_lower == "li":
|
|
73
|
+
self._pieces.append("\n- ")
|
|
74
|
+
elif tag_lower == "a":
|
|
75
|
+
href = attr_dict.get("href", "").strip()
|
|
76
|
+
if href and not href.startswith(("javascript:", "mailto:", "#")):
|
|
77
|
+
self._current_link = href
|
|
78
|
+
self._link_text = []
|
|
79
|
+
|
|
80
|
+
def handle_endtag(self, tag: str):
|
|
81
|
+
tag_lower = tag.lower()
|
|
82
|
+
if tag_lower in self.IGNORE_TAGS:
|
|
83
|
+
self._ignore_depth = max(0, self._ignore_depth - 1)
|
|
84
|
+
return
|
|
85
|
+
if self._ignore_depth > 0:
|
|
86
|
+
return
|
|
87
|
+
|
|
88
|
+
if tag_lower in self.HEADING_TAGS:
|
|
89
|
+
self._pieces.append("\n\n")
|
|
90
|
+
elif tag_lower in self.BLOCK_TAGS:
|
|
91
|
+
self._pieces.append("\n")
|
|
92
|
+
elif tag_lower == "pre":
|
|
93
|
+
self._in_pre = False
|
|
94
|
+
self._pieces.append("\n```\n")
|
|
95
|
+
elif tag_lower == "code":
|
|
96
|
+
if not self._in_pre and self._in_code:
|
|
97
|
+
self._in_code = False
|
|
98
|
+
self._pieces.append("`")
|
|
99
|
+
elif tag_lower == "a":
|
|
100
|
+
if self._current_link:
|
|
101
|
+
text = "".join(self._link_text).strip()
|
|
102
|
+
if text:
|
|
103
|
+
self._pieces.append(f"[{text}]({self._current_link})")
|
|
104
|
+
self._current_link = None
|
|
105
|
+
self._link_text = []
|
|
106
|
+
|
|
107
|
+
def handle_data(self, data: str):
|
|
108
|
+
if self._ignore_depth > 0:
|
|
109
|
+
return
|
|
110
|
+
if self._current_link is not None:
|
|
111
|
+
self._link_text.append(data)
|
|
112
|
+
return
|
|
113
|
+
|
|
114
|
+
if self._in_pre:
|
|
115
|
+
self._pieces.append(data)
|
|
116
|
+
else:
|
|
117
|
+
# Clean up whitespace
|
|
118
|
+
cleaned = re.sub(r"[ \t]+", " ", data)
|
|
119
|
+
self._pieces.append(cleaned)
|
|
120
|
+
|
|
121
|
+
def get_markdown(self) -> str:
|
|
122
|
+
raw_text = "".join(self._pieces)
|
|
123
|
+
# Collapse multiple empty lines
|
|
124
|
+
cleaned = re.sub(r"\n{3,}", "\n\n", raw_text).strip()
|
|
125
|
+
return cleaned
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class WebReader:
|
|
129
|
+
"""Safely fetches web pages and returns clean Markdown."""
|
|
130
|
+
|
|
131
|
+
_BLOCKED_HOSTS = {"localhost", "127.0.0.1", "0.0.0.0", "::1", "169.254.169.254"}
|
|
132
|
+
|
|
133
|
+
@classmethod
|
|
134
|
+
def is_safe_url(cls, url: str) -> bool:
|
|
135
|
+
try:
|
|
136
|
+
parsed = urllib.parse.urlparse(url)
|
|
137
|
+
if parsed.scheme not in ("http", "https"):
|
|
138
|
+
return False
|
|
139
|
+
host = (parsed.hostname or "").lower()
|
|
140
|
+
if host in cls._BLOCKED_HOSTS or host.startswith(("10.", "192.168.", "172.16.")):
|
|
141
|
+
return False
|
|
142
|
+
return True
|
|
143
|
+
except Exception:
|
|
144
|
+
return False
|
|
145
|
+
|
|
146
|
+
@classmethod
|
|
147
|
+
def html_to_markdown(cls, html_content: str, url: str = "") -> Tuple[str, bool]:
|
|
148
|
+
"""Converts raw HTML string to clean Markdown."""
|
|
149
|
+
parser = _HTMLToMarkdownParser()
|
|
150
|
+
try:
|
|
151
|
+
parser.feed(html_content)
|
|
152
|
+
md = parser.get_markdown()
|
|
153
|
+
except Exception:
|
|
154
|
+
# Basic regex fallback if HTMLParser fails on corrupt tags
|
|
155
|
+
cleaned = re.sub(r"<(script|style)[^>]*>.*?</\1>", "", html_content, flags=re.DOTALL | re.IGNORECASE)
|
|
156
|
+
cleaned = re.sub(r"<[^>]+>", " ", cleaned)
|
|
157
|
+
md = re.sub(r"\s+", " ", cleaned).strip()
|
|
158
|
+
|
|
159
|
+
if len(html_content) > 3000 and len(md) < len(html_content) * 0.7:
|
|
160
|
+
hash8, marker = stash_block(html_content, source=f"web:{url[:60]}")
|
|
161
|
+
header = f"# [TokenSafe Web Extract: {url}]\n\n" if url else ""
|
|
162
|
+
return f"{header}{md}\n\n{marker}", True
|
|
163
|
+
|
|
164
|
+
return md, False
|
|
165
|
+
|
|
166
|
+
@classmethod
|
|
167
|
+
def fetch_url(cls, url: str, timeout: float = 8.0) -> Tuple[str, bool, Optional[str]]:
|
|
168
|
+
"""
|
|
169
|
+
Fetches URL, converts to clean Markdown.
|
|
170
|
+
Returns (content_or_error, is_success, opt_error_msg).
|
|
171
|
+
"""
|
|
172
|
+
if not cls.is_safe_url(url):
|
|
173
|
+
return "", False, f"Refused to fetch potentially unsafe or internal URL: {url}"
|
|
174
|
+
|
|
175
|
+
req = urllib.request.Request(
|
|
176
|
+
url,
|
|
177
|
+
headers={
|
|
178
|
+
"User-Agent": "Mozilla/5.0 (compatible; TokenSafeBot/3.3; +https://tokensafe.dev)",
|
|
179
|
+
"Accept": "text/html,application/xhtml+xml,text/plain;q=0.9",
|
|
180
|
+
}
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
|
185
|
+
status = resp.status
|
|
186
|
+
if status >= 400:
|
|
187
|
+
return "", False, f"HTTP Error {status}"
|
|
188
|
+
content_type = resp.headers.get("Content-Type", "").lower()
|
|
189
|
+
raw_bytes = resp.read(2 * 1024 * 1024) # 2MB max
|
|
190
|
+
charset = "utf-8"
|
|
191
|
+
if "charset=" in content_type:
|
|
192
|
+
charset = content_type.split("charset=")[-1].split(";")[0].strip()
|
|
193
|
+
|
|
194
|
+
raw_text = raw_bytes.decode(charset, errors="replace")
|
|
195
|
+
|
|
196
|
+
if "text/html" in content_type or "<html" in raw_text.lower():
|
|
197
|
+
md, _ = cls.html_to_markdown(raw_text, url=url)
|
|
198
|
+
return md, True, None
|
|
199
|
+
else:
|
|
200
|
+
return raw_text, True, None
|
|
201
|
+
except Exception as e:
|
|
202
|
+
return "", False, f"Fetch error: {e}"
|