pi-chrome-search 2.1.0 → 2.2.0

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.
package/README.md CHANGED
@@ -9,8 +9,8 @@
9
9
 
10
10
  Web search and page reading for [pi](https://pi.dev), through your own visible Chrome. Same profile,
11
11
  cookies and IP. Google, DuckDuckGo and Yandex return compact Markdown and their native AI summary when
12
- there is one; Avito listings (price, location, age) are available opt-in. No keys, no paid APIs, no
13
- headless mode, no fingerprint spoofing. Node 26+, Chrome 136+.
12
+ there is one; Avito listings (price, location, age) and Ozon goods (price, rating) are available opt-in.
13
+ No keys, no paid APIs, no headless mode, no fingerprint spoofing. Node 26+, Chrome 136+.
14
14
 
15
15
  ## Install
16
16
 
@@ -32,7 +32,7 @@ The window stays visible. The extension attaches to it and never launches, resta
32
32
  <!-- tools:start -->
33
33
  | Tool | Exposure | Arguments |
34
34
  |---|---|---|
35
- | `web_search` | direct | `q` string; `n?` integer 1..10; `engines?` "auto" or ("google" or "duckduckgo" or "yandex" or "avito") or list of ("google" or "duckduckgo" or "yandex" or "avito") 1..4; `summary?` boolean; `page?` integer >=1; `format?` "md" or "json" |
35
+ | `web_search` | direct | `q` string; `n?` integer 1..10; `engines?` "auto" or ("google" or "duckduckgo" or "yandex" or "avito" or "ozon") or list of ("google" or "duckduckgo" or "yandex" or "avito" or "ozon") 1..5; `summary?` boolean; `page?` integer >=1; `format?` "md" or "json" |
36
36
  | `web_read` | direct | `url` string; `offset?` integer >=0; `maxChars?` integer >=1; `format?` "md" or "text" |
37
37
  | `image_search` | deferred | `q` string; `n?` integer 1..12; `engine?` "google" or "yandex"; `attach?` boolean or "bytes" |
38
38
  | `web_research` | deferred | `q` string; `budget?` "quick" or "normal" or "deep" |
@@ -40,14 +40,14 @@ The window stays visible. The extension attaches to it and never launches, resta
40
40
  <!-- tools:end -->
41
41
 
42
42
  A call has one 60 second deadline. DuckDuckGo has no pagination: `page > 1` is reported as
43
- `ignored.page`; Avito has no AI block: `summary` is reported as `ignored.summary`. Every unresolved
44
- link stays marked `unresolved`, and card facts (price/availability/rating/location) render on their
45
- own line after the snippet.
46
-
47
- `engines: "auto"` only ever means Google → DuckDuckGo → Yandex. Avito is a *special* engine: it is off
48
- by default and reachable only by naming it. To turn it on, set `engines.avito.enabled` to `true` (and
49
- optionally `engines.avito.location`, a region slug such as `kaluga` or `all`) in
50
- `~/.pi/agent/web-search.json` — ask your agent to do it, that is the intended path.
43
+ `ignored.page`; neither marketplace has an AI block, so `summary` is reported as `ignored.summary`. Every
44
+ unresolved link stays marked `unresolved`, and card facts (price/availability/rating/location) render on
45
+ their own line after the snippet.
46
+
47
+ `engines: "auto"` only ever means Google → DuckDuckGo → Yandex. Avito and Ozon are *special* engines:
48
+ off by default and reachable only by naming them. To turn one on, set `engines.avito.enabled` or
49
+ `engines.ozon.enabled` to `true` (Avito also takes `engines.avito.location`, a region slug such as
50
+ `kaluga` or `all`) in `~/.pi/agent/web-search.json` — ask your agent to do it, that is the intended path.
51
51
 
52
52
  ## Limits
53
53
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "pi-chrome-search",
3
- "version": "2.1.0",
4
- "description": "Free, keyless web search through the user's own visible Chrome (Google, DuckDuckGo, Yandex, and opt-in Avito listings) for pi",
3
+ "version": "2.2.0",
4
+ "description": "Free, keyless web search through the user's own visible Chrome (Google, DuckDuckGo, Yandex, and opt-in Avito/Ozon listings) for pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "pi": {
@@ -46,7 +46,8 @@
46
46
  "google",
47
47
  "duckduckgo",
48
48
  "yandex",
49
- "avito"
49
+ "avito",
50
+ "ozon"
50
51
  ],
51
52
  "files": [
52
53
  "index.ts",
@@ -63,11 +63,24 @@ export interface AvitoConfig {
63
63
  location: string;
64
64
  }
65
65
 
66
+ export interface OzonConfig {
67
+ /**
68
+ * OFF by default (SPEC §15 D14), for the same reason as Avito: a marketplace
69
+ * is a special engine and a fresh install must not visit it by itself.
70
+ *
71
+ * There is no `location`: Ozon's region is a cookie-backed UI choice, not a
72
+ * URL parameter, so a config key for it would be a key that cannot work
73
+ * (S7.5).
74
+ */
75
+ enabled: boolean;
76
+ }
77
+
66
78
  export interface EnginesConfig {
67
79
  google: GoogleConfig;
68
80
  duckduckgo: DuckDuckGoConfig;
69
81
  yandex: YandexConfig;
70
82
  avito: AvitoConfig;
83
+ ozon: OzonConfig;
71
84
  }
72
85
 
73
86
  export type PacingWindow = [number, number];
@@ -76,8 +89,9 @@ export interface PacingConfig {
76
89
  google: PacingWindow;
77
90
  duckduckgo: PacingWindow;
78
91
  yandex: PacingWindow;
79
- /** Slowest window: Avito is the most aggressive of the four about automation. */
92
+ /** Slowest windows: both marketplaces are aggressive about automation. */
80
93
  avito: PacingWindow;
94
+ ozon: PacingWindow;
81
95
  }
82
96
 
83
97
  export interface SearchConfig {
@@ -149,8 +163,15 @@ export const DEFAULT_CONFIG: Config = {
149
163
  duckduckgo: { enabled: true, kl: "auto" },
150
164
  yandex: { enabled: true, lr: "auto" },
151
165
  avito: { enabled: false, location: "all" },
166
+ ozon: { enabled: false },
167
+ },
168
+ pacing: {
169
+ google: [2500, 5000],
170
+ yandex: [5000, 9000],
171
+ duckduckgo: [2000, 4000],
172
+ avito: [6000, 12000],
173
+ ozon: [6000, 12000],
152
174
  },
153
- pacing: { google: [2500, 5000], yandex: [5000, 9000], duckduckgo: [2000, 4000], avito: [6000, 12000] },
154
175
  search: {
155
176
  budgetMs: 60000,
156
177
  n: 5,
package/src/config/doc.ts CHANGED
@@ -30,10 +30,12 @@ const CONFIG_DOCS: Readonly<Record<string, string>> = {
30
30
  "engines.yandex.lr": "`lr`; `auto` omits it.",
31
31
  "engines.avito.enabled": "Use the Avito marketplace engine (special: only an explicit `engines: \"avito\"` reaches it, `auto` never does). Off by default.",
32
32
  "engines.avito.location": "Region path slug in the Avito URL (`all`, `moskva`, `kaluga`), not a display name.",
33
+ "engines.ozon.enabled": "Use the Ozon marketplace engine (special: only an explicit `engines: \"ozon\"` reaches it, `auto` never does). Off by default.",
33
34
  "pacing.google": "Min/max gap in ms between Google searches.",
34
35
  "pacing.duckduckgo": "Min/max gap in ms between DuckDuckGo searches.",
35
36
  "pacing.yandex": "Min/max gap in ms between Yandex searches.",
36
37
  "pacing.avito": "Min/max gap in ms between Avito searches.",
38
+ "pacing.ozon": "Min/max gap in ms between Ozon searches.",
37
39
  "search.budgetMs": "Whole-call deadline in ms; pacing, settle, AI wait and link resolution draw from it (S8.1).",
38
40
  "search.n": "Default result count.",
39
41
  "search.nMax": "Hard ceiling for `n`; never above 10.",
@@ -55,6 +55,7 @@ export const CONFIG_SPEC: Spec = {
55
55
  duckduckgo: { kind: "object", fields: { enabled: BOOL, kl: STRING_NE } },
56
56
  yandex: { kind: "object", fields: { enabled: BOOL, lr: STRING_NE } },
57
57
  avito: { kind: "object", fields: { enabled: BOOL, location: STRING_NE } },
58
+ ozon: { kind: "object", fields: { enabled: BOOL } },
58
59
  },
59
60
  },
60
61
  pacing: {
@@ -64,6 +65,7 @@ export const CONFIG_SPEC: Spec = {
64
65
  duckduckgo: { kind: "tuple", items: [NUM(0), NUM(0)] },
65
66
  yandex: { kind: "tuple", items: [NUM(0), NUM(0)] },
66
67
  avito: { kind: "tuple", items: [NUM(0), NUM(0)] },
68
+ ozon: { kind: "tuple", items: [NUM(0), NUM(0)] },
67
69
  },
68
70
  },
69
71
  search: {
@@ -23,6 +23,7 @@ import { resolveConfigPath } from "../config/env.ts";
23
23
  import { avitoEngine } from "./avito.ts";
24
24
  import { duckduckgoEngine } from "./duckduckgo.ts";
25
25
  import { googleEngine } from "./google.ts";
26
+ import { ozonEngine } from "./ozon.ts";
26
27
  import { yandexEngine } from "./yandex.ts";
27
28
  import { WebSearchError } from "../runtime/error-codes.ts";
28
29
  import {
@@ -49,6 +50,7 @@ export const DEFAULT_ENGINES: EngineMap = Object.freeze({
49
50
  duckduckgo: duckduckgoEngine,
50
51
  yandex: yandexEngine,
51
52
  avito: avitoEngine,
53
+ ozon: ozonEngine,
52
54
  });
53
55
 
54
56
  /**
@@ -0,0 +1,493 @@
1
+ /**
2
+ * Ozon adapter (SPEC S6.5, §15 D14) — the second *special* engine: marketplace
3
+ * goods for one site, reachable only by naming it (`engines: "ozon"`).
4
+ *
5
+ * What the live SERP actually gives us (captured 2026-11-16 on the owner's
6
+ * profile; fixtures `tests/fixtures/ozon-serp.html.gz` and
7
+ * `ozon-no-match.html.gz` are the results area of those pages):
8
+ *
9
+ * - `https://www.ozon.ru/search/?text=…` answers with a *semantic redirect* to
10
+ * `/<category-slug>/?text=…` when Ozon predicts a catalog. Both shapes render
11
+ * the same grid, so one URL builder covers them and the landed URL is not
12
+ * evidence of a failed search. `page=N` survives the redirect (verified on a
13
+ * `page=2` navigation: a different product set came back).
14
+ * - A card is `.tile-root[data-index]`. The product link is the anchor that
15
+ * wraps the title; the image anchor carries the same href, so the title
16
+ * anchor is resolved from the title node instead of by position.
17
+ * - `span.tsBody500Medium` is the title, `span.tsHeadline500Medium` the visible
18
+ * price ("31 209 ₽"), `span.tsBodyControl300XSmall` the score-then-count pair
19
+ * ("4.7", "65 отзывов"). Those `ts*` tokens are Ozon's design-system
20
+ * typography, not hashed CSS-module names (`q4b1_6_0-a`), which is what makes
21
+ * them usable as markers at all.
22
+ * - A card carries no description, so `snippet` is empty on purpose: an Ozon
23
+ * tile has price and rating, not prose, and inventing a snippet from badges
24
+ * ("Чёрная пятница", "Стало дешевле") would be a lie with formatting.
25
+ * - A no-match query is answered with recommendations under the headline
26
+ * "Ничего не нашлось" (statusWidget). The cards are real, they just do not
27
+ * answer the query, so they are returned under an authored `notice` (S7.6).
28
+ * - The home page renders 20 `.tile-root` cards of its own, so a bare card
29
+ * selector would let the typed warm-up settle on the home page and read a
30
+ * carousel as results. The gate is therefore the *results* chrome
31
+ * (`searchResultsV2`/`searchResultsSort`/`statusWidget`), which the home page
32
+ * does not have (measured on the capture).
33
+ *
34
+ * Extraction is a self-contained in-page function (same `toString()` rule as the
35
+ * other adapters): live code sends `(${extractFromDocument})(document, arg)`
36
+ * through `Runtime.evaluate`, tests run the *same* source through `runInPage` in
37
+ * a `node:vm` context.
38
+ */
39
+
40
+ import type { CdpPage } from "../cdp/types.ts";
41
+ import { waitForMarker } from "../cdp/humanize.ts";
42
+ import { asFacts } from "../extract/facts.ts";
43
+ import { normalizeUrl } from "../extract/urls.ts";
44
+ import { fail } from "../runtime/errors.ts";
45
+ import type { Clock } from "../runtime/types.ts";
46
+ import type {
47
+ Engine,
48
+ EngineInteraction,
49
+ Query,
50
+ RawSerp,
51
+ SerpItem,
52
+ Wall,
53
+ } from "./types.ts";
54
+
55
+ /** A server-rendered page that hydrates a large client bundle; 12 s is generous. */
56
+ export const OZON_SETTLE_DEADLINE_MS = 12_000;
57
+ const SETTLE_POLL_MS = 200;
58
+
59
+ /**
60
+ * Readiness gate. The two observed markers are the results chrome:
61
+ *
62
+ * - `searchResultsSort` — the sort/filter bar of a catalog-shaped result page
63
+ * (every captured search landed on one of these);
64
+ * - `statusWidget` — the notice slot a zero-match search renders instead of a
65
+ * list, so "no exact match" settles too and is reported as a notice instead of
66
+ * burning the deadline.
67
+ *
68
+ * `searchResultsV2` is *anticipated, never observed*: it is the widget name of the
69
+ * plain `/search/?text=` result list, and every capture of 2026-11-16 was
70
+ * redirected to a category page. It costs one alternation to keep, and without it
71
+ * a non-redirected search list would time out instead of extracting. The canaries
72
+ * report its count, so a layout that uses it says so.
73
+ *
74
+ * The captcha half exists for the same reason Google keeps `#captcha-form` next
75
+ * to `#rso`: a wall page has no results chrome, so without it the settle would
76
+ * spend its whole deadline *before* `detectWall()` can report the wall it is
77
+ * looking at (S8.5).
78
+ */
79
+ export const OZON_CAPTCHA_SELECTOR =
80
+ '#captcha, .h-captcha, #h-captcha, iframe[src*="captcha"], form[action*="captcha"], [class*="captcha"]';
81
+ export const OZON_READY_SELECTOR = `[data-widget="searchResultsV2"], [data-widget="searchResultsSort"], [data-widget="statusWidget"], ${OZON_CAPTCHA_SELECTOR}`;
82
+ export const OZON_TILE_SELECTOR = ".tile-root";
83
+
84
+ const BOX_SELECTOR = 'input[name="text"]';
85
+
86
+ /**
87
+ * Typed-search profile. The box is `maxlength="255"` (captured), so a longer
88
+ * query is never typed — a truncated query would search for something the user
89
+ * did not ask for (the caller falls back to the pinned SERP URL instead).
90
+ */
91
+ const TYPE_PROFILE = Object.freeze({
92
+ box: BOX_SELECTOR,
93
+ maxChars: 255,
94
+ keyDelayMs: Object.freeze([30, 70] as const),
95
+ });
96
+
97
+ const INTERACTION: EngineInteraction = Object.freeze({
98
+ homeUrl: "https://www.ozon.ru/",
99
+ homeHosts: Object.freeze(["ozon.ru"]),
100
+ boxSelectors: Object.freeze([BOX_SELECTOR, '[data-widget="searchBarDesktop"] input']),
101
+ marker: "",
102
+ selector: OZON_READY_SELECTOR,
103
+ minCount: 1,
104
+ typeProfile: TYPE_PROFILE,
105
+ });
106
+
107
+ /**
108
+ * Wall markers (S9.3). Ozon's block page could not be captured: reaching it
109
+ * means provoking the firewall, which the hard rules forbid, and a fixture
110
+ * written from memory would be a claim, not evidence. So this list is
111
+ * *defensive* and text-first, corroborated exactly like the other adapters (a
112
+ * phrase alone is not a wall — a product title may quote it, but a wall has no
113
+ * cards). `docs/engines.md` says so in the same words.
114
+ */
115
+ const CAPTCHA_URL_MARKERS: readonly string[] = Object.freeze(["/captcha", "/blocked"]);
116
+ const CAPTCHA_TITLE_MARKERS: readonly string[] = Object.freeze([
117
+ "Доступ ограничен",
118
+ "Access denied",
119
+ "Request blocked",
120
+ ]);
121
+ const CAPTCHA_TEXT_MARKERS: readonly string[] = Object.freeze([
122
+ "Подтвердите, что вы не робот",
123
+ "проверка на робота",
124
+ "Доступ ограничен",
125
+ "Ограниченный доступ",
126
+ "Access denied",
127
+ "Too many requests",
128
+ ]);
129
+ const TILE_COUNT_EXPRESSION = `document.querySelectorAll(${JSON.stringify(OZON_TILE_SELECTOR)}).length`;
130
+ // ---------------------------------------------------------------------------
131
+ // In-page extraction (self-contained: no imports, no closures)
132
+ // ---------------------------------------------------------------------------
133
+
134
+ export interface OzonExtractedItem {
135
+ title: string;
136
+ url: string;
137
+ snippet: string;
138
+ facts: string[];
139
+ }
140
+
141
+ export interface OzonExtraction {
142
+ results: OzonExtractedItem[];
143
+ /** True when the page carried more cards than were returned. */
144
+ pageCarried: boolean;
145
+ /**
146
+ * Text of the notice headline the page rendered instead of a result list
147
+ * ("Ничего не нашлось" on the capture). Empty on a normal SERP.
148
+ *
149
+ * The adapter reports its *presence* as a no-match notice; it never keys on the
150
+ * words, because a locale or an A/B test may change them and a wrong-match is
151
+ * worse than a missing one.
152
+ */
153
+ headline: string;
154
+ }
155
+
156
+ export interface OzonExtractionArg {
157
+ n: number;
158
+ }
159
+
160
+ /**
161
+ * One-off in-page extractor. Everything it needs lives inside the body, because
162
+ * only its `toString()` crosses the CDP boundary.
163
+ */
164
+ export function extractFromDocument(doc: Document, arg: OzonExtractionArg): OzonExtraction {
165
+ const WHITESPACE = /[\s\u00a0\u202f]+/g;
166
+ const normalize = (value: string | null | undefined): string =>
167
+ (value === null || value === undefined ? "" : value).replace(WHITESPACE, " ").trim();
168
+
169
+ const base = doc.baseURI !== "" ? doc.baseURI : doc.URL;
170
+
171
+ /**
172
+ * http(s) only. A product link is its *path*: every query parameter Ozon
173
+ * attaches (`at`, `avtc`, `avts`, …) is attribution or session state, and the
174
+ * link the user clicks is the clean one (S7.4). Other links keep their query,
175
+ * because there the parameters may be the destination.
176
+ */
177
+ const toHttpUrl = (raw: string): string | null => {
178
+ const trimmed = raw.trim();
179
+ if (trimmed === "") return null;
180
+ let parsed: URL;
181
+ try {
182
+ parsed = new URL(trimmed, base === "" ? undefined : base);
183
+ } catch {
184
+ return null;
185
+ }
186
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
187
+ if (parsed.pathname.indexOf("/product/") === 0) parsed.search = "";
188
+ parsed.hash = "";
189
+ return parsed.href;
190
+ };
191
+
192
+ const textOf = (node: Element | null): string => (node === null ? "" : normalize(node.textContent));
193
+
194
+ const limit =
195
+ typeof arg.n === "number" && Number.isFinite(arg.n) ? Math.max(0, Math.floor(arg.n)) : 0;
196
+
197
+ const bodyText = normalize(doc.body === null ? "" : doc.body.textContent);
198
+ if (bodyText === "") return { results: [], pageCarried: false, headline: "" };
199
+
200
+ /**
201
+ * A zero-match search keeps its result chrome and replaces the grid with a
202
+ * status notice. The headline is only *reported* here; the meaning is the
203
+ * adapter's own constant (S7.6).
204
+ */
205
+ const headline = textOf(doc.querySelector('[data-widget="statusWidget"] .tsHeadline800XxLarge'));
206
+
207
+ const results: OzonExtractedItem[] = [];
208
+ const seenUrls: { [url: string]: boolean } = {};
209
+ let cards = 0;
210
+
211
+ for (const card of Array.from(doc.querySelectorAll(".tile-root"))) {
212
+ const titleNode = card.querySelector("span.tsBody500Medium");
213
+ const title = textOf(titleNode);
214
+ if (title === "") continue;
215
+ const anchor = titleNode === null ? null : titleNode.closest("a[href]");
216
+ const href = anchor === null ? null : anchor.getAttribute("href");
217
+ if (href === null || href === "") continue;
218
+ const url = toHttpUrl(href);
219
+ if (url === null) continue;
220
+ cards += 1;
221
+ if (seenUrls[url] === true) continue;
222
+ seenUrls[url] = true;
223
+ if (results.length >= limit) continue;
224
+
225
+ const facts: string[] = [];
226
+ const price = textOf(card.querySelector("span.tsHeadline500Medium"));
227
+ if (price !== "") facts.push(price);
228
+ /**
229
+ * Score then review count, both `tsBodyControl300XSmall`. Which one is which
230
+ * is decided by *shape* (a leaf that is only a number is the score; the
231
+ * other node is copied whole, whatever language it is in), never by the
232
+ * word for "reviews" (S7.7).
233
+ */
234
+ let rating = "";
235
+ let reviews = "";
236
+ for (const node of Array.from(card.querySelectorAll("span.tsBodyControl300XSmall"))) {
237
+ const text = textOf(node);
238
+ if (text === "") continue;
239
+ if (rating === "" && /^\d+(?:[.,]\d+)?$/.test(text)) {
240
+ rating = text;
241
+ continue;
242
+ }
243
+ if (reviews === "") reviews = text;
244
+ }
245
+ if (rating !== "") facts.push(rating);
246
+ if (reviews !== "") facts.push(reviews);
247
+
248
+ results.push({ title, url, snippet: "", facts });
249
+ }
250
+
251
+ return { results, pageCarried: cards > results.length, headline };
252
+ }
253
+
254
+ // ---------------------------------------------------------------------------
255
+ // Selector canaries (self-contained, same toString() rule)
256
+ // ---------------------------------------------------------------------------
257
+
258
+ export function canaryCounts(doc: Document): Record<string, number> {
259
+ const SELECTORS = [
260
+ ".tile-root",
261
+ '[data-widget="tileGridDesktop"]',
262
+ '[data-widget="searchResultsV2"]',
263
+ '[data-widget="searchResultsSort"]',
264
+ '[data-widget="statusWidget"]',
265
+ "span.tsBody500Medium",
266
+ "span.tsHeadline500Medium",
267
+ "span.tsBodyControl300XSmall",
268
+ ];
269
+ const counts: Record<string, number> = {};
270
+ for (const selector of SELECTORS) {
271
+ counts[selector] = doc.querySelectorAll(selector).length;
272
+ }
273
+ return counts;
274
+ }
275
+
276
+ /**
277
+ * 1 when the document carries a captcha widget, 0 otherwise. A JS scan instead
278
+ * of a CSS selector because the class test must be case-insensitive and
279
+ * `[attr*="captcha" i]` is not portable across the DOM implementations the
280
+ * offline harness uses.
281
+ */
282
+ export function captchaNodeCount(doc: Document): number {
283
+ if (doc.querySelector('#captcha, #h-captcha, iframe[src*="captcha"], form[action*="captcha"]') !== null) {
284
+ return 1;
285
+ }
286
+ for (const node of Array.from(doc.querySelectorAll("[class]"))) {
287
+ const className = node.getAttribute("class") ?? "";
288
+ if (className.toLowerCase().indexOf("captcha") !== -1) return 1;
289
+ }
290
+ return 0;
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // Result validation (TS side: the page is untrusted even when we wrote the code)
295
+ // ---------------------------------------------------------------------------
296
+
297
+ function isRecord(value: unknown): value is Record<string, unknown> {
298
+ return typeof value === "object" && value !== null && !Array.isArray(value);
299
+ }
300
+
301
+ function parseFailure(message: string): Error {
302
+ return fail("E_PARSE", "extract", {
303
+ engine: "ozon",
304
+ message,
305
+ hint: "the Ozon page returned an unexpected shape; run /web-doctor and inspect the artifact",
306
+ });
307
+ }
308
+
309
+ function asExtraction(value: unknown): OzonExtraction {
310
+ if (!isRecord(value)) throw parseFailure("in-page extractor returned no object");
311
+ const rawResults = value.results;
312
+ if (!Array.isArray(rawResults)) throw parseFailure("in-page extractor returned no results array");
313
+
314
+ const results: OzonExtractedItem[] = [];
315
+ const seenUrls = new Set<string>();
316
+ for (const rawItem of rawResults) {
317
+ if (!isRecord(rawItem)) throw parseFailure("in-page extractor returned a malformed result");
318
+ const { title, url, snippet } = rawItem;
319
+ if (typeof title !== "string" || typeof url !== "string" || typeof snippet !== "string") {
320
+ throw parseFailure("in-page extractor returned a result with non-string fields");
321
+ }
322
+ if (title === "") continue;
323
+ // Second, TS-side hygiene pass: the in-page copy cannot import `urls.ts`.
324
+ const normalized = normalizeUrl(url);
325
+ if (normalized === null || seenUrls.has(normalized)) continue;
326
+ seenUrls.add(normalized);
327
+ results.push({
328
+ title,
329
+ url: normalized,
330
+ snippet,
331
+ facts: asFacts(rawItem.facts),
332
+ });
333
+ }
334
+
335
+ return {
336
+ results,
337
+ pageCarried: value.pageCarried === true,
338
+ headline: typeof value.headline === "string" ? value.headline : "",
339
+ };
340
+ }
341
+
342
+ function asCanaries(value: unknown): Record<string, number> {
343
+ const counts: Record<string, number> = {};
344
+ if (!isRecord(value)) return counts;
345
+ for (const [selector, count] of Object.entries(value)) {
346
+ if (typeof count === "number" && Number.isFinite(count)) counts[selector] = count;
347
+ }
348
+ return counts;
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // Settle / wall
353
+ // ---------------------------------------------------------------------------
354
+
355
+ export interface OzonSettleOptions {
356
+ signal?: AbortSignal;
357
+ /** Test/live knob; defaults to 12 s. */
358
+ deadlineMs?: number;
359
+ /** Test/live knob; defaults to 200 ms plus humanize jitter. */
360
+ pollMs?: number;
361
+ clock?: Clock;
362
+ rng?: () => number;
363
+ }
364
+
365
+ /** Bounded settle on the structural gate; abort/timeout use the shared taxonomy. */
366
+ export async function settleOzon(page: CdpPage, options: OzonSettleOptions = {}): Promise<void> {
367
+ await waitForMarker(page, {
368
+ marker: INTERACTION.marker,
369
+ selector: INTERACTION.selector,
370
+ minCount: INTERACTION.minCount ?? 1,
371
+ deadlineMs: options.deadlineMs ?? OZON_SETTLE_DEADLINE_MS,
372
+ pollMs: options.pollMs ?? SETTLE_POLL_MS,
373
+ ...(options.clock === undefined ? {} : { clock: options.clock }),
374
+ ...(options.rng === undefined ? {} : { rng: options.rng }),
375
+ ...(options.signal === undefined ? {} : { signal: options.signal }),
376
+ });
377
+ }
378
+
379
+ async function tileCount(page: CdpPage): Promise<number> {
380
+ const count = await page.evaluate<unknown>(TILE_COUNT_EXPRESSION);
381
+ return typeof count === "number" && Number.isFinite(count) ? count : 0;
382
+ }
383
+
384
+ async function captchaNodes(page: CdpPage): Promise<number> {
385
+ const count = await page.evaluate<unknown>(`(${captchaNodeCount.toString()})(document)`);
386
+ return typeof count === "number" && Number.isFinite(count) ? count : 0;
387
+ }
388
+
389
+ /** Markers present in a lowercased haystack, in list order. */
390
+ function markersIn(haystack: string, markers: readonly string[]): string[] {
391
+ const found: string[] = [];
392
+ for (const marker of markers) {
393
+ if (haystack.indexOf(marker.toLowerCase()) !== -1) found.push(marker);
394
+ }
395
+ return found;
396
+ }
397
+
398
+ /**
399
+ * Wall detection. Nobody clicks anything here: the tool surfaces the window, the
400
+ * human solves it and retries (D5). The markers are defensive (see the top of
401
+ * this file): the one thing we can honestly say is that a wall has no product
402
+ * cards, so a phrase needs zero cards as corroboration.
403
+ */
404
+ export async function detectOzonWall(page: CdpPage): Promise<Wall | null> {
405
+ const url = page.url();
406
+ const urlMarkers = markersIn(url.toLowerCase(), CAPTCHA_URL_MARKERS);
407
+ if (urlMarkers.length > 0) return { kind: "captcha", url, markers: urlMarkers };
408
+
409
+ const title = await page.title().catch((): string => "");
410
+ const text = await page.innerText();
411
+ const markers = [
412
+ ...markersIn(title.toLowerCase(), CAPTCHA_TITLE_MARKERS),
413
+ ...markersIn(text.toLowerCase(), CAPTCHA_TEXT_MARKERS),
414
+ ];
415
+
416
+ // A captcha widget is evidence on its own: its label lives in an iframe the
417
+ // page-text scan cannot see.
418
+ if ((await captchaNodes(page)) > 0) {
419
+ return { kind: "captcha", url, markers: markers.length > 0 ? markers : ["captcha-node"] };
420
+ }
421
+ // A phrase can be quoted by a product title; a wall has no cards.
422
+ if (markers.length > 0 && (await tileCount(page)) === 0) {
423
+ return { kind: "blocked", url, markers };
424
+ }
425
+ return null;
426
+ }
427
+
428
+ // ---------------------------------------------------------------------------
429
+ // URL builder + engine
430
+ // ---------------------------------------------------------------------------
431
+
432
+ /**
433
+ * Pure: `https://www.ozon.ru/search/?text=<query>[&page=<page>]`.
434
+ *
435
+ * Verified live (2026-11-16): Ozon answers `?text=` either with the search grid
436
+ * or with a `307`-style redirect to a predicted catalog
437
+ * (`/category/<slug>/?…&text=<query>`), and both carry the same cards. `page` is
438
+ * 1-based and survives the redirect. Page 1 is the bare URL, because `page=1` is
439
+ * a parameter the SERP does not need.
440
+ */
441
+ function buildUrl(q: Query): string {
442
+ const parts = [`text=${encodeURIComponent(q.text)}`];
443
+ const page = typeof q.page === "number" && Number.isFinite(q.page) ? Math.floor(q.page) : 1;
444
+ if (page > 1) parts.push(`page=${page}`);
445
+ return `https://www.ozon.ru/search/?${parts.join("&")}`;
446
+ }
447
+
448
+ export const ozonEngine: Engine = {
449
+ id: "ozon",
450
+ interaction: INTERACTION,
451
+ buildUrl,
452
+
453
+ async settle(page: CdpPage, signal?: AbortSignal): Promise<void> {
454
+ await settleOzon(page, signal === undefined ? {} : { signal });
455
+ },
456
+
457
+ detectWall: detectOzonWall,
458
+
459
+ async extract(page: CdpPage, q: Query): Promise<RawSerp> {
460
+ const startedAt = Date.now();
461
+ const arg: OzonExtractionArg = { n: q.n };
462
+ const raw = await page.evaluate<unknown>(
463
+ `(${extractFromDocument.toString()})(document, ${JSON.stringify(arg)})`,
464
+ );
465
+ const parsed = asExtraction(raw);
466
+ const results: SerpItem[] = parsed.results.map((item) => ({
467
+ title: item.title,
468
+ url: item.url,
469
+ snippet: item.snippet,
470
+ ...(item.facts.length === 0 ? {} : { facts: item.facts }),
471
+ }));
472
+ const timings = { extractMs: Math.max(0, Date.now() - startedAt) };
473
+ return {
474
+ engine: "ozon",
475
+ query: q.text,
476
+ results,
477
+ pageCarried: parsed.pageCarried,
478
+ ...(parsed.headline === "" ? {} : { notice: NO_MATCH_NOTICE }),
479
+ timings,
480
+ };
481
+ },
482
+
483
+ async canaries(page: CdpPage): Promise<Record<string, number>> {
484
+ const raw = await page.evaluate<unknown>(`(${canaryCounts.toString()})(document)`);
485
+ return asCanaries(raw);
486
+ },
487
+ };
488
+
489
+ /**
490
+ * Adapter-authored (never page text): the caller must not read a page of
491
+ * recommendations as an answer to its query (S7.6).
492
+ */
493
+ export const NO_MATCH_NOTICE = "no exact match: Ozon answered with recommendations";
@@ -18,9 +18,9 @@ export const PRIMARY_ENGINES = ["google", "duckduckgo", "yandex"] as const;
18
18
  /**
19
19
  * Special engines answer one site, not the web (SPEC §15 D11). They are never
20
20
  * part of `auto`: a marketplace listing is not an answer to "search the web",
21
- * so a caller must name the engine (`engines: "avito"`) to get it.
21
+ * so a caller must name the engine (`engines: "avito"`, `engines: "ozon"`).
22
22
  */
23
- export const SPECIAL_ENGINES = ["avito"] as const;
23
+ export const SPECIAL_ENGINES = ["avito", "ozon"] as const;
24
24
 
25
25
  export type PrimaryEngineId = (typeof PRIMARY_ENGINES)[number];
26
26
  export type SpecialEngineId = (typeof SPECIAL_ENGINES)[number];
@@ -37,6 +37,7 @@ export const ENGINE_CLASS: Readonly<Record<EngineId, EngineClass>> = Object.free
37
37
  duckduckgo: "primary",
38
38
  yandex: "primary",
39
39
  avito: "special",
40
+ ozon: "special",
40
41
  });
41
42
 
42
43
  /** True when `auto` may pick this engine (SPEC S4.7). */
@@ -272,21 +273,21 @@ export type ArgumentSupport = "yes" | "flag";
272
273
  export const SUPPORT_MATRIX: Readonly<
273
274
  Record<SupportArgument, Readonly<Record<EngineId, ArgumentSupport>>>
274
275
  > = Object.freeze({
275
- n: Object.freeze({ google: "yes", duckduckgo: "yes", yandex: "yes", avito: "yes" }),
276
+ n: Object.freeze({ google: "yes", duckduckgo: "yes", yandex: "yes", avito: "yes", ozon: "yes" }),
276
277
  // DuckDuckGo has no pagination in this adapter: page > 1 is served as page 1
277
278
  // and must be reported as `ignored.page`, never silently dropped (S4.2, S7.1).
278
- // Avito paginates with `&p=` (verified live: the page-2 link carries `p=2`).
279
- page: Object.freeze({ google: "yes", duckduckgo: "flag", yandex: "yes", avito: "yes" }),
280
- // Avito has no native AI block at all (SPEC D12): asking is reported as
281
- // `ignored.summary`, never answered with an invented summary.
282
- summary: Object.freeze({ google: "yes", duckduckgo: "yes", yandex: "yes", avito: "flag" }),
279
+ // Avito paginates with `&p=` and Ozon with `&page=` (both verified live).
280
+ page: Object.freeze({ google: "yes", duckduckgo: "flag", yandex: "yes", avito: "yes", ozon: "yes" }),
281
+ // Neither marketplace has a native AI block (SPEC D12/D14): asking is reported
282
+ // as `ignored.summary`, never answered with an invented summary.
283
+ summary: Object.freeze({ google: "yes", duckduckgo: "yes", yandex: "yes", avito: "flag", ozon: "flag" }),
283
284
  });
284
285
 
285
286
  export interface EngineRegistry {
286
287
  /** Throws E_UNSUPPORTED when the adapter is missing or disabled. */
287
288
  get(id: EngineId): Engine;
288
289
  has(id: EngineId): boolean;
289
- /** Enabled engines in canonical order; yandex last. */
290
+ /** Enabled engines in canonical order; the primaries first, special engines last. */
290
291
  enabled(): EngineId[];
291
292
  /**
292
293
  * Resolve a user selection to a try-order (D9/D10): `auto` uses the canonical order
@@ -153,6 +153,10 @@ function probeLocale(engine: EngineId, config: Config): Pick<Query, "lang" | "re
153
153
  const region = resolveProbeLocale(config.engines.avito.location);
154
154
  return region === undefined ? {} : { region };
155
155
  }
156
+ case "ozon": {
157
+ // Ozon has no URL locale/region parameter (SPEC D14).
158
+ return {};
159
+ }
156
160
  }
157
161
  }
158
162
 
@@ -68,6 +68,7 @@ const engineIdSchema = Type.Union([
68
68
  Type.Literal("duckduckgo"),
69
69
  Type.Literal("yandex"),
70
70
  Type.Literal("avito"),
71
+ Type.Literal("ozon"),
71
72
  ]);
72
73
 
73
74
  /**
@@ -198,7 +199,7 @@ export interface WebSearchTool {
198
199
  * every word.
199
200
  */
200
201
  export const WEB_SEARCH_DESCRIPTION =
201
- "Search the web for free in the user's visible Chrome (Google, DuckDuckGo, Yandex; Avito listings opt-in) with each engine's native AI summary. Compact results, n<=10. Call web_read on a result URL to get that page as paged Markdown. site:/filetype:/quoted queries pass through; engines: id, list, or auto.";
202
+ "Search the web for free in the user's visible Chrome (Google, DuckDuckGo, Yandex; Avito and Ozon opt-in) with each engine's native AI summary. Compact results, n<=10. Call web_read on a result URL to get that page as paged Markdown. site:/filetype:/quoted queries pass through; engines: id, list, or auto.";
202
203
 
203
204
  /**
204
205
  * SPEC S3.6: `q` is passed verbatim, so narrowing happens in the query. The
@@ -206,7 +207,7 @@ export const WEB_SEARCH_DESCRIPTION =
206
207
  */
207
208
  export const WEB_SEARCH_GUIDELINES: readonly string[] = [
208
209
  "web_search passes q verbatim: use quoted phrases, -term, OR, site:, filetype:; narrow by date with after:/before: on Google or date: on Yandex (there is no date argument).",
209
- "engines:\"avito\" searches Avito listings (price, location); it is opt-in: enable engines.avito.enabled in web-search.json first, and auto never uses it.",
210
+ "engines:\"avito\" (listings) and \"ozon\" (goods) are opt-in marketplaces: enable engines.<id>.enabled in web-search.json first; auto never uses them.",
210
211
  ];
211
212
 
212
213
  /**
@@ -391,6 +392,12 @@ function buildQuery(engine: EngineId, input: NormalizedInput, config: Config): Q
391
392
  query.region = resolveLocale(config.engines.avito.location) ?? "all";
392
393
  break;
393
394
  }
395
+ case "ozon": {
396
+ // No locale plumbing: Ozon has no URL region/language parameter (its city
397
+ // is a cookie-backed UI choice), so a value here would be a phantom key
398
+ // (S7.5). The query text is the whole input.
399
+ break;
400
+ }
394
401
  }
395
402
  return query;
396
403
  }