From bd03d3b8fff9ed18d3cdb104c55908ba5be6c424 Mon Sep 17 00:00:00 2001 From: Igor Soarez Date: Tue, 4 Aug 2026 15:08:47 +0100 Subject: Write up what AI answer blocks would cost before building one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Google, Bing and Brave all put a generated answer above their results now, and none of it is being read. Investigated against castle's Chrome; nothing in src/ changed, because the cost turned out to be worth deciding on rather than absorbing. Two things make it expensive. Google's AI Overview exists only on the classic layout — udm=14 is the "Web" tab, and having no overview is part of what that tab is — so enabling it means giving back the clean page the extractor was built around. And all three stream in after the results are already parseable: Google settles ~2.3s in, Brave was still growing at 5s, against an extractor that returns at ~0.5s. The wait is often wasted, since the blocks are query-dependent — no Google overview for "how does postgres MVCC vacuum work" after 15s, no Bing answer for "who founded anthropic". Selectors, the traps behind them (#m-x-content briefly holds ~29k characters of unrelated page; Google's "Show more" hides only the disclaimer), the measured timings, three possible designs and their tradeoffs are all in the doc, so this does not have to be re-measured if the answer turns out to be yes. --- castle-search/.gitignore | 4 + castle-search/README.md | 224 ++++++++++++++++++ castle-search/docs/2026-08-04-ai-answers.md | 235 +++++++++++++++++++ castle-search/package.json | 38 ++++ castle-search/src/cdp.ts | 342 ++++++++++++++++++++++++++++ castle-search/src/endpoint.ts | 108 +++++++++ castle-search/src/engine-store.ts | 81 +++++++ castle-search/src/engine-target.ts | 79 +++++++ castle-search/src/engines.ts | 229 +++++++++++++++++++ castle-search/src/errors.ts | 83 +++++++ castle-search/src/extract.ts | 294 ++++++++++++++++++++++++ castle-search/src/format.ts | 54 +++++ castle-search/src/index.ts | 315 +++++++++++++++++++++++++ castle-search/src/paths.ts | 41 ++++ castle-search/src/search.ts | 339 +++++++++++++++++++++++++++ castle-search/src/target-store.ts | 42 ++++ castle-search/test/concurrency.test.ts | 86 +++++++ castle-search/test/endpoint.test.ts | 64 ++++++ castle-search/test/engine-target.test.ts | 89 ++++++++ castle-search/test/format.test.ts | 70 ++++++ castle-search/test/search-url.test.ts | 88 +++++++ castle-search/tsconfig.json | 18 ++ 22 files changed, 2923 insertions(+) create mode 100644 castle-search/.gitignore create mode 100644 castle-search/README.md create mode 100644 castle-search/docs/2026-08-04-ai-answers.md create mode 100644 castle-search/package.json create mode 100644 castle-search/src/cdp.ts create mode 100644 castle-search/src/endpoint.ts create mode 100644 castle-search/src/engine-store.ts create mode 100644 castle-search/src/engine-target.ts create mode 100644 castle-search/src/engines.ts create mode 100644 castle-search/src/errors.ts create mode 100644 castle-search/src/extract.ts create mode 100644 castle-search/src/format.ts create mode 100644 castle-search/src/index.ts create mode 100644 castle-search/src/paths.ts create mode 100644 castle-search/src/search.ts create mode 100644 castle-search/src/target-store.ts create mode 100644 castle-search/test/concurrency.test.ts create mode 100644 castle-search/test/endpoint.test.ts create mode 100644 castle-search/test/engine-target.test.ts create mode 100644 castle-search/test/format.test.ts create mode 100644 castle-search/test/search-url.test.ts create mode 100644 castle-search/tsconfig.json diff --git a/castle-search/.gitignore b/castle-search/.gitignore new file mode 100644 index 0000000..2d153b7 --- /dev/null +++ b/castle-search/.gitignore @@ -0,0 +1,4 @@ +node_modules/ +package-lock.json +*.tsbuildinfo +.DS_Store diff --git a/castle-search/README.md b/castle-search/README.md new file mode 100644 index 0000000..6dac8a7 --- /dev/null +++ b/castle-search/README.md @@ -0,0 +1,224 @@ +# pi-castle-cdp-search + +Web search for [pi](https://pi.dev) through a Chrome that is **already running** +on the wire network, driven over the Chrome DevTools Protocol. + +It never launches a browser. It attaches to one a person or a launchd job +started — by default castle's shared Chrome on `10.88.0.25:9223` — opens a +background tab, reads the results page, and closes the tab again. + +Because the search runs in a real browser with a real profile, it reaches pages +that reject datacentre traffic, and it costs nothing per query. + +## The tool + +One tool, `castle_cdp_search`. Deliberately **not** named `web_search`, so it +coexists with `pi-web-access` rather than shadowing it — both stay registered and +the model picks. + +| Parameter | Type | Notes | +|---|---|---| +| `query` | string, required | As you would type it into a search box | +| `numResults` | integer, optional | 1–20, default 10 | +| `recency` | `day` \| `week` \| `month` \| `year`, optional | Omit for no time limit | +| `engine` | `google` \| `duckduckgo` \| `bing` \| `brave`, optional | Overrides the configured default for one call | + +It returns titles, URLs and snippets — **search results only**. It does not fetch +the linked pages; follow up with a read/fetch tool for full content. + +## Engines + +Four, with independent indexes and independent rate limits. That last part is +the point: when one starts serving captchas, the others generally still work, +and the tool tells the agent so inside the error. + +| Engine | Recency windows | Notes | +|---|---|---| +| `google` | day, week, month, year | Best results; blocks aggressively under automation | +| `duckduckgo` | day, week, month, year | No-JS endpoint — the most stable markup here, least likely to challenge | +| `bing` | day, week, month | No year window exists | +| `brave` | none | Independent index, unwrapped links; challenges quickly | + +Aliases are accepted: `ddg`, `duck`, `g`, `b`. + +**An unsupported recency window is refused, not ignored.** Asking Bing for the +past year raises `RecencyUnsupportedError` naming the engines that can do it. +Silently returning unfiltered results would be indistinguishable from success. + +### Switching engines + +Exactly like switching the CDP host, plus a per-call override: + +``` +/search-engine show the current engine and where it came from +/search-engine ddg persist a choice (machine-wide, survives restarts) +/search-engine default back to Google +CCS_SEARCH_ENGINE=bing pi … pin for one process +``` + +Precedence: **`engine` parameter > `CCS_SEARCH_ENGINE` > `/search-engine` > +Google.** The stored choice lives in +`~/.pi/agent/castle-cdp-search-engine.json`, written atomically. + +Note the tool parameter sits *above* the environment variable, which is the +opposite of how the CDP target treats an explicit endpoint. That is deliberate: +for the browser, an env var must win because quietly driving a different machine +means automating the operator's own signed-in Chrome — a safety property. +Choosing a different search engine carries no such hazard, and letting the agent +fall back when one engine is blocked is the single most useful thing it can do +with this tool. + +An unrecognised engine name is reported rather than skipped, so a typo in +`CCS_SEARCH_ENGINE` never silently searches Google instead. + +## Which browser it drives + +Exactly the same configuration as [`pi-browser-harness`](../pi-browser-harness), +on purpose: one decision governs both packages, so they can never end up driving +different browsers in the same session. + +| `BU_CDP_HTTP` | Behaviour | +|---|---| +| unset | the `/browser-target` choice stored by pi-browser-harness, else castle (`10.88.0.25:9223`) | +| `host:port` | that endpoint | +| `local` (also `localhost`, `off`, `none`, `0`, `no`) | this machine's own browser on `127.0.0.1:9222` | + +Precedence is `BU_CDP_HTTP` > `/browser-target` > built-in default, matching the +harness. The `/browser-target` file (`~/.pi/agent/browser-target.json`) is read +only, never written — the harness owns that setting. + +**One deliberate difference from the harness.** When the configured endpoint is +unreachable, this extension reports that and stops. The harness falls back from +its built-in default to a local browser; here that fallback would mean silently +running searches through the operator's own signed-in Chrome without saying so. +Say `local` explicitly if that is what you want. + +The endpoint is re-resolved from `/json/version` on every connect, never cached: +castle recycles Chrome hourly and Chrome re-mints its browser UUID each launch, +so a pinned `ws://` URL breaks on the first recycle. A dropped socket reconnects +transparently on the next search. + +## Behaviour worth knowing + +- **Nothing is dialled at load.** pi runs extension factories in invocations that + never start a session, so the connection is made on first search and closed by + an idempotent `session_shutdown` handler. +- **One fresh background tab per search**, closed on every path including errors + and aborts. `background: true` so it does not steal focus from whoever is + looking at that screen. +- **Two concurrent searches**, queued beyond that. +- **20-second deadline** per call, covering the queue wait, connect, navigate and + extract together. Esc aborts an in-flight navigation. +- **Every failure throws.** pi only sets `isError: true` when `execute()` throws; + a returned `{ error }` object would read to the model as a search that simply + found nothing. + +## What it touches + +The browser is shared and belongs to a person. Worth being aware of: + +- Queries the agent runs land in that browser profile's history and cookies, and + in the search engine's account history if that profile is signed in. +- Tabs open and close on someone's screen. `background: true` keeps them from + stealing focus, but they are visible. +- Searching hard trips rate limiters for the whole host, and the challenge + affects the human using that browser too. Measured during development: + **Google** tolerated a lot, then roughly 30 queries in a few minutes cost about + 90 minutes of blocking. **Brave** is far stricter — it challenges after as few + as one or two queries and clears again in roughly 15–20 minutes. **DuckDuckGo** + and **Bing** never challenged once across the whole of development, which is + why DuckDuckGo is the one to reach for when you need to run several searches + in a row. +- **A decaying block does not look like a block.** Once the challenge page stops + being served, engines return an *empty results page* for a while instead — + indistinguishable from a query with no hits. It surfaces as `NoResultsError`, + not `SearchChallengeError`. If one engine comes back empty and another answers + the same query, that is rate limiting. + +## When a captcha appears + +Every engine eventually serves an interstitial: Google's `/sorry/` page, Brave's +"Verifying you're not a bot", a consent wall, a Cloudflare challenge. The +extension detects these and throws `SearchChallengeError` naming the challenge, +the engine, the browser, and the URL a human would have to visit. + +The error tells the agent to **try another engine first**, because a challenge on +one engine says nothing about the others and that is a fix it can apply itself. +Only when engines run out should it ask the user to clear the challenge in the +browser. The cookie is profile-wide, so one pass unblocks later searches. + +The tab is closed rather than left open on the challenge page: leaving it would +let the operator solve it in place, but would also litter a shared browser with +abandoned tabs on every failure. The URL in the error is enough. + +## Search parameters, and three traps + +Everything below was observed against castle's real Chrome, not inferred. All +three fail *silently* — the results look entirely plausible, just wrong. + +1. **Google: `tbs=qdr:*` renders an empty page.** That is the parameter Google's + own Tools menu writes. The older `as_qdr=*` works. +2. **Google: any date filter combined with `udm=14` renders that same empty + page.** So a time-limited search drops `udm` and uses the classic layout. +3. **Bing: `count=` silently cancels `filters=`.** With `ex1:"ez1"` alone every + result is hours old; add `count` in either order and months-old results come + back, unfiltered and unremarkable-looking. So Bing drops `count` whenever a + date filter is present and the caller slices the list instead. + +Each has a regression test asserting the parameter combination, since none of +them would announce itself if it regressed. + +## Result extraction + +Two modes, because the engines genuinely differ: + +- **items** — DuckDuckGo (`.result`), Bing (`li.b_algo`) and Brave + (`.snippet[data-type=web]`) each have a clean per-result container. +- **headings** — Google has no stable container; its class names (`MjjYud`, + `kb0PBd`, `yuRUbf`) are generated. Results are found from each `

` outward, + climbing to the enclosing block but abandoning the climb if a second `

` + comes into scope. + +DuckDuckGo and Bing both route outbound links through redirectors +(`duckduckgo.com/l/?uddg=…`, `bing.com/ck/a?…&u=a1`); both are +unwrapped in the page so the agent gets real URLs. Google and Brave link +straight out. + +Markup will change. When it does, `NoResultsError` distinguishes "container +rendered but unparseable" (that engine's extractor needs updating) from "no +container at all" (query, or rate limiting). + +## Install + +``` +pi install ssh://sz@10.88.0.25/Users/sz/repos/pi-castle-cdp-search.git +``` + +The ssh form is what pi-browser-harness uses, and it is the portable one: pi +records local-path installs by resolved absolute path, and `settings.json` is +shared across hosts through the dotfiles symlink. + +To try it without installing: + +``` +pi -e ./src/index.ts +``` + +## Development + +``` +npm install +npm run typecheck +npm test # unit tests, no browser needed +``` + +The tests cover engine selection and precedence, URL building for all four +engines (including the three traps above), recency refusal, formatting, the +challenge error, and the concurrency semaphore. The semaphore tests point at an +unreachable endpoint on purpose — the questions there are about slot +bookkeeping, and hitting a real browser to test a counter would be slow, flaky, +and rude to whoever is using it. + +Requires Node 22+, for the global `WebSocket`. There are no runtime +dependencies; pi supplies `@earendil-works/pi-coding-agent`, +`@earendil-works/pi-ai` and `typebox` to extensions through its own loader. diff --git a/castle-search/docs/2026-08-04-ai-answers.md b/castle-search/docs/2026-08-04-ai-answers.md new file mode 100644 index 0000000..29b5a6b --- /dev/null +++ b/castle-search/docs/2026-08-04-ai-answers.md @@ -0,0 +1,235 @@ +# AI answers on the SERP — findings, 2026-08-04 + +Status: **investigated, not implemented, not decided.** Nothing in `src/` has +changed. This is the field notes for whoever picks it up. + +The question was whether the AI answer block that Google, Bing and Brave now put +above their results ("AI Overview", the Bing generative answer, Brave's AI +summary) is worth pulling into `castle_cdp_search`'s output alongside the ranked +results. It is not obviously worth it — the cost is real and is set out below — +so the decision was deferred rather than taken. + +Everything here was read off the live SERPs in castle's Chrome on 2026-08-04, in +the signed-in `~/.chrome-cdp-profile`, `hl=en`. Same rule as `engines.ts`: what +is written down is what was observed. Where something was *not* verified it says +so. + +## What is there, per engine + +| Engine | Block | Container observed | Sources exposed | +| --- | --- | --- | --- | +| Google | "AI Overview" | `#m-x-content` | yes, with titles | +| Bing | generative answer | `li.b_ans.b_top.b_qnacdxcont` → `.gs_caphead_main` | yes, cards in `.gs_cit` | +| Brave | AI summary | `#chatllm-main-answer-content` | no | +| DuckDuckGo | none | — | — | + +DuckDuckGo is a genuine "none", not an unfinished check: the engine points at the +no-JS `html.duckduckgo.com` endpoint, which cannot render one. There is no +`.zci`/zero-click block on it either — that was checked directly. + +### Google + +The overview lives **outside `#search` and `#rso`**, above them. That was +verified (`rso.contains(node) === false`), and it means the current extractor +neither sees it nor is disturbed by it — no existing behaviour is at risk here. + +Structure of `#m-x-content`, on a query that had one: + +``` +#m-x-content + [jsname=txosbe] "AI Overview" ← the header + [jsname=HKDuG] the answer body ← also contains the citations + … answer prose + [role=dialog] "6 sites" + cards + "Show all" +``` + +Hooks, ranked by how much they can be trusted: + +- `#m-x-content` — an id, present on both loads. The most durable thing found. + **But see the trap below: the id alone is not sufficient.** +- `[role=heading]` with the exact text `AI Overview`, and + `[aria-label="Show more AI Overview"]` on the collapse control. Semantic, and + the natural anchor if the id ever moves. +- `[role=dialog]` around the citation carousel (`data-type=hovc`). +- Class names — **useless**, as everywhere else on Google. The answer body was + `.LT6XE` on one load and `.jloFI GkDqAd rJweXb` on the next, same query, + minutes apart. This is the same churn `engines.ts` already warns about. + +**Citations are the good part.** Anchors inside `#m-x-content` carry the source +title in `aria-label`, suffixed `". Opens in a new tab."`: + +``` +aria-label="Open source agentic startup LangChain hits $1.25B valuation | TechCrunch. Opens in a new tab." +href="https://techcrunch.com/2025/10/21/open-source-agentic-startup-langchain-hits-1-25b-valuation/" +``` + +Their `innerText` is empty — the visible label is an icon — so `aria-label` is +the only way to get a title. Links out directly, no redirector, so the existing +`unwrap: "none"` holds. Google's own hosts appear among them (a privacy-policy +link) and are already excluded by `selfHostPattern`. + +Two traps: + +1. **`#m-x-content` exists before the overview does, holding something else.** + Polling a fresh load at 250ms intervals caught it at 1502ms containing 28,864 + characters — approximately the whole SERP — and at 1752ms containing 142, then + growing to its real 903. So the id is reused by, or briefly wraps, a larger + shell. An extractor that reads it on sight will occasionally return the entire + page as the "AI answer". **Require the text to begin with `AI Overview`, or + anchor on the heading and climb, before trusting the node.** +2. **"Show more" is not hiding any of the answer.** Clicking it took the text + from 1124 to 1262 characters, and the 138 added were the disclaimer footer + ("Double-check important information… AI responses may include mistakes"). + The answer body is complete in the DOM while still visually truncated. So + there is no need to click anything — which is good, because clicking in a + browser a human is using is exactly what this package avoids. + +To render usefully, the extractor has to drop the `AI Overview` header line, the +`[role=dialog]` citation carousel, the "Show all" / "Dismiss" / "Learn how" +buttons and the disclaimer. Cleanest approach found: `cloneNode(true)`, remove +those by selector on the clone, take `innerText`. The page itself is never +mutated, which matters on a shared browser. + +### Bing + +``` +li.b_ans.b_top.b_qnacdxcont + .gs_caphead_main the answer prose ← clean, nothing else in it + .gs_cit_cont + .gs_cit source card: name, title, snippet + .gs_cit … + .cit_exp_cont "View all" +``` + +The `gs_` prefix ("generative search") is descriptive rather than hashed, and +`.gs_caphead_main` held the answer and *only* the answer — no header, no cards, +no disclaimer. The nicest of the three to extract. + +`li.b_ans` on its own is **not** a safe selector: "People also ask" is also a +`li.b_ans`. The discriminator is `b_qnacdxcont` on the `li`, or the presence of +`.gs_caphead_main` inside it. + +Citation anchors go through Bing's `/ck/a?…&u=a1…` redirector, so the existing +`unwrap: "bing"` already handles them — no new unwrapping needed. + +No URL change is needed: the answer appears on the plain +`bing.com/search?q=…` the engine already builds. + +### Brave + +`#chatllm-main-answer-content` contained the answer and nothing else — no +header, no disclaimer (that sits outside it, in `cite.chatllm-disclaimer`), no +citations. The wrapper is `#llm-snippet`, a `.snippet.standalone` sitting first +in `#results`. + +Worth noting: `engines.ts` already restricts Brave's results to +`.snippet[data-type="web"]` specifically to exclude this block. That filter +stays correct — the AI answer would be read separately, not as a result. + +No sources are exposed. The only anchors inside are `search.brave.com/ask?…` +follow-up prompts ("Elaborate", "Who are LangChain's main competitors?"), which +`selfHostPattern` already discards. There is a "+4 More" control that may reveal +sources; **not investigated** — it would need a click, and clicking was avoided. + +No URL change needed. + +## The two reasons this is not free + +### 1. Google's AI Overview requires giving up `udm=14` + +`udm` is Google's undocumented vertical selector — the parameter its own tab +strip writes. `udm=2` is Images, `udm=7` Videos, `udm=12` News, `udm=28` +Shopping, and `udm=14` is the "Web" tab added in May 2024: plain ranked links, +no AI Overview, no knowledge panel, no carousels. `engines.ts` sets it as +Google's default precisely for that cleanliness. + +So "no AI Overview" is not incidental to `udm=14`, it is part of what the Web tab +*is*. Every page where `#m-x-content` was found was a no-`udm` classic SERP. +Enabling overviews on Google means dropping `udm`. + +That is less alarming than it sounds: the engine **already** drops `udm` for any +time-limited search, because `udm=14` plus a date filter renders an empty page +(README, trap 2). Heading-mode extraction is therefore already exercised against +the classic layout. The cost is that the classic layout puts back all the +furniture — knowledge panels, "People also ask", carousels — that the extractor +then has to keep ignoring. + +### 2. They stream in after the results are ready, and are often absent + +Measured from navigation start, polling at 250ms via an `initScript`: + +| Engine | results parseable | AI answer appears | AI answer settles | +| --- | --- | --- | --- | +| Google | ~500ms | ~1500ms | ~2300ms | +| Brave | ~290ms | ~1260ms | **still growing at 5000ms** | +| Bing | ~520ms | — (absent on that query) | — | + +`search.ts` reads results and returns as soon as anything parses, retrying at +most twice at 700ms (`EXTRACT_RETRIES`, `EXTRACT_RETRY_DELAY_MS`) and breaking +the moment `results.length > 0`. In other words it returns roughly 2s before +Google's overview lands and 5s+ before Brave's finishes. **Capturing an AI answer +means deliberately waiting past the point where the useful part of the job is +already done.** + +And the wait is frequently wasted, because the blocks are query-dependent: + +- `how does postgres MVCC vacuum work` → **no** Google AI Overview at all, still + absent after 15s, in a foreground tab. (Checked in a foreground tab + specifically to rule out background-tab throttling as the cause — an earlier + `window.open` probe was discarded for that reason.) +- `who founded anthropic and when` → **no** Bing generative answer after 13.5s; + Bing served an ordinary big-Wikipedia card instead. +- `LangChain valuation Series C funding 2026` → all three produced one. + +There is no cheap way to know in advance which case you are in, so a fixed wait +pays the full cost on every query that was never going to have an answer. + +## The decision that was not taken + +Three shapes were on the table: + +1. **Opt-in `aiAnswer` parameter (the one that was going to be recommended).** + Default off: today's latency and today's `udm=14` layout, byte-identical + behaviour. When true: Google drops `udm`, and the probe polls until the text + stops growing or a budget (~6s) expires. Costs nothing unless asked for, and + the model can ask for it when the query is a question rather than a lookup. + Downside: another parameter on a tool that already has four, and the model has + to decide when to set it. +2. **Always on.** Simplest surface, no new parameter. Every search pays ~2s + (Google) to ~5s (Brave), much of it waiting for answers that never arrive, + against a 20s whole-call deadline (`SEARCH_TIMEOUT_MS`) that also has to cover + connect and navigate. +3. **Opportunistic, never wait.** Include an AI answer only if it is already + rendered when results are read. Zero added latency, but Google would + essentially never contribute one (`udm=14` stays), and Brave would usually be + caught mid-sentence — see the growth curve above. Risks putting a truncated, + confident-sounding half-answer in front of the model, which is worse than + putting none there. + +Unresolved either way: whether an AI answer belongs in the model's context at +all. It is a summary generated by another model from pages the agent could read +itself, it carries no provenance beyond its citations, and `promptGuidelines` +currently tells the model in plain terms not to treat a snippet as the page. +An AI answer invites exactly that confusion at greater length. If it goes in, it +should be labelled unmistakably as the engine's generated text — engine name +included, e.g. "Google AI Overview" — and never merged into the numbered results. + +## If you implement it + +- `ExtractionConfig` in `src/engines.ts` is the right place for the per-engine + selectors; it is already plain JSON crossing into the page. +- `PageProbe` in `src/extract.ts` gains an optional field; `SearchResult` should + **not** — an AI answer is not a hit and must not be numbered among them. +- The settle-poll belongs in the page script, not in round trips from + `search.ts`. One `Runtime.evaluate` that polls locally until the text stops + growing is one round trip; polling from the host is one per sample. +- `formatResults` in `src/format.ts` puts it above the numbered list. Mind the + budget note at the top of that file — an overview plus citations is another + 1-2KB on top of the 15KB worst case. +- Tests: `test/search-url.test.ts` is where a "Google drops `udm` when an AI + answer is wanted" assertion goes, next to the existing parameter-trap tests. + The extraction itself cannot be tested without a browser; the existing suite + does not try, and this should not either. +- Re-verify every selector before trusting it. Google's classes churned between + two loads minutes apart during this very investigation, and these blocks are + changing faster than the rest of the SERP. diff --git a/castle-search/package.json b/castle-search/package.json new file mode 100644 index 0000000..3e31124 --- /dev/null +++ b/castle-search/package.json @@ -0,0 +1,38 @@ +{ + "name": "pi-castle-cdp-search", + "version": "0.1.0", + "private": true, + "description": "Web search for pi through an already-running Chrome on the wire network, driven over CDP", + "keywords": [ + "pi-package", + "pi-extension", + "search", + "cdp", + "chrome" + ], + "license": "MIT", + "type": "module", + "engines": { + "node": ">=22.0.0" + }, + "files": [ + "src/", + "tsconfig.json", + "README.md" + ], + "pi": { + "extensions": [ + "./src/index.ts" + ] + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "node --experimental-strip-types --test test/*.test.ts" + }, + "devDependencies": { + "@earendil-works/pi-ai": "*", + "@earendil-works/pi-coding-agent": "*", + "typebox": "*", + "typescript": "^5.0.0" + } +} diff --git a/castle-search/src/cdp.ts b/castle-search/src/cdp.ts new file mode 100644 index 0000000..aa01b56 --- /dev/null +++ b/castle-search/src/cdp.ts @@ -0,0 +1,342 @@ +/** + * A minimal CDP client — just enough to open a page, navigate it, read the DOM, + * and close it again. + * + * Deliberately dependency-free: Node 22 ships a global `WebSocket`, so this + * needs no `ws`. That matters because an extension installed by `pi install` + * gets its own `node_modules`, and fewer moving parts there is fewer things to + * go wrong on a machine that is not the one it was written on. + * + * The browser is *not* ours. It is a shared Chrome someone may be looking at, + * recycled hourly (`me.soarez.chrome-cdp-recycle`). Two consequences run + * through this file: + * + * 1. The websocket URL is re-resolved from `/json/version` on every connect, + * never cached. Chrome re-mints its browser UUID on each launch, so a + * pinned ws:// URL breaks the first time the browser is recycled. + * 2. Every page this opens is created in the background and closed again, + * including on error paths, so a failed search does not leave tabs behind + * in someone else's window. + */ + +import { BrowserUnavailableError, SearchAbortedError, messageOf } from "./errors.ts"; +import type { CdpTarget } from "./endpoint.ts"; + +/** How long a single CDP command may take before the socket is presumed dead. */ +const COMMAND_TIMEOUT_MS = 15_000; +/** How long to wait for /json/version and for the websocket handshake. */ +const CONNECT_TIMEOUT_MS = 5_000; + +type CdpMessage = { + id?: number; + method?: string; + params?: Record; + sessionId?: string; + result?: Record; + error?: { code?: number; message?: string }; +}; + +type Pending = { + resolve: (value: Record) => void; + reject: (reason: Error) => void; + timer: ReturnType; +}; + +/** + * Reject if `signal` fires before `promise` settles, cleaning up the listener + * either way. Node's own abort-aware APIs are not available here — the + * websocket predates them — so aborts are raced in rather than plumbed through. + */ +export const raceAbort = (promise: Promise, signal: AbortSignal | undefined): Promise => { + if (!signal) return promise; + if (signal.aborted) return Promise.reject(abortError(signal)); + return new Promise((resolve, reject) => { + const onAbort = (): void => reject(abortError(signal)); + signal.addEventListener("abort", onAbort, { once: true }); + promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)); + }); +}; + +const abortError = (signal: AbortSignal): Error => { + const reason: unknown = signal.reason; + if (reason instanceof Error && reason.name === "TimeoutError") { + return new SearchAbortedError("search timed out"); + } + return new SearchAbortedError("search was cancelled"); +}; + +/** Ask the browser for its current websocket endpoint. Never cached — see above. */ +const queryWebSocketUrl = async (target: CdpTarget, signal?: AbortSignal): Promise => { + const url = `http://${target.host}:${target.port}/json/version`; + let payload: unknown; + try { + const res = await fetch(url, { + signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(CONNECT_TIMEOUT_MS)]) : AbortSignal.timeout(CONNECT_TIMEOUT_MS), + }); + if (!res.ok) { + throw new BrowserUnavailableError(`${url} answered HTTP ${res.status}`); + } + payload = await res.json(); + } catch (e) { + if (e instanceof BrowserUnavailableError) throw e; + if (signal?.aborted) throw abortError(signal); + throw new BrowserUnavailableError( + `No CDP endpoint answered at ${url} (${messageOf(e)}). Is the browser running and reachable on the overlay?`, + ); + } + const ws = (payload as Record | null)?.["webSocketDebuggerUrl"]; + if (typeof ws !== "string" || ws === "") { + throw new BrowserUnavailableError(`${url} answered without a webSocketDebuggerUrl`); + } + return ws; +}; + +/** A live browser-level CDP connection. */ +export class BrowserConnection { + #ws: WebSocket; + #nextId = 1; + #pending = new Map(); + #listeners = new Set<(msg: CdpMessage) => void>(); + #closedReason: string | null = null; + + readonly target: CdpTarget; + + private constructor(ws: WebSocket, target: CdpTarget) { + this.#ws = ws; + this.target = target; + + ws.addEventListener("message", (ev: MessageEvent) => { + let msg: CdpMessage; + try { + msg = JSON.parse(String(ev.data)) as CdpMessage; + } catch { + return; + } + if (msg.id !== undefined) { + const pending = this.#pending.get(msg.id); + if (!pending) return; + this.#pending.delete(msg.id); + clearTimeout(pending.timer); + if (msg.error) { + pending.reject(new BrowserUnavailableError(`CDP error: ${msg.error.message ?? "unknown"}`)); + } else { + pending.resolve(msg.result ?? {}); + } + return; + } + for (const listener of [...this.#listeners]) listener(msg); + }); + + const fail = (reason: string): void => { + this.#closedReason ??= reason; + for (const [, pending] of this.#pending) { + clearTimeout(pending.timer); + pending.reject(new BrowserUnavailableError(reason)); + } + this.#pending.clear(); + }; + ws.addEventListener("close", () => fail("CDP connection closed (the browser may have been recycled)")); + ws.addEventListener("error", () => fail("CDP connection failed")); + } + + /** Resolve the endpoint afresh and dial it. */ + static async connect(target: CdpTarget, signal?: AbortSignal): Promise { + const wsUrl = await queryWebSocketUrl(target, signal); + const ws = new WebSocket(wsUrl); + try { + await raceAbort( + new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new BrowserUnavailableError(`timed out opening ${wsUrl}`)), + CONNECT_TIMEOUT_MS, + ); + ws.addEventListener( + "open", + () => { + clearTimeout(timer); + resolve(); + }, + { once: true }, + ); + ws.addEventListener( + "error", + () => { + clearTimeout(timer); + reject(new BrowserUnavailableError(`could not open ${wsUrl}`)); + }, + { once: true }, + ); + }), + signal, + ); + } catch (e) { + try { + ws.close(); + } catch { + // Already failed; nothing useful to do with a second failure. + } + throw e; + } + return new BrowserConnection(ws, target); + } + + /** False once the socket has closed or failed — the reconnect trigger. */ + get isOpen(): boolean { + return this.#closedReason === null && this.#ws.readyState === 1 /* OPEN */; + } + + send(method: string, params: Record = {}, sessionId?: string): Promise> { + if (!this.isOpen) { + return Promise.reject(new BrowserUnavailableError(this.#closedReason ?? "CDP connection is not open")); + } + const id = this.#nextId++; + const payload: CdpMessage = sessionId ? { id, method, params, sessionId } : { id, method, params }; + return new Promise>((resolve, reject) => { + const timer = setTimeout(() => { + this.#pending.delete(id); + reject(new BrowserUnavailableError(`CDP command ${method} timed out after ${COMMAND_TIMEOUT_MS}ms`)); + }, COMMAND_TIMEOUT_MS); + this.#pending.set(id, { resolve, reject, timer }); + try { + this.#ws.send(JSON.stringify(payload)); + } catch (e) { + this.#pending.delete(id); + clearTimeout(timer); + reject(new BrowserUnavailableError(`could not send ${method}: ${messageOf(e)}`)); + } + }); + } + + /** Subscribe to unsolicited protocol events. Returns an unsubscribe function. */ + onEvent(listener: (msg: CdpMessage) => void): () => void { + this.#listeners.add(listener); + return () => this.#listeners.delete(listener); + } + + close(): void { + this.#closedReason ??= "CDP connection closed by this extension"; + this.#listeners.clear(); + try { + this.#ws.close(); + } catch { + // Closing an already-dead socket is not a failure worth reporting. + } + } +} + +/** + * One throwaway page. + * + * Created in the background so it does not steal focus from whoever is using + * the browser, and closed by {@link close} on every path. + */ +export class PageSession { + readonly #conn: BrowserConnection; + readonly #targetId: string; + readonly #sessionId: string; + #closed = false; + + private constructor(conn: BrowserConnection, targetId: string, sessionId: string) { + this.#conn = conn; + this.#targetId = targetId; + this.#sessionId = sessionId; + } + + static async open(conn: BrowserConnection, signal?: AbortSignal): Promise { + if (signal?.aborted) throw abortError(signal); + + // Deliberately NOT raced against the abort signal. raceAbort abandons the + // promise, it cannot cancel the command — and this command's side effect is + // a tab. Abandoning it would leave a tab open in a browser someone else is + // using, with nothing left holding its targetId to close it. It is a fast + // command already bounded by COMMAND_TIMEOUT_MS, so waiting it out costs + // little and guarantees we own whatever it created. + const created = await conn.send("Target.createTarget", { url: "about:blank", background: true }); + const targetId = created["targetId"]; + if (typeof targetId !== "string") { + throw new BrowserUnavailableError("Target.createTarget did not return a targetId"); + } + + // From here on the page exists, so every failure — including a late abort — + // must still close it. + try { + if (signal?.aborted) throw abortError(signal); + const attached = await raceAbort( + conn.send("Target.attachToTarget", { targetId, flatten: true }), + signal, + ); + const sessionId = attached["sessionId"]; + if (typeof sessionId !== "string") { + throw new BrowserUnavailableError("Target.attachToTarget did not return a sessionId"); + } + const page = new PageSession(conn, targetId, sessionId); + await raceAbort(conn.send("Page.enable", {}, sessionId), signal); + return page; + } catch (e) { + await conn.send("Target.closeTarget", { targetId }).catch(() => {}); + throw e; + } + } + + /** Navigate and wait for the load event, or for `signal` to fire. */ + async navigate(url: string, signal?: AbortSignal): Promise { + // Subscribed before navigating, so a page that loads faster than the + // Page.navigate reply cannot slip its load event past us. + let off: () => void = () => {}; + const loaded = new Promise((resolve) => { + off = this.#conn.onEvent((msg) => { + if (msg.sessionId === this.#sessionId && msg.method === "Page.loadEventFired") resolve(); + }); + }); + + try { + const nav = await raceAbort(this.#conn.send("Page.navigate", { url }, this.#sessionId), signal); + const errorText = nav["errorText"]; + if (typeof errorText === "string" && errorText !== "") { + throw new BrowserUnavailableError(`navigation to ${url} failed: ${errorText}`); + } + + try { + await raceAbort(loaded, signal); + } catch (e) { + // Stop the in-flight load so the page is not still fetching while we + // tear it down; the tab is closed either way, this just makes it quicker. + await this.#conn.send("Page.stopLoading", {}, this.#sessionId).catch(() => {}); + throw e; + } + } finally { + // Unsubscribing here rather than inside the listener: on the failure paths + // the listener never fires, and a subscription left on a connection that + // outlives many searches accumulates. + off(); + } + } + + /** Evaluate an expression in the page and return its value by value. */ + async evaluate(expression: string, signal?: AbortSignal): Promise { + const res = await raceAbort( + this.#conn.send( + "Runtime.evaluate", + { expression, returnByValue: true, awaitPromise: true }, + this.#sessionId, + ), + signal, + ); + const exception = res["exceptionDetails"] as { text?: string; exception?: { description?: string } } | undefined; + if (exception) { + const text = exception.exception?.description ?? exception.text ?? "unknown error"; + throw new BrowserUnavailableError(`page script failed: ${text}`); + } + return (res["result"] as { value?: T } | undefined)?.value as T; + } + + /** + * Close the tab. Idempotent and never throws: it runs on error paths, where a + * second failure would mask the one worth reporting. + */ + async close(): Promise { + if (this.#closed) return; + this.#closed = true; + await this.#conn.send("Target.closeTarget", { targetId: this.#targetId }).catch(() => {}); + } +} diff --git a/castle-search/src/endpoint.ts b/castle-search/src/endpoint.ts new file mode 100644 index 0000000..d3f4b0d --- /dev/null +++ b/castle-search/src/endpoint.ts @@ -0,0 +1,108 @@ +/** + * Which browser this extension searches through. + * + * Deliberately the *same* configuration as pi-browser-harness, so one decision + * governs both packages and they never drive different browsers in the same + * session: `BU_CDP_HTTP`, then the `/browser-target` file that harness writes, + * then the built-in castle default. + * + * Resolution is pure — no I/O — so it can be unit-tested and reported without + * touching the network. + */ + +/** Default CDP endpoint: castle's Chrome, exposed on the wg8 overlay. */ +export const DEFAULT_REMOTE_CDP = "10.88.0.25:9223"; + +/** Values of BU_CDP_HTTP that mean "ignore the default, use this machine". */ +const LOCAL_ALIASES = new Set(["local", "localhost", "off", "none", "0", "no"]); + +/** Port a local Chrome is expected to serve CDP on when the target is "local". */ +export const LOCAL_CDP_PORT = 9222; + +/** + * Where a target came from. "env" is BU_CDP_HTTP, "stored" is the harness's + * `/browser-target`, "default" is the built-in. + */ +export type CdpTargetSource = "env" | "stored" | "default"; + +export type CdpTarget = { + readonly host: string; + readonly port: number; + readonly source: CdpTargetSource; +}; + +export type CdpTargetResolution = + | { readonly kind: "ok"; readonly target: CdpTarget } + | { readonly kind: "invalid"; readonly raw: string; readonly reason: string; readonly source: CdpTargetSource }; + +/** + * Precedence: BU_CDP_HTTP, then the stored `/browser-target` choice, then the + * built-in default. The environment wins so a one-off `BU_CDP_HTTP=… pi` is + * never silently overridden by a choice made days ago. + * + * Unlike pi-browser-harness this never falls back from the default to a local + * browser on its own. The harness can fall back because it drives a browser the + * operator is watching; here a silent fallback would mean *searching from the + * operator's own signed-in Chrome* without saying so. When the configured + * endpoint is unreachable the caller reports that, and the operator can say + * `local` explicitly. + * + * `stored` is passed in rather than read here so this stays pure and synchronous. + */ +export const resolveCdpTarget = ( + env: NodeJS.ProcessEnv = process.env, + stored: string | null = null, +): CdpTargetResolution => { + const fromEnv = env["BU_CDP_HTTP"]?.trim(); + const fromStore = stored?.trim(); + + const hasEnv = fromEnv !== undefined && fromEnv !== ""; + const raw = hasEnv ? fromEnv : fromStore; + const source: CdpTargetSource = hasEnv ? "env" : "stored"; + + if (raw === undefined || raw === "") { + const parsed = parseHostPort(DEFAULT_REMOTE_CDP); + // Unreachable in practice: the constant above is covered by its own test. + if (!parsed) { + return { kind: "invalid", raw: DEFAULT_REMOTE_CDP, source: "default", reason: "built-in default is malformed" }; + } + return { kind: "ok", target: { ...parsed, source: "default" } }; + } + + if (LOCAL_ALIASES.has(raw.toLowerCase())) { + return { kind: "ok", target: { host: "127.0.0.1", port: LOCAL_CDP_PORT, source } }; + } + + const parsed = parseHostPort(raw); + if (!parsed) { + return { + kind: "invalid", + raw, + source, + reason: `expected "host:port" or one of ${[...LOCAL_ALIASES].join(", ")}`, + }; + } + return { kind: "ok", target: { ...parsed, source } }; +}; + +const parseHostPort = (value: string): { host: string; port: number } | null => { + const sep = value.lastIndexOf(":"); + if (sep === -1) return null; + const host = value.slice(0, sep).trim(); + const port = Number(value.slice(sep + 1).trim()); + if (!host) return null; + if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null; + return { host, port }; +}; + +const sourceLabel = (source: CdpTargetSource): string => + source === "env" ? "BU_CDP_HTTP" : source === "stored" ? "/browser-target" : "built-in default"; + +/** One-line description for progress messages and errors. */ +export const describeCdpTarget = (target: CdpTarget): string => + `${target.host}:${target.port} (${sourceLabel(target.source)})`; + +/** One-line description of a resolution failure. */ +export const describeResolutionFailure = ( + failure: Extract, +): string => `invalid CDP target "${failure.raw}" from ${sourceLabel(failure.source)} — ${failure.reason}`; diff --git a/castle-search/src/engine-store.ts b/castle-search/src/engine-store.ts new file mode 100644 index 0000000..d218d2b --- /dev/null +++ b/castle-search/src/engine-store.ts @@ -0,0 +1,81 @@ +/** + * Persistence for the `/search-engine` choice. + * + * Deliberately the same shape, and the same atomic write, as the harness's + * browser-target store: a sibling temp file plus rename, so a crash mid-write + * cannot leave a half-written engine name behind. Its own file rather than a + * shared settings blob, so a corrupt engine choice cannot cost anything else. + * + * Like the CDP target, the stored value is the raw string a user would have put + * in the environment variable ("ddg", "bing", …), not a pre-parsed id. One + * vocabulary, one resolution path in engine-target.ts, and a stored value can + * never mean something the variable could not. + * + * Every read failure degrades to "nothing stored" rather than throwing. + */ + +import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { dirname, join } from "node:path"; + +import { agentDir } from "./paths.ts"; + +const CURRENT_VERSION = 1; + +const engineFilePath = (): string => join(agentDir(), "castle-cdp-search-engine.json"); + +type EngineFile = { + readonly version: 1; + /** Raw CCS_SEARCH_ENGINE-style value, or null when cleared. */ + readonly engine: string | null; + readonly savedAt: string; +}; + +/** + * The persisted engine, or null when nothing is stored, the file is missing, or + * it cannot be parsed. A file written by a newer version is treated as "nothing + * stored" rather than guessed at. + */ +export const readStoredEngine = async (): Promise => { + let raw: string; + try { + raw = await readFile(engineFilePath(), "utf8"); + } catch { + return null; + } + try { + const parsed: unknown = JSON.parse(raw); + if (typeof parsed !== "object" || parsed === null) return null; + const file = parsed as Record; + if (file["version"] !== CURRENT_VERSION) return null; + const engine = file["engine"]; + if (typeof engine !== "string") return null; + const trimmed = engine.trim(); + return trimmed.length > 0 ? trimmed : null; + } catch { + return null; + } +}; + +const write = async (engine: string | null): Promise => { + const path = engineFilePath(); + const tmp = `${path}.${randomUUID()}.tmp`; + const payload: EngineFile = { version: CURRENT_VERSION, engine, savedAt: new Date().toISOString() }; + try { + await mkdir(dirname(path), { recursive: true }); + await writeFile(tmp, `${JSON.stringify(payload, null, 2)}\n`, "utf8"); + await rename(tmp, path); + } catch (e) { + await unlink(tmp).catch(() => {}); + throw new Error(`could not save search engine to ${path}: ${e instanceof Error ? e.message : String(e)}`); + } +}; + +/** Persist the chosen engine. */ +export const writeStoredEngine = (engine: string): Promise => write(engine); + +/** Clear the choice, restoring the built-in default. */ +export const clearStoredEngine = (): Promise => write(null); + +/** Exposed so the command can tell the user where the choice lives. */ +export const storedEngineLocation = (): string => engineFilePath(); diff --git a/castle-search/src/engine-target.ts b/castle-search/src/engine-target.ts new file mode 100644 index 0000000..db4d81f --- /dev/null +++ b/castle-search/src/engine-target.ts @@ -0,0 +1,79 @@ +/** + * Which search engine to use, resolved the same way the CDP host is: + * environment variable, then a persisted choice, then a built-in default. + * + * Pure — no I/O — so the `/search-engine` command can report the configured + * intent without touching disk twice, and so it is testable. + */ + +import { type EngineId, parseEngineId, engineAliases } from "./engines.ts"; + +/** Used when nothing else says otherwise. */ +export const DEFAULT_ENGINE: EngineId = "google"; + +/** The environment variable that pins the engine for one process. */ +export const ENGINE_ENV_VAR = "CCS_SEARCH_ENGINE"; + +export type EngineSource = "parameter" | "env" | "stored" | "default"; + +export type EngineResolution = + | { readonly kind: "ok"; readonly id: EngineId; readonly source: EngineSource } + | { readonly kind: "invalid"; readonly raw: string; readonly source: EngineSource }; + +/** + * Precedence: the per-call tool parameter, then `CCS_SEARCH_ENGINE`, then the + * `/search-engine` choice, then the built-in default. + * + * Note the tool parameter sits *above* the environment variable, which is the + * opposite of how the CDP target treats an explicit endpoint. That difference + * is deliberate. For the browser, an environment variable has to win, because + * quietly driving a different machine means automating the operator's own + * signed-in Chrome — a safety property. Choosing a different search engine has + * no equivalent hazard, and the ability to fall back to another engine when the + * first one is serving a captcha is the single most useful thing the agent can + * do with this tool. So the model is allowed to override the default; the + * operator sets what it starts from. + */ +export const resolveEngine = ( + parameter: string | null | undefined, + env: NodeJS.ProcessEnv = process.env, + stored: string | null = null, +): EngineResolution => { + const candidates: Array<{ raw: string; source: EngineSource }> = []; + + const fromParam = parameter?.trim(); + if (fromParam) candidates.push({ raw: fromParam, source: "parameter" }); + + const fromEnv = env[ENGINE_ENV_VAR]?.trim(); + if (fromEnv) candidates.push({ raw: fromEnv, source: "env" }); + + const fromStore = stored?.trim(); + if (fromStore) candidates.push({ raw: fromStore, source: "stored" }); + + for (const candidate of candidates) { + const id = parseEngineId(candidate.raw); + // An unparseable value is reported rather than skipped over. Falling + // through to the next source would mean a typo in CCS_SEARCH_ENGINE + // silently searches Google instead of saying so. + if (!id) return { kind: "invalid", raw: candidate.raw, source: candidate.source }; + return { kind: "ok", id, source: candidate.source }; + } + + return { kind: "ok", id: DEFAULT_ENGINE, source: "default" }; +}; + +const sourceLabel = (source: EngineSource): string => + source === "parameter" + ? "engine parameter" + : source === "env" + ? ENGINE_ENV_VAR + : source === "stored" + ? "/search-engine" + : "built-in default"; + +export const describeEngineSource = (source: EngineSource): string => sourceLabel(source); + +/** One-line description of a bad engine name, listing what would have worked. */ +export const describeEngineFailure = (failure: Extract): string => + `unknown search engine "${failure.raw}" from ${sourceLabel(failure.source)} — ` + + `expected one of ${engineAliases().join(", ")}`; diff --git a/castle-search/src/engines.ts b/castle-search/src/engines.ts new file mode 100644 index 0000000..ef8baef --- /dev/null +++ b/castle-search/src/engines.ts @@ -0,0 +1,229 @@ +/** + * The search engines this extension knows how to drive. + * + * Every selector and every URL parameter below was read off the real SERP in + * castle's Chrome, not recalled or inferred. That is not pedantry: Google's own + * Tools menu writes `tbs=qdr:*`, which renders an *empty* page on that profile, + * while the undocumented-looking `as_qdr=*` works. Anything in here that was not + * observed is a bug waiting to be reported as "no results". + * + * Two extraction modes, because the engines genuinely differ: + * + * - "items" — the SERP has a clean per-result container (`li.b_algo`, + * `.result`, `.snippet[data-type=web]`). Straightforward. + * - "headings" — Google has no stable result container, so results are found + * from each

outward. Kept as its own mode rather than + * forced into the item shape, because it is the one that has + * been through the most verification. + */ + +export type EngineId = "google" | "duckduckgo" | "bing" | "brave"; + +export type Recency = "day" | "week" | "month" | "year"; + +export const RECENCY_VALUES = ["day", "week", "month", "year"] as const; + +export const ENGINE_IDS: readonly EngineId[] = ["google", "duckduckgo", "bing", "brave"]; + +/** Aliases accepted from humans and from the model. */ +const ENGINE_ALIASES: Record = { + google: "google", + g: "google", + duckduckgo: "duckduckgo", + ddg: "duckduckgo", + duck: "duckduckgo", + bing: "bing", + b: "bing", + brave: "brave", +}; + +/** + * How the in-page script should read one engine's results. Passed into the + * browser as JSON, so everything here must be plain data. + */ +export type ExtractionConfig = { + mode: "items" | "headings"; + /** Results container candidates, first match wins. */ + roots: string[]; + /** "items" mode: one result. */ + item?: string; + /** Anchor carrying the outbound link, relative to the item. */ + link?: string; + /** Title element, relative to the item. Falls back to the anchor's text. */ + title?: string; + /** Description element, relative to the item. */ + snippet?: string; + /** + * "items" mode with no snippet selector: text from these is subtracted from + * the item's text to leave the description behind. + */ + subtract?: string[]; + /** Items matching any of these are ads or non-web cards, and are skipped. */ + exclude?: string[]; + /** How outbound links are wrapped, if they are. */ + unwrap: "none" | "ddg" | "bing"; + /** Hosts belonging to the engine itself; links to them are not results. */ + selfHostPattern: string; +}; + +export type EngineDefinition = { + readonly id: EngineId; + readonly label: string; + /** Human-facing note about what makes this engine worth choosing. */ + readonly note: string; + /** + * Recency windows this engine can actually express, mapped to the parameter + * value. A window that is absent is one the engine does not support — never + * one that is silently dropped. + */ + readonly recency: Partial>; + readonly buildUrl: (query: string, numResults: number, recency: Recency | undefined) => string; + readonly extraction: ExtractionConfig; +}; + +const GOOGLE: EngineDefinition = { + id: "google", + label: "Google", + note: "best result quality; blocks aggressively under repeated automated queries", + recency: { day: "d", week: "w", month: "m", year: "y" }, + buildUrl: (query, numResults, recency) => { + const params = new URLSearchParams({ q: query, num: String(numResults), hl: "en" }); + // `udm=14` is the plain "Web" tab: no AI overview, no carousels. But any + // date restriction combined with it renders an empty page, and `tbs=qdr:*` + // renders an empty page on its own — both observed. So a time-limited + // search drops udm and uses the older as_qdr instead. + if (recency) params.set("as_qdr", GOOGLE.recency[recency] as string); + else params.set("udm", "14"); + return `https://www.google.com/search?${params.toString()}`; + }, + extraction: { + mode: "headings", + roots: ["#rso", "#search"], + unwrap: "none", + selfHostPattern: String.raw`^https?://(www\.)?google\.[a-z.]+/`, + }, +}; + +const DUCKDUCKGO: EngineDefinition = { + id: "duckduckgo", + label: "DuckDuckGo", + note: "no-JS endpoint, the most stable markup here and the least likely to challenge", + // Read off DuckDuckGo's own