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/__init__.py +5 -0
- foxfetch/__main__.py +3 -0
- foxfetch/cli.py +80 -0
- foxfetch/config.py +56 -0
- foxfetch/contexts.py +235 -0
- foxfetch/doctor.py +217 -0
- foxfetch/engine.py +502 -0
- foxfetch/probe.py +187 -0
- foxfetch/server.py +160 -0
- foxfetch/shapes.py +172 -0
- foxfetch-0.1.0.dist-info/METADATA +171 -0
- foxfetch-0.1.0.dist-info/RECORD +15 -0
- foxfetch-0.1.0.dist-info/WHEEL +4 -0
- foxfetch-0.1.0.dist-info/entry_points.txt +2 -0
- foxfetch-0.1.0.dist-info/licenses/LICENSE +24 -0
foxfetch/__init__.py
ADDED
foxfetch/__main__.py
ADDED
foxfetch/cli.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Command line: `foxfetch` starts the MCP server, subcommands are diagnostics."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from . import engine
|
|
10
|
+
from .config import SETTINGS
|
|
11
|
+
from .doctor import doctor as run_doctor
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _print(payload: object) -> None:
|
|
15
|
+
stream = sys.stdout
|
|
16
|
+
reconfigure = getattr(stream, "reconfigure", None) # a cp936 console mangles UTF-8 JSON
|
|
17
|
+
if reconfigure is not None:
|
|
18
|
+
try:
|
|
19
|
+
reconfigure(encoding="utf-8", errors="replace")
|
|
20
|
+
except Exception:
|
|
21
|
+
pass
|
|
22
|
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def main(argv: list[str] | None = None) -> int:
|
|
26
|
+
parser = argparse.ArgumentParser(prog="foxfetch", description="Firefox-engine page fetching for AI agents")
|
|
27
|
+
sub = parser.add_subparsers(dest="command")
|
|
28
|
+
|
|
29
|
+
sub.add_parser("serve", help="start the MCP stdio server (default)")
|
|
30
|
+
sub.add_parser("doctor", help="check python, ruyijs, mcp, chromium and artifact usage")
|
|
31
|
+
sub.add_parser("status", help="list live contexts and artifact usage")
|
|
32
|
+
|
|
33
|
+
probe_parser = sub.add_parser("probe", help="check whether a URL needs a browser engine")
|
|
34
|
+
probe_parser.add_argument("url")
|
|
35
|
+
probe_parser.add_argument("--timeout", type=float, default=15.0)
|
|
36
|
+
|
|
37
|
+
run_parser = sub.add_parser("run", help="evaluate JavaScript in the engine")
|
|
38
|
+
run_parser.add_argument("js")
|
|
39
|
+
run_parser.add_argument("--url")
|
|
40
|
+
run_parser.add_argument("--advance", type=int, dest="advance_ms")
|
|
41
|
+
run_parser.add_argument("--read")
|
|
42
|
+
run_parser.add_argument("--timeout", type=int, dest="timeout_ms")
|
|
43
|
+
|
|
44
|
+
cleanup_parser = sub.add_parser("cleanup", help="delete artifacts and close contexts")
|
|
45
|
+
cleanup_parser.add_argument("--scope", default="all", choices=["artifacts", "contexts", "all"])
|
|
46
|
+
cleanup_parser.add_argument("--keep", action="append", default=[])
|
|
47
|
+
|
|
48
|
+
args = parser.parse_args(argv)
|
|
49
|
+
command = args.command or "serve"
|
|
50
|
+
|
|
51
|
+
if command == "serve":
|
|
52
|
+
from .server import main as serve
|
|
53
|
+
|
|
54
|
+
serve()
|
|
55
|
+
return 0
|
|
56
|
+
if command == "doctor":
|
|
57
|
+
report = run_doctor()
|
|
58
|
+
_print(report)
|
|
59
|
+
return 0 if report["ok"] else 1
|
|
60
|
+
if command == "status":
|
|
61
|
+
_print(engine.inventory())
|
|
62
|
+
return 0
|
|
63
|
+
if command == "probe":
|
|
64
|
+
from .probe import probe as run_probe
|
|
65
|
+
|
|
66
|
+
_print(run_probe(args.url, args.timeout))
|
|
67
|
+
return 0
|
|
68
|
+
if command == "run":
|
|
69
|
+
_print(engine.run(args.js, url=args.url, advance_ms=args.advance_ms, read=args.read, timeout_ms=args.timeout_ms))
|
|
70
|
+
return 0
|
|
71
|
+
if command == "cleanup":
|
|
72
|
+
_print(engine.cleanup(scope=args.scope, keep=args.keep))
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
parser.print_help()
|
|
76
|
+
return 1
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
if __name__ == "__main__":
|
|
80
|
+
sys.exit(main())
|
foxfetch/config.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Runtime settings, all overridable by environment variables.
|
|
2
|
+
|
|
3
|
+
Defaults are deliberately tight: the previous plugin kept four 90 MB contexts alive
|
|
4
|
+
for three minutes each, which is a lot of idle RAM for a tool that is used in bursts.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import os
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
APP_NAME = "foxfetch"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _env_int(name: str, default: int, *, low: int, high: int) -> int:
|
|
17
|
+
raw = os.environ.get(name)
|
|
18
|
+
if raw is None or not raw.strip():
|
|
19
|
+
return default
|
|
20
|
+
try:
|
|
21
|
+
value = int(raw.strip())
|
|
22
|
+
except ValueError:
|
|
23
|
+
return default
|
|
24
|
+
return max(low, min(high, value))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def default_home() -> Path:
|
|
28
|
+
"""Artifact root: local app data, never the installed package directory."""
|
|
29
|
+
override = os.environ.get("FOXFETCH_HOME")
|
|
30
|
+
if override:
|
|
31
|
+
return Path(override).expanduser()
|
|
32
|
+
if os.name == "nt":
|
|
33
|
+
base = os.environ.get("LOCALAPPDATA") or os.path.expanduser("~")
|
|
34
|
+
return Path(base) / APP_NAME
|
|
35
|
+
xdg = os.environ.get("XDG_DATA_HOME")
|
|
36
|
+
return (Path(xdg) if xdg else Path.home() / ".local" / "share") / APP_NAME
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass(frozen=True)
|
|
40
|
+
class Settings:
|
|
41
|
+
home: Path = field(default_factory=default_home)
|
|
42
|
+
max_contexts: int = field(default_factory=lambda: _env_int("FOXFETCH_MAX_CONTEXTS", 2, low=1, high=16))
|
|
43
|
+
idle_seconds: int = field(default_factory=lambda: _env_int("FOXFETCH_IDLE_SECONDS", 60, low=5, high=3600))
|
|
44
|
+
default_timeout_ms: int = field(default_factory=lambda: _env_int("FOXFETCH_TIMEOUT_MS", 30_000, low=1_000, high=600_000))
|
|
45
|
+
max_bytes: int = field(default_factory=lambda: _env_int("FOXFETCH_MAX_BYTES", 65_536, low=1_024, high=4 * 1024 * 1024))
|
|
46
|
+
artifact_ttl_seconds: int = field(default_factory=lambda: _env_int("FOXFETCH_ARTIFACT_TTL", 24 * 3600, low=60, high=30 * 24 * 3600))
|
|
47
|
+
artifact_max_bytes: int = field(default_factory=lambda: _env_int("FOXFETCH_ARTIFACT_MAX", 64 * 1024 * 1024, low=1024, high=4 * 1024 * 1024 * 1024))
|
|
48
|
+
# Seconds before a pending artifact starts being mentioned in tool results. 0 disables.
|
|
49
|
+
remind_after_seconds: int = field(default_factory=lambda: _env_int("FOXFETCH_REMIND_AFTER", 600, low=0, high=7 * 24 * 3600))
|
|
50
|
+
|
|
51
|
+
@property
|
|
52
|
+
def artifacts(self) -> Path:
|
|
53
|
+
return self.home / "artifacts"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
SETTINGS = Settings()
|
foxfetch/contexts.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Live ruyijs contexts, keyed by origin.
|
|
2
|
+
|
|
3
|
+
One Firefox world per origin, created on first use and dropped after `idle_seconds`
|
|
4
|
+
of silence or when the pool is over its cap (least recently used first). A slot owns
|
|
5
|
+
its lock: ruyijs contexts are not thread-safe, and MCP may serve calls concurrently.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
import uuid
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from typing import Any
|
|
15
|
+
from urllib.parse import urlsplit
|
|
16
|
+
|
|
17
|
+
from .config import SETTINGS
|
|
18
|
+
from .shapes import failure
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ContextError(Exception):
|
|
22
|
+
"""Anything that should surface as an `env`/`context` failure, not a crash."""
|
|
23
|
+
|
|
24
|
+
def __init__(self, message: str, kind: str = "env") -> None:
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.kind = kind
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Slot:
|
|
31
|
+
context_id: str
|
|
32
|
+
origin: str
|
|
33
|
+
ctx: Any
|
|
34
|
+
lock: threading.RLock = field(default_factory=threading.RLock)
|
|
35
|
+
created: float = field(default_factory=time.time)
|
|
36
|
+
used: float = field(default_factory=time.time)
|
|
37
|
+
url: str | None = None
|
|
38
|
+
|
|
39
|
+
def touch(self) -> None:
|
|
40
|
+
self.used = time.time()
|
|
41
|
+
|
|
42
|
+
def close(self) -> None:
|
|
43
|
+
try:
|
|
44
|
+
self.ctx.close()
|
|
45
|
+
except Exception:
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
def summarize(self) -> dict[str, Any]:
|
|
49
|
+
return {
|
|
50
|
+
"context_id": self.context_id,
|
|
51
|
+
"origin": self.origin,
|
|
52
|
+
"url": self.url,
|
|
53
|
+
"age_s": round(time.time() - self.created, 1),
|
|
54
|
+
"idle_s": round(time.time() - self.used, 1),
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def origin_of(url: str) -> str:
|
|
59
|
+
parts = urlsplit(url)
|
|
60
|
+
if parts.scheme.lower() not in {"http", "https"} or not parts.netloc:
|
|
61
|
+
raise ContextError(f"url must be an absolute http(s) URL, got {url!r}", "nav")
|
|
62
|
+
scheme = parts.scheme.lower()
|
|
63
|
+
return f"{scheme}://{parts.netloc.lower()}"
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ContextPool:
|
|
67
|
+
def __init__(self, max_contexts: int | None = None, idle_seconds: int | None = None) -> None:
|
|
68
|
+
self._slots: dict[str, Slot] = {}
|
|
69
|
+
self._lock = threading.RLock()
|
|
70
|
+
self._max = max_contexts if max_contexts is not None else SETTINGS.max_contexts
|
|
71
|
+
self._idle = idle_seconds if idle_seconds is not None else SETTINGS.idle_seconds
|
|
72
|
+
self._reaper = threading.Thread(target=self._reap_loop, name="foxfetch-reaper", daemon=True)
|
|
73
|
+
self._stop = threading.Event()
|
|
74
|
+
self._reaper.start()
|
|
75
|
+
|
|
76
|
+
# ── lookup ──────────────────────────────────────────────────────────────
|
|
77
|
+
|
|
78
|
+
def get(self, context_id: str | None = None, url: str | None = None) -> Slot:
|
|
79
|
+
"""Find a live slot by id or by the origin of `url`."""
|
|
80
|
+
with self._lock:
|
|
81
|
+
if context_id:
|
|
82
|
+
slot = self._slots.get(context_id)
|
|
83
|
+
if slot is None:
|
|
84
|
+
raise ContextError(f"no live context {context_id!r}; it was closed, idled out, or never opened", "context")
|
|
85
|
+
return slot
|
|
86
|
+
if not url:
|
|
87
|
+
raise ContextError("pass url or context_id: neither was given", "context")
|
|
88
|
+
origin = origin_of(url)
|
|
89
|
+
slot = self._by_origin(origin)
|
|
90
|
+
if slot is None:
|
|
91
|
+
raise ContextError(
|
|
92
|
+
f"no live context for {origin}; pass url again with a call that creates one",
|
|
93
|
+
"context",
|
|
94
|
+
)
|
|
95
|
+
return slot
|
|
96
|
+
|
|
97
|
+
def _by_origin(self, origin: str) -> Slot | None:
|
|
98
|
+
candidates = [s for s in self._slots.values() if s.origin == origin]
|
|
99
|
+
if not candidates:
|
|
100
|
+
return None
|
|
101
|
+
return max(candidates, key=lambda s: s.used)
|
|
102
|
+
|
|
103
|
+
def has_origin(self, url: str) -> bool:
|
|
104
|
+
try:
|
|
105
|
+
origin = origin_of(url)
|
|
106
|
+
except ContextError:
|
|
107
|
+
return False
|
|
108
|
+
with self._lock:
|
|
109
|
+
return self._by_origin(origin) is not None
|
|
110
|
+
|
|
111
|
+
# ── creation ────────────────────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
def open(
|
|
114
|
+
self,
|
|
115
|
+
url: str,
|
|
116
|
+
*,
|
|
117
|
+
proxy: str | None = None,
|
|
118
|
+
fingerprint: dict[str, Any] | None = None,
|
|
119
|
+
http_timeout: float | None = None,
|
|
120
|
+
timeout_s: float = 30.0,
|
|
121
|
+
) -> Slot:
|
|
122
|
+
origin = origin_of(url)
|
|
123
|
+
with self._lock:
|
|
124
|
+
existing = self._by_origin(origin)
|
|
125
|
+
if existing is not None:
|
|
126
|
+
existing.touch()
|
|
127
|
+
return existing
|
|
128
|
+
self._evict_if_full()
|
|
129
|
+
slot = self._spawn(origin, proxy=proxy, fingerprint=fingerprint, http_timeout=http_timeout, timeout_s=timeout_s)
|
|
130
|
+
self._slots[slot.context_id] = slot
|
|
131
|
+
return slot
|
|
132
|
+
|
|
133
|
+
def _spawn(
|
|
134
|
+
self,
|
|
135
|
+
origin: str,
|
|
136
|
+
*,
|
|
137
|
+
proxy: str | None,
|
|
138
|
+
fingerprint: dict[str, Any] | None,
|
|
139
|
+
http_timeout: float | None,
|
|
140
|
+
timeout_s: float,
|
|
141
|
+
) -> Slot:
|
|
142
|
+
try:
|
|
143
|
+
from ruyijs import Context # type: ignore[import-untyped]
|
|
144
|
+
except ImportError as error: # pragma: no cover - depends on the host
|
|
145
|
+
raise ContextError(f"ruyijs is not importable: {error}. Run: pip install -U ruyijs", "env") from error
|
|
146
|
+
|
|
147
|
+
kwargs: dict[str, Any] = {"timeout": float(timeout_s)}
|
|
148
|
+
if proxy:
|
|
149
|
+
kwargs["proxy"] = proxy
|
|
150
|
+
if http_timeout is not None:
|
|
151
|
+
kwargs["http_timeout"] = float(http_timeout)
|
|
152
|
+
try:
|
|
153
|
+
ctx = Context(**kwargs)
|
|
154
|
+
except Exception as error:
|
|
155
|
+
raise ContextError(f"cannot start the Firefox engine: {error}", "env") from error
|
|
156
|
+
if fingerprint:
|
|
157
|
+
try:
|
|
158
|
+
ctx.configure_fingerprint(fingerprint)
|
|
159
|
+
except Exception as error:
|
|
160
|
+
try:
|
|
161
|
+
ctx.close()
|
|
162
|
+
finally:
|
|
163
|
+
raise ContextError(f"fingerprint rejected: {error}", "env") from error
|
|
164
|
+
return Slot(context_id=f"ctx-{uuid.uuid4().hex[:10]}", origin=origin, ctx=ctx)
|
|
165
|
+
|
|
166
|
+
def _evict_if_full(self) -> None:
|
|
167
|
+
if len(self._slots) < self._max:
|
|
168
|
+
return
|
|
169
|
+
victim = min(self._slots.values(), key=lambda s: s.used)
|
|
170
|
+
del self._slots[victim.context_id]
|
|
171
|
+
victim.close()
|
|
172
|
+
|
|
173
|
+
# ── teardown ────────────────────────────────────────────────────────────
|
|
174
|
+
|
|
175
|
+
def close(self, context_id: str) -> bool:
|
|
176
|
+
with self._lock:
|
|
177
|
+
slot = self._slots.pop(context_id, None)
|
|
178
|
+
if slot is None:
|
|
179
|
+
return False
|
|
180
|
+
slot.close()
|
|
181
|
+
return True
|
|
182
|
+
|
|
183
|
+
def close_origin(self, url: str) -> int:
|
|
184
|
+
origin = origin_of(url)
|
|
185
|
+
with self._lock:
|
|
186
|
+
victims = [s for s in self._slots.values() if s.origin == origin]
|
|
187
|
+
for slot in victims:
|
|
188
|
+
del self._slots[slot.context_id]
|
|
189
|
+
for slot in victims:
|
|
190
|
+
slot.close()
|
|
191
|
+
return len(victims)
|
|
192
|
+
|
|
193
|
+
def close_all(self) -> int:
|
|
194
|
+
with self._lock:
|
|
195
|
+
victims = list(self._slots.values())
|
|
196
|
+
self._slots.clear()
|
|
197
|
+
for slot in victims:
|
|
198
|
+
slot.close()
|
|
199
|
+
return len(victims)
|
|
200
|
+
|
|
201
|
+
def inventory(self) -> list[dict[str, Any]]:
|
|
202
|
+
with self._lock:
|
|
203
|
+
return [slot.summarize() for slot in self._slots.values()]
|
|
204
|
+
|
|
205
|
+
# ── idle reaping ────────────────────────────────────────────────────────
|
|
206
|
+
|
|
207
|
+
def _reap_loop(self) -> None:
|
|
208
|
+
interval = max(2.0, min(15.0, self._idle / 4))
|
|
209
|
+
while not self._stop.wait(interval):
|
|
210
|
+
cutoff = time.time() - self._idle
|
|
211
|
+
with self._lock:
|
|
212
|
+
dead = [s for s in self._slots.values() if s.used < cutoff]
|
|
213
|
+
for slot in dead:
|
|
214
|
+
del self._slots[slot.context_id]
|
|
215
|
+
for slot in dead:
|
|
216
|
+
slot.close()
|
|
217
|
+
|
|
218
|
+
def shutdown(self) -> None:
|
|
219
|
+
self._stop.set()
|
|
220
|
+
self.close_all()
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
POOL = ContextPool()
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def as_failure(error: Exception) -> dict[str, Any]:
|
|
227
|
+
"""Map pool/engine exceptions onto the uniform failure payload."""
|
|
228
|
+
if isinstance(error, ContextError):
|
|
229
|
+
return failure(str(error), kind=error.kind)
|
|
230
|
+
name = type(error).__name__
|
|
231
|
+
if name == "JSError":
|
|
232
|
+
return failure(str(getattr(error, "message", error)), kind="js", error_name=getattr(error, "name", None))
|
|
233
|
+
if "timeout" in name.lower() or "deadline" in str(error).lower():
|
|
234
|
+
return failure(f"{name}: {error}", kind="timeout")
|
|
235
|
+
return failure(f"{name}: {error}", kind="internal")
|
foxfetch/doctor.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
"""Environment self-check.
|
|
2
|
+
|
|
3
|
+
Runs at service start and on demand. Every finding carries the command that fixes it,
|
|
4
|
+
because the caller is usually an agent that must not guess.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from .config import SETTINGS
|
|
17
|
+
|
|
18
|
+
MIN_PYTHON = (3, 10)
|
|
19
|
+
MIN_RUYIJS = (0, 4, 5)
|
|
20
|
+
RISKY_RUYIJS = (0, 4, 0) # below this, today's bot checks (DataDome & co.) are not passable
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _version_tuple(text: str) -> tuple[int, ...]:
|
|
24
|
+
parts: list[int] = []
|
|
25
|
+
for chunk in str(text).replace("-", ".").split("."):
|
|
26
|
+
digits = "".join(ch for ch in chunk if ch.isdigit())
|
|
27
|
+
if not digits:
|
|
28
|
+
break
|
|
29
|
+
parts.append(int(digits))
|
|
30
|
+
return tuple(parts)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _package_version(name: str) -> str | None:
|
|
34
|
+
try:
|
|
35
|
+
from importlib.metadata import version
|
|
36
|
+
|
|
37
|
+
return version(name)
|
|
38
|
+
except Exception:
|
|
39
|
+
return None
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def playwright_roots() -> list[Path]:
|
|
43
|
+
roots: list[Path] = []
|
|
44
|
+
explicit = os.environ.get("PLAYWRIGHT_BROWSERS_PATH")
|
|
45
|
+
if explicit:
|
|
46
|
+
roots.append(Path(explicit).expanduser())
|
|
47
|
+
if os.name == "nt":
|
|
48
|
+
local = os.environ.get("LOCALAPPDATA")
|
|
49
|
+
if local:
|
|
50
|
+
roots.append(Path(local) / "ms-playwright")
|
|
51
|
+
else:
|
|
52
|
+
roots.append(Path.home() / ".cache" / "ms-playwright")
|
|
53
|
+
return roots
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def find_browsers() -> dict[str, Any]:
|
|
57
|
+
"""Locate Chromium builds without launching one."""
|
|
58
|
+
found: list[dict[str, str]] = []
|
|
59
|
+
for root in playwright_roots():
|
|
60
|
+
if not root.is_dir():
|
|
61
|
+
continue
|
|
62
|
+
try:
|
|
63
|
+
entries = sorted(p for p in root.iterdir() if p.is_dir())
|
|
64
|
+
except OSError:
|
|
65
|
+
continue
|
|
66
|
+
for entry in entries:
|
|
67
|
+
name = entry.name
|
|
68
|
+
if not name.startswith(("chromium", "chromium_headless_shell")):
|
|
69
|
+
continue
|
|
70
|
+
exe = None
|
|
71
|
+
for candidate in (
|
|
72
|
+
entry / "chrome-headless-shell-win64" / "chrome-headless-shell.exe",
|
|
73
|
+
entry / "chrome-win" / "headless_shell.exe",
|
|
74
|
+
entry / "chrome-win" / "chrome.exe",
|
|
75
|
+
entry / "chrome.exe",
|
|
76
|
+
entry / "chrome-linux" / "headless_shell",
|
|
77
|
+
entry / "chrome-linux" / "chrome",
|
|
78
|
+
):
|
|
79
|
+
if candidate.is_file():
|
|
80
|
+
exe = candidate
|
|
81
|
+
break
|
|
82
|
+
found.append({"build": name, "dir": str(entry), "executable": str(exe) if exe else ""})
|
|
83
|
+
headless = [item for item in found if item["build"].startswith("chromium_headless_shell")]
|
|
84
|
+
picked = (headless or found or [{}])[0]
|
|
85
|
+
return {
|
|
86
|
+
"found": bool(found),
|
|
87
|
+
"builds": found,
|
|
88
|
+
"headless_shell": bool(headless),
|
|
89
|
+
"path": picked.get("executable") or None,
|
|
90
|
+
"roots": [str(p) for p in playwright_roots()],
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def node_global_roots() -> list[Path]:
|
|
95
|
+
"""Where npm puts global packages, without shelling out to `npm root -g`."""
|
|
96
|
+
roots: list[Path] = []
|
|
97
|
+
if os.name == "nt":
|
|
98
|
+
appdata = os.environ.get("APPDATA")
|
|
99
|
+
if appdata:
|
|
100
|
+
roots.append(Path(appdata) / "npm" / "node_modules")
|
|
101
|
+
else:
|
|
102
|
+
roots.extend([Path("/usr/local/lib/node_modules"), Path("/usr/lib/node_modules"), Path.home() / ".npm-global"])
|
|
103
|
+
return roots
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def find_node_playwright() -> dict[str, Any]:
|
|
107
|
+
"""Is the `playwright` npm package installed? Pure filesystem check: no subprocesses.
|
|
108
|
+
|
|
109
|
+
Spawning `node -e` here used to wedge the MCP server when the call arrived on a worker
|
|
110
|
+
thread, so the probe reads package.json instead.
|
|
111
|
+
"""
|
|
112
|
+
node = shutil.which("node")
|
|
113
|
+
candidates: list[Path] = [Path.cwd() / "node_modules" / "playwright", *[root / "playwright" for root in node_global_roots()]]
|
|
114
|
+
for candidate in candidates:
|
|
115
|
+
manifest = candidate / "package.json"
|
|
116
|
+
try:
|
|
117
|
+
if manifest.is_file():
|
|
118
|
+
version = json.loads(manifest.read_text(encoding="utf-8")).get("version")
|
|
119
|
+
return {"found": True, "version": version, "reason": None, "path": str(candidate)}
|
|
120
|
+
except Exception:
|
|
121
|
+
continue
|
|
122
|
+
if not node:
|
|
123
|
+
return {"found": False, "version": None, "reason": "node is not on PATH"}
|
|
124
|
+
return {
|
|
125
|
+
"found": False,
|
|
126
|
+
"version": None,
|
|
127
|
+
"reason": "npm package 'playwright' not found in the local or global node_modules",
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def artifacts_status() -> dict[str, Any]:
|
|
132
|
+
directory = SETTINGS.artifacts
|
|
133
|
+
files = 0
|
|
134
|
+
total = 0
|
|
135
|
+
if directory.is_dir():
|
|
136
|
+
for entry in directory.iterdir():
|
|
137
|
+
try:
|
|
138
|
+
if entry.is_file():
|
|
139
|
+
files += 1
|
|
140
|
+
total += entry.stat().st_size
|
|
141
|
+
except OSError:
|
|
142
|
+
continue
|
|
143
|
+
return {"dir": str(directory), "files": files, "bytes": total, "ttl_s": SETTINGS.artifact_ttl_seconds}
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def doctor() -> dict[str, Any]:
|
|
147
|
+
fixes: list[str] = []
|
|
148
|
+
warnings: list[str] = []
|
|
149
|
+
|
|
150
|
+
python_version = ".".join(str(part) for part in sys.version_info[:3])
|
|
151
|
+
python_ok = sys.version_info[:2] >= MIN_PYTHON
|
|
152
|
+
if not python_ok:
|
|
153
|
+
fixes.append(f"install Python {MIN_PYTHON[0]}.{MIN_PYTHON[1]} or newer (running {python_version})")
|
|
154
|
+
|
|
155
|
+
ruyijs_version = _package_version("ruyijs")
|
|
156
|
+
ruyijs_tuple = _version_tuple(ruyijs_version) if ruyijs_version else ()
|
|
157
|
+
ruyijs_ok = bool(ruyijs_tuple) and ruyijs_tuple[:2] >= MIN_RUYIJS[:2]
|
|
158
|
+
if not ruyijs_version:
|
|
159
|
+
fixes.append("pip install -U 'ruyijs>=0.4.5'")
|
|
160
|
+
elif ruyijs_tuple and ruyijs_tuple < RISKY_RUYIJS:
|
|
161
|
+
warnings.append(
|
|
162
|
+
f"ruyijs {ruyijs_version} is older than 0.4.0: the Firefox engine, TLS profile and the "
|
|
163
|
+
"DataDome/Kasada fixes landed in 0.4.x. Run: pip install -U ruyijs"
|
|
164
|
+
)
|
|
165
|
+
elif ruyijs_tuple and ruyijs_tuple < MIN_RUYIJS:
|
|
166
|
+
warnings.append(f"ruyijs {ruyijs_version} predates {'.'.join(map(str, MIN_RUYIJS))}; run: pip install -U ruyijs")
|
|
167
|
+
|
|
168
|
+
mcp_version = _package_version("mcp")
|
|
169
|
+
mcp_tuple = _version_tuple(mcp_version) if mcp_version else ()
|
|
170
|
+
mcp_ok = bool(mcp_tuple) and 1 <= mcp_tuple[0] < 2
|
|
171
|
+
if not mcp_version:
|
|
172
|
+
fixes.append("pip install 'mcp>=1.30,<2'")
|
|
173
|
+
elif mcp_tuple and mcp_tuple[0] >= 2:
|
|
174
|
+
fixes.append("mcp 2.x renamed FastMCP -> MCPServer; pin 'mcp>=1.30,<2' for this server")
|
|
175
|
+
|
|
176
|
+
browsers = find_browsers()
|
|
177
|
+
node_playwright = find_node_playwright()
|
|
178
|
+
if not browsers["found"]:
|
|
179
|
+
warnings.append("no Playwright Chromium found: handoff still exports cookies, but cannot write a screenshot script")
|
|
180
|
+
fixes.append("npx playwright install chromium")
|
|
181
|
+
elif not node_playwright["found"]:
|
|
182
|
+
warnings.append(
|
|
183
|
+
"Chromium builds exist but node cannot require('playwright'): write the screenshot script with "
|
|
184
|
+
"PLAYWRIGHT_PATH pointing at the package"
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
payload = {
|
|
188
|
+
"ok": python_ok and ruyijs_ok and mcp_ok,
|
|
189
|
+
"python": {"version": python_version, "ok": python_ok},
|
|
190
|
+
"ruyijs": {"version": ruyijs_version, "ok": ruyijs_ok, "min": ".".join(map(str, MIN_RUYIJS))},
|
|
191
|
+
"mcp": {"version": mcp_version, "ok": mcp_ok, "constraint": ">=1.30,<2"},
|
|
192
|
+
"chromium": browsers,
|
|
193
|
+
"node_playwright": node_playwright,
|
|
194
|
+
"artifacts": artifacts_status(),
|
|
195
|
+
"settings": {
|
|
196
|
+
"home": str(SETTINGS.home),
|
|
197
|
+
"max_contexts": SETTINGS.max_contexts,
|
|
198
|
+
"idle_seconds": SETTINGS.idle_seconds,
|
|
199
|
+
"timeout_ms": SETTINGS.default_timeout_ms,
|
|
200
|
+
"max_bytes": SETTINGS.max_bytes,
|
|
201
|
+
},
|
|
202
|
+
"warnings": warnings,
|
|
203
|
+
"fixes": fixes,
|
|
204
|
+
"error": None,
|
|
205
|
+
"error_kind": None,
|
|
206
|
+
}
|
|
207
|
+
return payload
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def main() -> int:
|
|
211
|
+
report = doctor()
|
|
212
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
213
|
+
return 0 if report["ok"] else 1
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
if __name__ == "__main__":
|
|
217
|
+
raise SystemExit(main())
|