searchio 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.
searchio/__init__.py ADDED
File without changes
searchio/cli.py ADDED
@@ -0,0 +1,494 @@
1
+ """Command line interface.
2
+
3
+ The commands mirror the three price points in :mod:`searchio.engine`, and the
4
+ help text says which is which, because the most common way to misuse this tool
5
+ is to reach for ``research`` when ``search`` would have answered in a fifth of
6
+ a second for nothing.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import asyncio
12
+ import json as jsonlib
13
+ import sys
14
+
15
+ import typer
16
+ from pydantic import ValidationError
17
+ from rich.console import Console
18
+ from rich.json import JSON
19
+ from rich.panel import Panel
20
+ from rich.table import Table
21
+
22
+ from .config import Settings, get_settings, set_settings
23
+ from .engine import Engine
24
+ from .errors import Blocked, ConfigError, SearchioError
25
+
26
+ app = typer.Typer(
27
+ add_completion=False,
28
+ no_args_is_help=True,
29
+ help="LLM-assisted search over a blocking-resistant acquisition ladder.",
30
+ )
31
+
32
+ # Windows terminals default to cp1252, which raises on the first em dash in a
33
+ # page title. Force UTF-8 rather than mangling output.
34
+ console = Console(legacy_windows=False)
35
+ #: Diagnostics and errors (bug 90): stdout is the payload when --json is
36
+ #: on, so everything that is not the payload goes here.
37
+ err_console = Console(stderr=True, legacy_windows=False)
38
+
39
+
40
+ def _emit_json(text: str) -> None:
41
+ """Raw JSON on stdout: rich's JSON renderable wraps at the terminal
42
+ width (80 in a pipe), which split a long URL across lines and left the
43
+ consumer with a document that was not JSON (bug 90)."""
44
+ sys.stdout.write(text + "\n")
45
+ sys.stdout.flush()
46
+ if sys.platform == "win32":
47
+ try:
48
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
49
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
50
+ except Exception:
51
+ pass
52
+
53
+
54
+ def _settings(max_tier: int | None, no_cache: bool) -> Settings:
55
+ try:
56
+ s = get_settings()
57
+ except ValidationError as exc:
58
+ # A bad SEARCHIO_* value is an operator error, one line (bug 89).
59
+ err_console.print(f"[bold red]config:[/] {_one_line(exc)}")
60
+ raise typer.Exit(2)
61
+ if max_tier is not None:
62
+ s.max_tier = max_tier
63
+ if no_cache:
64
+ s.cache_enabled = False
65
+ set_settings(s)
66
+ return s
67
+
68
+
69
+ def _one_line(exc: ValidationError) -> str:
70
+ """'intent: Input should be ...' -- the field and the reason, nothing else."""
71
+ try:
72
+ e = exc.errors()[0]
73
+ loc = ".".join(str(p) for p in e.get("loc", ())) or "input"
74
+ return f"{loc}: {e.get('msg', '')}"[:300]
75
+ except Exception: # noqa: BLE001
76
+ return str(exc).splitlines()[0][:300]
77
+
78
+
79
+ def _cooling(eng, intent: str) -> dict[str, str]:
80
+ """Configured providers for ``intent`` whose breaker is open.
81
+
82
+ An empty item result is honest ("no listings") only when providers were
83
+ actually asked. When every provider that serves the intent sits
84
+ circuit-open from earlier failures, the emptiness is a cooldown, not an
85
+ absence -- the same story /search names as ``providers_skipped`` (bug 164)
86
+ and the tool bridge names as a circuit note (bug 129). The CLI item
87
+ commands used to print a calm "No listings found." and exit 0 on it (the
88
+ CLI twin of bug 75/164): now they say so and exit 1 (bug 182).
89
+ """
90
+ # Delegates to the router's canonical breaker read (bug 164), so the CLI,
91
+ # /search and /items all name a cooldown the same way rather than three
92
+ # copies drifting apart.
93
+ router = getattr(eng, "router", None)
94
+ cooling = getattr(router, "_cooling", None)
95
+ return cooling(intent) if callable(cooling) else {}
96
+
97
+
98
+ def _report_no_items(eng, intent: str) -> None:
99
+ """Print the empty-item verdict and set the exit code (bug 182)."""
100
+ cooling = _cooling(eng, intent)
101
+ if cooling:
102
+ err_console.print("[bold red]error:[/] all providers cooling down: "
103
+ + "; ".join(f"{n}: {e}" for n, e in cooling.items()))
104
+ raise typer.Exit(1)
105
+ console.print("[yellow]No listings found.[/]")
106
+
107
+
108
+ def _run(coro):
109
+ try:
110
+ return asyncio.run(coro)
111
+ except ValidationError as exc:
112
+ # An invalid argument (--intent bogus) used to escape as a rich
113
+ # traceback -- exit 1 with forty frames for an expected input
114
+ # error (bug 89). Usage errors are exit 2, one line.
115
+ err_console.print(f"[bold red]invalid:[/] {_one_line(exc)}")
116
+ raise typer.Exit(2)
117
+ except ConfigError as exc:
118
+ err_console.print(f"[bold red]config:[/] {exc}")
119
+ raise typer.Exit(2)
120
+ except SearchioError as exc:
121
+ err_console.print(f"[bold red]error:[/] {exc}")
122
+ raise typer.Exit(1)
123
+ except KeyboardInterrupt:
124
+ raise typer.Exit(130)
125
+
126
+
127
+ @app.command()
128
+ def search(
129
+ query: str = typer.Argument(..., help="What to search for."),
130
+ intent: str = typer.Option("web", "--intent", "-i",
131
+ help="web|news|video|shopping|academic|code|local|reference|forum"),
132
+ k: int = typer.Option(10, "--k", "-k", help="Number of results."),
133
+ domains: str = typer.Option("", "--domains", "-d", help="Comma-separated domain allowlist."),
134
+ json_out: bool = typer.Option(False, "--json", help="Emit JSON."),
135
+ max_tier: int = typer.Option(None, "--max-tier", help="0=http 1=+TLS-impersonation 2=+browser"),
136
+ no_cache: bool = typer.Option(False, "--no-cache"),
137
+ verbose: bool = typer.Option(False, "--verbose", "-v", help="Show provider diagnostics."),
138
+ ) -> None:
139
+ """Fast multi-provider search. No model, no API key, no cost."""
140
+ s = _settings(max_tier, no_cache)
141
+
142
+ async def go():
143
+ async with Engine(s) as eng:
144
+ res = await eng.search(
145
+ query, intent=intent, k=k,
146
+ domains=[d.strip() for d in domains.split(",") if d.strip()],
147
+ )
148
+ if json_out:
149
+ _emit_json(jsonlib.dumps(
150
+ {"query": query, "used": res.used, "failed": res.failed,
151
+ "skipped": dict(getattr(res, "skipped", None) or {}),
152
+ "elapsed_ms": res.elapsed_ms,
153
+ "results": [d.model_dump(exclude={"text"}) for d in res.docs]},
154
+ default=str))
155
+ return
156
+ skipped = dict(getattr(res, "skipped", None) or {})
157
+ if not res.docs:
158
+ if not res.used and (res.failed or skipped):
159
+ # Nobody answered: exit 1 with the reasons, not a calm
160
+ # "No results." and exit 0 (the CLI twin of bug 75); a
161
+ # fan-out where everyone sat circuit-open is the same
162
+ # story (bug 164).
163
+ reasons = {**res.failed, **skipped}
164
+ err_console.print("[bold red]error:[/] "
165
+ + ("all providers failed: " if res.failed
166
+ else "all providers cooling down: ")
167
+ + "; ".join(f"{n}: {e}" for n, e in reasons.items()))
168
+ raise typer.Exit(1)
169
+ console.print("[yellow]No results.[/]")
170
+ for name, err in {**res.failed, **skipped}.items():
171
+ console.print(f" [dim]{name}: {err}[/]")
172
+ return
173
+ table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
174
+ table.add_column("#", width=3, style="dim")
175
+ table.add_column("Result")
176
+ for i, d in enumerate(res.docs, 1):
177
+ agree = d.meta.get("agreement", 1)
178
+ badge = f" [green]×{agree}[/]" if agree > 1 else ""
179
+ srcs = ",".join(d.meta.get("sources", [d.source]))
180
+ table.add_row(
181
+ str(i),
182
+ f"[bold]{d.title or '(untitled)'}[/]{badge}\n"
183
+ f"[blue]{d.url}[/]\n"
184
+ f"[dim]{d.snippet[:200]}[/]\n"
185
+ f"[dim italic]{srcs} · score {d.score:.4f}[/]",
186
+ )
187
+ console.print(table)
188
+ foot = f"{len(res.docs)} results · {res.elapsed_ms}ms · providers: {', '.join(res.used)}"
189
+ if res.failed:
190
+ foot += f" · [red]failed: {', '.join(res.failed)}[/]"
191
+ if skipped:
192
+ foot += f" · [yellow]cooling down: {', '.join(skipped)}[/]"
193
+ console.print(f"[dim]{foot}[/]")
194
+ if verbose:
195
+ for name, err in {**res.failed, **skipped}.items():
196
+ console.print(f" [dim]{name}: {err}[/]")
197
+
198
+ _run(go())
199
+
200
+
201
+ @app.command()
202
+ def items(
203
+ query: str = typer.Argument(..., help="Product to look up."),
204
+ k: int = typer.Option(10, "--k", "-k"),
205
+ domains: str = typer.Option("", "--domains", "-d", help="Marketplace domains to restrict to."),
206
+ browser: bool = typer.Option(False, "--browser", help="Allow the stealth browser tier."),
207
+ json_out: bool = typer.Option(False, "--json"),
208
+ no_cache: bool = typer.Option(False, "--no-cache"),
209
+ ) -> None:
210
+ """Look up a product across marketplaces, merged into one row per product."""
211
+ s = _settings(2 if browser else 1, no_cache)
212
+
213
+ async def go():
214
+ async with Engine(s) as eng:
215
+ found = await eng.find_items(
216
+ query, k=k, use_browser=browser,
217
+ domains=[d.strip() for d in domains.split(",") if d.strip()] or None,
218
+ )
219
+ if json_out:
220
+ _emit_json(jsonlib.dumps([i.model_dump() for i in found], default=str))
221
+ return
222
+ if not found:
223
+ _report_no_items(eng, "shopping")
224
+ return
225
+ table = Table(show_header=True, header_style="bold", box=None)
226
+ table.add_column("Price", justify="right", style="green", width=12)
227
+ table.add_column("Product")
228
+ table.add_column("Seller", width=18)
229
+ table.add_column("Rating", width=12)
230
+ for it in found:
231
+ offers = it.meta.get("offer_count")
232
+ name = it.title[:70] + (f"\n[dim]+{offers - 1} other offers[/]" if offers else "")
233
+ rating = f"{it.rating:.1f} ({it.reviews or 0})" if it.rating is not None else "—"
234
+ table.add_row(
235
+ str(it.price) if it.price.amount is not None else "[dim]—[/]",
236
+ name,
237
+ it.seller or it.domain,
238
+ rating,
239
+ )
240
+ console.print(table)
241
+ console.print(f"[dim]{len(found)} products[/]")
242
+
243
+ _run(go())
244
+
245
+
246
+ @app.command()
247
+ def marketplace(
248
+ query: str = typer.Argument(..., help="What to look for."),
249
+ city: str = typer.Option("", "--city", "-c",
250
+ help="Marketplace city slug, e.g. nyc, seattle, la. "
251
+ "Without one, Facebook answers against your exit IP."),
252
+ k: int = typer.Option(20, "--k", "-k"),
253
+ json_out: bool = typer.Option(False, "--json"),
254
+ no_cache: bool = typer.Option(False, "--no-cache"),
255
+ ) -> None:
256
+ """Search Facebook Marketplace classifieds. Browser-backed, ~15-30s."""
257
+ s = _settings(2, no_cache) # browser-only; there is no cheaper tier here
258
+
259
+ async def go():
260
+ async with Engine(s) as eng:
261
+ found = await eng.find_local_items(query, city=city, k=k)
262
+ if json_out:
263
+ _emit_json(jsonlib.dumps([i.model_dump() for i in found], default=str))
264
+ return
265
+ if not found:
266
+ _report_no_items(eng, "local")
267
+ return
268
+ table = Table(show_header=True, header_style="bold", box=None)
269
+ table.add_column("Price", justify="right", style="green", width=11)
270
+ table.add_column("Was", justify="right", style="dim", width=6)
271
+ table.add_column("Listing")
272
+ table.add_column("Where", width=22)
273
+ for it in found:
274
+ table.add_row(
275
+ str(it.price) if it.price.amount is not None else "[dim]-[/]",
276
+ it.attributes.get("was_price", ""),
277
+ it.title[:64],
278
+ it.attributes.get("location") or it.attributes.get("delivery") or "[dim]-[/]",
279
+ )
280
+ console.print(table)
281
+ if any(it.meta.get("session_gate") == "empty_feed" for it in found):
282
+ console.print(
283
+ "[yellow]The saved Facebook session silently returned an empty search "
284
+ "feed (account gate) -- these listings were fetched anonymously. "
285
+ "Log in with a real, established account for full results, or set "
286
+ "SEARCHIO_FACEBOOK_HEADED=1 for roughly triple the anonymous "
287
+ "volume.[/]"
288
+ )
289
+ where = f"city:{city}" if city else "[yellow]exit-IP location[/]"
290
+ console.print(f"[dim]{len(found)} listings · {where}[/]")
291
+ if not city:
292
+ console.print(
293
+ "[dim]Pass --city to pin the metro; otherwise these are "
294
+ "wherever your traffic egresses.[/]"
295
+ )
296
+
297
+ _run(go())
298
+
299
+
300
+ @app.command()
301
+ def read(
302
+ url: str = typer.Argument(..., help="URL to fetch and extract."),
303
+ max_tier: int = typer.Option(None, "--max-tier"),
304
+ chars: int = typer.Option(4000, "--chars", help="Characters of text to print."),
305
+ ) -> None:
306
+ """Fetch one URL through the ladder and print its readable text."""
307
+ s = _settings(max_tier, False)
308
+
309
+ async def go():
310
+ async with Engine(s) as eng:
311
+ try:
312
+ res = await eng.ladder.fetch(url)
313
+ except Blocked as exc:
314
+ err_console.print(f"[bold red]blocked[/] by {exc.vendor or 'unknown'}: {exc.reason}")
315
+ raise typer.Exit(1)
316
+ from .extract import to_markdown, title_of
317
+
318
+ text = to_markdown(res.body, url)
319
+ console.print(Panel(
320
+ f"[bold]{title_of(res.body) or url}[/]\n"
321
+ f"[dim]{res.final_url}\ntier {res.tier} ({res.via}) · {res.status} · "
322
+ f"{res.elapsed_ms}ms · {len(text):,} chars"
323
+ + (f"\nescalations: {res.escalations}" if res.escalations else "") + "[/]",
324
+ expand=False))
325
+ console.print(text[:chars])
326
+ if len(text) > chars:
327
+ console.print(f"[dim]... {len(text) - chars:,} more characters[/]")
328
+
329
+ _run(go())
330
+
331
+
332
+ @app.command()
333
+ def research(
334
+ question: str = typer.Argument(..., help="The research question."),
335
+ json_out: bool = typer.Option(False, "--json"),
336
+ max_tier: int = typer.Option(None, "--max-tier"),
337
+ ) -> None:
338
+ """Run the research swarm. Costs real money; needs ANTHROPIC_API_KEY."""
339
+ s = _settings(max_tier, False)
340
+
341
+ async def go():
342
+ async with Engine(s) as eng:
343
+ out = err_console if json_out else console
344
+
345
+ def progress(event: str, data: dict) -> None:
346
+ if event == "planning":
347
+ out.print("[dim]planning…[/]")
348
+ elif event == "planned":
349
+ out.print(Panel(
350
+ f"[italic]{data['interpretation']}[/]\n\n"
351
+ + "\n".join(f"[cyan]{s_['id']}[/] {s_['objective']}"
352
+ for s_ in data["subtasks"]),
353
+ title=f"plan · {len(data['subtasks'])} parallel workers", expand=False))
354
+ elif event == "worker_start":
355
+ out.print(f" [dim]▸ {data['id']} started[/]")
356
+ elif event == "worker_done":
357
+ mark = "[red]✗[/]" if data["error"] else "[green]✓[/]"
358
+ out.print(
359
+ f" {mark} [bold]{data['id']}[/] {data['findings']} findings, "
360
+ f"{data['sources']} sources, {data['tool_calls']} tool calls"
361
+ + (f" [red]{data['error']}[/]" if data["error"] else ""))
362
+ elif event == "synthesising":
363
+ out.print("[dim]synthesising…[/]")
364
+
365
+ result = await eng.research(question, progress=progress)
366
+ if json_out:
367
+ _emit_json(result.model_dump_json())
368
+ return
369
+ console.print()
370
+ console.print(Panel(result.answer, title="answer", expand=False))
371
+ if result.sources:
372
+ console.print("\n[bold]Sources[/]")
373
+ for d in result.sources[:20]:
374
+ console.print(f" [blue]{d.url}[/] [dim]{d.title[:60]}[/]")
375
+ # The cost comes from the run's own budget, which knows which
376
+ # backend it used. Recomputing it here with Claude's list price
377
+ # printed a confident, wrong dollar figure for every other backend.
378
+ cost = (
379
+ f" · ~${result.estimated_cost_usd:.3f}"
380
+ if result.estimated_cost_usd is not None
381
+ else " · cost not priced for this backend"
382
+ )
383
+ console.print(
384
+ f"\n[dim]{result.model or 'model'} · {result.elapsed_s:.1f}s · "
385
+ f"{result.input_tokens:,} in / {result.output_tokens:,} out{cost}"
386
+ + (f" · stopped early: {result.stopped_early}" if result.stopped_early else "")
387
+ + "[/]")
388
+
389
+ _run(go())
390
+
391
+
392
+ @app.command()
393
+ def providers() -> None:
394
+ """List providers, their capabilities, and whether they are configured."""
395
+ s = _settings(None, False) # guarded: a bad SEARCHIO_* value is a one-line exit 2
396
+
397
+ async def go():
398
+ async with Engine(s) as eng:
399
+ table = Table(show_header=True, header_style="bold", box=None)
400
+ table.add_column("Provider", width=18)
401
+ table.add_column("Ready", width=6)
402
+ table.add_column("Capabilities")
403
+ table.add_column("Breaker", width=8)
404
+ for row in eng.router.health_report():
405
+ table.add_row(
406
+ row["provider"],
407
+ "[green]yes[/]" if row["configured"] else "[yellow]no[/]",
408
+ ", ".join(row["capabilities"]),
409
+ row["breaker"],
410
+ )
411
+ console.print(table)
412
+
413
+ _run(go())
414
+
415
+
416
+ @app.command()
417
+ def doctor() -> None:
418
+ """Check the environment: tiers, sidecar, keys, cache."""
419
+ s = _settings(None, False) # guarded: a bad SEARCHIO_* value is a one-line exit 2
420
+
421
+ async def go():
422
+ console.print(f"[bold]state dir[/] {s.state_dir}")
423
+ console.print(f"[bold]max tier[/] {s.max_tier}")
424
+ console.print(f"[bold]robots policy[/] {s.robots_policy}")
425
+
426
+ ok_key = bool(s.anthropic_key())
427
+ console.print(
428
+ f"[bold]anthropic key[/] " + ("[green]set[/]" if ok_key else
429
+ "[yellow]missing (research disabled)[/]"))
430
+
431
+ try:
432
+ from curl_cffi import requests # noqa: F401
433
+ console.print("[bold]tier 1[/] [green]curl_cffi available[/]")
434
+ except ImportError:
435
+ console.print("[bold]tier 1[/] [red]curl_cffi missing[/]")
436
+
437
+ async with Engine(s) as eng:
438
+ from .net.sidecar import default_script_path
439
+
440
+ script = default_script_path()
441
+ console.print(f"[bold]sidecar script[/] {script or '[yellow]not found[/]'}")
442
+ try:
443
+ url = await eng.ladder.sidecar.ensure()
444
+ console.print(f"[bold]tier 2[/] [green]sidecar live at {url}[/]")
445
+ except Exception as exc:
446
+ console.print(f"[bold]tier 2[/] [yellow]unavailable: {exc}[/]")
447
+
448
+ console.print("\n[bold]probing tiers[/]")
449
+ for url in ("https://example.com", "https://www.indeed.com/"):
450
+ try:
451
+ r = await eng.ladder.fetch(url, use_cache=False)
452
+ console.print(f" [green]ok[/] tier {r.tier} ({r.via}) {r.elapsed_ms:5}ms {url}")
453
+ except Exception as exc:
454
+ console.print(f" [red]fail[/] {type(exc).__name__}: {str(exc)[:60]} {url}")
455
+
456
+ profiles = eng.ladder.profiles.all()[:10]
457
+ if profiles:
458
+ console.print("\n[bold]learned domain tiers[/]")
459
+ for p in profiles:
460
+ console.print(
461
+ f" tier {p.min_tier} {p.domain:24} "
462
+ f"[dim]{p.successes} ok / {p.blocks} blocked"
463
+ + (f" · {p.last_block_vendor}" if p.last_block_vendor else "") + "[/]")
464
+
465
+ _run(go())
466
+
467
+
468
+ @app.command()
469
+ def serve(
470
+ host: str = typer.Option("127.0.0.1", "--host"),
471
+ port: int = typer.Option(8080, "--port"),
472
+ ) -> None:
473
+ """Run the HTTP API."""
474
+ import uvicorn
475
+
476
+ uvicorn.run("searchio.server:app", host=host, port=port, log_level="info")
477
+
478
+
479
+ @app.command()
480
+ def mcp(
481
+ transport: str = typer.Option("stdio", "--transport",
482
+ help="stdio | sse | streamable-http"),
483
+ host: str = typer.Option("127.0.0.1", "--host"),
484
+ port: int = typer.Option(8080, "--port"),
485
+ path: str = typer.Option("/mcp", "--path"),
486
+ ) -> None:
487
+ """Run the MCP server (Model Context Protocol) for search + research."""
488
+ from .mcp import main as mcp_main
489
+
490
+ mcp_main(["--transport", transport, "--host", host, "--port", port, "--path", path])
491
+
492
+
493
+ if __name__ == "__main__":
494
+ app()