prism-search 0.2.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.
Files changed (48) hide show
  1. prism_search/__init__.py +26 -0
  2. prism_search/_pdf_worker.py +43 -0
  3. prism_search/browser.py +425 -0
  4. prism_search/cli.py +1095 -0
  5. prism_search/contracts.py +286 -0
  6. prism_search/egress.py +268 -0
  7. prism_search/embedder.py +417 -0
  8. prism_search/evidence.py +145 -0
  9. prism_search/fetcher.py +1527 -0
  10. prism_search/pipelines/__init__.py +1 -0
  11. prism_search/pipelines/frontier.py +1548 -0
  12. prism_search/pipelines/similar.py +495 -0
  13. prism_search/pipelines/verify.py +1450 -0
  14. prism_search/providers/__init__.py +115 -0
  15. prism_search/providers/_endpoint.py +130 -0
  16. prism_search/providers/base.py +278 -0
  17. prism_search/providers/bing.py +269 -0
  18. prism_search/providers/bing_news.py +213 -0
  19. prism_search/providers/community.py +213 -0
  20. prism_search/providers/ddg.py +63 -0
  21. prism_search/providers/gnews.py +208 -0
  22. prism_search/providers/naver.py +537 -0
  23. prism_search/providers/registry.py +349 -0
  24. prism_search/providers/research.py +367 -0
  25. prism_search/providers/searxng.py +73 -0
  26. prism_search/providers/wikidata.py +185 -0
  27. prism_search/providers/wikipedia.py +437 -0
  28. prism_search/providers/yahoo_jp.py +182 -0
  29. prism_search/regions/eu.yaml +49 -0
  30. prism_search/regions/global.yaml +45 -0
  31. prism_search/regions/jp.yaml +51 -0
  32. prism_search/regions/kr.yaml +61 -0
  33. prism_search/regions/us.yaml +47 -0
  34. prism_search/regions.py +109 -0
  35. prism_search/sdk.py +188 -0
  36. prism_search/security.py +547 -0
  37. prism_search/server.py +212 -0
  38. prism_search/signals.py +1026 -0
  39. prism_search/skill/SKILL.md +93 -0
  40. prism_search/skill_install.py +97 -0
  41. prism_search/store.py +1085 -0
  42. prism_search/temporal.py +1194 -0
  43. prism_search/tools.py +256 -0
  44. prism_search-0.2.0.dist-info/METADATA +70 -0
  45. prism_search-0.2.0.dist-info/RECORD +48 -0
  46. prism_search-0.2.0.dist-info/WHEEL +4 -0
  47. prism_search-0.2.0.dist-info/entry_points.txt +3 -0
  48. prism_search-0.2.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,26 @@
1
+ """Prism Search — Zero-API-key Adaptive Progressive Frontier web search."""
2
+
3
+ from typing import Any
4
+
5
+ __all__ = [
6
+ "CLIENT_USER_AGENT",
7
+ "PROJECT_URL",
8
+ "PrismClient",
9
+ "__version__",
10
+ "extract",
11
+ "search",
12
+ "verify",
13
+ ]
14
+ __version__ = "0.2.0"
15
+
16
+ # Public APIs such as Wikimedia reject automated clients without contact information.
17
+ PROJECT_URL = "https://github.com/tenderloinsteak/prism-search"
18
+ CLIENT_USER_AGENT = f"prism-search/{__version__} ({PROJECT_URL})"
19
+
20
+
21
+ def __getattr__(name: str) -> Any:
22
+ if name in {"PrismClient", "extract", "search", "verify"}:
23
+ from prism_search import sdk
24
+
25
+ return getattr(sdk, name)
26
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,43 @@
1
+ """Subprocess worker for bounded, killable PDF text extraction."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import sys
7
+
8
+ from prism_search.contracts import ErrorCode, PrismError
9
+ from prism_search.fetcher import extract_pdf_raw
10
+ from prism_search.security import MAX_RESPONSE_BYTES
11
+
12
+
13
+ def main() -> int:
14
+ data = sys.stdin.buffer.read(MAX_RESPONSE_BYTES + 1)
15
+ if len(data) > MAX_RESPONSE_BYTES:
16
+ payload: dict[str, object] = {
17
+ "ok": False,
18
+ "code": ErrorCode.UPSTREAM_BROKEN.value,
19
+ "message": "PDF exceeds size limit",
20
+ }
21
+ else:
22
+ try:
23
+ payload = {"ok": True, "data": extract_pdf_raw(data)}
24
+ except PrismError as exc:
25
+ payload = {
26
+ "ok": False,
27
+ "code": exc.code.value,
28
+ "message": exc.message,
29
+ "hint": exc.hint,
30
+ }
31
+ except Exception: # noqa: BLE001
32
+ payload = {
33
+ "ok": False,
34
+ "code": ErrorCode.UPSTREAM_BROKEN.value,
35
+ "message": "Could not parse PDF",
36
+ }
37
+ sys.stdout.buffer.write(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
38
+ sys.stdout.buffer.flush()
39
+ return 0
40
+
41
+
42
+ if __name__ == "__main__":
43
+ raise SystemExit(main())
@@ -0,0 +1,425 @@
1
+ """Optional local headless browser fallback (system Chrome/Chromium or Playwright extra)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import datetime as dt
8
+ import os
9
+ import shutil
10
+ import sys
11
+ import tempfile
12
+ import time
13
+ from importlib.util import find_spec
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from prism_search.contracts import ErrorCode, FetchedDocument, PrismError
18
+ from prism_search.egress import BLOCK_MARKER, EgressGuardProxy
19
+ from prism_search.fetcher import parse_html_to_document
20
+ from prism_search.regions import RegionPack
21
+ from prism_search.security import (
22
+ MAX_REDIRECTS,
23
+ MAX_RESPONSE_BYTES,
24
+ public_destination,
25
+ scrub_url_credentials,
26
+ validate_public_url,
27
+ )
28
+
29
+ _MAC_BROWSER_PATHS = (
30
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
31
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
32
+ "/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",
33
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
34
+ )
35
+
36
+ _PATH_BROWSER_NAMES = (
37
+ "google-chrome",
38
+ "google-chrome-stable",
39
+ "chromium",
40
+ "chromium-browser",
41
+ "brave-browser",
42
+ "msedge",
43
+ "microsoft-edge",
44
+ )
45
+
46
+ _WINDOWS_BROWSER_PATHS = (
47
+ r"C:\Program Files\Google\Chrome\Application\chrome.exe",
48
+ r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
49
+ r"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe",
50
+ r"C:\Program Files\Microsoft\Edge\Application\msedge.exe",
51
+ r"C:\Program Files\BraveSoftware\Brave-Browser\Application\brave.exe",
52
+ )
53
+
54
+
55
+ def find_system_browser() -> str | None:
56
+ """Return an executable system Chromium-family browser path if installed locally."""
57
+ env_path = os.environ.get("PRISM_BROWSER_PATH", "").strip()
58
+ if env_path:
59
+ candidate = Path(env_path).expanduser()
60
+ if candidate.is_file() and os.access(candidate, os.X_OK):
61
+ return str(candidate)
62
+
63
+ if sys.platform == "darwin":
64
+ for raw in _MAC_BROWSER_PATHS:
65
+ p = Path(raw)
66
+ if p.is_file() and os.access(p, os.X_OK):
67
+ return str(p)
68
+
69
+ for name in _PATH_BROWSER_NAMES:
70
+ found = shutil.which(name)
71
+ if found:
72
+ return found
73
+
74
+ if sys.platform.startswith("win"):
75
+ for raw in _WINDOWS_BROWSER_PATHS:
76
+ p = Path(raw)
77
+ if p.is_file():
78
+ return str(p)
79
+
80
+ return None
81
+
82
+
83
+ def detect_browser_backend() -> dict[str, Any]:
84
+ """Inspect available local JS rendering backends without importing Playwright."""
85
+ pw_installed = find_spec("playwright") is not None
86
+ browser_path = find_system_browser()
87
+ backend = "playwright" if pw_installed else ("system_chrome" if browser_path else None)
88
+ return {
89
+ "available": backend is not None,
90
+ "backend": backend,
91
+ "playwright_installed": pw_installed,
92
+ "browser_path": browser_path,
93
+ }
94
+
95
+
96
+ async def _render_via_playwright(
97
+ clean_url: str, *, timeout_s: float, resolve_dns: bool, proxy_url: str
98
+ ) -> tuple[str, str]:
99
+ from playwright.async_api import Error as PlaywrightError
100
+ from playwright.async_api import async_playwright
101
+
102
+ deadline = time.monotonic() + timeout_s
103
+ redirect_exceeded = False
104
+ nav_redirects = 0
105
+ async with async_playwright() as pw:
106
+ launch_args = [*_EGRESS_ARGS]
107
+ if os.environ.get("PRISM_BROWSER_NO_SANDBOX") == "1":
108
+ launch_args.append("--no-sandbox")
109
+ browser = await pw.chromium.launch(
110
+ headless=True, args=launch_args, proxy={"server": proxy_url, "bypass": "<-loopback>"}
111
+ )
112
+ try:
113
+ context = await browser.new_context(ignore_https_errors=False)
114
+ page = await context.new_page()
115
+
116
+ def on_response(resp) -> None:
117
+ nonlocal nav_redirects, redirect_exceeded
118
+ if (
119
+ resp.status in {301, 302, 303, 307, 308}
120
+ and resp.request.is_navigation_request()
121
+ ):
122
+ nav_redirects += 1
123
+ if nav_redirects > MAX_REDIRECTS:
124
+ redirect_exceeded = True
125
+
126
+ page.on("response", on_response)
127
+
128
+ async def handle_route(route) -> None:
129
+ nonlocal redirect_exceeded
130
+ req = route.request
131
+ if req.resource_type in {"image", "media", "font"}:
132
+ await route.abort()
133
+ return
134
+ hops = 0
135
+ prev = req.redirected_from
136
+ while prev is not None:
137
+ hops += 1
138
+ prev = prev.redirected_from
139
+ if hops > MAX_REDIRECTS or nav_redirects > MAX_REDIRECTS:
140
+ redirect_exceeded = True
141
+ await route.abort()
142
+ return
143
+ try:
144
+ await asyncio.to_thread(validate_public_url, req.url, resolve_dns=resolve_dns)
145
+ except PrismError:
146
+ await route.abort()
147
+ return
148
+ await route.continue_()
149
+
150
+ await page.route("**/*", handle_route)
151
+ nav_ms = max(1000, int((deadline - time.monotonic()) * 1000))
152
+ try:
153
+ await page.goto(clean_url, wait_until="domcontentloaded", timeout=nav_ms)
154
+ except PlaywrightError:
155
+ if redirect_exceeded:
156
+ raise PrismError(
157
+ ErrorCode.UPSTREAM_BROKEN,
158
+ f"Exceeded maximum redirects ({MAX_REDIRECTS})",
159
+ final_url=clean_url,
160
+ ) from None
161
+ raise
162
+ if redirect_exceeded:
163
+ raise PrismError(
164
+ ErrorCode.UPSTREAM_BROKEN,
165
+ f"Exceeded maximum redirects ({MAX_REDIRECTS})",
166
+ final_url=clean_url,
167
+ )
168
+ remaining = deadline - time.monotonic()
169
+ if remaining > 0.5:
170
+ with contextlib.suppress(PlaywrightError, TimeoutError):
171
+ await page.wait_for_load_state(
172
+ "networkidle", timeout=int(min(3.0, remaining) * 1000)
173
+ )
174
+ final_url = await asyncio.to_thread(
175
+ validate_public_url, page.url, resolve_dns=resolve_dns
176
+ )
177
+ html = await page.content()
178
+ finally:
179
+ await browser.close()
180
+
181
+ if len(html.encode("utf-8", errors="ignore")) > MAX_RESPONSE_BYTES:
182
+ raise PrismError(
183
+ ErrorCode.UPSTREAM_BROKEN,
184
+ "Rendered page exceeds the size limit",
185
+ final_url=scrub_url_credentials(final_url),
186
+ )
187
+ return scrub_url_credentials(final_url), html
188
+
189
+
190
+ # Send all browser traffic, loopback included, through the egress guard and keep WebRTC UDP
191
+ # from reaching the network outside it.
192
+ _EGRESS_ARGS = (
193
+ "--proxy-bypass-list=<-loopback>",
194
+ "--force-webrtc-ip-handling-policy=disable_non_proxied_udp",
195
+ "--disable-quic",
196
+ )
197
+
198
+
199
+ async def _render_via_system_chrome(
200
+ binary: str, clean_url: str, *, timeout_s: float, proxy_url: str
201
+ ) -> tuple[str, str]:
202
+ profile_dir = tempfile.TemporaryDirectory(prefix="prism-render-")
203
+ try:
204
+ return await _run_system_chrome(
205
+ binary, clean_url, timeout_s=timeout_s, proxy_url=proxy_url, profile=profile_dir.name
206
+ )
207
+ finally:
208
+ with contextlib.suppress(OSError):
209
+ profile_dir.cleanup()
210
+
211
+
212
+ async def _run_system_chrome(
213
+ binary: str, clean_url: str, *, timeout_s: float, proxy_url: str, profile: str
214
+ ) -> tuple[str, str]:
215
+ """Run headless Chromium ``--dump-dom`` through the egress proxy.
216
+
217
+ Note: ``--dump-dom`` cannot report redirected paths inside TLS (``CONNECT``) tunnels.
218
+ ``render="auto"`` pre-resolves HTTP/HTTPS redirects in ``fetch_safe_document`` first, and the
219
+ optional Playwright backend reports all HTTPS/JS ``final_url`` values directly.
220
+ """
221
+ args = [
222
+ binary,
223
+ f"--proxy-server={proxy_url}",
224
+ *_EGRESS_ARGS,
225
+ f"--user-data-dir={profile}",
226
+ "--headless=new",
227
+ "--disable-gpu",
228
+ "--no-first-run",
229
+ "--no-default-browser-check",
230
+ "--disable-extensions",
231
+ "--disable-background-networking",
232
+ "--disable-sync",
233
+ "--virtual-time-budget=5000",
234
+ "--dump-dom",
235
+ ]
236
+ if os.environ.get("PRISM_BROWSER_NO_SANDBOX") == "1":
237
+ args.append("--no-sandbox")
238
+ args.extend(["--", clean_url])
239
+
240
+ proc = await asyncio.create_subprocess_exec(
241
+ *args,
242
+ stdin=asyncio.subprocess.DEVNULL,
243
+ stdout=asyncio.subprocess.PIPE,
244
+ stderr=asyncio.subprocess.DEVNULL,
245
+ )
246
+ try:
247
+ if getattr(proc, "stdout", None) is not None:
248
+ deadline = time.monotonic() + timeout_s
249
+ stdout_buf = bytearray()
250
+
251
+ async def _read_bounded() -> bytes:
252
+ while chunk := await proc.stdout.read(65536):
253
+ if len(stdout_buf) + len(chunk) > MAX_RESPONSE_BYTES:
254
+ with contextlib.suppress(ProcessLookupError):
255
+ proc.kill()
256
+ await proc.wait()
257
+ raise PrismError(
258
+ ErrorCode.UPSTREAM_BROKEN,
259
+ "Rendered page exceeds the streaming byte limit",
260
+ final_url=clean_url,
261
+ )
262
+ stdout_buf.extend(chunk)
263
+ remaining = max(0.1, deadline - time.monotonic())
264
+ await asyncio.wait_for(proc.wait(), timeout=remaining)
265
+ return bytes(stdout_buf)
266
+
267
+ stdout = await asyncio.wait_for(_read_bounded(), timeout=timeout_s)
268
+ else:
269
+ stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout_s)
270
+ except TimeoutError as exc:
271
+ with contextlib.suppress(ProcessLookupError):
272
+ proc.kill()
273
+ await proc.wait()
274
+ raise PrismError(
275
+ ErrorCode.TIMEOUT,
276
+ f"Headless browser timed out for {clean_url}",
277
+ final_url=clean_url,
278
+ ) from exc
279
+ except BaseException:
280
+ if proc.returncode is None:
281
+ with contextlib.suppress(ProcessLookupError):
282
+ proc.kill()
283
+ await proc.wait()
284
+ raise
285
+
286
+ if len(stdout) > MAX_RESPONSE_BYTES:
287
+ raise PrismError(
288
+ ErrorCode.UPSTREAM_BROKEN,
289
+ "Rendered page exceeds the streaming byte limit",
290
+ final_url=clean_url,
291
+ )
292
+ html = stdout.decode("utf-8", errors="replace")
293
+ if proc.returncode != 0 or len(html.strip()) < 32:
294
+ raise PrismError(
295
+ ErrorCode.JS_REQUIRED,
296
+ f"Headless browser failed to render {clean_url}",
297
+ hint="Open this URL in an interactive browser if the answer depends on it.",
298
+ final_url=clean_url,
299
+ )
300
+ return clean_url, html
301
+
302
+
303
+ async def render_url_html(
304
+ url: str,
305
+ *,
306
+ timeout_s: float = 12.0,
307
+ resolve_dns: bool = True,
308
+ ) -> tuple[str, str]:
309
+ """Validate a public URL (SSRF check) and render its DOM using an available local browser.
310
+
311
+ Every request the browser makes goes through ``EgressGuardProxy``. A render that asked for
312
+ a private or non-public destination is refused as a whole, so redirects and scripts cannot
313
+ turn a public page into a view of localhost, the intranet or cloud metadata.
314
+ """
315
+ clean_url, _ = await asyncio.to_thread(public_destination, url, resolve_dns=resolve_dns)
316
+ info = detect_browser_backend()
317
+ if not info["backend"]:
318
+ raise PrismError(
319
+ ErrorCode.JS_REQUIRED,
320
+ "No local browser backend available for JS rendering",
321
+ hint="Install Google Chrome/Chromium, or install the browser extra: "
322
+ "uv pip install 'prism-search[browser]' && playwright install chromium.",
323
+ final_url=clean_url,
324
+ )
325
+
326
+ async with EgressGuardProxy(resolve_dns=resolve_dns) as proxy:
327
+ try:
328
+ final_url, html = await _render_with_backend(
329
+ info, clean_url, timeout_s=timeout_s, resolve_dns=resolve_dns, proxy_url=proxy.url
330
+ )
331
+ except PrismError:
332
+ if proxy.blocked:
333
+ raise PrismError(
334
+ ErrorCode.SSRF_BLOCKED,
335
+ f"Rendering {clean_url} requested a private or non-public destination",
336
+ hint="The page redirected or sent requests to a blocked address; "
337
+ "the render was refused.",
338
+ final_url=clean_url,
339
+ ) from None
340
+ if proxy.redirect_limit_exceeded:
341
+ raise PrismError(
342
+ ErrorCode.UPSTREAM_BROKEN,
343
+ f"Exceeded maximum redirects ({MAX_REDIRECTS})",
344
+ final_url=clean_url,
345
+ ) from None
346
+ raise
347
+ blocked = list(proxy.blocked)
348
+ redirect_exceeded = proxy.redirect_limit_exceeded
349
+ last_http_doc = proxy.last_http_document_url
350
+
351
+ if blocked or BLOCK_MARKER in html:
352
+ raise PrismError(
353
+ ErrorCode.SSRF_BLOCKED,
354
+ f"Rendering {clean_url} requested a private or non-public destination",
355
+ hint="The page redirected or sent requests to a blocked address; the render was refused.",
356
+ final_url=clean_url,
357
+ )
358
+ if redirect_exceeded:
359
+ raise PrismError(
360
+ ErrorCode.UPSTREAM_BROKEN,
361
+ f"Exceeded maximum redirects ({MAX_REDIRECTS})",
362
+ final_url=clean_url,
363
+ )
364
+ if final_url == clean_url and last_http_doc:
365
+ final_url = last_http_doc
366
+ return final_url, html
367
+
368
+
369
+ async def _render_with_backend(
370
+ info: dict[str, Any], clean_url: str, *, timeout_s: float, resolve_dns: bool, proxy_url: str
371
+ ) -> tuple[str, str]:
372
+ if info["backend"] == "playwright":
373
+ try:
374
+ return await _render_via_playwright(
375
+ clean_url, timeout_s=timeout_s, resolve_dns=resolve_dns, proxy_url=proxy_url
376
+ )
377
+ except PrismError:
378
+ raise
379
+ except Exception as exc: # noqa: BLE001
380
+ # If playwright package exists without chromium binary installed, try system Chrome.
381
+ if info["browser_path"]:
382
+ return await _render_via_system_chrome(
383
+ info["browser_path"], clean_url, timeout_s=timeout_s, proxy_url=proxy_url
384
+ )
385
+ raise PrismError(
386
+ ErrorCode.JS_REQUIRED,
387
+ f"Playwright failed to render {clean_url}: {type(exc).__name__}",
388
+ hint="Run `playwright install chromium` or install Google Chrome/Chromium.",
389
+ final_url=clean_url,
390
+ ) from exc
391
+ return await _render_via_system_chrome(
392
+ info["browser_path"], clean_url, timeout_s=timeout_s, proxy_url=proxy_url
393
+ )
394
+
395
+
396
+ async def render_safe_document(
397
+ url: str,
398
+ *,
399
+ region: RegionPack,
400
+ timeout_s: float = 12.0,
401
+ freshness_days: int | None = None,
402
+ published_hint: str | None = None,
403
+ resolve_dns: bool = True,
404
+ ) -> FetchedDocument:
405
+ """Render a JS-heavy public URL via local browser and parse into FetchedDocument."""
406
+ rewritten = scrub_url_credentials(region.rewrite_url(url))
407
+ final_url, html = await render_url_html(rewritten, timeout_s=timeout_s, resolve_dns=resolve_dns)
408
+ today = dt.date.fromisoformat(region.now_context().iso_date)
409
+ parse = asyncio.create_task(
410
+ asyncio.to_thread(
411
+ parse_html_to_document,
412
+ url=url,
413
+ final_url=final_url,
414
+ html=html,
415
+ region=region,
416
+ today=today,
417
+ freshness_days=freshness_days,
418
+ published_hint=published_hint,
419
+ )
420
+ )
421
+ try:
422
+ return await asyncio.shield(parse)
423
+ except asyncio.CancelledError:
424
+ await asyncio.gather(parse, return_exceptions=True)
425
+ raise