@tiens.nguyen/gu-cli 1.0.913 → 1.0.915

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.
@@ -722,6 +722,79 @@ def _bk_ddg_html(q, timeout=6):
722
722
  return out
723
723
 
724
724
 
725
+ # GH #455: DuckDuckGo's HTML endpoint answers 200 with ZERO results once a few searches arrive in a
726
+ # row (measured: results 1-3 fine, 4-6 empty). A second keyless engine (Bing) answered 6 of 6 in the
727
+ # same test, and an engine that returned nothing is left alone for a while instead of being hit again.
728
+ _ENGINE_COOL: dict = {} # engine name -> time.time() until which it is skipped
729
+ _ENGINE_COOL_SECS = 180
730
+
731
+
732
+ def _engine_cooling(name):
733
+ import time as _t
734
+ return _ENGINE_COOL.get(name, 0) > _t.time()
735
+
736
+
737
+ def _engine_cool(name, secs=None):
738
+ import time as _t
739
+ _ENGINE_COOL[name] = _t.time() + (secs or _ENGINE_COOL_SECS)
740
+ _log(f"web_search: {name} returned no results; skipping it for {secs or _ENGINE_COOL_SECS}s")
741
+
742
+
743
+ def _bing_real_url(href):
744
+ """Bing wraps every result link as bing.com/ck/a?...&u=a1<base64url>; unwrap to the real URL."""
745
+ import base64
746
+ import html as _html
747
+ from urllib.parse import urlsplit, parse_qs
748
+ href = _html.unescape(href or "")
749
+ if "bing.com/ck/a" not in href:
750
+ return href
751
+ u = (parse_qs(urlsplit(href).query).get("u") or [""])[0]
752
+ if u.startswith("a1"):
753
+ t = u[2:]
754
+ try:
755
+ return base64.urlsafe_b64decode(t + "=" * (-len(t) % 4)).decode("utf-8", "replace")
756
+ except Exception: # noqa: BLE001
757
+ return ""
758
+ return ""
759
+
760
+
761
+ _SEARCH_STOP = frozenset("a an and are as at be by do does for from how in is it of on or the to what when where which who why with".split())
762
+
763
+
764
+ def _result_relevant(r, query):
765
+ """Bing (and DDG) sometimes answer a scripted request with unrelated pages (measured: 'nextjs 15 caching
766
+ behaviour' → zhihu.com, 'postgres 17 vacuum settings' → baidu). People put the subject first, so a result
767
+ is kept only if the query's first meaningful word (not a stop word, not a bare version number) appears in
768
+ its title, snippet or URL. Measured on 8 queries: 6 kept every good page, the 2 junk answers were dropped."""
769
+ toks = [t for t in re.findall(r"[a-z0-9.#+]+", (query or "").lower())
770
+ if t not in _SEARCH_STOP and len(t) > 1 and not re.fullmatch(r"[\d.]+", t)]
771
+ if not toks:
772
+ return True
773
+ return toks[0] in f"{r.get('title','')} {r.get('snippet','')} {r.get('url','')}".lower()
774
+
775
+
776
+ def _bk_bing_html(q, timeout=6):
777
+ """Bing HTML results → [{title,snippet,url}] (keyless). One <li class="b_algo"> per result."""
778
+ from urllib.parse import quote
779
+ body = _get_text(f"https://www.bing.com/search?q={quote(q)}&setlang=en", timeout=timeout)
780
+ if not body:
781
+ return []
782
+ out = []
783
+ for blk in re.findall(r'<li class="b_algo"[^>]*>.*?</li>', body, re.S):
784
+ blk = re.sub(r"<link[^>]*>", "", blk)
785
+ h = re.search(r'<h2[^>]*>\s*<a[^>]*href="([^"]*)"[^>]*>(.*?)</a>', blk, re.S)
786
+ if not h:
787
+ continue
788
+ real = _bing_real_url(h.group(1))
789
+ title = _search_strip(h.group(2))
790
+ if not real.startswith("http") or not title:
791
+ continue
792
+ sm = (re.search(r'<p[^>]*class="[^"]*b_lineclamp[^"]*"[^>]*>(.*?)</p>', blk, re.S)
793
+ or re.search(r'<div class="b_caption[^"]*"[^>]*>.*?<p[^>]*>(.*?)</p>', blk, re.S))
794
+ out.append({"title": title[:120], "snippet": _search_strip(sm.group(1)) if sm else "", "url": real})
795
+ return out
796
+
797
+
725
798
  def _bk_searxng(q, base, timeout=6):
726
799
  """Self-hosted SearXNG JSON API → {results:[{title,snippet,url}], answers:[str]} (keyless).
727
800
 
@@ -960,7 +1033,11 @@ def _web_search_impl(query, max_results=5, searxng_url="",
960
1033
  overall = 5 # overall deadline; a straggler is abandoned (shutdown is non-blocking)
961
1034
 
962
1035
  # Result-producing backends (run in parallel). Order = tie-break priority in the merge.
963
- tasks = [("ddg", lambda: _bk_ddg_html(q, per_timeout))]
1036
+ tasks = []
1037
+ if not _engine_cooling("ddg"):
1038
+ tasks.append(("ddg", lambda: _bk_ddg_html(q, per_timeout)))
1039
+ if not _engine_cooling("bing"):
1040
+ tasks.append(("bing", lambda: _bk_bing_html(q, per_timeout)))
964
1041
  if searxng:
965
1042
  # SearXNG aggregates Wikipedia (and everything else) server-side, so the standalone
966
1043
  # Wikipedia backend is redundant here — and its full-text API is the slow straggler
@@ -996,23 +1073,30 @@ def _web_search_impl(query, max_results=5, searxng_url="",
996
1073
  results_by[name] = r
997
1074
  finally:
998
1075
  ex.shutdown(wait=False, cancel_futures=True)
1076
+ for _eng in ("ddg", "bing"): # asked and got nothing → leave it alone for a while (GH #455)
1077
+ if _eng in results_by and not results_by[_eng]:
1078
+ _engine_cool(_eng)
999
1079
 
1000
1080
  # Merge + dedupe by normalized URL; rank by cross-engine AGREEMENT then first-seen order.
1001
1081
  merged = {}
1002
1082
  order = 0
1003
- for name in ("searxng", "ddg", "wikipedia"):
1004
- for r in results_by.get(name, []):
1083
+ for name in ("searxng", "ddg", "bing", "wikipedia"):
1084
+ rs = results_by.get(name, [])
1085
+ if name in ("ddg", "bing"):
1086
+ rs = [r for r in rs if _result_relevant(r, q)]
1087
+ for r in rs:
1005
1088
  nu = _norm_url(r.get("url"))
1006
1089
  if not nu:
1007
1090
  continue
1008
1091
  if nu in merged:
1009
- merged[nu]["hits"] += 1
1092
+ if name != "wikipedia": # GH #455: the encyclopedia must not outrank real web hits
1093
+ merged[nu]["hits"] += 1
1010
1094
  if not merged[nu]["snippet"] and r.get("snippet"):
1011
1095
  merged[nu]["snippet"] = r["snippet"]
1012
1096
  else:
1013
1097
  merged[nu] = {
1014
1098
  "title": r.get("title") or r["url"], "snippet": r.get("snippet", ""),
1015
- "url": r["url"], "hits": 1, "order": order,
1099
+ "url": r["url"], "hits": 0 if name == "wikipedia" else 1, "order": order,
1016
1100
  }
1017
1101
  order += 1
1018
1102
  ranked = sorted(merged.values(), key=lambda e: (-e["hits"], e["order"]))[:max_results]
@@ -1024,7 +1108,8 @@ def _web_search_impl(query, max_results=5, searxng_url="",
1024
1108
  "web_search backends → "
1025
1109
  f"searxng={'on' if searxng else 'off'}"
1026
1110
  + (f"({len(results_by.get('searxng', []))})" if searxng else "")
1027
- + f" ddg({len(results_by.get('ddg', []))})"
1111
+ + f" ddg({len(results_by.get('ddg', []))}{'*' if _engine_cooling('ddg') else ''})"
1112
+ + f" bing({len(results_by.get('bing', []))}{'*' if _engine_cooling('bing') else ''})"
1028
1113
  + (f" wikipedia({len(results_by.get('wikipedia', []))})" if not searxng else "")
1029
1114
  + f" answers({len(answers)}) → {len(ranked)} ranked"
1030
1115
  + (f" [searxng={searxng}]" if searxng else "")
@@ -1050,6 +1135,12 @@ def _web_search_impl(query, max_results=5, searxng_url="",
1050
1135
  page_texts = _read_pages(ranked[:read_k], q, page_chars) if (read_on and ranked) else {}
1051
1136
 
1052
1137
  parts = []
1138
+ # GH #455: every web engine came back empty and only the encyclopedia matched. Say so — those
1139
+ # pages are matches on the words, not an answer, and the model must not present them as one.
1140
+ if ranked and not answers and all(e["hits"] == 0 for e in ranked):
1141
+ parts.append("Note: the web search engines returned nothing for this query (they may be rate "
1142
+ "limiting). The pages below are Wikipedia matches only and may not answer it. "
1143
+ "Say that, or try again with different words.")
1053
1144
  # Answer box(es) first — a direct answer often needs no page read at all.
1054
1145
  answer_lines = [f"• {a[:600]}" for a in answers[:3]]
1055
1146
  if summary:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.913",
3
+ "version": "1.0.915",
4
4
  "description": "gu: the coding agent in your terminal. It reads your repo, makes the change and runs the tests, with your own models (Ollama or any OpenAI-compatible provider). Free installs keep the agent, its API and its database on your machine. macOS, Linux and Windows.",
5
5
  "keywords": [
6
6
  "ai",