@simplexai/localmodels-linux-x64 0.1.0-dev.44 → 0.1.0-dev.45

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 (64) hide show
  1. package/bootstrap.identity +1 -1
  2. package/bootstrap.sha256 +59 -63
  3. package/modules/localmodels/__init__.py +1 -1
  4. package/modules/localmodels/__main__.py +0 -1
  5. package/modules/localmodels/bifrost_checks.py +3 -127
  6. package/modules/localmodels/bifrost_clients.py +1 -1
  7. package/modules/localmodels/bifrost_config.py +2 -2
  8. package/modules/localmodels/bifrost_pi.py +1 -1
  9. package/modules/localmodels/budget.py +16 -1
  10. package/modules/localmodels/catalog.json +15 -50
  11. package/modules/localmodels/catalog_recipes.py +1 -1
  12. package/modules/localmodels/engines-strata-poly-0.1.45-poly.9.json +41 -1
  13. package/modules/localmodels/gateway.py +50 -15
  14. package/modules/localmodels/gateway_accept.py +8 -5
  15. package/modules/localmodels/gateway_bifrost.py +13 -12
  16. package/modules/localmodels/gateway_cli.py +5 -2
  17. package/modules/localmodels/gateway_requests.py +9 -2
  18. package/modules/localmodels/harness.py +38 -11
  19. package/modules/localmodels/harness_gateway.py +1 -1
  20. package/modules/localmodels/hosts.py +7 -20
  21. package/modules/localmodels/library_gateway.py +12 -9
  22. package/modules/localmodels/library_pricing.py +1 -5
  23. package/modules/localmodels/npm_transport.py +62 -54
  24. package/modules/localmodels/recommend.py +1 -1
  25. package/modules/localmodels/recommend_cli.py +2 -2
  26. package/modules/localmodels/remote_ops.py +14 -6
  27. package/modules/localmodels/remote_ops_download.py +1 -1
  28. package/modules/localmodels/remote_ops_verify.py +0 -33
  29. package/modules/localmodels/runtime_install.py +2 -1
  30. package/modules/localmodels/runtime_io.py +149 -34
  31. package/modules/localmodels/source_byok.py +6 -3
  32. package/modules/localmodels/source_cli.py +8 -1
  33. package/modules/localmodels/stack.py +1 -5
  34. package/modules/localmodels/stack_args.py +6 -8
  35. package/modules/localmodels/stack_binding.py +3 -3
  36. package/modules/localmodels/stack_compose.py +3 -8
  37. package/modules/localmodels/stack_events.py +2 -1
  38. package/modules/localmodels/stack_plan.py +1 -4
  39. package/modules/localmodels/stack_ports.py +0 -1
  40. package/modules/localmodels/stack_run.py +15 -30
  41. package/modules/localmodels/stack_suite.py +23 -46
  42. package/modules/localmodels/stack_summary.py +0 -1
  43. package/modules/localmodels/stack_try.py +3 -92
  44. package/modules/localmodels/stack_up.py +7 -3
  45. package/modules/localmodels/stack_update.py +5 -5
  46. package/modules/localmodels/stack_view_apply.py +1 -1
  47. package/modules/localmodels/stack_view_sandbox.py +0 -2
  48. package/modules/localmodels/stack_view_text.py +0 -1
  49. package/modules/localmodels/stack_view_words.py +0 -1
  50. package/modules/localmodels/suite.py +4 -7
  51. package/modules/localmodels/tui_dialogs.py +0 -1
  52. package/modules/localmodels/web/view/view.css +0 -3
  53. package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/METADATA +1 -1
  54. package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/RECORD +56 -60
  55. package/package.json +1 -1
  56. package/tool.json +1 -1
  57. package/modules/localmodels/bifrost_search.py +0 -66
  58. package/modules/localmodels/gateway_search.py +0 -223
  59. package/modules/localmodels/search-ddgs-9.16.1.txt +0 -222
  60. package/modules/localmodels/search_server.py +0 -474
  61. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/WHEEL +0 -0
  62. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/entry_points.txt +0 -0
  63. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/NOTICE +0 -0
  64. /package/modules/{simplex_localmodels-0.1.0.dev44.dist-info → simplex_localmodels-0.1.0.dev45.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
@@ -1,474 +0,0 @@
1
- """Free web search for either gateway, on loopback, answered through ddgs.
2
-
3
- Copied beside a search deployment and run by its service in the hash-locked venv the stack builds
4
- (ddgs, primp, lxml; see the recipe's requirements file). Two doors open on the same search:
5
-
6
- - Magpie's ``searxng`` search API sends ``GET {url}/search?q=<query>&format=json`` and reads
7
- ``{"results": [{"title", "url", "content"}]}``.
8
- - Bifrost connects to ``POST {url}/mcp`` as an MCP client (streamable HTTP, answered as plain
9
- JSON) and injects the ``search`` tool into the local LLM's requests as ``web_search``. When no
10
- engine finds anything, this door asks You.com's free MCP profile (``--you``), as Magpie asks
11
- its own You.com search API after this service's 502.
12
-
13
- Either way a client's web search (Codex ``web_search``, Claude Code ``WebSearch``, pi) reaches
14
- DuckDuckGo first and the other engines in ``--engines`` when it gives too few results. ddgs sends
15
- the requests with a browser TLS fingerprint (primp): plain HTTP clients get DuckDuckGo's anti-bot
16
- page from lab-12021 (2026-10-31). No engine, You.com included, needs a key, so the service holds
17
- no secret and listens on loopback only.
18
-
19
- Logs carry status, result count and latency, never the query. ddgs is imported at start-up, so
20
- the module itself needs only the standard library.
21
- """
22
-
23
- from __future__ import annotations
24
-
25
- import argparse
26
- import importlib
27
- import json
28
- import logging
29
- import threading
30
- import time
31
- import urllib.error
32
- import urllib.parse
33
- import urllib.request
34
- from collections.abc import Callable
35
- from email.message import Message
36
- from http import HTTPStatus
37
- from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
38
- from io import BufferedIOBase
39
- from typing import Any, Protocol, TypedDict, cast
40
-
41
- # DuckDuckGo first, always; Bing last. From home-m6's network (Apple M6, 2026-11-17, ddgs 9.16.1,
42
- # 10 queries each) DuckDuckGo, Brave and Mojeek answered none and Yahoo half (anti-bot pages read
43
- # as no results), so a stack apply's search checks failed about one apply in four; Bing answered
44
- # 7 of 10 at about 12 s. Asked only after every other engine found nothing.
45
- ENGINES = "duckduckgo,yahoo,brave,mojeek,bing"
46
- MAX_QUERY_CHARS = 512
47
- MAX_RESULTS = 10
48
- REST_S = 120.0
49
- MCP_PATH = "/mcp"
50
- MCP_PROTOCOL = "2025-06-18" # answered when the client names no version
51
- MAX_MCP_BODY = 64 << 10
52
- LOCAL_HOSTS = ("127.0.0.1", "localhost", "::1")
53
- # You.com's free MCP profile: its you-search tool, no key, 100 searches a day (You.com developer
54
- # guide, checked 2026-11-04).
55
- YOU_MCP = "https://api.you.com/mcp?profile=free"
56
- YOU_TOOL = "you-search"
57
- YOU_AGENT = "localmodels-search/1" # You.com counts keyless traffic by user agent
58
- MAX_YOU_BODY = 4 << 20
59
- # Why a search brought nothing back, as the model reads it. ddgs reads an engine's 429 or anti-bot
60
- # page as no results, so only You.com's answer tells a rate limit from an empty search.
61
- NO_RESULTS = "SEARCH_NO_RESULTS"
62
- RATE_LIMITED = "SEARCH_RATE_LIMITED"
63
- UNANSWERED = "SEARCH_UNAVAILABLE"
64
- NO_ANSWER_TEXT = {
65
- NO_RESULTS: "the web search found nothing for this query; try other words",
66
- RATE_LIMITED: "the search engines are rate-limiting this machine (You.com gives 100 free"
67
- " searches a day); try again later",
68
- UNANSWERED: "no search engine answered: they may be rate-limiting this machine or be out of"
69
- " reach; try again in a few minutes",
70
- }
71
- SEARCH_TOOL: dict[str, Any] = {
72
- "name": "search",
73
- "description": (
74
- "Search the web. Returns up to 10 results, each with its title, URL and a snippet. "
75
- "Cite the URLs you use."
76
- ),
77
- "inputSchema": {
78
- "type": "object",
79
- "properties": {"query": {"type": "string", "description": "What to search the web for"}},
80
- "required": ["query"],
81
- },
82
- }
83
-
84
- log = logging.getLogger("search")
85
-
86
-
87
- class Result(TypedDict):
88
- title: str
89
- url: str
90
- content: str
91
-
92
-
93
- class Searcher(Protocol):
94
- def search(self, query: str, count: int) -> tuple[str, list[Result]]: ...
95
-
96
-
97
- class NoAnswerError(RuntimeError):
98
- """Every engine failed or found nothing; ``reason`` is one of ``NO_ANSWER_TEXT`` and
99
- ``detail`` what the engine said, for the model."""
100
-
101
- def __init__(self, reason: str = UNANSWERED, detail: str = "") -> None:
102
- super().__init__(reason)
103
- self.reason = reason
104
- self.detail = detail
105
-
106
-
107
- class Ddgs:
108
- """ddgs text search, one engine at a time in ``engines`` order: the first that finds anything
109
- answers. ddgs's own comma-list backend stops waiting at the first engine that raises and drops
110
- a slower one's results (9.16.1, lab-12021 2026-10-31), so the order is kept here. An engine
111
- that failed rests for ``rest_s`` (an anti-bot page or 429 lasts minutes, and asking again
112
- prolongs it); when all rest, all are asked. ``concurrency`` searches run at once."""
113
-
114
- def __init__(
115
- self,
116
- engines: list[str],
117
- timeout: int,
118
- concurrency: int,
119
- rest_s: float,
120
- clock: Callable[[], float] = time.monotonic,
121
- ) -> None:
122
- self._ddgs: Any = importlib.import_module("ddgs")
123
- self._provider_error = cast(
124
- "type[Exception]", importlib.import_module("ddgs.exceptions").DDGSException
125
- )
126
- self._clock = clock
127
- self._engines = engines
128
- self._timeout = timeout
129
- self._rest_s = rest_s
130
- self._resting: dict[str, float] = {}
131
- self._gate = threading.BoundedSemaphore(concurrency)
132
-
133
- def search(self, query: str, count: int) -> tuple[str, list[Result]]:
134
- with self._gate:
135
- now = self._clock()
136
- awake = [e for e in self._engines if self._resting.get(e, 0) <= now]
137
- for engine in awake or self._engines:
138
- try:
139
- found = self._ddgs.DDGS(timeout=self._timeout).text(
140
- query, backend=engine, max_results=count
141
- )
142
- except self._provider_error: # known ddgs timeout/rate-limit/no-results errors
143
- found = []
144
- results = results_of(found)
145
- if results:
146
- self._resting.pop(engine, None)
147
- return engine, results[:count]
148
- self._resting[engine] = self._clock() + self._rest_s
149
- raise NoAnswerError()
150
-
151
-
152
- class YouCom:
153
- """You.com's free MCP profile, asked by the MCP door when no ddgs engine found anything: one
154
- stateless ``tools/call`` POST, answered as server-sent events or JSON, the result pages in
155
- ``structuredContent.results.web``. A 429 is the only rate limit it reports apart."""
156
-
157
- def __init__(self, url: str, timeout: float) -> None:
158
- self._url = url
159
- self._timeout = timeout
160
-
161
- def search(self, query: str, count: int) -> tuple[str, list[Result]]:
162
- call = {"jsonrpc": "2.0", "id": 1, "method": "tools/call"}
163
- call["params"] = {"name": YOU_TOOL, "arguments": {"query": query, "count": count}}
164
- headers = {
165
- "Content-Type": "application/json",
166
- "Accept": "application/json, text/event-stream",
167
- "MCP-Protocol-Version": MCP_PROTOCOL,
168
- "User-Agent": YOU_AGENT,
169
- }
170
- request = urllib.request.Request(self._url, json.dumps(call).encode(), headers)
171
- try:
172
- with urllib.request.urlopen(request, timeout=self._timeout) as response:
173
- body = response.read(MAX_YOU_BODY).decode("utf-8", "replace")
174
- except urllib.error.HTTPError as error:
175
- raise NoAnswerError(RATE_LIMITED if error.code == 429 else UNANSWERED) from None
176
- except OSError: # unreachable or timed out
177
- raise NoAnswerError() from None
178
- reply = rpc_answer(body, 1)
179
- result = _object(reply.get("result"))
180
- if not result or result.get("isError"):
181
- content = result.get("content")
182
- said = _object(content[0]) if isinstance(content, list) and content else {}
183
- text = said.get("text") or _object(reply.get("error")).get("message") or "no answer"
184
- raise NoAnswerError(UNANSWERED, "You.com: " + " ".join(str(text).split())[:200])
185
- found = _object(_object(result.get("structuredContent")).get("results")).get("web")
186
- results = you_results(found if isinstance(found, list) else [])
187
- if not results:
188
- raise NoAnswerError(NO_RESULTS)
189
- return "you.com", results[:count]
190
-
191
-
192
- class Fallback:
193
- """``first``, then ``then`` when ``first`` found nothing; the reason given is ``then``'s, the
194
- later and more telling answer."""
195
-
196
- def __init__(self, first: Searcher, then: Searcher) -> None:
197
- self._first = first
198
- self._then = then
199
-
200
- def search(self, query: str, count: int) -> tuple[str, list[Result]]:
201
- try:
202
- return self._first.search(query, count)
203
- except NoAnswerError:
204
- return self._then.search(query, count)
205
-
206
-
207
- def rpc_answer(body: str, rid: int) -> dict[str, Any]:
208
- """The JSON-RPC answer with id ``rid`` in a JSON or server-sent-events body, or {}."""
209
- lines = body.splitlines()
210
- chunks = [body] if body.lstrip().startswith("{") else [x[5:] for x in lines if x[:5] == "data:"]
211
- for chunk in chunks:
212
- try:
213
- message = json.loads(chunk)
214
- except ValueError:
215
- continue
216
- if isinstance(message, dict) and message.get("id") == rid:
217
- return message
218
- return {}
219
-
220
-
221
- def you_results(hits: list[Any]) -> list[Result]:
222
- """You.com's web results as result pages: its description, else its first highlight."""
223
- results: list[Result] = []
224
- for hit in hits:
225
- item = _object(hit)
226
- url = str(item.get("url") or "")
227
- if not url.startswith(("http://", "https://")):
228
- continue
229
- highlights = _object(item.get("contents")).get("highlights")
230
- first = highlights[0] if isinstance(highlights, list) and highlights else ""
231
- snippet = " ".join(str(item.get("description") or first).split())
232
- results.append(
233
- {"title": str(item.get("title") or ""), "url": url, "content": snippet[:400]}
234
- )
235
- return results
236
-
237
-
238
- def results_of(found: list[dict[str, Any]]) -> list[Result]:
239
- return [
240
- {
241
- "title": str(hit.get("title") or ""),
242
- "url": str(hit.get("href") or ""),
243
- "content": str(hit.get("body") or ""),
244
- }
245
- for hit in found
246
- if str(hit.get("href") or "").startswith(("http://", "https://"))
247
- ]
248
-
249
-
250
- def search_request(path: str) -> tuple[str, int]:
251
- """The query and result count of a ``/search`` URL; ValueError when the query is unusable."""
252
- params = urllib.parse.parse_qs(urllib.parse.urlsplit(path).query)
253
- query = " ".join((params.get("q") or [""])[0].split())
254
- if not query:
255
- raise ValueError("q is required")
256
- if len(query) > MAX_QUERY_CHARS:
257
- raise ValueError(f"q is longer than {MAX_QUERY_CHARS} characters")
258
- if (params.get("format") or ["json"])[0] != "json":
259
- raise ValueError("only format=json is served")
260
- try:
261
- count = int((params.get("count") or [str(MAX_RESULTS)])[0])
262
- except ValueError:
263
- raise ValueError("count is not a number") from None
264
- return query, min(max(count, 1), MAX_RESULTS)
265
-
266
-
267
- def local_origin(origin: str | None) -> bool:
268
- """A request without Origin (any non-browser client), or from a loopback page. Refusing other
269
- origins keeps a web page that rebinds a DNS name to 127.0.0.1 off the MCP door."""
270
- return origin is None or urllib.parse.urlsplit(origin).hostname in LOCAL_HOSTS
271
-
272
-
273
- def _rpc(rid: object, result: dict[str, Any]) -> dict[str, Any]:
274
- return {"jsonrpc": "2.0", "id": rid, "result": result}
275
-
276
-
277
- def _rpc_error(rid: object, code: int, message: str) -> dict[str, Any]:
278
- return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}}
279
-
280
-
281
- def _tool_result(rid: object, text: str, error: bool = False) -> dict[str, Any]:
282
- """A tool answer as the model reads it: one text block, flagged only when the search failed."""
283
- result: dict[str, Any] = {"content": [{"type": "text", "text": text}]}
284
- if error:
285
- result["isError"] = True
286
- return _rpc(rid, result)
287
-
288
-
289
- def _object(value: object) -> dict[str, Any]:
290
- return cast("dict[str, Any]", value) if isinstance(value, dict) else {}
291
-
292
-
293
- def results_text(results: list[Result]) -> str:
294
- return "\n\n".join(
295
- f"{i}. {r['title']}\n{r['url']}\n{r['content']}" for i, r in enumerate(results, 1)
296
- )
297
-
298
-
299
- def mcp_reply(engine: Searcher, message: object) -> dict[str, Any] | None:
300
- """The answer to one JSON-RPC message of MCP's streamable HTTP transport; None for a
301
- notification or a response, which take no answer. The server offers one tool, ``search``, and
302
- nothing that needs a session, so every request stands alone."""
303
- if not isinstance(message, dict) or message.get("jsonrpc") != "2.0":
304
- return _rpc_error(None, -32600, "invalid request")
305
- method, rid = message.get("method"), message.get("id")
306
- if not isinstance(method, str):
307
- if "result" in message or "error" in message:
308
- return None
309
- return _rpc_error(rid, -32600, "invalid request")
310
- if "id" not in message:
311
- return None
312
- params = _object(message.get("params"))
313
- if method == "initialize":
314
- # One tool and no session state are the same in every protocol version, so the version
315
- # the client asks for is the version answered.
316
- asked = params.get("protocolVersion")
317
- version = asked if isinstance(asked, str) and asked else MCP_PROTOCOL
318
- return _rpc(
319
- rid,
320
- {
321
- "protocolVersion": version,
322
- "capabilities": {"tools": {}},
323
- "serverInfo": {"name": "localmodels-search", "version": "1"},
324
- },
325
- )
326
- if method == "ping":
327
- return _rpc(rid, {})
328
- if method == "tools/list":
329
- return _rpc(rid, {"tools": [SEARCH_TOOL]})
330
- if method != "tools/call":
331
- return _rpc_error(rid, -32601, "method not found")
332
- if params.get("name") != SEARCH_TOOL["name"]:
333
- return _rpc_error(rid, -32602, "unknown tool")
334
- arguments = _object(params.get("arguments"))
335
- query = " ".join(str(arguments.get("query") or "").split())
336
- if not query or len(query) > MAX_QUERY_CHARS:
337
- return _tool_result(rid, f"query must be 1-{MAX_QUERY_CHARS} characters", error=True)
338
- started = time.perf_counter()
339
- try:
340
- name, results = engine.search(query, MAX_RESULTS)
341
- except NoAnswerError as error:
342
- log.warning("mcp %s ms=%.0f", error.reason, _ms(started))
343
- said = f" ({error.detail})" if error.detail else ""
344
- text = f"{error.reason}: {NO_ANSWER_TEXT[error.reason]}{said}"
345
- return _tool_result(rid, text, error=True)
346
- except Exception as error: # noqa: BLE001 - told to the model, never the query
347
- log.warning("mcp error %s ms=%.0f", type(error).__name__, _ms(started))
348
- return _tool_result(rid, f"{UNANSWERED}: {NO_ANSWER_TEXT[UNANSWERED]}", error=True)
349
- log.info("mcp 200 engine=%s results=%d ms=%.0f", name, len(results), _ms(started))
350
- return _tool_result(rid, results_text(results))
351
-
352
-
353
- def mcp_post(
354
- engine: Searcher, headers: Message, body: BufferedIOBase
355
- ) -> tuple[HTTPStatus, dict[str, Any] | None]:
356
- """Status and JSON answer to one ``POST /mcp``; no answer means an empty 202."""
357
- if not local_origin(headers.get("Origin")):
358
- return HTTPStatus.FORBIDDEN, {"error": "origin not allowed"}
359
- try:
360
- length = int(headers.get("Content-Length") or "0")
361
- except ValueError:
362
- length = 0
363
- if not 0 < length <= MAX_MCP_BODY:
364
- status = HTTPStatus.REQUEST_ENTITY_TOO_LARGE if length > 0 else HTTPStatus.LENGTH_REQUIRED
365
- return status, {"error": f"a JSON body of at most {MAX_MCP_BODY} bytes"}
366
- try:
367
- message = json.loads(body.read(length))
368
- except ValueError:
369
- return HTTPStatus.OK, _rpc_error(None, -32700, "parse error")
370
- reply = mcp_reply(engine, message)
371
- return (HTTPStatus.ACCEPTED, None) if reply is None else (HTTPStatus.OK, reply)
372
-
373
-
374
- def make_handler(
375
- engine: Searcher, mcp_engine: Searcher | None = None
376
- ) -> type[BaseHTTPRequestHandler]:
377
- """``engine`` answers /search; ``mcp_engine`` (else ``engine``) answers /mcp."""
378
-
379
- class Handler(BaseHTTPRequestHandler):
380
- protocol_version = "HTTP/1.1"
381
-
382
- def log_message(self, format: str, *args: object) -> None: # noqa: A002
383
- pass # the request line holds the query; do_GET logs without it
384
-
385
- def _json(self, status: HTTPStatus, value: object) -> None:
386
- body = json.dumps(value, ensure_ascii=False).encode()
387
- self.send_response(status)
388
- self.send_header("Content-Type", "application/json")
389
- self.send_header("Content-Length", str(len(body)))
390
- self.end_headers()
391
- self.wfile.write(body)
392
-
393
- def do_POST(self) -> None:
394
- if urllib.parse.urlsplit(self.path).path != MCP_PATH:
395
- self._json(HTTPStatus.NOT_FOUND, {"error": "not found"})
396
- return
397
- status, reply = mcp_post(mcp_engine or engine, self.headers, self.rfile)
398
- if reply is None:
399
- self.send_response(status)
400
- self.send_header("Content-Length", "0")
401
- self.end_headers()
402
- return
403
- self._json(status, reply)
404
-
405
- def do_GET(self) -> None:
406
- route = urllib.parse.urlsplit(self.path).path
407
- if route == "/health":
408
- self._json(HTTPStatus.OK, {"status": "ok"})
409
- return
410
- if route == MCP_PATH: # no server-initiated stream: the transport's answer is 405
411
- self._json(HTTPStatus.METHOD_NOT_ALLOWED, {"error": "POST only"})
412
- return
413
- if route != "/search":
414
- self._json(HTTPStatus.NOT_FOUND, {"error": "not found"})
415
- return
416
- started = time.perf_counter()
417
- try:
418
- query, count = search_request(self.path)
419
- except ValueError as error:
420
- self._json(HTTPStatus.BAD_REQUEST, {"error": str(error)})
421
- return
422
- try:
423
- name, results = engine.search(query, count)
424
- except Exception as error: # noqa: BLE001 - a generic 502, never the query
425
- # Not 429: Magpie rests a search API that reports a rate limit for up to 10 min.
426
- log.warning("502 %s ms=%.0f", type(error).__name__, _ms(started))
427
- self._json(
428
- HTTPStatus.BAD_GATEWAY,
429
- {
430
- "error": "SEARCH_PROVIDER_UNAVAILABLE"
431
- if isinstance(error, NoAnswerError)
432
- else "no engine answered"
433
- },
434
- )
435
- return
436
- hits = [{**r, "engine": name} for r in results]
437
- self._json(HTTPStatus.OK, {"query": query, "results": hits})
438
- log.info("200 engine=%s results=%d ms=%.0f", name, len(results), _ms(started))
439
-
440
- return Handler
441
-
442
-
443
- def _ms(started: float) -> float:
444
- return (time.perf_counter() - started) * 1000
445
-
446
-
447
- def main() -> None:
448
- parser = argparse.ArgumentParser(description=__doc__)
449
- parser.add_argument("--host", default="127.0.0.1", help="address to listen on")
450
- parser.add_argument("--port", type=int, required=True, help="port to listen on")
451
- parser.add_argument("--engines", default=ENGINES, help="ddgs backends, asked in this order")
452
- parser.add_argument("--timeout", type=int, default=10, help="seconds per engine request")
453
- parser.add_argument("--concurrency", type=int, default=2, help="searches at once")
454
- parser.add_argument("--rest", type=float, default=REST_S, help="seconds a failed engine rests")
455
- parser.add_argument(
456
- "--you",
457
- default=YOU_MCP,
458
- help="You.com MCP the /mcp door asks after the engines; '' for none",
459
- )
460
- args = parser.parse_args()
461
- logging.basicConfig(level=logging.WARNING, format="%(asctime)s %(levelname)s %(message)s")
462
- log.setLevel(logging.INFO)
463
- for name in ("ddgs", "primp"): # their messages carry engine URLs, and so the query
464
- logging.getLogger(name).setLevel(logging.CRITICAL + 1)
465
- engines = [e.strip() for e in args.engines.split(",") if e.strip()]
466
- engine = cast(Searcher, Ddgs(engines, args.timeout, args.concurrency, args.rest))
467
- mcp_engine = Fallback(engine, YouCom(args.you, args.timeout)) if args.you else None
468
- server = ThreadingHTTPServer((args.host, args.port), make_handler(engine, mcp_engine))
469
- log.info("listening on %s:%d, engines %s", args.host, args.port, args.engines)
470
- server.serve_forever()
471
-
472
-
473
- if __name__ == "__main__":
474
- main()