@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/src/query.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * La demande, mise au propre avant de partir vers les moteurs.
3
+ *
4
+ * - Les opérateurs `site:` et `-site:` écrits dans la requête deviennent des
5
+ * filtres : chaque moteur reçoit alors sa forme à lui (paramètre natif ou
6
+ * opérateur), et le filtre est réappliqué à l'arrivée, quoi qu'ait fait le moteur.
7
+ * - La fraîcheur : `freshness` ('day', 'week', 'month', 'year') est un FILTRE
8
+ * demandé aux moteurs et revérifié sur les dates connues. `'auto'` (défaut)
9
+ * ne filtre rien : il repère les questions qui veulent du récent (« aujourd'hui »,
10
+ * « dernière version », l'année en cours…) et fait alors passer le récent devant.
11
+ */
12
+
13
+ const { WebSearchError, CODES } = require('./errors');
14
+ const { normalizeSite } = require('./url');
15
+
16
+ const FRESHNESS = ['day', 'week', 'month', 'year'];
17
+ const FRESHNESS_DAYS = Object.freeze({ day: 1, week: 7, month: 31, year: 366 });
18
+ const MAX_QUERY = 400;
19
+ const MAX_SITES = 20;
20
+ const DEFAULT_LIMIT = 8;
21
+ const MAX_LIMIT = 20;
22
+
23
+ const fold = (text) => String(text).normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
24
+
25
+ /* Des mots qui demandent du récent, en français et en anglais. Repérés comme mots
26
+ entiers, sur le texte sans accents. */
27
+ const RECENCY_WORDS = [
28
+ ['day', /\b(aujourd'?hui|ce matin|ce soir|hier|en direct|today|tonight|yesterday|live|breaking)\b/],
29
+ ['week', /\b(cette semaine|this week|actualites?|news|derniere minute)\b/],
30
+ ['month', /\b(derniere?s?|recente?s?|recemment|actuel(le)?s?|actuellement|en ce moment|nouveaux?|nouvelles?|latest|newest|recent(ly)?|current(ly)?|right now|now|this month|ce mois)\b/]
31
+ ];
32
+
33
+ /**
34
+ * Ce que la question dit de la fraîcheur voulue, sans rien filtrer.
35
+ * @returns {{ wanted: boolean, window: string|null, reason: string|null }}
36
+ */
37
+ function detectRecency(query, { now = Date.now() } = {}) {
38
+ const text = fold(query);
39
+ for (const [window, pattern] of RECENCY_WORDS) {
40
+ const match = text.match(pattern);
41
+ if (match) return { wanted: true, window, reason: match[0] };
42
+ }
43
+ const year = new Date(now).getUTCFullYear();
44
+ const years = text.match(/\b(19|20)\d{2}\b/g) || [];
45
+ if (years.some((value) => Number(value) >= year)) return { wanted: true, window: 'year', reason: String(year) };
46
+ return { wanted: false, window: null, reason: null };
47
+ }
48
+
49
+ function cleanCode(value, name) {
50
+ if (value === undefined || value === null || value === '') return null;
51
+ const code = String(value).trim().toLowerCase();
52
+ if (!/^[a-z]{2}$/.test(code)) throw new WebSearchError(CODES.BAD_REQUEST, `${name} must be a two-letter code`);
53
+ return code;
54
+ }
55
+
56
+ function cleanSites(list, name) {
57
+ if (list === undefined || list === null) return [];
58
+ if (!Array.isArray(list)) throw new WebSearchError(CODES.BAD_REQUEST, `${name} must be an array of sites`);
59
+ const sites = [];
60
+ for (const site of list) {
61
+ const domain = normalizeSite(site);
62
+ if (!domain) throw new WebSearchError(CODES.BAD_REQUEST, `${name} has an invalid site`);
63
+ if (!sites.includes(domain)) sites.push(domain);
64
+ }
65
+ if (sites.length > MAX_SITES) throw new WebSearchError(CODES.BAD_REQUEST, `${name} has more than ${MAX_SITES} sites`);
66
+ return sites;
67
+ }
68
+
69
+ /**
70
+ * @param {object} input
71
+ * @param {{ now?: number, lang?: string, country?: string, limit?: number }} [defaults]
72
+ * @returns {{ query: string, lang: string|null, country: string|null, freshness: string|null,
73
+ * recency: { wanted: boolean, window: string|null, reason: string|null }, sites: string[],
74
+ * excludeSites: string[], limit: number }}
75
+ */
76
+ function normalizeRequest(input, defaults = {}) {
77
+ const request = typeof input === 'string' ? { query: input } : (input || {});
78
+ // eslint-disable-next-line no-control-regex -- les caractères de contrôle sont justement ceux qu'on retire
79
+ let query = String(request.query ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ');
80
+ const sites = cleanSites(request.sites, 'sites');
81
+ const excludeSites = cleanSites(request.excludeSites, 'excludeSites');
82
+
83
+ /* Les opérateurs écrits dans la requête deviennent des filtres. */
84
+ query = query.replace(/(^|\s)(-?)site:(\S+)/gi, (_whole, space, minus, site) => {
85
+ const domain = normalizeSite(site);
86
+ if (!domain) return space;
87
+ const list = minus ? excludeSites : sites;
88
+ if (!list.includes(domain)) list.push(domain);
89
+ return space;
90
+ });
91
+ query = query.replace(/\s+/g, ' ').trim();
92
+ if (!query) throw new WebSearchError(CODES.BAD_REQUEST, 'query is empty');
93
+ if (query.length > MAX_QUERY) throw new WebSearchError(CODES.BAD_REQUEST, `query is longer than ${MAX_QUERY} characters`);
94
+ if (sites.length > MAX_SITES || excludeSites.length > MAX_SITES) throw new WebSearchError(CODES.BAD_REQUEST, `more than ${MAX_SITES} sites`);
95
+
96
+ const asked = request.freshness ?? 'auto';
97
+ if (asked !== 'auto' && asked !== 'any' && !FRESHNESS.includes(asked)) {
98
+ throw new WebSearchError(CODES.BAD_REQUEST, 'freshness must be auto, any, day, week, month or year');
99
+ }
100
+ const freshness = FRESHNESS.includes(asked) ? asked : null;
101
+ const recency = freshness
102
+ ? { wanted: true, window: freshness, reason: 'asked' }
103
+ : asked === 'auto' ? detectRecency(query, { now: defaults.now }) : { wanted: false, window: null, reason: null };
104
+
105
+ const limitValue = request.limit ?? defaults.limit ?? DEFAULT_LIMIT;
106
+ const limit = Math.min(MAX_LIMIT, Math.max(1, Math.floor(Number(limitValue) || DEFAULT_LIMIT)));
107
+
108
+ return {
109
+ query,
110
+ lang: cleanCode(request.lang ?? defaults.lang, 'lang'),
111
+ country: cleanCode(request.country ?? defaults.country, 'country'),
112
+ freshness,
113
+ recency,
114
+ sites: sites.filter((site) => !excludeSites.includes(site)),
115
+ excludeSites,
116
+ limit
117
+ };
118
+ }
119
+
120
+ /** La requête avec des opérateurs, pour un moteur qui n'a pas de filtre natif. */
121
+ function withOperators(request, { includeSites = true } = {}) {
122
+ const parts = [request.query];
123
+ if (includeSites && request.sites.length === 1) parts.push(`site:${request.sites[0]}`);
124
+ else if (includeSites && request.sites.length > 1) parts.push(`(${request.sites.map((site) => `site:${site}`).join(' OR ')})`);
125
+ for (const site of request.excludeSites) parts.push(`-site:${site}`);
126
+ return parts.join(' ');
127
+ }
128
+
129
+ module.exports = { normalizeRequest, detectRecency, withOperators, FRESHNESS, FRESHNESS_DAYS, MAX_LIMIT };
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Lire une page du web sans ouvrir de porte vers le réseau interne (SSRF).
3
+ *
4
+ * - https seulement, sur le port 443 (ou ceux que l'appelant autorise), sans
5
+ * identifiants dans l'adresse ;
6
+ * - le nom est résolu AVANT la connexion, et la connexion part vers l'adresse
7
+ * vérifiée elle-même (la résolution passe par `lookup` de https.request) :
8
+ * un DNS qui changerait de réponse entre la vérification et la connexion
9
+ * (DNS rebinding) n'y gagne rien. Si UNE des adresses du nom est interne, tout
10
+ * est refusé ;
11
+ * - le certificat reste vérifié pour le nom demandé (SNI) ;
12
+ * - les redirections sont suivies à la main, chacune revérifiée, 5 au plus ;
13
+ * - un délai pour toute la lecture, redirections comprises ; une taille
14
+ * maximale comptée APRÈS décompression (une bombe gzip s'arrête là) ;
15
+ * - seulement du HTML ou du texte.
16
+ */
17
+
18
+ const https = require('https');
19
+ const dns = require('dns');
20
+ const zlib = require('zlib');
21
+ const { PassThrough, pipeline } = require('stream');
22
+ const { WebSearchError, CODES } = require('./errors');
23
+ const { parseHttps } = require('./url');
24
+ const { isPublicAddress, isBlockedHostname } = require('./address');
25
+
26
+ const DEFAULTS = Object.freeze({
27
+ timeoutMs: 10_000,
28
+ maxBytes: 2_000_000,
29
+ maxRedirects: 5,
30
+ ports: [443],
31
+ userAgent: 'Mozilla/5.0 (compatible; AstratraWebSearch/1.0)'
32
+ });
33
+ const ACCEPTED_TYPES = ['text/html', 'application/xhtml+xml', 'text/plain'];
34
+
35
+ function blocked(code, message) {
36
+ return new WebSearchError(code, message);
37
+ }
38
+
39
+ /**
40
+ * Un `lookup` pour https.request qui ne rend que des adresses publiques.
41
+ * @param {Function} resolve (hostname, { all: true }, cb) — dns.lookup par défaut.
42
+ */
43
+ function safeLookup(resolve = dns.lookup) {
44
+ return function lookup(hostname, options, callback) {
45
+ const cb = typeof options === 'function' ? options : callback;
46
+ const opts = typeof options === 'object' && options ? options : {};
47
+ resolve(hostname, { all: true, family: opts.family || 0 }, (error, addresses) => {
48
+ if (error) return cb(error);
49
+ const list = (Array.isArray(addresses) ? addresses : [{ address: addresses, family: opts.family || 4 }])
50
+ .filter((entry) => entry && entry.address);
51
+ if (!list.length) return cb(blocked(CODES.BLOCKED_ADDRESS, 'no address'));
52
+ if (list.some((entry) => !isPublicAddress(entry.address))) return cb(blocked(CODES.BLOCKED_ADDRESS, 'address is not public'));
53
+ if (opts.all) return cb(null, list.map(({ address, family }) => ({ address, family: family || (address.includes(':') ? 6 : 4) })));
54
+ const first = list[0];
55
+ return cb(null, first.address, first.family || (first.address.includes(':') ? 6 : 4));
56
+ });
57
+ };
58
+ }
59
+
60
+ /** Vérifie une adresse avant tout appel réseau. */
61
+ function checkUrl(value, ports) {
62
+ const url = parseHttps(value);
63
+ if (!url) throw blocked(CODES.BLOCKED_URL, 'only https addresses without credentials can be read');
64
+ const port = url.port ? Number(url.port) : 443;
65
+ if (!ports.includes(port)) throw blocked(CODES.BLOCKED_URL, `port ${port} is not allowed`);
66
+ if (isBlockedHostname(url.hostname)) throw blocked(CODES.BLOCKED_ADDRESS, 'host is not public');
67
+ return url;
68
+ }
69
+
70
+ function decoderFor(encoding) {
71
+ const value = String(encoding || '').toLowerCase().trim();
72
+ if (value === 'gzip' || value === 'x-gzip') return zlib.createGunzip();
73
+ if (value === 'deflate') return zlib.createInflate();
74
+ if (value === 'br') return zlib.createBrotliDecompress();
75
+ return null;
76
+ }
77
+
78
+ function charsetOf(contentType, head) {
79
+ const fromHeader = /charset\s*=\s*"?([\w.:-]+)/i.exec(contentType || '');
80
+ if (fromHeader) return fromHeader[1];
81
+ const fromMeta = /<meta[^>]+charset\s*=\s*["']?([\w.:-]+)/i.exec(head);
82
+ return fromMeta ? fromMeta[1] : 'utf-8';
83
+ }
84
+
85
+ function decode(buffer, charset) {
86
+ try {
87
+ return new globalThis.TextDecoder(charset, { fatal: false }).decode(buffer);
88
+ } catch (_error) {
89
+ return new globalThis.TextDecoder('utf-8').decode(buffer);
90
+ }
91
+ }
92
+
93
+ /** Une seule requête, sans suivre de redirection. */
94
+ function once(url, { request, lookup, deadline, maxBytes, headers, signal }) {
95
+ return new Promise((resolvePromise, reject) => {
96
+ let settled = false;
97
+ const finish = (fn, value) => {
98
+ if (settled) return;
99
+ settled = true;
100
+ clearTimeout(timer);
101
+ signal?.removeEventListener?.('abort', onAbort);
102
+ fn(value);
103
+ };
104
+ const remaining = deadline - Date.now();
105
+ if (remaining <= 0) return reject(blocked(CODES.TIMEOUT, 'page read timed out'));
106
+ const req = request({
107
+ protocol: 'https:',
108
+ hostname: url.hostname.replace(/^\[|\]$/g, ''),
109
+ port: url.port ? Number(url.port) : 443,
110
+ path: `${url.pathname}${url.search}`,
111
+ method: 'GET',
112
+ headers,
113
+ lookup,
114
+ servername: url.hostname.replace(/^\[|\]$/g, ''),
115
+ agent: false
116
+ }, (res) => {
117
+ /* Une réponse qu'on ne lit pas ferme la connexion : jamais un corps lu à vide, sans fin ni plafond. */
118
+ const refuse = (fn, value) => {
119
+ req.destroy();
120
+ res.destroy?.();
121
+ finish(fn, value);
122
+ };
123
+ const status = res.statusCode || 0;
124
+ if (status >= 300 && status < 400 && res.headers.location) return refuse(resolvePromise, { redirect: String(res.headers.location), status });
125
+ if (status < 200 || status >= 300) return refuse(reject, new WebSearchError(CODES.BAD_STATUS, `page answered ${status}`, { status }));
126
+ const contentType = String(res.headers['content-type'] || '');
127
+ const type = contentType.split(';')[0].trim().toLowerCase();
128
+ if (type && !ACCEPTED_TYPES.includes(type)) return refuse(reject, blocked(CODES.UNSUPPORTED_TYPE, `content type ${type.slice(0, 60)} is not read`));
129
+ const declared = Number(res.headers['content-length']);
130
+ const encoding = res.headers['content-encoding'];
131
+ if (!encoding && Number.isFinite(declared) && declared > maxBytes * 4) return refuse(reject, blocked(CODES.TOO_LARGE, 'page is too large'));
132
+ /* pipeline : une connexion coupée en plein corps (compressé ou non) est une erreur tout de suite, pas un délai. */
133
+ const sink = decoderFor(encoding) || new PassThrough();
134
+ const chunks = [];
135
+ let size = 0;
136
+ let truncated = false;
137
+ const done = () => {
138
+ const buffer = Buffer.concat(chunks);
139
+ const charset = charsetOf(contentType, buffer.subarray(0, 2048).toString('latin1'));
140
+ finish(resolvePromise, { status, contentType: type || 'text/html', body: decode(buffer, charset), bytes: buffer.length, truncated });
141
+ };
142
+ sink.on('data', (chunk) => {
143
+ if (truncated) return;
144
+ const room = maxBytes - size;
145
+ if (chunk.length >= room) {
146
+ chunks.push(chunk.subarray(0, room));
147
+ size = maxBytes;
148
+ truncated = true;
149
+ done();
150
+ req.destroy();
151
+ sink.destroy();
152
+ return;
153
+ }
154
+ chunks.push(chunk);
155
+ size += chunk.length;
156
+ });
157
+ sink.on('end', done);
158
+ pipeline(res, sink, (error) => {
159
+ if (!error || truncated) return;
160
+ req.destroy();
161
+ finish(reject, new WebSearchError(CODES.READ_FAILED, `page could not be read (${String(error.code || 'interrupted').slice(0, 60)})`));
162
+ });
163
+ });
164
+ const timer = setTimeout(() => {
165
+ req.destroy();
166
+ finish(reject, blocked(CODES.TIMEOUT, 'page read timed out'));
167
+ }, remaining);
168
+ const onAbort = () => {
169
+ req.destroy();
170
+ finish(reject, signal.reason ?? blocked(CODES.TIMEOUT, 'page read aborted'));
171
+ };
172
+ if (signal) {
173
+ if (signal.aborted) return onAbort();
174
+ signal.addEventListener('abort', onAbort, { once: true });
175
+ }
176
+ req.on('error', (error) => {
177
+ if (error instanceof WebSearchError) return finish(reject, error);
178
+ finish(reject, new WebSearchError(CODES.READ_FAILED, `page could not be read (${String(error.code || 'network').slice(0, 40)})`));
179
+ });
180
+ req.end();
181
+ });
182
+ }
183
+
184
+ /**
185
+ * @param {string} address
186
+ * @param {object} [options]
187
+ * @param {number} [options.timeoutMs] pour toute la lecture. Défaut 10 s.
188
+ * @param {number} [options.maxBytes] après décompression. Défaut 2 000 000 ; au-delà, la page est coupée (`truncated`).
189
+ * @param {number} [options.maxRedirects] Défaut 5.
190
+ * @param {number[]} [options.ports] Défaut [443].
191
+ * @param {string} [options.userAgent]
192
+ * @param {string} [options.lang] l'en-tête Accept-Language.
193
+ * @param {AbortSignal} [options.signal]
194
+ * @param {Function} [options.request] https.request (remplaçable dans les tests).
195
+ * @param {Function} [options.resolve] dns.lookup (remplaçable dans les tests).
196
+ * @returns {Promise<{ url: string, finalUrl: string, redirects: string[], status: number, contentType: string, body: string, bytes: number, truncated: boolean }>}
197
+ */
198
+ async function safeFetch(address, options = {}) {
199
+ const settings = { ...DEFAULTS, ...Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined)) };
200
+ const deadline = Date.now() + settings.timeoutMs;
201
+ const lookup = safeLookup(settings.resolve || dns.lookup);
202
+ const request = settings.request || https.request;
203
+ const headers = {
204
+ 'user-agent': settings.userAgent,
205
+ accept: 'text/html,application/xhtml+xml,text/plain;q=0.9',
206
+ 'accept-encoding': 'gzip, deflate, br',
207
+ ...(settings.lang ? { 'accept-language': `${settings.lang},*;q=0.5` } : {})
208
+ };
209
+ const redirects = [];
210
+ let url = checkUrl(address, settings.ports);
211
+ for (;;) {
212
+ const answer = await once(url, { request, lookup, deadline, maxBytes: settings.maxBytes, headers, signal: settings.signal });
213
+ if (!answer.redirect) {
214
+ return { url: String(address), finalUrl: url.href, redirects, status: answer.status, contentType: answer.contentType, body: answer.body, bytes: answer.bytes, truncated: answer.truncated };
215
+ }
216
+ if (redirects.length >= settings.maxRedirects) throw blocked(CODES.TOO_MANY_REDIRECTS, 'too many redirects');
217
+ let next;
218
+ try {
219
+ next = new URL(answer.redirect, url);
220
+ } catch (_error) {
221
+ throw blocked(CODES.BLOCKED_URL, 'redirect to an invalid address');
222
+ }
223
+ url = checkUrl(next.href, settings.ports);
224
+ redirects.push(url.href);
225
+ }
226
+ }
227
+
228
+ module.exports = { safeFetch, safeLookup, checkUrl, SAFE_FETCH_DEFAULTS: DEFAULTS };
package/src/stores.js ADDED
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Les magasins par défaut : un cache et des compteurs de quotas en mémoire.
3
+ *
4
+ * Ce sont des interfaces, à remplacer par Redis ou une base quand plusieurs
5
+ * processus partagent le même budget :
6
+ * cache : { get(key) => value | undefined, set(key, value, ttlMs) }
7
+ * quotas : { get(key) => number, incr(key, ttlMs) => number }
8
+ * Toutes les méthodes peuvent être asynchrones.
9
+ */
10
+
11
+ /** Un cache en mémoire, borné : le plus ancien part quand il est plein. */
12
+ function createMemoryCache({ maxEntries = 500, now = Date.now } = {}) {
13
+ const entries = new Map();
14
+ return {
15
+ get(key) {
16
+ const entry = entries.get(key);
17
+ if (!entry) return undefined;
18
+ if (entry.expires <= now()) {
19
+ entries.delete(key);
20
+ return undefined;
21
+ }
22
+ return globalThis.structuredClone(entry.value);
23
+ },
24
+ set(key, value, ttlMs) {
25
+ if (!(ttlMs > 0)) return;
26
+ entries.delete(key);
27
+ entries.set(key, { value: globalThis.structuredClone(value), expires: now() + ttlMs });
28
+ while (entries.size > maxEntries) entries.delete(entries.keys().next().value);
29
+ },
30
+ clear() {
31
+ entries.clear();
32
+ },
33
+ size: () => entries.size
34
+ };
35
+ }
36
+
37
+ /** Des compteurs en mémoire, chacun oublié à l'échéance de sa fenêtre. */
38
+ function createMemoryCounters({ now = Date.now } = {}) {
39
+ const counters = new Map();
40
+ const live = (key) => {
41
+ const counter = counters.get(key);
42
+ if (counter && counter.expires <= now()) {
43
+ counters.delete(key);
44
+ return null;
45
+ }
46
+ return counter || null;
47
+ };
48
+ return {
49
+ get(key) {
50
+ return live(key)?.count || 0;
51
+ },
52
+ incr(key, ttlMs) {
53
+ const counter = live(key) || { count: 0, expires: now() + ttlMs };
54
+ counter.count += 1;
55
+ counters.set(key, counter);
56
+ return counter.count;
57
+ }
58
+ };
59
+ }
60
+
61
+ module.exports = { createMemoryCache, createMemoryCounters };
package/src/text.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Du texte propre à partir de morceaux de HTML : les entités décodées, les
3
+ * balises retirées, les espaces resserrés. Sert aux extraits des moteurs (Brave
4
+ * met des <strong> dans ses descriptions) et à l'extraction des pages.
5
+ */
6
+
7
+ const NAMED = {
8
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0', laquo: '«', raquo: '»',
9
+ hellip: '…', mdash: '—', ndash: '–', lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”',
10
+ eacute: 'é', egrave: 'è', ecirc: 'ê', agrave: 'à', acirc: 'â', ccedil: 'ç', ocirc: 'ô',
11
+ ucirc: 'û', ugrave: 'ù', icirc: 'î', iuml: 'ï', euml: 'ë', oelig: 'œ', copy: '©', reg: '®',
12
+ trade: '™', euro: '€', deg: '°', middot: '·', bull: '•', times: '×', shy: ''
13
+ };
14
+
15
+ function decodeEntities(text) {
16
+ return String(text ?? '').replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, body) => {
17
+ if (body[0] === '#') {
18
+ const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
19
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff) ? String.fromCodePoint(code) : '';
20
+ }
21
+ if (NAMED[body] !== undefined) return NAMED[body];
22
+ const named = NAMED[body.toLowerCase()];
23
+ if (named === undefined) return whole;
24
+ /* &Eacute; → É : la majuscule suit celle du nom de l'entité. */
25
+ return /^[A-Z][a-z]+$/.test(body) && /^\p{Ll}$/u.test(named) ? named.toUpperCase() : named;
26
+ });
27
+ }
28
+
29
+ /** Retire les balises en une passe (indexOf) : une balise jamais fermée coupe le reste. */
30
+ function stripTags(text) {
31
+ let out = '';
32
+ let i = 0;
33
+ for (;;) {
34
+ const lt = text.indexOf('<', i);
35
+ if (lt === -1) return out + text.slice(i);
36
+ out += text.slice(i, lt);
37
+ const gt = text.indexOf('>', lt + 1);
38
+ if (gt === -1) return out;
39
+ i = gt + 1;
40
+ }
41
+ }
42
+
43
+ /** Une ligne de texte : sans balises, entités décodées, espaces resserrés. */
44
+ function plainText(fragment) {
45
+ // eslint-disable-next-line no-control-regex -- les caractères de contrôle sont justement ceux qu'on retire
46
+ return decodeEntities(stripTags(String(fragment ?? ''))).replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '').replace(/\s+/g, ' ').trim();
47
+ }
48
+
49
+ /** Coupe à `max` caractères sur une limite de mot, avec « … » si coupé. */
50
+ function clip(text, max) {
51
+ const value = String(text ?? '');
52
+ if (!Number.isFinite(max) || value.length <= max) return value;
53
+ if (max <= 0) return '';
54
+ const cut = value.slice(0, Math.max(0, max - 1));
55
+ const space = cut.lastIndexOf(' ');
56
+ return `${(space > max * 0.6 ? cut.slice(0, space) : cut).trimEnd()}…`;
57
+ }
58
+
59
+ module.exports = { decodeEntities, plainText, stripTags, clip };
package/src/tools.js ADDED
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Brancher la recherche sur un modèle : deux outils, `web_search` et `read_page`.
3
+ *
4
+ * - `toolDefinitions(format)` : les schémas tels que chaque API les attend
5
+ * (Anthropic, OpenAI, Mistral, Gemini) ;
6
+ * - `nativeTools(ws)` : des outils pour `runToolLoop` de @astratra/ai (genre
7
+ * `read`, risque LOW), qui rendent `{ data, sources }` : les sources vont au
8
+ * registre des sources (`createSourceLedger`), en `kind: 'web'`, ce qui
9
+ * marque la lecture comme non fiable pour `readsUntrusted` ;
10
+ * - `registryTools(ws, { roles })` : les mêmes pour le registre de
11
+ * `runAgentLoop` (`external: true` : la requête part hors de l'application,
12
+ * le masque des données personnelles s'applique).
13
+ *
14
+ * `runTool(ws, name, args)` est le cœur commun : il valide les arguments du
15
+ * modèle et rend le texte cadré.
16
+ */
17
+
18
+ const { formatForModel, formatPageForModel } = require('./format');
19
+ const { WebSearchError, CODES } = require('./errors');
20
+ const { geminiSchema } = require('@astratra/ai');
21
+
22
+ const SEARCH_DESCRIPTION = 'Search the web. Returns a numbered list of sources; each source is one page of one site, with its exact url, '
23
+ + 'its date when known and an excerpt of that page only. Cite sources by id ([S1]). Use freshness for recent events, sites to stay on '
24
+ + 'trusted sites. Set read to 1-3 to also get verbatim passages from the top pages.';
25
+ const READ_DESCRIPTION = 'Read one web page (https only) and return its main text, its date and verbatim passages. '
26
+ + 'Give quotes to check whether the page really contains them: each quote is reported as found (with its position) or NOT found.';
27
+
28
+ const SEARCH_SCHEMA = Object.freeze({
29
+ type: 'object',
30
+ properties: {
31
+ query: { type: 'string', description: 'What to search for, in the language of the expected pages.' },
32
+ freshness: { type: 'string', enum: ['auto', 'any', 'day', 'week', 'month', 'year'], description: 'Only pages from this period. auto (default) puts recent pages first when the question asks for recent facts.' },
33
+ sites: { type: 'array', items: { type: 'string' }, description: 'Only these sites (example.com).' },
34
+ exclude_sites: { type: 'array', items: { type: 'string' }, description: 'Never these sites.' },
35
+ lang: { type: 'string', description: 'Two-letter language code (fr, en).' },
36
+ country: { type: 'string', description: 'Two-letter country code (fr, us).' },
37
+ limit: { type: 'integer', minimum: 1, maximum: 10, description: 'Number of sources (default 6).' },
38
+ read: { type: 'integer', minimum: 0, maximum: 3, description: 'Read the top pages and add verbatim passages (default 0).' }
39
+ },
40
+ required: ['query'],
41
+ additionalProperties: false
42
+ });
43
+
44
+ const READ_SCHEMA = Object.freeze({
45
+ type: 'object',
46
+ properties: {
47
+ url: { type: 'string', description: 'The https address of the page, exactly as given by web_search.' },
48
+ quotes: { type: 'array', items: { type: 'string' }, maxItems: 5, description: 'Sentences to look for on the page, word for word.' },
49
+ query: { type: 'string', description: 'What you are looking for on the page, to get the best passages.' }
50
+ },
51
+ required: ['url'],
52
+ additionalProperties: false
53
+ });
54
+
55
+ const TOOLS = [
56
+ { name: 'web_search', description: SEARCH_DESCRIPTION, parameters: SEARCH_SCHEMA },
57
+ { name: 'read_page', description: READ_DESCRIPTION, parameters: READ_SCHEMA }
58
+ ];
59
+
60
+ /**
61
+ * Les définitions d'outils au format d'une API.
62
+ * @param {'anthropic'|'openai'|'mistral'|'gemini'|'generic'} format
63
+ */
64
+ function toolDefinitions(format = 'generic') {
65
+ const copy = (value) => JSON.parse(JSON.stringify(value));
66
+ switch (format) {
67
+ case 'anthropic':
68
+ return TOOLS.map(({ name, description, parameters }) => ({ name, description, input_schema: copy(parameters) }));
69
+ case 'openai':
70
+ case 'mistral':
71
+ return TOOLS.map(({ name, description, parameters }) => ({ type: 'function', function: { name, description, parameters: copy(parameters) } }));
72
+ case 'gemini':
73
+ return [{ functionDeclarations: TOOLS.map(({ name, description, parameters }) => ({ name, description, parameters: geminiSchema(copy(parameters)) })) }];
74
+ case 'generic':
75
+ return TOOLS.map(copy);
76
+ default:
77
+ throw new Error(`Unknown tool format ${format}: anthropic, openai, mistral, gemini or generic.`);
78
+ }
79
+ }
80
+
81
+ const strings = (value) => (Array.isArray(value) ? value.filter((item) => typeof item === 'string') : undefined);
82
+
83
+ /** Les arguments du modèle, en demande pour ws.search. */
84
+ function searchArgs(args = {}, defaults = {}) {
85
+ if (!args || typeof args !== 'object' || typeof args.query !== 'string') throw new WebSearchError(CODES.BAD_REQUEST, 'web_search needs a query string');
86
+ const limit = Number.isInteger(args.limit) ? Math.min(10, Math.max(1, args.limit)) : defaults.limit ?? 6;
87
+ const read = Number.isInteger(args.read) ? Math.min(3, Math.max(0, args.read)) : defaults.read ?? 0;
88
+ return {
89
+ query: args.query,
90
+ ...(typeof args.freshness === 'string' ? { freshness: args.freshness } : {}),
91
+ ...(strings(args.sites) ? { sites: strings(args.sites) } : {}),
92
+ ...(strings(args.exclude_sites) ? { excludeSites: strings(args.exclude_sites) } : {}),
93
+ ...(typeof args.lang === 'string' && args.lang ? { lang: args.lang } : {}),
94
+ ...(typeof args.country === 'string' && args.country ? { country: args.country } : {}),
95
+ limit,
96
+ read
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Exécute un outil pour un modèle.
102
+ * @returns {Promise<{ text: string, sources: object[], found: object }>}
103
+ */
104
+ async function runTool(ws, name, args, { signal, defaults, maxChars } = {}) {
105
+ if (name === 'web_search') {
106
+ const found = await ws.search(searchArgs(args, defaults), { signal });
107
+ return {
108
+ text: formatForModel(found, { maxChars }),
109
+ sources: found.results.map((result) => ({
110
+ kind: 'web', id: result.id, url: result.url, title: result.title, domain: result.domain,
111
+ publishedAt: result.publishedAt, excerpt: result.snippet
112
+ })),
113
+ found
114
+ };
115
+ }
116
+ if (name === 'read_page') {
117
+ if (!args || typeof args.url !== 'string') throw new WebSearchError(CODES.BAD_REQUEST, 'read_page needs a url string');
118
+ const page = await ws.read(args.url, { quotes: strings(args.quotes)?.slice(0, 5), query: typeof args.query === 'string' ? args.query : undefined, signal });
119
+ return {
120
+ text: formatPageForModel(page, { maxChars }),
121
+ 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) }],
122
+ found: page
123
+ };
124
+ }
125
+ throw new WebSearchError(CODES.BAD_REQUEST, `unknown tool ${name}`);
126
+ }
127
+
128
+ /**
129
+ * Pour runToolLoop / createToolCaller de @astratra/ai. Le texte rendu tient dans
130
+ * 5 000 caractères par défaut : createToolCaller coupe à 6 000 (`resultMax`), et
131
+ * une coupe ôterait la marque de fin du cadre. Monter `maxChars` avec `resultMax`.
132
+ */
133
+ function nativeTools(ws, options = {}) {
134
+ const maxChars = options.maxChars ?? 5_000;
135
+ return TOOLS.map(({ name, description, parameters }) => ({
136
+ name,
137
+ description,
138
+ parameters: JSON.parse(JSON.stringify(parameters)),
139
+ kind: 'read',
140
+ risk: 'LOW',
141
+ summary: (args = {}) => (name === 'web_search' ? { query: String(args.query ?? '') } : { url: String(args.url ?? '') }),
142
+ 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 };
145
+ }
146
+ }));
147
+ }
148
+
149
+ /** 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 } = {}) {
151
+ if (!Array.isArray(roles) || !roles.length) throw new Error('registryTools needs the roles allowed to search.');
152
+ return TOOLS.map(({ name, description, parameters }) => ({
153
+ name,
154
+ description,
155
+ type: 'read',
156
+ risk: 'LOW',
157
+ external: true,
158
+ roles: [...roles],
159
+ params: Object.fromEntries(Object.entries(parameters.properties).map(([key, value]) => [key, `${value.type}${parameters.required.includes(key) ? '' : ', optional'} — ${value.description}`])),
160
+ handler: async (params, ctx = {}) => (await runTool(ws, name, params, { signal: ctx.signal, defaults, maxChars })).text
161
+ }));
162
+ }
163
+
164
+ module.exports = { toolDefinitions, nativeTools, registryTools, runTool, searchArgs, TOOL_SCHEMAS: { web_search: SEARCH_SCHEMA, read_page: READ_SCHEMA } };