@astratra/web-search 1.1.0 → 1.2.1

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/src/tools.js CHANGED
@@ -1,5 +1,8 @@
1
1
  /**
2
- * Brancher la recherche sur un modèle : deux outils, `web_search` et `read_page`.
2
+ * Brancher la recherche sur un modèle : deux outils, `web_search` et `read_page`,
3
+ * plus deux quand le navigateur intégré est branché (`createWebSearch({ browser })`) :
4
+ * `browse_page` (la page rendue, ses liens numérotés, sa capture sur demande) et
5
+ * `search_site` (la recherche interne d'un site, sans clic).
3
6
  *
4
7
  * - `toolDefinitions(format)` : les schémas tels que chaque API les attend
5
8
  * (Anthropic, OpenAI, Mistral, Gemini) ;
@@ -15,7 +18,7 @@
15
18
  * modèle et rend le texte cadré.
16
19
  */
17
20
 
18
- const { formatForModel, formatPageForModel } = require('./format');
21
+ const { formatForModel, formatPageForModel, formatBrowsedForModel } = require('./format');
19
22
  const { WebSearchError, CODES } = require('./errors');
20
23
  const { geminiSchema } = require('@astratra/ai');
21
24
 
@@ -52,27 +55,74 @@ const READ_SCHEMA = Object.freeze({
52
55
  additionalProperties: false
53
56
  });
54
57
 
58
+ const BROWSE_DESCRIPTION = 'Open one web page (https only) in a real browser, after its JavaScript ran, and return the text a person sees, '
59
+ + 'its date, verbatim passages and its links numbered [L1], [L2]… (links of the same site first). To follow a link, call browse_page again with its exact url. '
60
+ + 'Use it for pages that read_page cannot read (built with JavaScript) and to explore a site. Pages refused by their robots.txt are not opened.';
61
+ const SITE_SEARCH_DESCRIPTION = "Search inside one website with the site's own search (its OpenSearch description or its search form), "
62
+ + 'and return the results page as a browser shows it, with its links numbered. Give any page of the site. Not for general web search: use web_search.';
63
+
64
+ const BROWSE_SCHEMA = Object.freeze({
65
+ type: 'object',
66
+ properties: {
67
+ url: { type: 'string', description: 'The https address of the page, exactly as given by web_search or by a link [Ln].' },
68
+ query: { type: 'string', description: 'What you are looking for on the page, to get the best passages.' },
69
+ quotes: { type: 'array', items: { type: 'string' }, maxItems: 5, description: 'Sentences to look for on the page, word for word.' }
70
+ },
71
+ required: ['url'],
72
+ additionalProperties: false
73
+ });
74
+ const SCREENSHOT_PROPERTY = Object.freeze({ type: 'boolean', description: 'Also return a screenshot of the visible part of the page (1280 × 800 at most). Only when the layout or images matter.' });
75
+
76
+ const SITE_SEARCH_SCHEMA = Object.freeze({
77
+ type: 'object',
78
+ properties: {
79
+ url: { type: 'string', description: 'The https address of any page of the site to search.' },
80
+ query: { type: 'string', description: 'What to search for on that site (200 characters at most).' }
81
+ },
82
+ required: ['url', 'query'],
83
+ additionalProperties: false
84
+ });
85
+
55
86
  const TOOLS = [
56
87
  { name: 'web_search', description: SEARCH_DESCRIPTION, parameters: SEARCH_SCHEMA },
57
88
  { name: 'read_page', description: READ_DESCRIPTION, parameters: READ_SCHEMA }
58
89
  ];
90
+ const BROWSER_TOOLS = [
91
+ { name: 'browse_page', description: BROWSE_DESCRIPTION, parameters: BROWSE_SCHEMA },
92
+ { name: 'search_site', description: SITE_SEARCH_DESCRIPTION, parameters: SITE_SEARCH_SCHEMA }
93
+ ];
94
+
95
+ /** Les outils offerts : les deux de base, plus ceux du navigateur quand il est là. */
96
+ function toolList({ browser = false, screenshots = false } = {}) {
97
+ if (!browser) return TOOLS;
98
+ const browse = screenshots
99
+ ? { ...BROWSER_TOOLS[0], parameters: { ...BROWSE_SCHEMA, properties: { ...BROWSE_SCHEMA.properties, screenshot: SCREENSHOT_PROPERTY } } }
100
+ : BROWSER_TOOLS[0];
101
+ return [...TOOLS, browse, BROWSER_TOOLS[1]];
102
+ }
103
+
104
+ /** Les options d'outils d'une recherche : le navigateur est offert s'il est branché. */
105
+ const toolOptions = (ws, options = {}) => ({ browser: Boolean(ws?.hasBrowser) && options.browser !== false, screenshots: options.screenshots === true });
59
106
 
60
107
  /**
61
108
  * Les définitions d'outils au format d'une API.
62
109
  * @param {'anthropic'|'openai'|'mistral'|'gemini'|'generic'} format
110
+ * @param {{ browser?: boolean, screenshots?: boolean }} [options] browser : ajouter browse_page et search_site ;
111
+ * screenshots : le modèle lit les images (paramètre screenshot de browse_page).
63
112
  */
64
- function toolDefinitions(format = 'generic') {
113
+ function toolDefinitions(format = 'generic', options = {}) {
65
114
  const copy = (value) => JSON.parse(JSON.stringify(value));
115
+ const offered = toolList(options);
66
116
  switch (format) {
67
117
  case 'anthropic':
68
- return TOOLS.map(({ name, description, parameters }) => ({ name, description, input_schema: copy(parameters) }));
118
+ return offered.map(({ name, description, parameters }) => ({ name, description, input_schema: copy(parameters) }));
69
119
  case 'openai':
70
120
  case 'mistral':
71
- return TOOLS.map(({ name, description, parameters }) => ({ type: 'function', function: { name, description, parameters: copy(parameters) } }));
121
+ return offered.map(({ name, description, parameters }) => ({ type: 'function', function: { name, description, parameters: copy(parameters) } }));
72
122
  case 'gemini':
73
- return [{ functionDeclarations: TOOLS.map(({ name, description, parameters }) => ({ name, description, parameters: geminiSchema(copy(parameters)) })) }];
123
+ return [{ functionDeclarations: offered.map(({ name, description, parameters }) => ({ name, description, parameters: geminiSchema(copy(parameters)) })) }];
74
124
  case 'generic':
75
- return TOOLS.map(copy);
125
+ return offered.map(copy);
76
126
  default:
77
127
  throw new Error(`Unknown tool format ${format}: anthropic, openai, mistral, gemini or generic.`);
78
128
  }
@@ -99,9 +149,10 @@ function searchArgs(args = {}, defaults = {}) {
99
149
 
100
150
  /**
101
151
  * Exécute un outil pour un modèle.
102
- * @returns {Promise<{ text: string, sources: object[], found: object }>}
152
+ * `screenshots` : le modèle lit les images ; sans lui, une capture demandée est refusée.
153
+ * @returns {Promise<{ text: string, sources: object[], images?: object[], found: object }>}
103
154
  */
104
- async function runTool(ws, name, args, { signal, defaults, maxChars } = {}) {
155
+ async function runTool(ws, name, args, { signal, defaults, maxChars, screenshots = false } = {}) {
105
156
  if (name === 'web_search') {
106
157
  const found = await ws.search(searchArgs(args, defaults), { signal });
107
158
  return {
@@ -122,6 +173,20 @@ async function runTool(ws, name, args, { signal, defaults, maxChars } = {}) {
122
173
  found: page
123
174
  };
124
175
  }
176
+ if (name === 'browse_page' || name === 'search_site') {
177
+ if (!ws.hasBrowser) throw new WebSearchError(CODES.BAD_REQUEST, `unknown tool ${name}`);
178
+ if (!args || typeof args.url !== 'string') throw new WebSearchError(CODES.BAD_REQUEST, `${name} needs a url string`);
179
+ if (args.screenshot === true && !screenshots) throw new WebSearchError(CODES.BAD_REQUEST, 'screenshots are not available for this model');
180
+ const page = name === 'browse_page'
181
+ ? await ws.browse(args.url, { screenshot: args.screenshot === true, quotes: strings(args.quotes)?.slice(0, 5), query: typeof args.query === 'string' ? args.query : undefined, signal })
182
+ : await ws.searchSite(args.url, typeof args.query === 'string' ? args.query : '', { signal });
183
+ return {
184
+ text: formatBrowsedForModel(page, { maxChars }),
185
+ sources: [{ kind: 'web', url: page.finalUrl, title: page.title, domain: page.domain, publishedAt: page.publishedAt, excerpt: page.passages[0]?.text || page.text.slice(0, 300) }],
186
+ images: page.screenshot ? [{ mediaType: page.screenshot.mediaType, data: page.screenshot.data }] : [],
187
+ found: page
188
+ };
189
+ }
125
190
  throw new WebSearchError(CODES.BAD_REQUEST, `unknown tool ${name}`);
126
191
  }
127
192
 
@@ -132,24 +197,27 @@ async function runTool(ws, name, args, { signal, defaults, maxChars } = {}) {
132
197
  */
133
198
  function nativeTools(ws, options = {}) {
134
199
  const maxChars = options.maxChars ?? 5_000;
135
- return TOOLS.map(({ name, description, parameters }) => ({
200
+ const offered = toolOptions(ws, options);
201
+ return toolList(offered).map(({ name, description, parameters }) => ({
136
202
  name,
137
203
  description,
138
204
  parameters: JSON.parse(JSON.stringify(parameters)),
139
205
  kind: 'read',
140
206
  risk: 'LOW',
141
- summary: (args = {}) => (name === 'web_search' ? { query: String(args.query ?? '') } : { url: String(args.url ?? '') }),
207
+ summary: (args = {}) => (name === 'web_search' ? { query: String(args.query ?? '') }
208
+ : name === 'search_site' ? { url: String(args.url ?? ''), query: String(args.query ?? '') } : { url: String(args.url ?? '') }),
142
209
  run: async (args, ctx = {}) => {
143
- const { text, sources } = await runTool(ws, name, args, { signal: ctx.signal, defaults: options.defaults, maxChars });
144
- return { data: text, sources };
210
+ const { text, sources, images } = await runTool(ws, name, args, { signal: ctx.signal, defaults: options.defaults, maxChars, screenshots: offered.screenshots });
211
+ return images?.length ? { data: text, sources, images } : { data: text, sources };
145
212
  }
146
213
  }));
147
214
  }
148
215
 
149
216
  /** Pour createToolRegistry / runAgentLoop de @astratra/ai (qui met de côté au-delà de 12 000 caractères). */
150
- function registryTools(ws, { roles, defaults, maxChars = 10_000 } = {}) {
217
+ function registryTools(ws, { roles, defaults, maxChars = 10_000, browser } = {}) {
151
218
  if (!Array.isArray(roles) || !roles.length) throw new Error('registryTools needs the roles allowed to search.');
152
- return TOOLS.map(({ name, description, parameters }) => ({
219
+ /* Le registre rend du texte seulement : pas de capture d'écran. */
220
+ return toolList(toolOptions(ws, { browser })).map(({ name, description, parameters }) => ({
153
221
  name,
154
222
  description,
155
223
  type: 'read',
@@ -161,4 +229,15 @@ function registryTools(ws, { roles, defaults, maxChars = 10_000 } = {}) {
161
229
  }));
162
230
  }
163
231
 
164
- module.exports = { toolDefinitions, nativeTools, registryTools, runTool, searchArgs, TOOL_SCHEMAS: { web_search: SEARCH_SCHEMA, read_page: READ_SCHEMA } };
232
+ // Des noms seuls et des « ...require() » dans l'objet exporté : Node les lit sans exécuter le fichier, pour les
233
+ // imports nommés d'un module ES.
234
+ const TOOL_SCHEMAS = { web_search: SEARCH_SCHEMA, read_page: READ_SCHEMA, browse_page: BROWSE_SCHEMA, search_site: SITE_SEARCH_SCHEMA };
235
+ module.exports = {
236
+ toolDefinitions,
237
+ nativeTools,
238
+ registryTools,
239
+ runTool,
240
+ searchArgs,
241
+ toolList,
242
+ TOOL_SCHEMAS
243
+ };
package/src/webSearch.js CHANGED
@@ -25,7 +25,7 @@ const crypto = require('crypto');
25
25
  const { WebSearchError, CODES } = require('./errors');
26
26
  const { normalizeRequest } = require('./query');
27
27
  const { fuseRankings, rankEntries } = require('./fusion');
28
- const { canonicalUrl, domainOf, sameSite, normalizeSite } = require('./url');
28
+ const { canonicalUrl, domainOf, sameSite, normalizeSite, inSite } = require('./url');
29
29
  const { safeFetch, checkUrl, SAFE_FETCH_DEFAULTS } = require('./safeFetch');
30
30
  const { extractPage } = require('./extract');
31
31
  const { findQuote, bestPassages } = require('./passages');
@@ -45,6 +45,14 @@ const defaultSleep = (ms, signal) => new Promise((resolve, reject) => {
45
45
  }, { once: true });
46
46
  });
47
47
 
48
+ /* Les mots d'un texte : ce qui porte une lettre ou un chiffre. */
49
+ const wordCount = (text) => String(text || '').split(/\s+/).filter((word) => /[\p{L}\p{N}]/u.test(word)).length;
50
+
51
+ /** L'adresse https donnée, sinon celle de repli. */
52
+ function parseHttpsOr(value, fallback) {
53
+ return typeof value === 'string' && canonicalUrl(value) ? value : fallback;
54
+ }
55
+
48
56
  function validateProviders(providers) {
49
57
  if (!Array.isArray(providers) || providers.length === 0) {
50
58
  throw new WebSearchError(CODES.NO_PROVIDER, 'createWebSearch needs at least one provider');
@@ -74,7 +82,10 @@ function validateProviders(providers) {
74
82
  * @param {number} [options.cooldownMs] repos d'un moteur à court de quota. Défaut 60 s.
75
83
  * @param {number} [options.budgetMs] temps total d'une recherche, lectures comprises. Défaut 25 s.
76
84
  * @param {object} [options.ranking] { blockDomains, preferDomains, demoteDomains, domainScore, maxPerDomain }.
77
- * @param {object} [options.reading] { timeoutMs, maxBytes, maxChars, passages, passageSize, ports, userAgent }.
85
+ * @param {object} [options.reading] { timeoutMs, maxBytes, maxChars, passages, passageSize, ports, userAgent,
86
+ * browser: 'fallback'|'always'|'never', minWords }.
87
+ * @param {object} [options.browser] le navigateur intégré : createBrowserClient(…) ou createLocalBrowser(…).
88
+ * @param {string[]} [options.allowDomains] si donné, seules ces pages (et leurs sous-domaines) sont lues ou ouvertes.
78
89
  * @param {Function} [options.rewrite] async (request) => string | { query } : réécrire la requête.
79
90
  * @param {Function} [options.extract] (html, { url }) => { text, title?, … } : un autre extracteur.
80
91
  * @param {Function} [options.onReport] (report) => void, après chaque recherche.
@@ -110,7 +121,14 @@ function createWebSearch(options = {}) {
110
121
  preferDomains: (options.ranking?.preferDomains || []).map(normalizeSite).filter(Boolean),
111
122
  demoteDomains: (options.ranking?.demoteDomains || []).map(normalizeSite).filter(Boolean)
112
123
  };
113
- const reading = { maxChars: 60_000, passages: 3, passageSize: 500, ...(options.reading || {}) };
124
+ const reading = { maxChars: 60_000, passages: 3, passageSize: 500, minWords: 200, ...(options.reading || {}) };
125
+ const browser = options.browser || null;
126
+ if (browser && (typeof browser.open !== 'function' || typeof browser.siteSearch !== 'function')) {
127
+ throw new Error('browser must come from createBrowserClient() or createLocalBrowser().');
128
+ }
129
+ const browserMode = browser ? (reading.browser || 'fallback') : 'never';
130
+ if (!['fallback', 'always', 'never'].includes(browserMode)) throw new Error("reading.browser must be 'fallback', 'always' or 'never'.");
131
+ const allowDomains = (options.allowDomains || []).map(normalizeSite).filter(Boolean);
114
132
  const extract = options.extract || extractPage;
115
133
  const resting = new Map();
116
134
 
@@ -260,6 +278,91 @@ function createWebSearch(options = {}) {
260
278
  return { lists, traces };
261
279
  }
262
280
 
281
+ /** Refuse une adresse d'un site bloqué, ou hors des sites permis. */
282
+ function checkDomain(url) {
283
+ const domain = domainOf(url);
284
+ if (!domain) return;
285
+ if (ranking.blockDomains.some((site) => inSite(domain, site))) throw new WebSearchError(CODES.BLOCKED_DOMAIN, 'this site is blocked');
286
+ if (allowDomains.length && !allowDomains.some((site) => inSite(domain, site))) throw new WebSearchError(CODES.BLOCKED_DOMAIN, 'this site is not in the allowed sites');
287
+ }
288
+
289
+ const linkAllowed = (url) => {
290
+ const domain = domainOf(url);
291
+ return Boolean(domain) && !ranking.blockDomains.some((site) => inSite(domain, site))
292
+ && (!allowDomains.length || allowDomains.some((site) => inSite(domain, site)));
293
+ };
294
+
295
+ /** Ce que le navigateur rend, en erreur du paquet. */
296
+ function browserError(outcome) {
297
+ if (!outcome.ok) {
298
+ if (outcome.code === 'busy') return new WebSearchError(CODES.BROWSE_BUSY, 'the browser is busy; try again later', { retryable: true });
299
+ if (outcome.code === 'invalid_input') return new WebSearchError(CODES.BAD_REQUEST, 'the browser refused the request');
300
+ return new WebSearchError(CODES.BROWSER_UNAVAILABLE, `the browser is unavailable (${String(outcome.code).slice(0, 40)})`, { retryable: Boolean(outcome.retryable) });
301
+ }
302
+ const result = outcome.result;
303
+ switch (result.status) {
304
+ case 'blocked': return new WebSearchError(CODES.BLOCKED_ADDRESS, 'the page or one of its redirects is not public');
305
+ case 'domain_refused': return new WebSearchError(CODES.BLOCKED_DOMAIN, 'the page or one of its redirects is on a refused site');
306
+ case 'robots_disallowed': return new WebSearchError(CODES.BROWSE_ROBOTS, "the site's robots.txt does not allow this page");
307
+ case 'bad_status': return new WebSearchError(CODES.BAD_STATUS, `page answered ${Number(result.httpStatus) || 0}`, { status: Number(result.httpStatus) || undefined });
308
+ case 'timeout': return new WebSearchError(CODES.BROWSE_TIMEOUT, 'the page took too long to load');
309
+ case 'too_many_redirects': return new WebSearchError(CODES.TOO_MANY_REDIRECTS, 'too many redirects');
310
+ case 'unsupported_type': return new WebSearchError(CODES.UNSUPPORTED_TYPE, 'this address is not a web page');
311
+ case 'no_site_search': return new WebSearchError(CODES.NO_SITE_SEARCH, 'this site has no search the browser can use (OpenSearch or a GET search form)');
312
+ case 'search_engine_refused': return new WebSearchError(CODES.BROWSE_REFUSED, 'search engines are queried through their API (web_search), not through their pages');
313
+ default: return new WebSearchError(CODES.BROWSE_FAILED, 'the browser could not read the page');
314
+ }
315
+ }
316
+
317
+ /** Le résultat du navigateur, en page du paquet. */
318
+ function browsedPage(result, asked) {
319
+ const fullText = String(result.text || '');
320
+ const text = fullText.length > reading.maxChars ? clip(fullText, reading.maxChars) : fullText;
321
+ const finalUrl = parseHttpsOr(result.finalUrl, asked);
322
+ const pageCanonical = result.canonical && sameSite(result.canonical, finalUrl) ? canonicalUrl(result.canonical) : null;
323
+ return {
324
+ url: asked,
325
+ finalUrl,
326
+ redirects: [],
327
+ canonicalUrl: pageCanonical || canonicalUrl(finalUrl),
328
+ domain: domainOf(finalUrl),
329
+ title: String(result.title || ''),
330
+ lang: result.lang || null,
331
+ publishedAt: result.publishedAt || null,
332
+ modifiedAt: result.modifiedAt || null,
333
+ text,
334
+ truncated: Boolean(result.truncated) || text.length < fullText.length,
335
+ bytes: null,
336
+ via: 'browser'
337
+ };
338
+ }
339
+
340
+ /** Les liens rendus par le navigateur : sites bloqués ou hors des sites permis retirés, renumérotés. */
341
+ function browsedLinks(result) {
342
+ return (Array.isArray(result.links) ? result.links : [])
343
+ .filter((link) => link && typeof link.url === 'string' && canonicalUrl(link.url) && linkAllowed(link.url))
344
+ .map((link, index) => ({ n: index + 1, url: link.url, text: String(link.text || '').replace(/\s+/g, ' ').trim().slice(0, 120), sameSite: Boolean(link.sameSite) }));
345
+ }
346
+
347
+ const browserPolicy = () => ({
348
+ ...(allowDomains.length ? { allowDomains } : {}),
349
+ ...(ranking.blockDomains.length ? { blockDomains: ranking.blockDomains } : {})
350
+ });
351
+
352
+ /** Une page ouverte par le navigateur, en cache comme les lectures. */
353
+ async function openWithBrowser(url, { signal, lang, screenshot = false } = {}) {
354
+ const key = `ws:browse:${hash(canonicalUrl(url))}`;
355
+ if (!screenshot) {
356
+ const cached = await cacheGet(key);
357
+ if (cached && cached.page) return { ...cached, cached: true };
358
+ }
359
+ const outcome = await browser.open({ url, ...(screenshot ? { screenshot: true } : {}), ...(lang && /^[a-z]{2}$/.test(lang) ? { lang } : {}), ...browserPolicy() }, { signal });
360
+ if (!outcome.ok || outcome.result?.status !== 'ok') throw browserError(outcome);
361
+ const value = { page: browsedPage(outcome.result, url), links: browsedLinks(outcome.result) };
362
+ await cacheSet(key, value, readCacheTtlMs);
363
+ return { ...value, cached: false, screenshot: outcome.result.screenshot || null };
364
+ }
365
+
263
366
  /**
264
367
  * Lit une page : le texte principal, sa date, et les passages cités mot pour mot.
265
368
  * @param {string} url
@@ -268,47 +371,40 @@ function createWebSearch(options = {}) {
268
371
  async function read(url, readOptions = {}) {
269
372
  const started = now();
270
373
  checkUrl(url, reading.ports || SAFE_FETCH_DEFAULTS.ports);
374
+ checkDomain(url);
271
375
  const quotes = (Array.isArray(readOptions.quotes) ? readOptions.quotes : []).filter((quote) => typeof quote === 'string' && quote.trim()).slice(0, MAX_QUOTES);
272
- const key = `ws:read:${hash(canonicalUrl(url))}`;
273
- let page = await cacheGet(key);
274
- const cached = Boolean(page);
275
- if (!page) {
276
- const fetched = await safeFetch(url, {
277
- timeoutMs: reading.timeoutMs,
278
- maxBytes: reading.maxBytes,
279
- maxRedirects: reading.maxRedirects,
280
- ports: reading.ports,
281
- userAgent: reading.userAgent,
282
- lang: readOptions.lang,
283
- signal: readOptions.signal,
284
- request: options.request,
285
- resolve: options.resolve
286
- });
287
- const extracted = fetched.contentType === 'text/plain'
288
- ? { title: '', text: fetched.body.replace(/\r\n?/g, '\n').trim() }
289
- : (await extract(fetched.body, { url: fetched.finalUrl, now: now() })) || { text: '' };
290
- const fullText = String(extracted.text || '');
291
- const text = fullText.length > reading.maxChars ? clip(fullText, reading.maxChars) : fullText;
292
- const pageCanonical = extracted.canonical && sameSite(extracted.canonical, fetched.finalUrl) ? canonicalUrl(extracted.canonical) : null;
293
- page = {
294
- url: fetched.url,
295
- finalUrl: fetched.finalUrl,
296
- redirects: fetched.redirects,
297
- canonicalUrl: pageCanonical || canonicalUrl(fetched.finalUrl),
298
- domain: domainOf(fetched.finalUrl),
299
- title: String(extracted.title || ''),
300
- lang: extracted.lang || null,
301
- publishedAt: extracted.publishedAt || null,
302
- modifiedAt: extracted.modifiedAt || null,
303
- text,
304
- truncated: fetched.truncated || text.length < fullText.length,
305
- bytes: fetched.bytes
306
- };
307
- await cacheSet(key, page, readCacheTtlMs);
376
+ let page;
377
+ let cached;
378
+ if (browserMode === 'always') {
379
+ const opened = await openWithBrowser(url, { signal: readOptions.signal, lang: readOptions.lang });
380
+ page = opened.page;
381
+ cached = opened.cached;
382
+ } else {
383
+ const key = `ws:read:${hash(canonicalUrl(url))}`;
384
+ page = await cacheGet(key);
385
+ cached = Boolean(page);
386
+ if (!page) {
387
+ page = await fetchPage(url, readOptions);
388
+ await cacheSet(key, page, readCacheTtlMs);
389
+ }
390
+ /* Une page construite en JavaScript donne presque rien sans navigateur : il prend le relais. */
391
+ if (browserMode === 'fallback' && wordCount(page.text) < reading.minWords) {
392
+ try {
393
+ const opened = await openWithBrowser(url, { signal: readOptions.signal, lang: readOptions.lang });
394
+ if (wordCount(opened.page.text) > wordCount(page.text)) {
395
+ page = opened.page;
396
+ cached = opened.cached;
397
+ }
398
+ } catch (_error) {
399
+ /* le navigateur en panne, refusé ou bloqué : la lecture simple reste */
400
+ }
401
+ }
308
402
  }
403
+ checkDomain(page.finalUrl);
309
404
  const passageCount = readOptions.passages ?? reading.passages;
310
405
  return {
311
406
  ...page,
407
+ via: page.via || 'fetch',
312
408
  sameSite: sameSite(url, page.finalUrl),
313
409
  quotes: quotes.map((quote) => findQuote(page.text, quote)),
314
410
  passages: readOptions.query ? bestPassages(page.text, readOptions.query, { count: passageCount, size: reading.passageSize }) : [],
@@ -316,6 +412,104 @@ function createWebSearch(options = {}) {
316
412
  };
317
413
  }
318
414
 
415
+ /** La lecture simple (sans JavaScript) d'une page. */
416
+ async function fetchPage(url, readOptions) {
417
+ const fetched = await safeFetch(url, {
418
+ timeoutMs: reading.timeoutMs,
419
+ maxBytes: reading.maxBytes,
420
+ maxRedirects: reading.maxRedirects,
421
+ ports: reading.ports,
422
+ userAgent: reading.userAgent,
423
+ lang: readOptions.lang,
424
+ signal: readOptions.signal,
425
+ request: options.request,
426
+ resolve: options.resolve
427
+ });
428
+ const extracted = fetched.contentType === 'text/plain'
429
+ ? { title: '', text: fetched.body.replace(/\r\n?/g, '\n').trim() }
430
+ : (await extract(fetched.body, { url: fetched.finalUrl, now: now() })) || { text: '' };
431
+ const fullText = String(extracted.text || '');
432
+ const text = fullText.length > reading.maxChars ? clip(fullText, reading.maxChars) : fullText;
433
+ const pageCanonical = extracted.canonical && sameSite(extracted.canonical, fetched.finalUrl) ? canonicalUrl(extracted.canonical) : null;
434
+ return {
435
+ url: fetched.url,
436
+ finalUrl: fetched.finalUrl,
437
+ redirects: fetched.redirects,
438
+ canonicalUrl: pageCanonical || canonicalUrl(fetched.finalUrl),
439
+ domain: domainOf(fetched.finalUrl),
440
+ title: String(extracted.title || ''),
441
+ lang: extracted.lang || null,
442
+ publishedAt: extracted.publishedAt || null,
443
+ modifiedAt: extracted.modifiedAt || null,
444
+ text,
445
+ truncated: fetched.truncated || text.length < fullText.length,
446
+ bytes: fetched.bytes,
447
+ via: 'fetch'
448
+ };
449
+ }
450
+
451
+ function requireBrowser(name) {
452
+ if (!browser) throw new WebSearchError(CODES.BROWSER_UNAVAILABLE, `${name} needs the integrated browser (createWebSearch({ browser }))`);
453
+ }
454
+
455
+ /**
456
+ * Ouvre une page dans le navigateur : son texte rendu, ses liens numérotés,
457
+ * et sa capture d'écran si on la demande.
458
+ * @param {string} url
459
+ * @param {{ screenshot?: boolean, quotes?: string[], query?: string, passages?: number, lang?: string, signal?: AbortSignal }} [browseOptions]
460
+ */
461
+ async function browse(url, browseOptions = {}) {
462
+ requireBrowser('browse');
463
+ const started = now();
464
+ checkUrl(url, reading.ports || SAFE_FETCH_DEFAULTS.ports);
465
+ checkDomain(url);
466
+ const opened = await openWithBrowser(url, { signal: browseOptions.signal, lang: browseOptions.lang, screenshot: browseOptions.screenshot === true });
467
+ return finishBrowsed(url, opened, browseOptions, started);
468
+ }
469
+
470
+ function finishBrowsed(url, opened, extra, started) {
471
+ const { page } = opened;
472
+ const quotes = (Array.isArray(extra.quotes) ? extra.quotes : []).filter((quote) => typeof quote === 'string' && quote.trim()).slice(0, MAX_QUOTES);
473
+ return {
474
+ ...page,
475
+ sameSite: sameSite(url, page.finalUrl),
476
+ links: opened.links,
477
+ ...(opened.screenshot ? { screenshot: opened.screenshot } : {}),
478
+ quotes: quotes.map((quote) => findQuote(page.text, quote)),
479
+ passages: extra.query ? bestPassages(page.text, extra.query, { count: extra.passages ?? reading.passages, size: reading.passageSize }) : [],
480
+ report: { ms: now() - started, cached: Boolean(opened.cached) }
481
+ };
482
+ }
483
+
484
+ /**
485
+ * La recherche interne d'un site (OpenSearch ou formulaire GET), sans clic.
486
+ * @param {string} url une page du site.
487
+ * @param {string} query
488
+ * @param {{ screenshot?: boolean, passages?: number, lang?: string, signal?: AbortSignal }} [searchOptions]
489
+ */
490
+ async function searchSite(url, query, searchOptions = {}) {
491
+ requireBrowser('searchSite');
492
+ const started = now();
493
+ checkUrl(url, reading.ports || SAFE_FETCH_DEFAULTS.ports);
494
+ checkDomain(url);
495
+ if (typeof query !== 'string' || !query.trim()) throw new WebSearchError(CODES.BAD_REQUEST, 'searchSite needs a query');
496
+ const outcome = await browser.siteSearch({
497
+ url,
498
+ query: query.trim().slice(0, 200),
499
+ ...(searchOptions.screenshot === true ? { screenshot: true } : {}),
500
+ ...(searchOptions.lang && /^[a-z]{2}$/.test(searchOptions.lang) ? { lang: searchOptions.lang } : {}),
501
+ ...browserPolicy()
502
+ }, { signal: searchOptions.signal });
503
+ if (!outcome.ok || outcome.result?.status !== 'ok') throw browserError(outcome);
504
+ const result = outcome.result;
505
+ const opened = { page: browsedPage(result, result.searchUrl || url), links: browsedLinks(result), screenshot: result.screenshot || null, cached: false };
506
+ checkDomain(opened.page.finalUrl);
507
+ return {
508
+ ...finishBrowsed(url, opened, { query, passages: searchOptions.passages }, started),
509
+ siteSearch: { query: query.trim().slice(0, 200), via: result.via, searchUrl: result.searchUrl }
510
+ };
511
+ }
512
+
319
513
  /**
320
514
  * @param {string|object} input la requête, ou { query, lang, country, freshness, sites, excludeSites, limit, read }.
321
515
  * @param {{ signal?: AbortSignal }} [callOptions]
@@ -460,7 +654,7 @@ function createWebSearch(options = {}) {
460
654
  }
461
655
  }
462
656
 
463
- return { search, read, providerIds: providers.map((provider) => provider.id) };
657
+ return { search, read, browse, searchSite, hasBrowser: Boolean(browser), providerIds: providers.map((provider) => provider.id) };
464
658
  }
465
659
 
466
660
  module.exports = { createWebSearch };