@astratra/web-search 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/README.fr.md +224 -0
- package/README.md +214 -2
- package/package.json +71 -4
- package/src/address.js +71 -0
- package/src/dates.js +91 -0
- package/src/errors.js +64 -0
- package/src/evaluation.js +126 -0
- package/src/extract.js +277 -0
- package/src/format.js +102 -0
- package/src/fusion.js +155 -0
- package/src/index.d.ts +379 -0
- package/src/index.js +26 -0
- package/src/mcp.d.ts +7 -0
- package/src/mcp.js +63 -0
- package/src/mcpStdio.js +53 -0
- package/src/passages.js +129 -0
- package/src/providers/brave.js +72 -0
- package/src/providers/exa.js +73 -0
- package/src/providers/gateway.js +73 -0
- package/src/providers/http.js +51 -0
- package/src/providers/serper.js +55 -0
- package/src/providers/tavily.js +81 -0
- package/src/query.js +129 -0
- package/src/safeFetch.js +228 -0
- package/src/stores.js +61 -0
- package/src/text.js +59 -0
- package/src/tools.js +164 -0
- package/src/url.js +77 -0
- package/src/webSearch.js +466 -0
package/src/fusion.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* La fusion des classements de plusieurs moteurs, SANS fusion des contenus.
|
|
3
|
+
*
|
|
4
|
+
* Reciprocal Rank Fusion (Cormack, Clarke et Büttcher, 2009) : une page gagne
|
|
5
|
+
* 1 / (k + rang) dans chaque liste où elle paraît. Seul le CLASSEMENT est
|
|
6
|
+
* fusionné. Le texte d'une entrée (titre, extrait, extraits en plus) vient d'un
|
|
7
|
+
* seul moteur, celui qui l'a le mieux classée, et `snippetFrom` le nomme : deux
|
|
8
|
+
* extraits de deux moteurs ne sont jamais collés ensemble, même pour la même page.
|
|
9
|
+
*
|
|
10
|
+
* Une entrée = une page canonique = un site. Deux adresses qui mènent à la
|
|
11
|
+
* même page canonique ne font qu'une entrée ; deux pages différentes ne sont
|
|
12
|
+
* jamais réunies, même si leur texte se ressemble.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const { canonicalUrl, domainOf, inSite } = require('./url');
|
|
16
|
+
const { ageInDays } = require('./dates');
|
|
17
|
+
const { FRESHNESS_DAYS } = require('./query');
|
|
18
|
+
|
|
19
|
+
const DEFAULT_K = 60;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @param {{ provider: string, hits: object[], weight?: number }[]} lists dans l'ordre de préférence des moteurs.
|
|
23
|
+
* @param {{ k?: number }} [options]
|
|
24
|
+
* @returns {object[]} les entrées, de la mieux classée à la moins bien classée.
|
|
25
|
+
*/
|
|
26
|
+
function fuseRankings(lists, { k = DEFAULT_K } = {}) {
|
|
27
|
+
const entries = new Map();
|
|
28
|
+
lists.forEach(({ provider, hits, weight = 1 }, listIndex) => {
|
|
29
|
+
const seenHere = new Set();
|
|
30
|
+
(hits || []).forEach((hit, index) => {
|
|
31
|
+
const canonical = canonicalUrl(hit.url);
|
|
32
|
+
if (!canonical || seenHere.has(canonical)) return;
|
|
33
|
+
seenHere.add(canonical);
|
|
34
|
+
const rank = index + 1;
|
|
35
|
+
const gain = weight / (k + rank);
|
|
36
|
+
const entry = entries.get(canonical);
|
|
37
|
+
if (!entry) {
|
|
38
|
+
entries.set(canonical, {
|
|
39
|
+
canonicalUrl: canonical,
|
|
40
|
+
url: hit.url,
|
|
41
|
+
domain: domainOf(canonical),
|
|
42
|
+
title: hit.title,
|
|
43
|
+
snippet: hit.snippet || '',
|
|
44
|
+
extraSnippets: Array.isArray(hit.extraSnippets) ? [...hit.extraSnippets] : [],
|
|
45
|
+
snippetFrom: provider,
|
|
46
|
+
publishedAt: hit.publishedAt || null,
|
|
47
|
+
dateSource: hit.publishedAt ? provider : null,
|
|
48
|
+
foundBy: [provider],
|
|
49
|
+
ranks: { [provider]: rank },
|
|
50
|
+
score: gain,
|
|
51
|
+
bestRank: rank,
|
|
52
|
+
bestList: listIndex
|
|
53
|
+
});
|
|
54
|
+
return;
|
|
55
|
+
}
|
|
56
|
+
entry.score += gain;
|
|
57
|
+
entry.foundBy.push(provider);
|
|
58
|
+
entry.ranks[provider] = rank;
|
|
59
|
+
/* Le texte suit le moteur qui a le mieux classé la page, en entier : titre,
|
|
60
|
+
adresse, extraits et date de ce moteur, jamais un mélange. */
|
|
61
|
+
if (rank < entry.bestRank || (rank === entry.bestRank && listIndex < entry.bestList)) {
|
|
62
|
+
entry.url = hit.url;
|
|
63
|
+
entry.title = hit.title;
|
|
64
|
+
entry.snippet = hit.snippet || '';
|
|
65
|
+
entry.extraSnippets = Array.isArray(hit.extraSnippets) ? [...hit.extraSnippets] : [];
|
|
66
|
+
entry.snippetFrom = provider;
|
|
67
|
+
if (hit.publishedAt) {
|
|
68
|
+
entry.publishedAt = hit.publishedAt;
|
|
69
|
+
entry.dateSource = provider;
|
|
70
|
+
}
|
|
71
|
+
entry.bestRank = rank;
|
|
72
|
+
entry.bestList = listIndex;
|
|
73
|
+
} else if (!entry.publishedAt && hit.publishedAt) {
|
|
74
|
+
/* Une date donnée par un autre moteur pour LA MÊME page : on la garde, en le disant. */
|
|
75
|
+
entry.publishedAt = hit.publishedAt;
|
|
76
|
+
entry.dateSource = provider;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
return [...entries.values()]
|
|
81
|
+
.sort((a, b) => (b.score - a.score) || (a.bestRank - b.bestRank) || (a.bestList - b.bestList))
|
|
82
|
+
.map(({ bestRank: _r, bestList: _l, ...entry }) => entry);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Le classement final : filtres de sites, fraîcheur, qualité des domaines, plafond par site.
|
|
87
|
+
*
|
|
88
|
+
* @param {object[]} entries sortie de fuseRankings
|
|
89
|
+
* @param {object} request sortie de normalizeRequest
|
|
90
|
+
* @param {object} [options]
|
|
91
|
+
* @param {number} [options.now]
|
|
92
|
+
* @param {string[]} [options.blockDomains] jamais rendus.
|
|
93
|
+
* @param {string[]} [options.preferDomains] score × 1,5.
|
|
94
|
+
* @param {string[]} [options.demoteDomains] score × 0,5.
|
|
95
|
+
* @param {Function} [options.domainScore] (domain) => multiplicateur (≥ 0 ; 0 écarte).
|
|
96
|
+
* @param {number} [options.maxPerDomain] Défaut 2.
|
|
97
|
+
* @returns {{ entries: object[], dropped: { domain: number, freshness: number, perDomain: number } }}
|
|
98
|
+
*/
|
|
99
|
+
function rankEntries(entries, request, options = {}) {
|
|
100
|
+
const now = options.now ?? Date.now();
|
|
101
|
+
const block = options.blockDomains || [];
|
|
102
|
+
const prefer = options.preferDomains || [];
|
|
103
|
+
const demote = options.demoteDomains || [];
|
|
104
|
+
const maxPerDomain = options.maxPerDomain ?? 2;
|
|
105
|
+
const dropped = { domain: 0, freshness: 0, perDomain: 0 };
|
|
106
|
+
const limitDays = request.freshness ? FRESHNESS_DAYS[request.freshness] + 1 : null;
|
|
107
|
+
|
|
108
|
+
const scored = [];
|
|
109
|
+
for (const entry of entries) {
|
|
110
|
+
const domain = entry.domain;
|
|
111
|
+
const blocked = block.some((site) => inSite(domain, site))
|
|
112
|
+
|| request.excludeSites.some((site) => inSite(domain, site))
|
|
113
|
+
|| (request.sites.length > 0 && !request.sites.some((site) => inSite(domain, site)));
|
|
114
|
+
if (blocked) {
|
|
115
|
+
dropped.domain += 1;
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
const age = ageInDays(entry.publishedAt, now);
|
|
119
|
+
if (limitDays !== null && age !== null && age > limitDays) {
|
|
120
|
+
dropped.freshness += 1;
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
let factor = 1;
|
|
124
|
+
if (prefer.some((site) => inSite(domain, site))) factor *= 1.5;
|
|
125
|
+
if (demote.some((site) => inSite(domain, site))) factor *= 0.5;
|
|
126
|
+
if (typeof options.domainScore === 'function') {
|
|
127
|
+
const value = Number(options.domainScore(domain));
|
|
128
|
+
if (Number.isFinite(value) && value >= 0) factor *= value;
|
|
129
|
+
}
|
|
130
|
+
if (factor === 0) {
|
|
131
|
+
dropped.domain += 1;
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
/* Récent d'abord quand la question le veut : un bonus qui décroît avec l'âge
|
|
135
|
+
(×2 aujourd'hui, ×1,5 à une semaine…) ; une page sans date n'en a pas. */
|
|
136
|
+
if (request.recency?.wanted && age !== null) factor *= 1 + 1 / (1 + age / 7);
|
|
137
|
+
scored.push({ ...entry, score: entry.score * factor });
|
|
138
|
+
}
|
|
139
|
+
scored.sort((a, b) => b.score - a.score);
|
|
140
|
+
|
|
141
|
+
const perDomain = new Map();
|
|
142
|
+
const kept = [];
|
|
143
|
+
for (const entry of scored) {
|
|
144
|
+
const count = perDomain.get(entry.domain) || 0;
|
|
145
|
+
if (count >= maxPerDomain) {
|
|
146
|
+
dropped.perDomain += 1;
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
perDomain.set(entry.domain, count + 1);
|
|
150
|
+
kept.push(entry);
|
|
151
|
+
}
|
|
152
|
+
return { entries: kept, dropped };
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
module.exports = { fuseRankings, rankEntries, RRF_K: DEFAULT_K };
|
package/src/index.d.ts
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
/* @astratra/web-search — une recherche web pour les IA où chaque fait reste attaché à sa page. */
|
|
2
|
+
|
|
3
|
+
export type FetchLike = (url: string, init?: any) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>;
|
|
4
|
+
export type Freshness = 'day' | 'week' | 'month' | 'year';
|
|
5
|
+
export type KeySource = string | (() => string | null | undefined | Promise<string | null | undefined>);
|
|
6
|
+
|
|
7
|
+
/* ─────────────────── Erreurs ─────────────────── */
|
|
8
|
+
|
|
9
|
+
export const CODES: Readonly<{
|
|
10
|
+
BAD_REQUEST: 'WEB_SEARCH_BAD_REQUEST';
|
|
11
|
+
NO_PROVIDER: 'WEB_SEARCH_NO_PROVIDER';
|
|
12
|
+
ALL_FAILED: 'WEB_SEARCH_ALL_FAILED';
|
|
13
|
+
PROVIDER_FAILED: 'WEB_SEARCH_PROVIDER_FAILED';
|
|
14
|
+
QUOTA: 'WEB_SEARCH_QUOTA';
|
|
15
|
+
BLOCKED_URL: 'WEB_READ_BLOCKED_URL';
|
|
16
|
+
BLOCKED_ADDRESS: 'WEB_READ_BLOCKED_ADDRESS';
|
|
17
|
+
TOO_MANY_REDIRECTS: 'WEB_READ_TOO_MANY_REDIRECTS';
|
|
18
|
+
TOO_LARGE: 'WEB_READ_TOO_LARGE';
|
|
19
|
+
TIMEOUT: 'WEB_READ_TIMEOUT';
|
|
20
|
+
BAD_STATUS: 'WEB_READ_BAD_STATUS';
|
|
21
|
+
UNSUPPORTED_TYPE: 'WEB_READ_UNSUPPORTED_TYPE';
|
|
22
|
+
READ_FAILED: 'WEB_READ_FAILED';
|
|
23
|
+
}>;
|
|
24
|
+
|
|
25
|
+
export class WebSearchError extends Error {
|
|
26
|
+
constructor(code: string, message: string, details?: { provider?: string; status?: number; retryable?: boolean; quota?: boolean });
|
|
27
|
+
readonly code: string;
|
|
28
|
+
readonly provider?: string;
|
|
29
|
+
readonly status?: number;
|
|
30
|
+
retryable: boolean;
|
|
31
|
+
quota: boolean;
|
|
32
|
+
/** Sur WEB_SEARCH_ALL_FAILED : le compte rendu de la recherche (sans clé). */
|
|
33
|
+
report?: SearchReport;
|
|
34
|
+
}
|
|
35
|
+
export function redact(text: unknown, secrets?: string[]): string;
|
|
36
|
+
export function providerFailure(provider: string, details?: { status?: number; cause?: unknown; secrets?: string[] }): WebSearchError;
|
|
37
|
+
|
|
38
|
+
/* ─────────────────── Demande ─────────────────── */
|
|
39
|
+
|
|
40
|
+
export interface SearchInput {
|
|
41
|
+
query: string;
|
|
42
|
+
lang?: string;
|
|
43
|
+
country?: string;
|
|
44
|
+
/** Un filtre ('day'…'year'), 'any', ou 'auto' (défaut : le récent passe devant quand la question le demande). */
|
|
45
|
+
freshness?: Freshness | 'auto' | 'any';
|
|
46
|
+
sites?: string[];
|
|
47
|
+
excludeSites?: string[];
|
|
48
|
+
/** 1 à 20, défaut 8. */
|
|
49
|
+
limit?: number;
|
|
50
|
+
/** Lire les N premières pages (0 à 5) et y ajouter des passages mot pour mot. */
|
|
51
|
+
read?: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface Recency { wanted: boolean; window: Freshness | null; reason: string | null }
|
|
55
|
+
|
|
56
|
+
export interface SearchRequest {
|
|
57
|
+
query: string;
|
|
58
|
+
lang: string | null;
|
|
59
|
+
country: string | null;
|
|
60
|
+
freshness: Freshness | null;
|
|
61
|
+
recency: Recency;
|
|
62
|
+
sites: string[];
|
|
63
|
+
excludeSites: string[];
|
|
64
|
+
limit: number;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const FRESHNESS: readonly Freshness[];
|
|
68
|
+
export const FRESHNESS_DAYS: Readonly<Record<Freshness, number>>;
|
|
69
|
+
export const MAX_LIMIT: number;
|
|
70
|
+
export function normalizeRequest(input: string | SearchInput, defaults?: { now?: number; lang?: string; country?: string; limit?: number }): SearchRequest;
|
|
71
|
+
export function detectRecency(query: string, options?: { now?: number }): Recency;
|
|
72
|
+
export function withOperators(request: SearchRequest, options?: { includeSites?: boolean }): string;
|
|
73
|
+
|
|
74
|
+
/* ─────────────────── Fournisseurs ─────────────────── */
|
|
75
|
+
|
|
76
|
+
export interface ProviderHit {
|
|
77
|
+
title: string;
|
|
78
|
+
url: string;
|
|
79
|
+
snippet: string;
|
|
80
|
+
/** D'autres extraits de LA MÊME page, donnés par le même moteur. */
|
|
81
|
+
extraSnippets?: string[];
|
|
82
|
+
publishedAt: string | null;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export interface SearchProvider {
|
|
86
|
+
id: string;
|
|
87
|
+
/** Estimation par appel réussi ; null quand un tiers compte le coût (la passerelle). */
|
|
88
|
+
costPerCallUsd?: number | null;
|
|
89
|
+
cacheTtlMs?: number;
|
|
90
|
+
search(request: SearchRequest, context: { signal?: AbortSignal; now?: number }): Promise<{ hits: ProviderHit[]; costUsd?: number; engine?: string | null }>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
interface ProviderOptions { key: KeySource; fetch?: FetchLike; endpoint?: string; timeoutMs?: number; costPerCallUsd?: number; cacheTtlMs?: number; id?: string }
|
|
94
|
+
|
|
95
|
+
export function serperProvider(options: ProviderOptions): SearchProvider;
|
|
96
|
+
export function braveProvider(options: ProviderOptions & { extraSnippets?: boolean; safesearch?: 'off' | 'moderate' | 'strict' }): SearchProvider;
|
|
97
|
+
export function tavilyProvider(options: ProviderOptions & { searchDepth?: 'basic' | 'fast' | 'advanced' }): SearchProvider;
|
|
98
|
+
export function exaProvider(options: ProviderOptions & { type?: 'auto' | 'fast' | 'deep'; highlightChars?: number }): SearchProvider;
|
|
99
|
+
export const TAVILY_COUNTRIES: Readonly<Record<string, string>>;
|
|
100
|
+
|
|
101
|
+
/** La passerelle de la Centrale : `search` reçoit la demande au format de `rechercher` (@astratra/centrale/passerelle). */
|
|
102
|
+
export function gatewayProvider(options: {
|
|
103
|
+
search: (
|
|
104
|
+
demande: { requete: string; nombre: number; langue?: string; pays?: string; periode?: 'jour' | 'semaine' | 'mois' | 'an' },
|
|
105
|
+
options: { signal?: AbortSignal }
|
|
106
|
+
) => Promise<{ fournisseur?: string; resultats: Array<{ titre: string; url: string; extrait: string; date?: string }> }>;
|
|
107
|
+
id?: string;
|
|
108
|
+
cacheTtlMs?: number;
|
|
109
|
+
}): SearchProvider;
|
|
110
|
+
|
|
111
|
+
/* ─────────────────── Résultats ─────────────────── */
|
|
112
|
+
|
|
113
|
+
export interface Passage { text: string; start: number; end: number }
|
|
114
|
+
|
|
115
|
+
export interface ResultPage {
|
|
116
|
+
status: 'read' | 'failed' | 'other_site';
|
|
117
|
+
finalUrl?: string;
|
|
118
|
+
canonicalUrl?: string;
|
|
119
|
+
title?: string;
|
|
120
|
+
lang?: string | null;
|
|
121
|
+
publishedAt?: string | null;
|
|
122
|
+
truncated?: boolean;
|
|
123
|
+
/** Découpés dans le texte de CETTE page : text === texte.slice(start, end). */
|
|
124
|
+
passages?: Passage[];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export interface SearchResult {
|
|
128
|
+
/** S1, S2… : l'identifiant à citer. */
|
|
129
|
+
id: string;
|
|
130
|
+
title: string;
|
|
131
|
+
url: string;
|
|
132
|
+
canonicalUrl: string;
|
|
133
|
+
domain: string;
|
|
134
|
+
publishedAt: string | null;
|
|
135
|
+
/** Le moteur qui a donné la date, ou 'page' quand elle vient de la page lue. */
|
|
136
|
+
dateSource: string | null;
|
|
137
|
+
snippet: string;
|
|
138
|
+
extraSnippets?: string[];
|
|
139
|
+
/** Le seul moteur dont viennent le titre et les extraits. */
|
|
140
|
+
snippetFrom: string;
|
|
141
|
+
foundBy: string[];
|
|
142
|
+
ranks: Record<string, number>;
|
|
143
|
+
score: number;
|
|
144
|
+
page?: ResultPage;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export interface ProviderTrace {
|
|
148
|
+
provider: string;
|
|
149
|
+
ok: boolean;
|
|
150
|
+
cached: boolean;
|
|
151
|
+
attempts: number;
|
|
152
|
+
ms: number;
|
|
153
|
+
hits: number;
|
|
154
|
+
costUsd: number | null;
|
|
155
|
+
skipped?: 'resting' | 'quota' | 'quota_store_failed';
|
|
156
|
+
engine?: string;
|
|
157
|
+
error?: { code: string; message: string; status?: number };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export interface SearchReport {
|
|
161
|
+
query: string;
|
|
162
|
+
rewrittenQuery?: string;
|
|
163
|
+
mode: 'fuse' | 'fallback';
|
|
164
|
+
recency: Recency;
|
|
165
|
+
providers: ProviderTrace[];
|
|
166
|
+
providersUsed: string[];
|
|
167
|
+
costUsd: number;
|
|
168
|
+
/** false quand un moteur utilisé ne donne pas son coût (la passerelle compte de son côté). */
|
|
169
|
+
costComplete: boolean;
|
|
170
|
+
dropped: { domain: number; freshness: number; perDomain: number; duplicate: number; otherSite: number };
|
|
171
|
+
reads: Array<{ url: string; ok: boolean; ms: number; cached?: boolean; error?: { code: string; message: string } }>;
|
|
172
|
+
ms: number;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export interface SearchResponse {
|
|
176
|
+
query: string;
|
|
177
|
+
request: SearchRequest;
|
|
178
|
+
results: SearchResult[];
|
|
179
|
+
report: SearchReport;
|
|
180
|
+
searchedAt: string;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export interface QuoteCheck { quote: string; found: boolean; exact?: boolean; start?: number; end?: number; text?: string }
|
|
184
|
+
|
|
185
|
+
export interface ReadPage {
|
|
186
|
+
url: string;
|
|
187
|
+
finalUrl: string;
|
|
188
|
+
redirects: string[];
|
|
189
|
+
canonicalUrl: string;
|
|
190
|
+
domain: string;
|
|
191
|
+
/** false : l'adresse a mené vers un autre site ; ce texte est celui de cet autre site. */
|
|
192
|
+
sameSite: boolean;
|
|
193
|
+
title: string;
|
|
194
|
+
lang: string | null;
|
|
195
|
+
publishedAt: string | null;
|
|
196
|
+
modifiedAt: string | null;
|
|
197
|
+
text: string;
|
|
198
|
+
truncated: boolean;
|
|
199
|
+
bytes: number;
|
|
200
|
+
quotes: QuoteCheck[];
|
|
201
|
+
passages: Array<Passage & { score: number }>;
|
|
202
|
+
report: { ms: number; cached: boolean };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/* ─────────────────── La recherche ─────────────────── */
|
|
206
|
+
|
|
207
|
+
export interface CacheStore {
|
|
208
|
+
get(key: string): unknown | Promise<unknown>;
|
|
209
|
+
set(key: string, value: unknown, ttlMs: number): unknown | Promise<unknown>;
|
|
210
|
+
}
|
|
211
|
+
export interface CounterStore {
|
|
212
|
+
get(key: string): number | Promise<number>;
|
|
213
|
+
incr(key: string, ttlMs: number): number | Promise<number>;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export interface RankingOptions {
|
|
217
|
+
blockDomains?: string[];
|
|
218
|
+
preferDomains?: string[];
|
|
219
|
+
demoteDomains?: string[];
|
|
220
|
+
domainScore?: (domain: string) => number;
|
|
221
|
+
maxPerDomain?: number;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export interface ReadingOptions {
|
|
225
|
+
timeoutMs?: number;
|
|
226
|
+
maxBytes?: number;
|
|
227
|
+
maxRedirects?: number;
|
|
228
|
+
maxChars?: number;
|
|
229
|
+
passages?: number;
|
|
230
|
+
passageSize?: number;
|
|
231
|
+
ports?: number[];
|
|
232
|
+
userAgent?: string;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export interface WebSearchOptions {
|
|
236
|
+
providers: SearchProvider[];
|
|
237
|
+
mode?: 'fuse' | 'fallback';
|
|
238
|
+
fuseCount?: number;
|
|
239
|
+
fallbackOnEmpty?: boolean;
|
|
240
|
+
cache?: CacheStore | false;
|
|
241
|
+
cacheTtlMs?: number;
|
|
242
|
+
readCacheTtlMs?: number;
|
|
243
|
+
quotas?: Record<string, { perMinute?: number; perDay?: number; perMonth?: number }>;
|
|
244
|
+
quotaStore?: CounterStore;
|
|
245
|
+
retry?: { retries?: number; baseDelayMs?: number; maxDelayMs?: number };
|
|
246
|
+
cooldownMs?: number;
|
|
247
|
+
budgetMs?: number;
|
|
248
|
+
ranking?: RankingOptions;
|
|
249
|
+
reading?: ReadingOptions;
|
|
250
|
+
rewrite?: (request: SearchRequest) => string | { query: string } | null | undefined | Promise<string | { query: string } | null | undefined>;
|
|
251
|
+
extract?: (html: string, context: { url: string; now: number }) => Partial<ExtractedPage> & { text: string } | Promise<Partial<ExtractedPage> & { text: string }>;
|
|
252
|
+
onReport?: (report: SearchReport) => void;
|
|
253
|
+
lang?: string;
|
|
254
|
+
country?: string;
|
|
255
|
+
limit?: number;
|
|
256
|
+
now?: () => number;
|
|
257
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
258
|
+
random?: () => number;
|
|
259
|
+
request?: (...args: any[]) => any;
|
|
260
|
+
resolve?: (...args: any[]) => any;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export interface WebSearch {
|
|
264
|
+
search(input: string | SearchInput, options?: { signal?: AbortSignal }): Promise<SearchResponse>;
|
|
265
|
+
read(url: string, options?: { quotes?: string[]; query?: string; passages?: number; lang?: string; signal?: AbortSignal }): Promise<ReadPage>;
|
|
266
|
+
readonly providerIds: string[];
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export function createWebSearch(options: WebSearchOptions): WebSearch;
|
|
270
|
+
|
|
271
|
+
/* ─────────────────── Briques ─────────────────── */
|
|
272
|
+
|
|
273
|
+
export function parseHttps(value: unknown): URL | null;
|
|
274
|
+
export function domainOf(value: string | URL): string | null;
|
|
275
|
+
export function canonicalUrl(value: unknown): string | null;
|
|
276
|
+
export function normalizeSite(site: unknown): string | null;
|
|
277
|
+
export function inSite(domain: string | null, site: string | null): boolean;
|
|
278
|
+
export function sameSite(a: string, b: string): boolean;
|
|
279
|
+
export const TRACKING_PARAMS: ReadonlySet<string>;
|
|
280
|
+
|
|
281
|
+
export function parseDate(value: unknown, options?: { now?: number }): string | null;
|
|
282
|
+
export function ageInDays(iso: string | null, now?: number): number | null;
|
|
283
|
+
|
|
284
|
+
export interface FusedEntry {
|
|
285
|
+
canonicalUrl: string; url: string; domain: string; title: string; snippet: string; extraSnippets: string[];
|
|
286
|
+
snippetFrom: string; publishedAt: string | null; dateSource: string | null; foundBy: string[]; ranks: Record<string, number>; score: number;
|
|
287
|
+
}
|
|
288
|
+
export const RRF_K: number;
|
|
289
|
+
export function fuseRankings(lists: Array<{ provider: string; hits: ProviderHit[]; weight?: number }>, options?: { k?: number }): FusedEntry[];
|
|
290
|
+
export function rankEntries(entries: FusedEntry[], request: SearchRequest, options?: RankingOptions & { now?: number }): { entries: FusedEntry[]; dropped: { domain: number; freshness: number; perDomain: number } };
|
|
291
|
+
|
|
292
|
+
export function isPublicAddress(address: string): boolean;
|
|
293
|
+
export function isBlockedHostname(hostname: string): boolean;
|
|
294
|
+
|
|
295
|
+
export const SAFE_FETCH_DEFAULTS: Readonly<{ timeoutMs: number; maxBytes: number; maxRedirects: number; ports: number[]; userAgent: string }>;
|
|
296
|
+
export function safeFetch(url: string, options?: ReadingOptions & { lang?: string; signal?: AbortSignal; request?: (...args: any[]) => any; resolve?: (...args: any[]) => any }): Promise<{
|
|
297
|
+
url: string; finalUrl: string; redirects: string[]; status: number; contentType: string; body: string; bytes: number; truncated: boolean;
|
|
298
|
+
}>;
|
|
299
|
+
export function safeLookup(resolve?: (...args: any[]) => any): (hostname: string, options: any, callback: (...args: any[]) => void) => void;
|
|
300
|
+
export function checkUrl(url: string, ports: number[]): URL;
|
|
301
|
+
|
|
302
|
+
export interface ExtractedPage {
|
|
303
|
+
title: string; text: string; lang: string | null; canonical: string | null; publishedAt: string | null;
|
|
304
|
+
modifiedAt: string | null; description: string | null; siteName: string | null;
|
|
305
|
+
}
|
|
306
|
+
export function extractPage(html: string, options?: { url?: string; now?: number }): ExtractedPage;
|
|
307
|
+
export function removeElements(html: string, drop: (tagName: string, openingTag: string) => boolean): string;
|
|
308
|
+
export function toText(html: string): string;
|
|
309
|
+
|
|
310
|
+
export function findQuote(text: string, quote: string): QuoteCheck;
|
|
311
|
+
export function verifyPassage(text: string, passage: Passage | null | undefined): boolean;
|
|
312
|
+
export function bestPassages(text: string, query: string, options?: { count?: number; size?: number }): Array<Passage & { score: number }>;
|
|
313
|
+
export function termsOf(query: string): string[];
|
|
314
|
+
|
|
315
|
+
export function createMemoryCache(options?: { maxEntries?: number; now?: () => number }): CacheStore & { clear(): void; size(): number };
|
|
316
|
+
export function createMemoryCounters(options?: { now?: () => number }): CounterStore;
|
|
317
|
+
|
|
318
|
+
/* ─────────────────── Pour les modèles ─────────────────── */
|
|
319
|
+
|
|
320
|
+
export const CITATION_RULES: string;
|
|
321
|
+
export function formatForModel(found: SearchResponse, options?: { maxChars?: number; snippetChars?: number; passageChars?: number }): string;
|
|
322
|
+
export function formatPageForModel(page: ReadPage, options?: { maxChars?: number }): string;
|
|
323
|
+
|
|
324
|
+
export type ToolFormat = 'anthropic' | 'openai' | 'mistral' | 'gemini' | 'generic';
|
|
325
|
+
export const TOOL_SCHEMAS: Readonly<{ web_search: Record<string, unknown>; read_page: Record<string, unknown> }>;
|
|
326
|
+
export function toolDefinitions(format?: ToolFormat): any[];
|
|
327
|
+
export function searchArgs(args: Record<string, unknown>, defaults?: { limit?: number; read?: number }): SearchInput;
|
|
328
|
+
|
|
329
|
+
export interface WebSource { kind: 'web'; id?: string; url: string; title: string; domain: string; publishedAt: string | null; excerpt: string }
|
|
330
|
+
export function runTool(ws: WebSearch, name: 'web_search' | 'read_page' | string, args: Record<string, unknown>, options?: {
|
|
331
|
+
signal?: AbortSignal; defaults?: { limit?: number; read?: number }; maxChars?: number;
|
|
332
|
+
}): Promise<{ text: string; sources: WebSource[]; found: SearchResponse | ReadPage }>;
|
|
333
|
+
|
|
334
|
+
export interface WebNativeTool {
|
|
335
|
+
name: 'web_search' | 'read_page';
|
|
336
|
+
description: string;
|
|
337
|
+
parameters: Record<string, unknown>;
|
|
338
|
+
kind: 'read';
|
|
339
|
+
risk: 'LOW';
|
|
340
|
+
summary(args?: Record<string, unknown>): Record<string, string>;
|
|
341
|
+
run(args: Record<string, unknown>, ctx?: { signal?: AbortSignal }): Promise<{ data: string; sources: WebSource[] }>;
|
|
342
|
+
}
|
|
343
|
+
export function nativeTools(ws: WebSearch, options?: { defaults?: { limit?: number; read?: number }; maxChars?: number }): WebNativeTool[];
|
|
344
|
+
|
|
345
|
+
export interface WebRegistryTool {
|
|
346
|
+
name: 'web_search' | 'read_page';
|
|
347
|
+
description: string;
|
|
348
|
+
type: 'read';
|
|
349
|
+
risk: 'LOW';
|
|
350
|
+
external: true;
|
|
351
|
+
roles: string[];
|
|
352
|
+
params: Record<string, string>;
|
|
353
|
+
handler(params: Record<string, unknown>, ctx?: { signal?: AbortSignal }): Promise<string>;
|
|
354
|
+
}
|
|
355
|
+
export function registryTools(ws: WebSearch, options: { roles: string[]; defaults?: { limit?: number; read?: number }; maxChars?: number }): WebRegistryTool[];
|
|
356
|
+
|
|
357
|
+
/* ─────────────────── Évaluation ─────────────────── */
|
|
358
|
+
|
|
359
|
+
export interface EvaluationCase {
|
|
360
|
+
id: string;
|
|
361
|
+
input: SearchInput;
|
|
362
|
+
expect?: { expectedDomain?: string; within?: number; recentFirst?: boolean; forbiddenDomains?: string[] };
|
|
363
|
+
}
|
|
364
|
+
export interface EvaluationRecorder {
|
|
365
|
+
providers: SearchProvider[];
|
|
366
|
+
hitsFor(providerId: string, url: string): ProviderHit[];
|
|
367
|
+
}
|
|
368
|
+
export function recordProviders(providers: SearchProvider[]): EvaluationRecorder;
|
|
369
|
+
export function rawSearch(provider: SearchProvider, request: Partial<SearchRequest> & { query: string }): Promise<{ query: string; results: Array<Partial<SearchResult>> }>;
|
|
370
|
+
export function checkCase(found: { results: Array<Partial<SearchResult>> }, expect: EvaluationCase['expect'], context: { recorder?: EvaluationRecorder; pageTexts: Map<string, string> }): Record<string, boolean>;
|
|
371
|
+
export function runEvaluation(options: {
|
|
372
|
+
cases: EvaluationCase[];
|
|
373
|
+
search: (input: SearchInput) => Promise<{ results: Array<Partial<SearchResult>> }>;
|
|
374
|
+
recorder?: EvaluationRecorder;
|
|
375
|
+
readText?: (url: string) => Promise<string>;
|
|
376
|
+
}): Promise<{
|
|
377
|
+
cases: Array<{ id: string; passed: boolean; error?: string; checks: Record<string, boolean>; results?: Array<{ id: string; domain: string; url: string; publishedAt: string | null }> }>;
|
|
378
|
+
summary: { cases: number; passed: number; checks: Record<string, { passed: number; total: number }> };
|
|
379
|
+
}>;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @astratra/web-search : une recherche web pour les IA où chaque fait reste
|
|
3
|
+
* attaché à sa page. Voir README.md.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
module.exports = {
|
|
7
|
+
...require('./webSearch'),
|
|
8
|
+
...require('./errors'),
|
|
9
|
+
...require('./url'),
|
|
10
|
+
...require('./dates'),
|
|
11
|
+
...require('./query'),
|
|
12
|
+
...require('./fusion'),
|
|
13
|
+
...require('./address'),
|
|
14
|
+
...require('./safeFetch'),
|
|
15
|
+
...require('./extract'),
|
|
16
|
+
...require('./passages'),
|
|
17
|
+
...require('./stores'),
|
|
18
|
+
...require('./format'),
|
|
19
|
+
...require('./tools'),
|
|
20
|
+
...require('./evaluation'),
|
|
21
|
+
...require('./providers/serper'),
|
|
22
|
+
...require('./providers/brave'),
|
|
23
|
+
...require('./providers/tavily'),
|
|
24
|
+
...require('./providers/exa'),
|
|
25
|
+
...require('./providers/gateway')
|
|
26
|
+
};
|
package/src/mcp.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { WebSearch } from './index';
|
|
2
|
+
|
|
3
|
+
/** Un serveur MCP (SDK officiel, serveur bas niveau) qui sert web_search et read_page. Brancher avec `server.connect(transport)`. */
|
|
4
|
+
export function createMcpServer(ws: WebSearch, options?: { name?: string; version?: string; defaults?: { limit?: number; read?: number }; maxChars?: number }): {
|
|
5
|
+
connect(transport: unknown): Promise<void>;
|
|
6
|
+
close(): Promise<void>;
|
|
7
|
+
};
|
package/src/mcp.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@astratra/web-search/mcp` : la recherche servie en MCP, avec les deux mêmes
|
|
3
|
+
* outils (`web_search`, `read_page`) et le même texte cadré.
|
|
4
|
+
*
|
|
5
|
+
* Le SDK MCP officiel (@modelcontextprotocol/sdk) est une dépendance
|
|
6
|
+
* facultative : il n'est chargé qu'ici. Le serveur bas niveau prend les
|
|
7
|
+
* schémas JSON tels quels (sans zod).
|
|
8
|
+
*
|
|
9
|
+
* const { createMcpServer } = require('@astratra/web-search/mcp');
|
|
10
|
+
* const server = createMcpServer(ws);
|
|
11
|
+
* await server.connect(transport); // StdioServerTransport, Streamable HTTP…
|
|
12
|
+
*
|
|
13
|
+
* Une erreur d'outil revient au client en `isError: true` avec son code et son
|
|
14
|
+
* message (jamais une clé), pas en panne du serveur.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const { toolDefinitions, runTool } = require('./tools');
|
|
18
|
+
|
|
19
|
+
function loadSdk() {
|
|
20
|
+
try {
|
|
21
|
+
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
|
|
22
|
+
const { ListToolsRequestSchema, CallToolRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
|
|
23
|
+
return { Server, ListToolsRequestSchema, CallToolRequestSchema };
|
|
24
|
+
} catch (_error) {
|
|
25
|
+
throw new Error('createMcpServer needs @modelcontextprotocol/sdk: npm install @modelcontextprotocol/sdk');
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* @param {object} ws createWebSearch(…)
|
|
31
|
+
* @param {{ name?: string, version?: string, defaults?: object, maxChars?: number }} [options]
|
|
32
|
+
*/
|
|
33
|
+
function createMcpServer(ws, options = {}) {
|
|
34
|
+
if (!ws || typeof ws.search !== 'function' || typeof ws.read !== 'function') throw new Error('createMcpServer needs a web search from createWebSearch().');
|
|
35
|
+
const { Server, ListToolsRequestSchema, CallToolRequestSchema } = loadSdk();
|
|
36
|
+
const server = new Server(
|
|
37
|
+
{ name: options.name || 'astratra-web-search', version: options.version || require('../package.json').version },
|
|
38
|
+
{
|
|
39
|
+
capabilities: { tools: {} },
|
|
40
|
+
instructions: 'Web search where every result is one page of one site. Cite sources by their id and url; never merge two sources into one claim.'
|
|
41
|
+
}
|
|
42
|
+
);
|
|
43
|
+
const tools = toolDefinitions('generic').map(({ name, description, parameters }) => ({
|
|
44
|
+
name,
|
|
45
|
+
description,
|
|
46
|
+
inputSchema: parameters,
|
|
47
|
+
annotations: { readOnlyHint: true, openWorldHint: true, destructiveHint: false }
|
|
48
|
+
}));
|
|
49
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
|
|
50
|
+
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
51
|
+
const { name, arguments: args } = request.params;
|
|
52
|
+
try {
|
|
53
|
+
const { text } = await runTool(ws, name, args || {}, { signal: extra?.signal, defaults: options.defaults, maxChars: options.maxChars });
|
|
54
|
+
return { content: [{ type: 'text', text }] };
|
|
55
|
+
} catch (error) {
|
|
56
|
+
if (extra?.signal?.aborted) throw error;
|
|
57
|
+
return { isError: true, content: [{ type: 'text', text: `${error.code || 'WEB_SEARCH_ERROR'}: ${error.code ? error.message : 'the tool failed'}` }] };
|
|
58
|
+
}
|
|
59
|
+
});
|
|
60
|
+
return server;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
module.exports = { createMcpServer };
|