foxfetch 0.1.0__py3-none-any.whl

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.
foxfetch/engine.py ADDED
@@ -0,0 +1,502 @@
1
+ """The five page-facing tools, implemented once for every entry point."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import glob
7
+ import json
8
+ import os
9
+ import shutil
10
+ import time
11
+ from pathlib import Path
12
+ from typing import Any, Callable, TypeVar, cast
13
+
14
+ from . import doctor as doctor_module
15
+ from .config import SETTINGS
16
+ from .contexts import POOL, ContextError, Slot, as_failure, origin_of
17
+ from .shapes import (
18
+ as_text,
19
+ clip_text,
20
+ dumps,
21
+ ensure_artifacts_dir,
22
+ failure,
23
+ prune_artifacts,
24
+ purge_artifacts,
25
+ spill,
26
+ tail,
27
+ )
28
+
29
+ READY_PROBE = "JSON.stringify([document.readyState, String(location.href), !!document.body, document.body ? document.body.childElementCount : 0])"
30
+ SETTLE_BUDGET_MS = 20_000
31
+ SETTLE_STEPS = (50, 100, 200)
32
+ NO_CONTEXT_HINT = "no live context for that origin. Pass url to open one; a context dies on idle, on close, or when the pool evicts it."
33
+
34
+
35
+ def _widen(payload: dict[str, Any], **empty: Any) -> dict[str, Any]:
36
+ """Give a failure the same keys as its success payload, so callers never branch on absence."""
37
+ for key, filler in empty.items():
38
+ payload.setdefault(key, filler)
39
+ return payload
40
+
41
+
42
+ RUN_EMPTY: dict[str, Any] = {"context_id": None, "origin": None, "url": None, "created": False,
43
+ "text": "", "value": None, "console": [], "net": [], "truncated": False,
44
+ "bytes": 0, "spilled_to": None, "elapsed_ms": 0}
45
+ NET_EMPTY: dict[str, Any] = {"context_id": None, "origin": None, "net": [], "console": []}
46
+ HANDOFF_EMPTY: dict[str, Any] = {"context_id": None, "origin": None, "url": None, "user_agent": None,
47
+ "cookies": [], "local_storage": {}, "script": None, "script_path": None,
48
+ "chromium_available": False, "note": None, "text": "", "truncated": False}
49
+
50
+
51
+ def _artifact_state() -> dict[str, Any]:
52
+ """What this service is still holding on disk, right now."""
53
+ directory = SETTINGS.artifacts
54
+ files = 0
55
+ total = 0
56
+ oldest: float | None = None
57
+ now = time.time()
58
+ if directory.is_dir():
59
+ try:
60
+ for entry in directory.iterdir():
61
+ try:
62
+ if not entry.is_file():
63
+ continue
64
+ stat = entry.stat()
65
+ except OSError:
66
+ continue
67
+ files += 1
68
+ total += stat.st_size
69
+ age = now - stat.st_mtime
70
+ oldest = age if oldest is None else max(oldest, age)
71
+ except OSError:
72
+ pass
73
+ return {"files": files, "bytes": total, "oldest_age_s": int(oldest) if oldest is not None else 0}
74
+
75
+
76
+ def _artifact_hint() -> dict[str, Any]:
77
+ """Attach the pending-artifact state to every tool response.
78
+
79
+ The agent reads tool results, not documentation, so the reminder has to arrive with the
80
+ data. It stays silent for the first few minutes (a run legitimately produces files
81
+ mid-task) and disappears on its own once `cleanup` runs.
82
+ """
83
+ state = _artifact_state()
84
+ reminder = None
85
+ if state["files"] and SETTINGS.remind_after_seconds and state["oldest_age_s"] >= SETTINGS.remind_after_seconds:
86
+ reminder = (
87
+ f"{state['files']} artifact(s) ({state['bytes']} bytes) written by this service are still on disk, "
88
+ f"the oldest {state['oldest_age_s']} s ago. They can contain live cookies and tokens: call "
89
+ f"`cleanup` once the task is delivered, keeping any file the user still needs via `keep`."
90
+ )
91
+ return {"artifacts_pending": state, "reminder": reminder}
92
+
93
+
94
+ F = TypeVar("F", bound=Callable[..., dict[str, Any]])
95
+
96
+
97
+ def _with_hint(fn: F) -> F:
98
+ """Every public tool result carries the artifact reminder."""
99
+
100
+ @functools.wraps(fn)
101
+ def wrapper(*args: Any, **kwargs: Any) -> dict[str, Any]:
102
+ result = fn(*args, **kwargs)
103
+ try:
104
+ result.update(_artifact_hint())
105
+ except Exception:
106
+ pass
107
+ return result
108
+
109
+ return cast(F, wrapper)
110
+
111
+
112
+ # ── navigation ──────────────────────────────────────────────────────────────
113
+
114
+
115
+ def _same_url(here: str, expected: str) -> bool:
116
+ """Browsers normalise away a trailing slash; a bare string compare never matches."""
117
+ if here == expected:
118
+ return True
119
+ return here.rstrip("/") == expected.rstrip("/")
120
+
121
+
122
+ def _settle(slot: Slot, expected_url: str | None, budget_ms: int = SETTLE_BUDGET_MS) -> bool:
123
+ """Advance until the target document is committed, parsed and has a body."""
124
+ deadline = time.monotonic() + budget_ms / 1000
125
+ index = 0
126
+ while True:
127
+ try:
128
+ state = slot.ctx.eval(READY_PROBE, to_py=True)
129
+ ready, here, has_body, children = json.loads(state)
130
+ except Exception:
131
+ ready, here, has_body, children = "", "", False, 0
132
+ if ready == "complete" and has_body and children > 0 and (expected_url is None or _same_url(here, expected_url)):
133
+ slot.url = here or slot.url
134
+ return True
135
+ if time.monotonic() >= deadline:
136
+ return False
137
+ slot.ctx.advance(SETTLE_STEPS[min(index, len(SETTLE_STEPS) - 1)])
138
+ index += 1
139
+
140
+
141
+ def _navigate(slot: Slot, url: str, budget_ms: int) -> dict[str, Any] | None:
142
+ slot.ctx.navigate(url)
143
+ slot.url = url
144
+ if _settle(slot, url, budget_ms):
145
+ return None
146
+ return failure(
147
+ f"navigation produced an empty document after {budget_ms} ms ({url}); the page may need more time or a real browser",
148
+ kind="nav",
149
+ )
150
+
151
+
152
+ def _acquire(
153
+ url: str | None,
154
+ context_id: str | None,
155
+ *,
156
+ proxy: str | None,
157
+ fingerprint: dict[str, Any] | None,
158
+ timeout_ms: int,
159
+ ) -> tuple[Slot, bool]:
160
+ """Return (slot, created). Without url/context_id only existing slots qualify."""
161
+ if context_id or (url and POOL.has_origin(url)):
162
+ return POOL.get(context_id=context_id, url=url), False
163
+ if not url:
164
+ raise ContextError(NO_CONTEXT_HINT, "context")
165
+ return POOL.open(url, proxy=proxy, fingerprint=fingerprint, timeout_s=timeout_ms / 1000), True
166
+
167
+
168
+ def _paged(
169
+ url: str | None,
170
+ context_id: str | None,
171
+ *,
172
+ proxy: str | None = None,
173
+ fingerprint: dict[str, Any] | None = None,
174
+ timeout_ms: int,
175
+ ) -> tuple[Slot, bool, dict[str, Any] | None]:
176
+ """Acquire a slot and make sure it shows `url`. Returns (slot, created, problem).
177
+
178
+ A context that is already on the requested URL is reused as-is: re-navigating would
179
+ throw away the JS world a previous call built up.
180
+ """
181
+ slot, created = _acquire(url, context_id, proxy=proxy, fingerprint=fingerprint, timeout_ms=timeout_ms)
182
+ if not url:
183
+ return slot, created, None
184
+ if not created and slot.url and _same_url(slot.url, url):
185
+ return slot, created, None
186
+ return slot, created, _navigate(slot, url, timeout_ms)
187
+
188
+
189
+ # ── tools ───────────────────────────────────────────────────────────────────
190
+
191
+
192
+ @_with_hint
193
+ def run(
194
+ js: str,
195
+ url: str | None = None,
196
+ context_id: str | None = None,
197
+ advance_ms: int | None = None,
198
+ read: str | None = None,
199
+ proxy: str | None = None,
200
+ fingerprint: dict[str, Any] | None = None,
201
+ timeout_ms: int | None = None,
202
+ max_bytes: int | None = None,
203
+ ) -> dict[str, Any]:
204
+ budget = int(timeout_ms or SETTINGS.default_timeout_ms)
205
+ cap = int(max_bytes or SETTINGS.max_bytes)
206
+ started = time.monotonic()
207
+ try:
208
+ slot, created, problem = _paged(
209
+ url, context_id, proxy=proxy, fingerprint=fingerprint, timeout_ms=budget
210
+ )
211
+ except ContextError as error:
212
+ return _widen(as_failure(error), **RUN_EMPTY)
213
+ if problem is not None:
214
+ return _widen(problem, **RUN_EMPTY)
215
+
216
+ with slot.lock:
217
+ slot.touch()
218
+ try:
219
+ value = slot.ctx.eval(js, filename="tool.js", to_py=True)
220
+ if advance_ms:
221
+ slot.ctx.advance(int(advance_ms))
222
+ if read:
223
+ value = slot.ctx.eval(read, filename="read.js", to_py=True)
224
+ slot.touch()
225
+ except Exception as error:
226
+ return _widen(as_failure(error), **RUN_EMPTY)
227
+ logs = _logs(slot, 40)
228
+
229
+ text, truncated, size = clip_text(as_text(value), cap)
230
+ payload: dict[str, Any] = {
231
+ "ok": True,
232
+ "context_id": slot.context_id,
233
+ "origin": slot.origin,
234
+ "url": slot.url,
235
+ "created": created,
236
+ "text": text,
237
+ "value": value if not truncated else text,
238
+ "console": logs["console"],
239
+ "net": logs["net"],
240
+ "truncated": truncated,
241
+ "bytes": size,
242
+ "spilled_to": None,
243
+ "elapsed_ms": int((time.monotonic() - started) * 1000),
244
+ "error": None,
245
+ "error_kind": None,
246
+ }
247
+ if truncated:
248
+ payload["spilled_to"] = spill("value", as_text(value))
249
+ return payload
250
+
251
+
252
+ @_with_hint
253
+ def net(url: str | None = None, context_id: str | None = None, count: int = 50) -> dict[str, Any]:
254
+ try:
255
+ slot = POOL.get(context_id=context_id, url=url)
256
+ except ContextError as error:
257
+ return _widen(as_failure(error), **NET_EMPTY)
258
+ with slot.lock:
259
+ slot.touch()
260
+ logs = _logs(slot, max(1, int(count)))
261
+ return {"ok": True, "context_id": slot.context_id, "origin": slot.origin, **logs, "error": None, "error_kind": None}
262
+
263
+
264
+ def _logs(slot: Slot, count: int) -> dict[str, list[Any]]:
265
+ entries: dict[str, list[Any]] = {"net": [], "console": []}
266
+ try:
267
+ entries["net"] = tail(_plain(slot.ctx.net_log()), count)
268
+ except Exception:
269
+ pass
270
+ try:
271
+ entries["console"] = tail(_plain(slot.ctx.console_log()), count)
272
+ except Exception:
273
+ pass
274
+ return entries
275
+
276
+
277
+ def _plain(value: Any) -> Any:
278
+ """JSON-safe projection: no NaN/-0 surprises, no live engine handles."""
279
+ if value is None or isinstance(value, (bool, str, int)):
280
+ return value
281
+ if isinstance(value, float):
282
+ if value != value or value in (float("inf"), float("-inf")):
283
+ return repr(value)
284
+ return 0 if value == 0 else value
285
+ if isinstance(value, (list, tuple)):
286
+ return [_plain(item) for item in value]
287
+ if isinstance(value, dict):
288
+ return {str(key): _plain(item) for key, item in value.items()}
289
+ return repr(value)
290
+
291
+
292
+ # ── handoff ─────────────────────────────────────────────────────────────────
293
+
294
+
295
+ def to_playwright_cookie(record: Any) -> dict[str, Any]:
296
+ """Firefox reports sameSite "Default"; Playwright only knows the three named values."""
297
+ raw = record if isinstance(record, dict) else getattr(record, "__dict__", {}) or {}
298
+ same_site = {"Strict": "Strict", "Lax": "Lax", "None": "None"}.get(str(raw.get("sameSite")), "Lax")
299
+ expires = raw.get("expires")
300
+ return {
301
+ "name": str(raw.get("name") or ""),
302
+ "value": str(raw.get("value") or ""),
303
+ "domain": str(raw.get("domain") or ""),
304
+ "path": str(raw.get("path") or "/"),
305
+ "expires": float(expires) if isinstance(expires, (int, float)) else -1,
306
+ "httpOnly": bool(raw.get("httpOnly")),
307
+ "secure": bool(raw.get("secure")),
308
+ "sameSite": same_site,
309
+ }
310
+
311
+
312
+ @_with_hint
313
+ def handoff(
314
+ url: str | None = None,
315
+ context_id: str | None = None,
316
+ keys: list[str] | None = None,
317
+ max_bytes: int | None = None,
318
+ ) -> dict[str, Any]:
319
+ cap = int(max_bytes or SETTINGS.max_bytes)
320
+ try:
321
+ slot, _created, problem = _paged(url, context_id, timeout_ms=SETTINGS.default_timeout_ms)
322
+ except ContextError as error:
323
+ return _widen(as_failure(error), **HANDOFF_EMPTY)
324
+ if problem is not None:
325
+ return _widen(problem, **HANDOFF_EMPTY)
326
+
327
+ with slot.lock:
328
+ slot.touch()
329
+ try:
330
+ cookies = [_plain(item) for item in slot.ctx.export_cookies()]
331
+ wanted = json.dumps([str(k) for k in keys]) if keys else None
332
+ enumeration = wanted or "Array.from({length: localStorage.length}, (_, i) => localStorage.key(i))"
333
+ expression = (
334
+ "JSON.stringify({origin: location.origin, url: location.href, ua: navigator.userAgent, ls: "
335
+ f"Object.fromEntries({enumeration}.filter((k) => k !== null && localStorage.getItem(k) !== null)"
336
+ ".map((k) => [k, localStorage.getItem(k)]))})"
337
+ )
338
+ page = json.loads(slot.ctx.eval(expression, filename="handoff.js", to_py=True))
339
+ except Exception as error:
340
+ return _widen(as_failure(error), **HANDOFF_EMPTY)
341
+
342
+ mapped = [to_playwright_cookie(item) for item in cookies]
343
+ chromium = doctor_module.find_browsers()
344
+ node_playwright = doctor_module.find_node_playwright()
345
+ script_path: str | None = None
346
+ note: str | None = None
347
+ script = _handoff_script(mapped, page.get("ls") or {}, page.get("ua") or "", page.get("url") or "")
348
+ if chromium["found"] and node_playwright["found"]:
349
+ script_path = _write_artifact("handoff.cjs", script, ".cjs")
350
+ else:
351
+ missing = "Chromium" if not chromium["found"] else "the node 'playwright' package"
352
+ note = f"{missing} not found, so no screenshot script was written. Run: npx playwright install chromium"
353
+
354
+ summary = (
355
+ f"{len(mapped)} cookie(s), {len(page.get('ls') or {})} local key(s) for {page.get('origin')}"
356
+ + (f"; script: {script_path}" if script_path else "")
357
+ + (f"; {note}" if note else "")
358
+ + " — these values are live credentials: delete them when the task is done"
359
+ )
360
+ text, truncated, _ = clip_text(summary, cap)
361
+ return {
362
+ "ok": True,
363
+ "context_id": slot.context_id,
364
+ "origin": page.get("origin"),
365
+ "url": page.get("url"),
366
+ "user_agent": page.get("ua"),
367
+ "cookies": mapped,
368
+ "local_storage": page.get("ls") or {},
369
+ "script": script if script_path else None,
370
+ "script_path": script_path,
371
+ "chromium_available": bool(chromium["found"]),
372
+ "note": note,
373
+ "text": text,
374
+ "truncated": truncated,
375
+ "error": None,
376
+ "error_kind": None,
377
+ }
378
+
379
+
380
+ def _handoff_script(cookies: list[dict[str, Any]], store: dict[str, str], user_agent: str, url: str) -> str:
381
+ shot = str(Path(SETTINGS.artifacts) / "handoff-shot.png")
382
+ return "\n".join(
383
+ [
384
+ "// Generated by foxfetch handoff. Run with: node <this file>",
385
+ "// PLAYWRIGHT_PATH points at the playwright package when node cannot resolve it.",
386
+ 'const { chromium } = require(process.env.PLAYWRIGHT_PATH || "playwright");',
387
+ "",
388
+ "(async () => {",
389
+ ' const browser = await chromium.launch({ channel: "chromium-headless-shell" });',
390
+ " try {",
391
+ f" const context = await browser.newContext({{ userAgent: {json.dumps(user_agent)} }});",
392
+ f" await context.addCookies({json.dumps(cookies)});",
393
+ " await context.addInitScript(() => {",
394
+ f" for (const [k, v] of Object.entries({json.dumps(store)})) localStorage.setItem(k, v);",
395
+ " });",
396
+ " const page = await context.newPage();",
397
+ f" await page.goto({json.dumps(url)});",
398
+ f" await page.screenshot({{ path: {json.dumps(shot)} }});",
399
+ f" console.log({json.dumps(shot)});",
400
+ " } finally {",
401
+ " // Close on every path: a throw here leaves a browser nobody holds.",
402
+ " await browser.close();",
403
+ " }",
404
+ "})().catch((error) => { console.error(error); process.exit(1); });",
405
+ ]
406
+ )
407
+
408
+
409
+ def _write_artifact(stem: str, text: str, suffix: str) -> str:
410
+ directory = Path(ensure_artifacts_dir())
411
+ stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
412
+ path = directory / f"{stamp}-{os.getpid()}-{stem if stem.endswith(suffix) else stem + suffix}"
413
+ path.write_text(text, encoding="utf-8")
414
+ prune_artifacts(protect=[str(path)])
415
+ return str(path)
416
+
417
+
418
+ # ── cleanup ─────────────────────────────────────────────────────────────────
419
+
420
+ TEMP_PATTERNS = (
421
+ "scoped_dir*",
422
+ "HeadlessChrome*",
423
+ "playwright-artifacts-*",
424
+ "playwright_chromiumdev_profile-*",
425
+ "playwright-*",
426
+ )
427
+
428
+
429
+ def _sweep_temp() -> dict[str, int]:
430
+ root = Path(os.environ.get("TEMP") or os.environ.get("TMPDIR") or "/tmp")
431
+ removed = freed = 0
432
+ for pattern in TEMP_PATTERNS:
433
+ for match in glob.glob(str(root / pattern)):
434
+ path = Path(match)
435
+ try:
436
+ size = sum(f.stat().st_size for f in path.rglob("*") if f.is_file()) if path.is_dir() else path.stat().st_size
437
+ except OSError:
438
+ size = 0
439
+ try:
440
+ if path.is_dir():
441
+ shutil.rmtree(path, ignore_errors=False)
442
+ else:
443
+ path.unlink()
444
+ removed += 1
445
+ freed += size
446
+ except OSError:
447
+ continue
448
+ return {"removed": removed, "freed": freed}
449
+
450
+
451
+ @_with_hint
452
+ def cleanup(scope: str = "all", keep: list[str] | None = None) -> dict[str, Any]:
453
+ if scope not in {"artifacts", "contexts", "all"}:
454
+ return failure("scope must be artifacts, contexts or all", kind="env")
455
+ protected = [str(Path(item).expanduser()) for item in (keep or [])]
456
+ artifacts = {"removed": 0, "freed": 0}
457
+ temp = {"removed": 0, "freed": 0}
458
+ closed = 0
459
+ if scope in {"artifacts", "all"}:
460
+ artifacts = purge_artifacts(protect=protected)
461
+ temp = _sweep_temp()
462
+ if scope in {"contexts", "all"}:
463
+ closed = POOL.close_all()
464
+ total_freed = artifacts["freed"] + temp["freed"]
465
+ return {
466
+ "ok": True,
467
+ "scope": scope,
468
+ "removed_files": artifacts["removed"] + temp["removed"],
469
+ "freed_bytes": total_freed,
470
+ "closed_contexts": closed,
471
+ "kept": protected,
472
+ "artifacts_dir": str(SETTINGS.artifacts),
473
+ "error": None,
474
+ "error_kind": None,
475
+ }
476
+
477
+
478
+ @_with_hint
479
+ def inventory() -> dict[str, Any]:
480
+ contexts = POOL.inventory()
481
+ return {
482
+ "ok": True,
483
+ "contexts": contexts,
484
+ "count": len(contexts),
485
+ "artifacts": doctor_module.artifacts_status(),
486
+ "error": None,
487
+ "error_kind": None,
488
+ }
489
+
490
+
491
+ @_with_hint
492
+ def close(url: str | None = None, context_id: str | None = None) -> dict[str, Any]:
493
+ if context_id:
494
+ closed = 1 if POOL.close(context_id) else 0
495
+ elif url:
496
+ try:
497
+ closed = POOL.close_origin(url)
498
+ except ContextError as error:
499
+ return as_failure(error)
500
+ else:
501
+ closed = POOL.close_all()
502
+ return {"ok": True, "closed": closed, "error": None, "error_kind": None}
foxfetch/probe.py ADDED
@@ -0,0 +1,187 @@
1
+ """Decide whether a page needs a browser engine at all.
2
+
3
+ The expensive path exists to defeat bot checks. Reaching for it on a page that answers
4
+ a plain request is pure waste: 90 MB of RAM and ~3 s of engine time to read a static
5
+ document. `probe` answers the question with evidence, so the caller picks a layer from
6
+ facts instead of a hunch.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import html
12
+ import re
13
+ import ssl
14
+ import time
15
+ import urllib.error
16
+ import urllib.request
17
+ from typing import Any
18
+
19
+ READ_CAP = 262_144 # 256 KiB is enough to tell a document from a challenge page
20
+ TEXT_MIN_CHARS = 120 # visible text below this is a stub, not a document
21
+ UA = "foxfetch-probe/0.1 (+plain http check)"
22
+ DEFAULT_TIMEOUT_S = 15.0
23
+
24
+ # Substrings that only show up on an interstitial or a bot check.
25
+ BLOCK_MARKERS: tuple[tuple[str, str], ...] = (
26
+ ("cf-chl", "Cloudflare challenge"),
27
+ ("challenge-platform", "Cloudflare challenge platform"),
28
+ ("cf_chl_opt", "Cloudflare challenge options"),
29
+ ("_incapsula_resource", "Imperva/Incapsula"),
30
+ ("datadome", "DataDome"),
31
+ ("px-captcha", "PerimeterX"),
32
+ ("kasada", "Kasada"),
33
+ ("_abck", "Akamai Bot Manager"),
34
+ ("perimeterx", "PerimeterX"),
35
+ ("just a moment", "Cloudflare 'Just a moment' interstitial"),
36
+ ("attention required", "Cloudflare block page"),
37
+ ("verify you are human", "human verification wall"),
38
+ ("enable javascript and cookies to continue", "JS/cookie wall"),
39
+ ("unusual traffic", "rate-limit or bot wall"),
40
+ ("access denied", "access denied page"),
41
+ )
42
+
43
+ BLOCK_STATUS = {401, 403, 407, 429, 451, 503}
44
+
45
+ # Empty mount points that a framework fills in later.
46
+ SKELETON_PATTERN = re.compile(
47
+ r"<div[^>]+id=[\"'](?:root|app|__next|__nuxt|__layout)[\"'][^>]*>\s*</div>",
48
+ re.IGNORECASE,
49
+ )
50
+ NOSCRIPT_PATTERN = re.compile(r"<noscript[^>]*>(.*?)</noscript>", re.IGNORECASE | re.DOTALL)
51
+ SCRIPT_STYLE = re.compile(r"<(script|style)\b[^>]*>.*?</\1>", re.IGNORECASE | re.DOTALL)
52
+ TAG = re.compile(r"<[^>]+>")
53
+ TITLE = re.compile(r"<title[^>]*>(.*?)</title>", re.IGNORECASE | re.DOTALL)
54
+
55
+
56
+ def _text_of(body: str) -> str:
57
+ stripped = SCRIPT_STYLE.sub(" ", body)
58
+ return html.unescape(TAG.sub(" ", stripped)).strip()
59
+
60
+
61
+ def _title_of(body: str) -> str:
62
+ match = TITLE.search(body)
63
+ return html.unescape(match.group(1)).strip()[:200] if match else ""
64
+
65
+
66
+ def probe(url: str, timeout_s: float = DEFAULT_TIMEOUT_S) -> dict[str, Any]:
67
+ """Fetch `url` over plain HTTP and classify what came back."""
68
+ started = time.monotonic()
69
+ evidence: list[dict[str, str]] = []
70
+ request = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "text/html,*/*"})
71
+ context = ssl.create_default_context()
72
+ status: int | None = None
73
+ body = ""
74
+ content_type = ""
75
+ final_url = url
76
+ capped = False
77
+ error: str | None = None
78
+
79
+ try:
80
+ with urllib.request.urlopen(request, timeout=timeout_s, context=context) as response:
81
+ status = response.status
82
+ final_url = response.geturl()
83
+ content_type = response.headers.get("Content-Type", "")
84
+ raw = response.read(READ_CAP)
85
+ capped = len(raw) >= READ_CAP
86
+ body = raw.decode(response.headers.get_content_charset() or "utf-8", "replace")
87
+ except urllib.error.HTTPError as http_error:
88
+ status = http_error.code
89
+ final_url = http_error.geturl() or url
90
+ content_type = http_error.headers.get("Content-Type", "") if http_error.headers else ""
91
+ try:
92
+ body = http_error.read(READ_CAP).decode("utf-8", "replace")
93
+ except Exception:
94
+ body = ""
95
+ except Exception as exc: # DNS, TLS, refused, timeout
96
+ error = f"{type(exc).__name__}: {exc}"
97
+
98
+ elapsed_ms = int((time.monotonic() - started) * 1000)
99
+ text = _text_of(body)
100
+ lowered = body.lower()
101
+
102
+ if error is not None:
103
+ evidence.append({"kind": "transport", "detail": error})
104
+ return _verdict(
105
+ "blocked",
106
+ status,
107
+ evidence,
108
+ "请求本身没成功(网络/证书/超时)。先确认地址可用;若是被墙或被拦,用 run 走引擎。",
109
+ final_url,
110
+ elapsed_ms,
111
+ len(body),
112
+ )
113
+
114
+ if status in BLOCK_STATUS:
115
+ evidence.append({"kind": "status", "detail": f"HTTP {status}"})
116
+ for needle, label in BLOCK_MARKERS:
117
+ if needle in lowered:
118
+ evidence.append({"kind": "marker", "detail": f"{label}(命中 {needle!r})"})
119
+
120
+ for match in NOSCRIPT_PATTERN.findall(body)[:2]:
121
+ hint = _text_of(match)
122
+ if len(hint) > 40:
123
+ evidence.append({"kind": "noscript", "detail": hint[:120]})
124
+
125
+ if SKELETON_PATTERN.search(body):
126
+ evidence.append({"kind": "skeleton", "detail": "页面只有一个空的挂载点(<div id=\"root|app\"></div>)"})
127
+
128
+ if capped:
129
+ evidence.append({"kind": "size", "detail": f"正文超过 {READ_CAP} 字节,已截断读取"})
130
+ evidence.append({"kind": "size", "detail": f"{len(body)} 字节,其中可见文本 {len(text)} 字符"})
131
+
132
+ has_block = any(item["kind"] in {"status", "marker"} for item in evidence)
133
+ thin = len(text) < TEXT_MIN_CHARS and not capped
134
+ skeleton = any(item["kind"] == "skeleton" for item in evidence)
135
+
136
+ if has_block:
137
+ return _verdict(
138
+ "blocked",
139
+ status,
140
+ evidence,
141
+ "被反爬或风控拦住了,普通 HTTP 拿不到内容。用 run:引擎的 TLS 与 JS 指纹跟真 Firefox 一致。",
142
+ final_url,
143
+ elapsed_ms,
144
+ len(body),
145
+ )
146
+ if thin or skeleton or any(item["kind"] == "noscript" for item in evidence):
147
+ return _verdict(
148
+ "needs_engine",
149
+ status,
150
+ evidence,
151
+ "响应正常但内容要等页面脚本填充。用 run 执行站点自己的 JS 后再读 DOM。",
152
+ final_url,
153
+ elapsed_ms,
154
+ len(body),
155
+ )
156
+ return _verdict(
157
+ "plain_http",
158
+ status,
159
+ evidence,
160
+ "普通 HTTP 已经拿到完整正文,不需要引擎。直接用 fetch/curl 更快更省。",
161
+ final_url,
162
+ elapsed_ms,
163
+ len(body),
164
+ )
165
+
166
+
167
+ def _verdict(
168
+ verdict: str,
169
+ status: int | None,
170
+ evidence: list[dict[str, str]],
171
+ suggestion: str,
172
+ final_url: str,
173
+ elapsed_ms: int,
174
+ size: int,
175
+ ) -> dict[str, Any]:
176
+ return {
177
+ "ok": True,
178
+ "verdict": verdict,
179
+ "status": status,
180
+ "url": final_url,
181
+ "bytes": size,
182
+ "elapsed_ms": elapsed_ms,
183
+ "evidence": evidence,
184
+ "suggestion": suggestion,
185
+ "error": None,
186
+ "error_kind": None,
187
+ }