@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/README.fr.md CHANGED
@@ -3,13 +3,15 @@
3
3
  Une recherche web pour les IA, où chaque fait reste attaché à sa page.
4
4
 
5
5
  Plusieurs moteurs (Serper pour les résultats Google, Brave Search, Tavily, Exa,
6
- ou la passerelle de la Centrale) avec repli automatique ; leurs **classements**
6
+ ou une passerelle de recherche à vous) avec repli automatique ; leurs **classements**
7
7
  sont fusionnés, leurs **contenus jamais**. Chaque résultat est une page d'un
8
8
  site, avec son adresse exacte, son domaine, sa date quand on la connaît,
9
9
  l'extrait d'**un seul** moteur pour **cette** page et, quand la page est lue,
10
10
  des passages cités mot pour mot avec leur position. Les pages sont lues sans
11
11
  ouvrir de porte vers votre réseau interne (SSRF), et tout ce qu'un modèle lit
12
- du web lui est présenté comme des données, pas comme des instructions.
12
+ du web lui est présenté comme des données, pas comme des instructions. Un
13
+ navigateur intégré, facultatif et isolé, lit les pages construites en
14
+ JavaScript, parcourt les liens d'un site et utilise sa recherche interne.
13
15
 
14
16
  [English version](README.md)
15
17
 
@@ -29,14 +31,13 @@ vient chacune. Ce paquet corrige les trois, et chacun se vérifie (voir
29
31
  ## Démarrage
30
32
 
31
33
  ```js
32
- const { createWebSearch, gatewayProvider, braveProvider, formatForModel } = require('@astratra/web-search');
33
- const { lirePasserelle, rechercher } = await import('@astratra/centrale/passerelle');
34
+ const { createWebSearch, braveProvider, tavilyProvider, formatForModel } = require('@astratra/web-search');
34
35
 
35
- const passerelle = lirePasserelle(process.env); // l'app ne garde qu'un jeton de projet
36
+ // Les moteurs et leur ordre sont les tiens : le paquet n'en choisit aucun.
36
37
  const ws = createWebSearch({
37
38
  providers: [
38
- gatewayProvider({ search: (demande, { signal }) => rechercher(passerelle, demande, { signal }) }),
39
- braveProvider({ key: () => process.env.BRAVE_SEARCH_API_KEY })
39
+ braveProvider({ key: () => process.env.BRAVE_SEARCH_API_KEY }),
40
+ tavilyProvider({ key: () => process.env.TAVILY_API_KEY })
40
41
  ]
41
42
  });
42
43
 
@@ -76,7 +77,7 @@ formatForModel(trouve); // le texte pour le modèle : règles de citation, puis
76
77
 
77
78
  | Fournisseur | Adresse | Notes |
78
79
  |---|---|---|
79
- | `gatewayProvider({ search })` | la passerelle de la Centrale (`rechercher` de `@astratra/centrale/passerelle`) | Conseillé : les clés restent dans le coffre de la Centrale, qui compte le coût (`costPerCallUsd: null`). Les sites partent en opérateurs `site:`. |
80
+ | `gatewayProvider({ search })` | une passerelle de recherche à toi : `search({ requete, nombre, langue?, pays?, periode? }, { signal })` rend `{ fournisseur, resultats: [{ titre, url, extrait, date? }] }` | Les clés des moteurs restent chez ta passerelle, qui compte le coût (`costPerCallUsd: null`). Les sites partent en opérateurs `site:`. |
80
81
  | `serperProvider({ key })` | `google.serper.dev` | Réutilise `searchSerper` de `@astratra/ai`. Pays (`gl`), langue (`hl`), période (`tbs`). |
81
82
  | `braveProvider({ key })` | `api.search.brave.com/res/v1/web/search` | Index indépendant. `extra_snippets` de la même page, `freshness`. Brave réserve le stockage des résultats aux forfaits qui l'incluent : le cache de ce moteur est d'une minute par défaut. |
82
83
  | `tavilyProvider({ key })` | `api.tavily.com/search` | Filtres de domaines natifs, `time_range`. `search_depth: 'basic'` (1 crédit) est fixé. La réponse générée (`answer`) n'est jamais demandée. |
@@ -159,16 +160,15 @@ toolDefinitions('gemini'); // [{ functionDeclarations: [...] }], schéma ne
159
160
  - **`runAgentLoop` de `@astratra/ai`** : `registryTools(ws, { roles })`
160
161
  inscrit `type: 'read'`, `risk: 'LOW'`, `external: true` (la requête sort de
161
162
  l'application : le masque des données personnelles s'y applique).
162
- - **MCP** : `createMcpServer(ws)` de `@astratra/web-search/mcp` (il faut
163
- `@modelcontextprotocol/sdk`) sert les deux mêmes outils, marqués en lecture
163
+ - **MCP** : `createMcpServer(ws)` de `@astratra/web-search/mcp` (protocole de
164
+ `@astratra/mcp`, sans dépendance) sert les deux mêmes outils, marqués en lecture
164
165
  seule. Un serveur stdio prêt à l'emploi lit ses moteurs dans l'environnement :
165
166
 
166
167
  ```bash
167
168
  SERPER_API_KEY=… npx astratra-web-search-mcp
168
169
  ```
169
170
 
170
- L'environnement est lu dans cet ordre : `CENTRALE_ADRESSE` +
171
- `CENTRALE_PASSERELLE_JETON` (passerelle), `SERPER_API_KEY`,
171
+ L'environnement est lu dans cet ordre : `SERPER_API_KEY`,
172
172
  `BRAVE_SEARCH_API_KEY`, `TAVILY_API_KEY`, `EXA_API_KEY`.
173
173
  `WEB_SEARCH_MODE=fallback` pour un moteur à la fois.
174
174
 
@@ -178,6 +178,216 @@ avec leur adresse, leur site, leur date, leur extrait et leurs passages mot
178
178
  pour mot, **dans** un cadre de données non fiables dont la marque aléatoire ne
179
179
  peut pas être refermée par la page. Le texte entier ne dépasse jamais `maxChars`.
180
180
 
181
+ ## Navigateur intégré (lecture seule)
182
+
183
+ Une page construite en JavaScript (React, Vue…) ne donne presque rien à la
184
+ lecture simple. Le navigateur intégré l'ouvre dans un vrai Chromium sans
185
+ fenêtre, attend qu'elle se pose et lit ce qu'une personne voit. Il permet aussi
186
+ de **parcourir** un site (liens numérotés), d'utiliser **sa recherche
187
+ interne** sans cliquer ni taper, et de prendre une **capture d'écran** sur
188
+ demande. Il ne modifie rien sur le web : ni clic qui envoie quelque chose, ni
189
+ formulaire autre qu'une recherche en GET, ni connexion, ni achat.
190
+
191
+ ```js
192
+ const { createWebSearch, createBrowserClient } = require('@astratra/web-search');
193
+
194
+ const ws = createWebSearch({
195
+ providers: [/* … */],
196
+ browser: createBrowserClient({ baseUrl: 'http://127.0.0.1:5008', tokenFile: '/etc/astratra/browser-token' })
197
+ });
198
+
199
+ await ws.read(url); // lecture simple, puis le navigateur sous 200 mots
200
+ const page = await ws.browse(url, { query }); // texte rendu, liens [L1]…, passages
201
+ await ws.browse(page.links[0].url); // suivre un lien
202
+ await ws.searchSite('https://docs.python.org/3/', 'asyncio'); // recherche interne du site
203
+ await ws.browse(url, { screenshot: true }); // page.screenshot : PNG 1280 × 800 au plus
204
+ ```
205
+
206
+ - `reading.browser` : `'fallback'` (défaut avec un navigateur : sous
207
+ `reading.minWords`, 200 mots, la lecture simple passe la main),
208
+ `'always'` ou `'never'`. `page.via` dit qui a lu (`fetch` ou `browser`).
209
+ - Deux outils s'ajoutent quand `browser` est donné, dans `toolDefinitions`
210
+ (`{ browser: true }`), `nativeTools`, `registryTools` et le serveur MCP :
211
+ `browse_page` `{ url, query?, quotes?, screenshot? }` et `search_site`
212
+ `{ url, query }`. Mêmes règles que `read_page` : https seulement, texte
213
+ dans le cadre des données non fiables (liens compris), sources
214
+ `kind: 'web'`, risque `LOW`, genre `read`, `external: true`.
215
+ - Capture d'écran : seulement pour un modèle qui lit les images
216
+ (`nativeTools(ws, { screenshots: true })` rend `images`, le serveur MCP
217
+ `createMcpServer(ws, { screenshots: true })` un contenu image) ; refusée
218
+ sinon. `registryTools` rend du texte seulement.
219
+ - `allowDomains: ['example.com']` (option de `createWebSearch`) limite les
220
+ pages lues et ouvertes à ces sites ; `ranking.blockDomains` est refusé pour
221
+ toutes les lectures (et pour les redirections, dans le navigateur).
222
+ - Recherche interne : la description OpenSearch du site, sinon un formulaire
223
+ `GET` à un seul champ texte de recherche ; l'adresse de résultats est
224
+ calculée puis ouverte, sur le même site. Les moteurs de recherche (Google,
225
+ Bing…) sont refusés : ils s'interrogent par leur API, avec `web_search`.
226
+
227
+ ### Le service `astratra-web-browser`
228
+
229
+ En production, un seul Chromium tourne sur le serveur, partagé par toutes les
230
+ applications, dans un service à part livré par le paquet. Il écoute
231
+ `127.0.0.1:5008` (jamais l'extérieur), demande un jeton `Authorization:
232
+ Bearer` relu dans un fichier à chaque requête, et sert `POST /v1/open`,
233
+ `POST /v1/site-search` et `GET /health`. Chaque requête ouvre un contexte neuf
234
+ (ni cookies, ni stockage, ni cache), une seule page, détruit à la fin ; deux
235
+ pages au plus en même temps (`--max-contexts`), puis une attente bornée, puis
236
+ `503 busy`.
237
+
238
+ Installation sur un serveur Linux (Ubuntu 24, en root) :
239
+
240
+ ```bash
241
+ npm install @astratra/web-search playwright
242
+ PLAYWRIGHT_BROWSERS_PATH=/opt/ms-playwright npx playwright install --with-deps chromium-headless-shell
243
+ npx astratra-web-browser setup --out ./navigateur --node "$(command -v node)" \
244
+ --token-file /etc/astratra/browser-token --browsers-path /opt/ms-playwright
245
+ ```
246
+
247
+ `setup` vérifie d'abord la machine (Linux, systemd, nftables, AppArmor, Node,
248
+ Chromium, résolveur DNS) et dit ce qui manque, puis écrit l'unité systemd, les
249
+ règles nftables et l'unité qui les charge au démarrage (sans toucher aux autres
250
+ règles de la machine), le profil AppArmor et la marche à suivre (`INSTALL.md` en
251
+ anglais, `INSTALL.fr.md` en français). Les résolveurs DNS viennent de
252
+ `/etc/resolv.conf` (`--dns` pour en donner d'autres).
253
+
254
+ **Le jeton** est un secret propre à la
255
+ machine, qui empêche les autres programmes du serveur d'utiliser le
256
+ navigateur. `astratra-web-browser token --out /etc/astratra/browser-token
257
+ --group astratra-browser` le tire au hasard (32 octets) et l'écrit à root, en
258
+ mode 640, lisible par le groupe `astratra-browser`. On met dans ce groupe
259
+ l'utilisateur de chaque application qui appelle le service ; elle le lit avec
260
+ `createBrowserClient({ tokenFile })`. Changer le jeton, c'est réécrire le
261
+ fichier : le service et les clients le relisent à chaque requête.
262
+
263
+ Pour le développement, `createLocalBrowser()` fait tourner le même moteur dans
264
+ le processus (il faut `playwright`) ; il refuse de démarrer quand
265
+ `NODE_ENV=production`, sauf `allowInProduction: true`. Ou bien
266
+ `astratra-web-browser serve --token-file … --unsafe-no-firewall` lance le
267
+ service sur un poste sans pare-feu.
268
+
269
+ `createBrowserPm2App` existe aussi, mais pm2 ne donne aucune des protections
270
+ de systemd (utilisateur à part, système en lecture seule, mémoire bornée) :
271
+ le pare-feu reste obligatoire, et pm2 doit tourner sous l'utilisateur du
272
+ service.
273
+
274
+ ### Pour les utilisateurs du framework : quelle installation choisir
275
+
276
+ Le paquet ne dépend d'aucun service d'Astratra : chacun fait tourner **son**
277
+ navigateur, sur **sa** machine, avec **son** jeton.
278
+
279
+ | Votre hébergement | Ce qu'il faut faire |
280
+ |---|---|
281
+ | Un serveur Linux à vous (VPS, dédié) avec systemd | Le service `astratra-web-browser`, installé par `setup` : la méthode conseillée, la seule avec toutes les protections. |
282
+ | Un serveur Linux sans systemd (pm2 seul) | `createBrowserPm2App`, sous l'utilisateur du service, avec le pare-feu ; moins de protections (ni système en lecture seule, ni mémoire bornée par le noyau). |
283
+ | Un hébergement sans accès root ou sans serveur (Vercel, Netlify, fonctions, Render, Heroku), un conteneur | Pas de navigateur en production pour l'instant : la recherche et `read_page` marchent sans lui. Le mode local ne remplace pas le service. |
284
+ | Un poste de développement (macOS, Windows, Linux) | `createLocalBrowser()`. |
285
+
286
+ - **Mettez votre propre identité.** Par défaut, tous les déploiements se
287
+ présentent comme `AstratraWebBrowser` avec la page GitHub du paquet : donnez
288
+ votre page avec `--info-url` (qui vous êtes, comment vous joindre), et, pour
289
+ signer vos requêtes, votre propre clé publiée sur votre domaine
290
+ (`keygen`, `--signing-key-file`, `--signature-agent`). Un site qui bloque le
291
+ nom `AstratraWebBrowser` dans son `robots.txt` est refusé pour tous.
292
+ - **Seul Ubuntu 24.04 a été essayé** de bout en bout (pare-feu, AppArmor,
293
+ cloisonnement). Debian 12 et Ubuntu 22.04 devraient convenir ; `setup` dit
294
+ ce qui manque.
295
+ - Vous répondez de votre usage : conditions des sites lus, `robots.txt` (le
296
+ paquet le respecte, ne le désactivez pas sans droit), données personnelles
297
+ des pages.
298
+
299
+ ### Isolement
300
+
301
+ Chaque protection tient si une autre cède :
302
+
303
+ - **Utilisateur et processus** : utilisateur système `navigateur`, unité
304
+ systemd durcie (`ProtectSystem=strict`, `ProtectHome`, `PrivateTmp`,
305
+ `NoNewPrivileges`, `MemoryMax=2G`, `CPUQuota=200%`, jeton par
306
+ `LoadCredential`, seuls les espaces de noms dont Chromium a besoin). Le
307
+ service refuse de tourner en root.
308
+ - **Cloisonnement de Chromium** actif : un lancement sans lui est refusé
309
+ (`--no-sandbox` interdit). Sur Ubuntu 23.10 et suivants, le profil AppArmor
310
+ de `setup` lui permet de créer ses espaces de noms.
311
+ - **Relais de sortie** : Chromium n'ouvre aucune connexion lui-même, tout
312
+ passe par un relais du service (boucle locale comprise). Le relais résout
313
+ chaque nom, refuse toute adresse non publique (mêmes plages que
314
+ `isPublicAddress`) et se connecte à l'adresse vérifiée : redirections,
315
+ WebSocket, images, `fetch` des scripts et DNS rebinding sont couverts.
316
+ WebRTC est coupé.
317
+ - **Pare-feu système, obligatoire** : les règles nftables refusent à
318
+ l'utilisateur `navigateur` toute sortie vers une adresse non publique, sauf
319
+ le résolveur DNS et le relais.
320
+ - **Contrôle au démarrage** : le service tente de joindre la boucle locale,
321
+ une adresse privée de la machine et `169.254.169.254` ; si l'une répond, il
322
+ refuse de démarrer (`isolation_failed`). `/health` donne le résultat.
323
+ - **Page** : ni téléchargement, ni `file://`, ni service worker, ni
324
+ permission, ni fenêtre surgissante (fermée), ni boîte de dialogue (refusée).
325
+ 15 s par page, 25 s par requête, 5 redirections, 10 Mo de ressources (les
326
+ requêtes suivantes sont coupées), 2 Mo de texte.
327
+
328
+ ### Ce que lit le modèle
329
+
330
+ Le texte **visible** seulement : les éléments cachés (`display`,
331
+ `visibility`, `opacity`, hors de l'écran, d'un pixel, découpés, police nulle,
332
+ couleur transparente ou égale au fond, `aria-hidden`) sont retirés avant la
333
+ lecture, car un texte caché est l'arme classique pour glisser un ordre à une
334
+ IA. Les bandeaux de cookies, fenêtres d'abonnement et boîtes modales sont
335
+ masqués **sans cliquer**. Les liens (https, 50 au plus, ceux du même site
336
+ d'abord) sont numérotés dans le cadre.
337
+
338
+ Ces protections sont pour l'IA ce que l'isolement est pour le serveur : à
339
+ passer aussi par les gardes de `@astratra/ai`, qui cherchent les injections
340
+ de consignes avec le modèle de garde de `@astratra/models` et refusent toute
341
+ action après un soupçon :
342
+
343
+ ```js
344
+ const { createGuards } = require('@astratra/ai/guards');
345
+ const guards = createGuards({ models }); // client de @astratra/models
346
+ const run = guards.newRun({ mode: 'action' });
347
+ const browse = nativeTools(ws).find((tool) => tool.name === 'browse_page');
348
+ const { data } = await browse.run({ url });
349
+ const checked = await guards.toolResult(data, run, { tool: 'browse_page', external: true });
350
+ // checked.suspected → plus aucune action sans l'accord d'une personne :
351
+ await guards.beforeAction({ name: 'send_email' }, run); // { decision: 'block', reason: 'confirmation_required' }
352
+ ```
353
+
354
+ ### Identité de l'agent
355
+
356
+ - `User-Agent` honnête : `Mozilla/5.0 (compatible; AstratraWebBrowser/<version>; +<infoUrl>)`.
357
+ `--info-url` donne la page qui explique l'agent (par défaut, la page GitHub
358
+ du paquet). Aucune imitation d'un humain, aucun module « furtif » : un site
359
+ qui refuse les agents est refusé.
360
+ - `robots.txt` est respecté pour chaque page ouverte par le navigateur (jeton
361
+ `AstratraWebBrowser`, sinon `*`, cache d'une heure ; un `robots.txt` en
362
+ panne vaut refus) : une page interdite rend `WEB_BROWSE_ROBOTS_DISALLOWED`.
363
+ La cible d'une redirection est vérifiée à l'arrivée : la requête est partie,
364
+ mais la page n'est pas rendue.
365
+ - **Web Bot Auth** (facultatif) : `astratra-web-browser keygen --out cle.pem
366
+ --directory annuaire.json` crée une clé Ed25519 et l'annuaire à publier à
367
+ `/.well-known/http-message-signatures-directory` de votre domaine ; avec
368
+ `--signing-key-file` et `--signature-agent https://votre-domaine`, chaque
369
+ requête est signée (RFC 9421 : `Signature`, `Signature-Input`,
370
+ `Signature-Agent`).
371
+
372
+ ### Erreurs
373
+
374
+ | Code | Quand |
375
+ |---|---|
376
+ | `WEB_BROWSE_ROBOTS_DISALLOWED` | `robots.txt` interdit la page (ou la cible d'une redirection) |
377
+ | `WEB_READ_BLOCKED_ADDRESS` | la page ou une redirection vise une adresse non publique |
378
+ | `WEB_READ_BLOCKED_DOMAIN` | site bloqué (`blockDomains`) ou hors de `allowDomains` |
379
+ | `WEB_BROWSE_NO_SITE_SEARCH` | ni OpenSearch ni formulaire GET de recherche |
380
+ | `WEB_BROWSE_REFUSED` | page de recherche d'un moteur (utiliser `web_search`) |
381
+ | `WEB_BROWSE_BUSY` | le service est plein ; réessayer |
382
+ | `WEB_BROWSE_TIMEOUT` | la page a dépassé son délai |
383
+ | `WEB_BROWSER_UNAVAILABLE` | service arrêté, disjoncteur ouvert, ou `browser` absent |
384
+ | `WEB_READ_BAD_STATUS`, `WEB_READ_UNSUPPORTED_TYPE`, `WEB_READ_TOO_MANY_REDIRECTS`, `WEB_BROWSE_FAILED` | comme pour `read_page` |
385
+
386
+ Le client ne lève jamais : `open` et `siteSearch` rendent `{ ok: true,
387
+ result }` (`result.status` : `ok`, `robots_disallowed`, `blocked`…) ou
388
+ `{ ok: false, code, retryable }`. Délai de 30 s, nouvel essai sur panne réseau
389
+ ou service plein, disjoncteur (trois pannes de suite : 30 s de refus rapides).
390
+
181
391
  ## Évaluation
182
392
 
183
393
  `runEvaluation({ cases, search, recorder, readText })` vérifie, pour chaque
@@ -201,9 +411,12 @@ SERPER_API_KEY=… BRAVE_SEARCH_API_KEY=… npm run eval:live -w @astratra/web-s
201
411
  ## Ce qu'il ne fait pas
202
412
 
203
413
  - Il n'écrit pas de réponse. Il donne des pages ; le modèle répond et cite.
204
- - Il n'exécute pas le JavaScript des pages : une page entièrement construite
205
- dans le navigateur donne peu de texte. Branchez votre `extract`, ou lisez ces
206
- pages autrement.
414
+ - Sans navigateur intégré, il n'exécute pas le JavaScript des pages : une page
415
+ entièrement construite dans le navigateur donne peu de texte (voir
416
+ [Navigateur intégré](#navigateur-intégré-lecture-seule)).
417
+ - Le navigateur intégré ne fait que lire : il ne clique pas, ne remplit aucun
418
+ formulaire (sauf une recherche en GET, par son adresse), ne se connecte pas,
419
+ n'achète rien. Ni JSON ni PDF.
207
420
  - Il ne lit ni les PDF ni les images.
208
421
  - Il ne contourne ni les murs payants, ni les règles des robots, ni les
209
422
  conditions des moteurs. Vérifiez les conditions de chaque moteur utilisé,
@@ -221,4 +434,7 @@ npm test -w @astratra/web-search
221
434
 
222
435
  Les tests n'appellent jamais Internet : les moteurs sont simulés, et les
223
436
  lectures de pages passent par un réseau simulé qui utilise le même `lookup`
224
- que le vrai.
437
+ que le vrai. Les tests du navigateur tournent sur un vrai Chromium contre un
438
+ petit site HTTPS local de pages pièges (texte caché, redirections et
439
+ WebSocket vers l'intérieur, téléchargement, page énorme…) ; ils sont sautés
440
+ sans Playwright ni Chromium.
package/README.md CHANGED
@@ -2,14 +2,15 @@
2
2
 
3
3
  Web search for AI agents, where every fact stays attached to its page.
4
4
 
5
- Several engines (Serper for Google results, Brave Search, Tavily, Exa, or the
6
- Centrale gateway) with automatic fallback; their **rankings** are fused, their
5
+ Several engines (Serper for Google results, Brave Search, Tavily, Exa, or a
6
+ search gateway of your own) with automatic fallback; their **rankings** are fused, their
7
7
  **contents never are**. Each result is one page of one site, with its exact
8
8
  address, its domain, its date when known, the excerpt of **one** engine for
9
9
  **that** page, and, when the page is read, passages quoted word for word with
10
10
  their position. Pages are read without opening a door to your internal network
11
11
  (SSRF), and everything a model reads from the web is framed as data, not
12
- instructions.
12
+ instructions. An optional, isolated integrated browser reads pages built with
13
+ JavaScript, walks a site's links and uses its own search.
13
14
 
14
15
  [Version française](README.fr.md)
15
16
 
@@ -29,14 +30,13 @@ each one checkable (see [Evaluation](#evaluation)).
29
30
  ## Quick start
30
31
 
31
32
  ```js
32
- const { createWebSearch, gatewayProvider, braveProvider, formatForModel } = require('@astratra/web-search');
33
- const { lirePasserelle, rechercher } = await import('@astratra/centrale/passerelle');
33
+ const { createWebSearch, braveProvider, tavilyProvider, formatForModel } = require('@astratra/web-search');
34
34
 
35
- const gateway = lirePasserelle(process.env); // the app only keeps a project token
35
+ // The engines and their order are yours: none is chosen by the package.
36
36
  const ws = createWebSearch({
37
37
  providers: [
38
- gatewayProvider({ search: (demande, { signal }) => rechercher(gateway, demande, { signal }) }),
39
- braveProvider({ key: () => process.env.BRAVE_SEARCH_API_KEY })
38
+ braveProvider({ key: () => process.env.BRAVE_SEARCH_API_KEY }),
39
+ tavilyProvider({ key: () => process.env.TAVILY_API_KEY })
40
40
  ]
41
41
  });
42
42
 
@@ -75,7 +75,7 @@ formatForModel(found); // the text to give a model: citation rules, then the s
75
75
 
76
76
  | Provider | Endpoint | Notes |
77
77
  |---|---|---|
78
- | `gatewayProvider({ search })` | the Centrale gateway (`rechercher` of `@astratra/centrale/passerelle`) | Recommended: the keys stay in the Centrale's vault, the cost is counted there (`costPerCallUsd: null`). Sites are sent as `site:` operators. |
78
+ | `gatewayProvider({ search })` | a search gateway of your own: `search({ requete, nombre, langue?, pays?, periode? }, { signal })` returns `{ fournisseur, resultats: [{ titre, url, extrait, date? }] }` | The engine keys stay with your gateway, which counts the cost (`costPerCallUsd: null`). Sites are sent as `site:` operators. |
79
79
  | `serperProvider({ key })` | `google.serper.dev` | Reuses `searchSerper` of `@astratra/ai`. Country (`gl`), language (`hl`), period (`tbs`). |
80
80
  | `braveProvider({ key })` | `api.search.brave.com/res/v1/web/search` | Independent index. `extra_snippets` of the same page, `freshness`. Brave reserves storing results to plans that include it: the cache of this engine is 1 minute by default. |
81
81
  | `tavilyProvider({ key })` | `api.tavily.com/search` | Native domain filters, `time_range`. `search_depth: 'basic'` (1 credit) is set explicitly. The generated `answer` is never requested. |
@@ -155,16 +155,15 @@ toolDefinitions('gemini'); // [{ functionDeclarations: [...] }], schema cle
155
155
  - **`runAgentLoop` of `@astratra/ai`**: `registryTools(ws, { roles })` registers
156
156
  `type: 'read'`, `risk: 'LOW'`, `external: true` (the query leaves the
157
157
  application: the masker applies to it).
158
- - **MCP**: `createMcpServer(ws)` from `@astratra/web-search/mcp` (needs
159
- `@modelcontextprotocol/sdk`) serves the same two tools, marked read-only. A
158
+ - **MCP**: `createMcpServer(ws)` from `@astratra/web-search/mcp` (protocol from
159
+ `@astratra/mcp`, no dependency) serves the same two tools, marked read-only. A
160
160
  ready-made stdio server reads its engines from the environment:
161
161
 
162
162
  ```bash
163
163
  SERPER_API_KEY=… npx astratra-web-search-mcp
164
164
  ```
165
165
 
166
- The environment is checked in this order: `CENTRALE_ADRESSE` +
167
- `CENTRALE_PASSERELLE_JETON` (gateway), `SERPER_API_KEY`,
166
+ The environment is checked in this order: `SERPER_API_KEY`,
168
167
  `BRAVE_SEARCH_API_KEY`, `TAVILY_API_KEY`, `EXA_API_KEY`. Set
169
168
  `WEB_SEARCH_MODE=fallback` to use one engine at a time.
170
169
 
@@ -173,6 +172,209 @@ words to another) **outside** the frame; the sources, with their address, site,
173
172
  date, snippet and verbatim passages, **inside** a frame of untrusted data whose
174
173
  random marker the page cannot close. The whole text never exceeds `maxChars`.
175
174
 
175
+ ## Integrated browser (read-only)
176
+
177
+ A page built with JavaScript (React, Vue…) gives almost nothing to a plain
178
+ read. The integrated browser opens it in a real headless Chromium, waits for it
179
+ to settle and reads what a person sees. It can also **walk** a site (numbered
180
+ links), use **its own search** without clicking or typing, and take a
181
+ **screenshot** on request. It changes nothing on the web: no click that sends
182
+ anything, no form other than a GET search, no sign-in, no purchase.
183
+
184
+ ```js
185
+ const { createWebSearch, createBrowserClient } = require('@astratra/web-search');
186
+
187
+ const ws = createWebSearch({
188
+ providers: [/* … */],
189
+ browser: createBrowserClient({ baseUrl: 'http://127.0.0.1:5008', tokenFile: '/etc/astratra/browser-token' })
190
+ });
191
+
192
+ await ws.read(url); // plain read, then the browser under 200 words
193
+ const page = await ws.browse(url, { query }); // rendered text, links [L1]…, passages
194
+ await ws.browse(page.links[0].url); // follow a link
195
+ await ws.searchSite('https://docs.python.org/3/', 'asyncio'); // the site's own search
196
+ await ws.browse(url, { screenshot: true }); // page.screenshot: PNG, 1280 × 800 at most
197
+ ```
198
+
199
+ - `reading.browser`: `'fallback'` (default with a browser: under
200
+ `reading.minWords`, 200 words, the plain read hands over), `'always'` or
201
+ `'never'`. `page.via` says who read it (`fetch` or `browser`).
202
+ - Two tools are added when `browser` is given, in `toolDefinitions`
203
+ (`{ browser: true }`), `nativeTools`, `registryTools` and the MCP server:
204
+ `browse_page` `{ url, query?, quotes?, screenshot? }` and `search_site`
205
+ `{ url, query }`. Same rules as `read_page`: https only, text inside the
206
+ untrusted-data frame (links included), sources `kind: 'web'`, risk `LOW`,
207
+ kind `read`, `external: true`.
208
+ - Screenshots: only for a model that reads images
209
+ (`nativeTools(ws, { screenshots: true })` returns `images`,
210
+ `createMcpServer(ws, { screenshots: true })` an image content); refused
211
+ otherwise. `registryTools` returns text only.
212
+ - `allowDomains: ['example.com']` (option of `createWebSearch`) limits the
213
+ pages read and opened to those sites; `ranking.blockDomains` is refused for
214
+ every read (and for redirects, inside the browser).
215
+ - Site search: the site's OpenSearch description, else a `GET` form with a
216
+ single search text field; the results address is computed, then opened, on
217
+ the same site. Search engines (Google, Bing…) are refused: query them through
218
+ their API, with `web_search`.
219
+
220
+ ### The `astratra-web-browser` service
221
+
222
+ In production, one Chromium runs on the server, shared by every application,
223
+ in a separate service shipped with the package. It listens on
224
+ `127.0.0.1:5008` (never outside), requires an `Authorization: Bearer` token
225
+ read from a file on every request, and serves `POST /v1/open`,
226
+ `POST /v1/site-search` and `GET /health`. Each request opens a fresh context
227
+ (no cookies, storage or cache), one page, destroyed at the end; two pages at
228
+ most at a time (`--max-contexts`), then a bounded wait, then `503 busy`.
229
+
230
+ Install on a Linux server (Ubuntu 24, as root):
231
+
232
+ ```bash
233
+ npm install @astratra/web-search playwright
234
+ PLAYWRIGHT_BROWSERS_PATH=/opt/ms-playwright npx playwright install --with-deps chromium-headless-shell
235
+ npx astratra-web-browser setup --out ./browser --node "$(command -v node)" \
236
+ --token-file /etc/astratra/browser-token --browsers-path /opt/ms-playwright
237
+ ```
238
+
239
+ `setup` first checks the machine (Linux, systemd, nftables, AppArmor, Node,
240
+ Chromium, DNS resolver) and says what is missing, then writes the systemd
241
+ unit, the nftables rules and the unit that loads them at boot (leaving the
242
+ machine's other rules alone), the AppArmor profile and the steps to follow
243
+ (`INSTALL.md` in English, `INSTALL.fr.md` in French). DNS resolvers are read
244
+ from `/etc/resolv.conf` (`--dns` to give others).
245
+
246
+ **The token** is a secret of the machine, which
247
+ keeps the server's other programs from using the browser.
248
+ `astratra-web-browser token --out /etc/astratra/browser-token --group
249
+ astratra-browser` draws it at random (32 bytes) and writes it owned by root,
250
+ mode 640, readable by the `astratra-browser` group. Put in that group the user
251
+ of each application that calls the service; it reads the token with
252
+ `createBrowserClient({ tokenFile })`. To change the token, rewrite the file:
253
+ the service and the clients read it again on every request.
254
+
255
+ For development, `createLocalBrowser()` runs the same engine in-process
256
+ (requires `playwright`); it refuses to start when `NODE_ENV=production`,
257
+ unless `allowInProduction: true`. Or `astratra-web-browser serve --token-file
258
+ … --unsafe-no-firewall` starts the service on a machine without the firewall.
259
+
260
+ `createBrowserPm2App` exists too, but pm2 gives none of systemd's protections
261
+ (own user, read-only system, bounded memory): the firewall stays mandatory,
262
+ and pm2 must run as the service user.
263
+
264
+ ### For framework users: which setup to choose
265
+
266
+ The package depends on no Astratra service: everyone runs **their own**
267
+ browser, on **their own** machine, with **their own** token.
268
+
269
+ | Your hosting | What to do |
270
+ |---|---|
271
+ | A Linux server of your own (VPS, dedicated) with systemd | The `astratra-web-browser` service, installed by `setup`: the recommended way, the only one with every protection. |
272
+ | A Linux server without systemd (pm2 only) | `createBrowserPm2App`, as the service user, with the firewall; fewer protections (no read-only system, no kernel-bounded memory). |
273
+ | Hosting without root access or without a server (Vercel, Netlify, functions, Render, Heroku), a container | No browser in production for now: search and `read_page` work without it. The local mode does not replace the service. |
274
+ | A development machine (macOS, Windows, Linux) | `createLocalBrowser()`. |
275
+
276
+ - **Use your own identity.** By default every deployment presents itself as
277
+ `AstratraWebBrowser` with the package's GitHub page: give your own page with
278
+ `--info-url` (who you are, how to reach you), and, to sign your requests,
279
+ your own key published on your domain (`keygen`, `--signing-key-file`,
280
+ `--signature-agent`). A site that blocks the `AstratraWebBrowser` name in its
281
+ `robots.txt` is refused for everyone.
282
+ - **Only Ubuntu 24.04 was tried** end to end (firewall, AppArmor, sandbox).
283
+ Debian 12 and Ubuntu 22.04 should do; `setup` says what is missing.
284
+ - You answer for your use: terms of the sites read, `robots.txt` (the package
285
+ respects it; do not turn that off without the right to), personal data on
286
+ the pages.
287
+
288
+ ### Isolation
289
+
290
+ Each protection holds if another one gives way:
291
+
292
+ - **User and process**: `navigateur` system user, hardened systemd unit
293
+ (`ProtectSystem=strict`, `ProtectHome`, `PrivateTmp`, `NoNewPrivileges`,
294
+ `MemoryMax=2G`, `CPUQuota=200%`, token through `LoadCredential`, only the
295
+ namespaces Chromium needs). The service refuses to run as root.
296
+ - **Chromium sandbox** on: a launch without it is refused (`--no-sandbox`
297
+ forbidden). On Ubuntu 23.10 and later, the AppArmor profile from `setup` lets
298
+ it create its namespaces.
299
+ - **Egress relay**: Chromium opens no connection itself; everything goes
300
+ through a relay inside the service (loopback included). The relay resolves
301
+ every name, refuses any non-public address (same ranges as
302
+ `isPublicAddress`) and connects to the checked address: redirects,
303
+ WebSockets, images, script `fetch` calls and DNS rebinding are covered.
304
+ WebRTC is off.
305
+ - **System firewall, mandatory**: the nftables rules refuse the `navigateur`
306
+ user any outgoing connection to a non-public address, except the DNS
307
+ resolver and the relay.
308
+ - **Startup check**: the service tries to reach loopback, a private address of
309
+ the machine and `169.254.169.254`; if one answers, it refuses to start
310
+ (`isolation_failed`). `/health` reports the result.
311
+ - **Page**: no downloads, no `file://`, no service workers, no permissions, no
312
+ pop-ups (closed), no dialogs (dismissed). 15 s per page, 25 s per request,
313
+ 5 redirects, 10 MB of resources (later requests are cut), 2 MB of text.
314
+
315
+ ### What the model reads
316
+
317
+ **Visible** text only: hidden elements (`display`, `visibility`, `opacity`,
318
+ off-screen, one pixel, clipped, zero font size, transparent colour or the
319
+ background's colour, `aria-hidden`) are removed before reading, because hidden
320
+ text is the classic way to slip an order to an AI. Cookie banners, subscription
321
+ pop-ups and modal boxes are hidden **without clicking**. Links (https, 50 at
322
+ most, same site first) are numbered inside the frame.
323
+
324
+ These protections do for the AI what isolation does for the server: also run
325
+ pages through the guards of `@astratra/ai`, which look for prompt injection
326
+ with the guard model of `@astratra/models` and refuse any action after a
327
+ suspicion:
328
+
329
+ ```js
330
+ const { createGuards } = require('@astratra/ai/guards');
331
+ const guards = createGuards({ models }); // @astratra/models client
332
+ const run = guards.newRun({ mode: 'action' });
333
+ const browse = nativeTools(ws).find((tool) => tool.name === 'browse_page');
334
+ const { data } = await browse.run({ url });
335
+ const checked = await guards.toolResult(data, run, { tool: 'browse_page', external: true });
336
+ // checked.suspected → no action without a person's approval:
337
+ await guards.beforeAction({ name: 'send_email' }, run); // { decision: 'block', reason: 'confirmation_required' }
338
+ ```
339
+
340
+ ### Agent identity
341
+
342
+ - Honest `User-Agent`: `Mozilla/5.0 (compatible; AstratraWebBrowser/<version>; +<infoUrl>)`.
343
+ `--info-url` is the page that explains the agent (by default, the package's
344
+ GitHub page). No human imitation, no "stealth" module: a site that refuses
345
+ agents is refused.
346
+ - `robots.txt` is respected for every page the browser opens (token
347
+ `AstratraWebBrowser`, else `*`, one-hour cache; a failing `robots.txt` means
348
+ no): a disallowed page gives `WEB_BROWSE_ROBOTS_DISALLOWED`. A redirect
349
+ target is checked on arrival: the request went out, but the page is not
350
+ returned.
351
+ - **Web Bot Auth** (optional): `astratra-web-browser keygen --out key.pem
352
+ --directory directory.json` creates an Ed25519 key and the directory to
353
+ publish at `/.well-known/http-message-signatures-directory` of your domain;
354
+ with `--signing-key-file` and `--signature-agent https://your-domain`, every
355
+ request is signed (RFC 9421: `Signature`, `Signature-Input`,
356
+ `Signature-Agent`).
357
+
358
+ ### Errors
359
+
360
+ | Code | When |
361
+ |---|---|
362
+ | `WEB_BROWSE_ROBOTS_DISALLOWED` | `robots.txt` disallows the page (or a redirect target) |
363
+ | `WEB_READ_BLOCKED_ADDRESS` | the page or a redirect points to a non-public address |
364
+ | `WEB_READ_BLOCKED_DOMAIN` | blocked site (`blockDomains`) or outside `allowDomains` |
365
+ | `WEB_BROWSE_NO_SITE_SEARCH` | neither OpenSearch nor a GET search form |
366
+ | `WEB_BROWSE_REFUSED` | a search engine's results page (use `web_search`) |
367
+ | `WEB_BROWSE_BUSY` | the service is full; try again |
368
+ | `WEB_BROWSE_TIMEOUT` | the page ran out of time |
369
+ | `WEB_BROWSER_UNAVAILABLE` | service down, circuit open, or no `browser` |
370
+ | `WEB_READ_BAD_STATUS`, `WEB_READ_UNSUPPORTED_TYPE`, `WEB_READ_TOO_MANY_REDIRECTS`, `WEB_BROWSE_FAILED` | as for `read_page` |
371
+
372
+ The client never throws: `open` and `siteSearch` return `{ ok: true, result }`
373
+ (`result.status`: `ok`, `robots_disallowed`, `blocked`…) or
374
+ `{ ok: false, code, retryable }`. 30 s timeout, a retry on network failure or
375
+ a full service, a circuit breaker (three failures in a row: 30 s of fast
376
+ refusals).
377
+
176
378
  ## Evaluation
177
379
 
178
380
  `runEvaluation({ cases, search, recorder, readText })` checks, for each case:
@@ -195,8 +397,11 @@ SERPER_API_KEY=… BRAVE_SEARCH_API_KEY=… npm run eval:live -w @astratra/web-s
195
397
  ## What it does not do
196
398
 
197
399
  - It does not write an answer. It gives pages; the model answers and cites.
198
- - It does not run JavaScript on pages: a page built entirely in the browser
199
- gives little text. Plug in your own `extract`, or read such pages another way.
400
+ - Without the integrated browser, it does not run JavaScript on pages: a page
401
+ built entirely in the browser gives little text (see
402
+ [Integrated browser](#integrated-browser-read-only)).
403
+ - The integrated browser only reads: it does not click, fill in any form
404
+ (except a GET search, through its address), sign in or buy. No JSON, no PDF.
200
405
  - It does not read PDFs or images.
201
406
  - It does not bypass paywalls, robots rules or engine terms. Check the terms of
202
407
  each engine you use, in particular about storing results.
@@ -212,4 +417,7 @@ npm test -w @astratra/web-search
212
417
  ```
213
418
 
214
419
  The tests never call the Internet: engines are simulated, and page reads go
215
- through a simulated network that uses the same `lookup` as the real one.
420
+ through a simulated network that uses the same `lookup` as the real one. The
421
+ browser tests run on a real Chromium against a small local HTTPS site of trap
422
+ pages (hidden text, redirects and WebSockets to the inside, downloads, a huge
423
+ page…); they are skipped without Playwright or Chromium.