@astratra/ai 1.14.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -11
- package/package.json +1 -1
- package/src/gemini.js +1 -1
- package/src/guards/createGuards.js +1 -1
- package/src/index.d.ts +10 -2
- package/src/mcpClient.js +2 -3
- package/src/webSearch.js +25 -6
package/README.md
CHANGED
|
@@ -51,7 +51,7 @@ ne fait que lire. Le mode d'une exécution est `newRun({ mode: 'action' | 'read'
|
|
|
51
51
|
|
|
52
52
|
**Textes courts (1.13.0)** : un texte de moins de `injection.minWords` mots (3 par
|
|
53
53
|
défaut ; `0` envoie tout) n'est pas soumis au modèle d'injection, qui note un ou
|
|
54
|
-
deux mots au hasard (mesuré
|
|
54
|
+
deux mots au hasard (mesuré en production le 20/10/2026 : « oui » 0,96,
|
|
55
55
|
« Salut » 0,72, alors que toutes les vraies attaques dépassaient 0,993 dès trois
|
|
56
56
|
mots). Le résultat porte `score: null` et la raison `too_short_to_scan`.
|
|
57
57
|
|
|
@@ -307,20 +307,20 @@ outils répond avec ce qui a été lu ; un tour sans texte ni outil lève
|
|
|
307
307
|
|
|
308
308
|
## Se brancher sur un serveur MCP
|
|
309
309
|
|
|
310
|
-
`connectMcpServer` relie une IA à un serveur MCP distant (transport « Streamable HTTP ») et rend ses outils au format des outils natifs, prêts pour `runToolLoop` ou `createToolCaller`.
|
|
310
|
+
`connectMcpServer` relie une IA à un serveur MCP distant (transport « Streamable HTTP ») et rend ses outils au format des outils natifs, prêts pour `runToolLoop` ou `createToolCaller`. Tout serveur MCP se branche de la même façon.
|
|
311
311
|
|
|
312
312
|
```js
|
|
313
313
|
const { connectMcpServer, runToolLoop } = require('@astratra/ai');
|
|
314
314
|
|
|
315
|
-
const
|
|
316
|
-
url: 'https://
|
|
317
|
-
headers: { Authorization: `Bearer ${process.env.
|
|
318
|
-
prefix: '
|
|
315
|
+
const salon = await connectMcpServer({
|
|
316
|
+
url: 'https://salon.example.com/mcp',
|
|
317
|
+
headers: { Authorization: `Bearer ${process.env.SALON_CLE}` },
|
|
318
|
+
prefix: 'salon_',
|
|
319
319
|
allow: ['lire_reunion', 'ecrire_message', 'prochaine_reunion', 'retenir_reunion'],
|
|
320
320
|
kinds: { ecrire_message: { kind: 'write', risk: 'LOW' } }
|
|
321
321
|
});
|
|
322
|
-
//
|
|
323
|
-
await
|
|
322
|
+
// salon.tools s'ajoute aux outils de l'IA ; salon.instructions donne les règles du serveur.
|
|
323
|
+
await salon.close();
|
|
324
324
|
```
|
|
325
325
|
|
|
326
326
|
- Ce que rend un serveur MCP est une donnée non fiable : chaque outil porte `external: true`, pour que les gardes le traitent comme tel.
|
|
@@ -343,14 +343,20 @@ un proxy (`X-Accel-Buffering: no`) ; écrire après la fin ne fait rien.
|
|
|
343
343
|
## Recherche web (Serper)
|
|
344
344
|
|
|
345
345
|
```js
|
|
346
|
-
const resultats = await searchSerper({ query, sites: ['
|
|
346
|
+
const resultats = await searchSerper({ query, sites: ['example.com'], hl: 'fr', gl: 'fr', period: 'week' }, {
|
|
347
347
|
key: process.env.SERPER_API_KEY, fetch,
|
|
348
348
|
accept: (resultat, url) => !estHostile(resultat) // écarté avant que le modèle ne lise
|
|
349
349
|
});
|
|
350
350
|
```
|
|
351
351
|
|
|
352
|
-
Des résultats https avec un titre, 8 au plus.
|
|
353
|
-
(`
|
|
352
|
+
Des résultats https avec un titre, 8 au plus. `gl` choisit le pays, `period`
|
|
353
|
+
(`hour`, `day`, `week`, `month`, `year`) ne garde que les résultats récents.
|
|
354
|
+
Sans clé, rien n'est demandé (`code: 'WEB_SEARCH_NO_KEY'`) ; une panne porte
|
|
355
|
+
`'WEB_SEARCH_FAILED'` et, si Serper a répondu, son `status` — jamais la clé.
|
|
356
|
+
|
|
357
|
+
Pour plusieurs moteurs (Serper, Brave, Tavily, Exa) fusionnés sans mélanger les
|
|
358
|
+
pages, la lecture sûre d'une page et un outil prêt pour les modèles, voir
|
|
359
|
+
[`@astratra/web-search`](../web-search/README.md), qui réutilise `searchSerper`.
|
|
354
360
|
|
|
355
361
|
## Registre d'outils
|
|
356
362
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/ai",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.15.0",
|
|
4
4
|
"description": "Generic AI provider routing, tool registry, and agent loop utilities for Astratra, plus agent guards (@astratra/ai/guards): outbound masking, prompt-injection handling for untrusted tool results, reply checks.",
|
|
5
5
|
"engines": {
|
|
6
6
|
"node": ">=20"
|
package/src/gemini.js
CHANGED
|
@@ -240,7 +240,7 @@ function createGuards(options = {}) {
|
|
|
240
240
|
|
|
241
241
|
async function scanForInjection(content, threshold) {
|
|
242
242
|
/* One or two words carry no instruction, and the injection model scores them at random (« oui » 0.96,
|
|
243
|
-
« Salut » 0.72
|
|
243
|
+
« Salut » 0.72 in production, 20/10/2026, where every real attack scored ≥ 0.993 from three words up). */
|
|
244
244
|
if (wordCount(content) < minWords) return { score: null, suspected: false, chunks: 0, short: true };
|
|
245
245
|
const pieces = windowsOf(content, chunkChars, overlapChars);
|
|
246
246
|
let max = 0;
|
package/src/index.d.ts
CHANGED
|
@@ -709,6 +709,8 @@ export function askGeminiModel(
|
|
|
709
709
|
|
|
710
710
|
/** Les sources d'une réponse generateContent (ou d'un de ses candidats), nettoyées et bornées. Ne lève jamais. */
|
|
711
711
|
export function readGeminiGrounding(answer: unknown): GeminiGrounding;
|
|
712
|
+
/** Un schéma JSON accepté par l'API Gemini native : additionalProperties, $schema et $id retirés à toute profondeur. */
|
|
713
|
+
export function geminiSchema<T>(schema: T): T;
|
|
712
714
|
|
|
713
715
|
export function createGeminiProvider(options: ChatProviderOptions & {
|
|
714
716
|
id?: string;
|
|
@@ -820,9 +822,15 @@ export function openEventStream(
|
|
|
820
822
|
|
|
821
823
|
export interface WebResult { title: string; url: string; snippet: string; date: string | null }
|
|
822
824
|
|
|
823
|
-
|
|
825
|
+
export type SerperPeriod = 'hour' | 'day' | 'week' | 'month' | 'year';
|
|
826
|
+
export const SERPER_PERIODS: Readonly<Record<SerperPeriod, string>>;
|
|
827
|
+
|
|
828
|
+
/**
|
|
829
|
+
* Lève une erreur de code 'WEB_SEARCH_NO_KEY' (rien n'est demandé) ou 'WEB_SEARCH_FAILED', avec `status` quand Serper a
|
|
830
|
+
* répondu. Pour plusieurs moteurs fusionnés et la lecture des pages, voir @astratra/web-search, qui réutilise celui-ci.
|
|
831
|
+
*/
|
|
824
832
|
export function searchSerper(
|
|
825
|
-
search: { query: string; sites?: string[]; hl?: string; num?: number },
|
|
833
|
+
search: { query: string; sites?: string[]; hl?: string; gl?: string; period?: SerperPeriod; num?: number },
|
|
826
834
|
io: { key: string | null | undefined; fetch: FetchLike; accept?: (result: WebResult, url: URL) => boolean; timeoutMs?: number; endpoint?: string }
|
|
827
835
|
): Promise<WebResult[]>;
|
|
828
836
|
|
package/src/mcpClient.js
CHANGED
|
@@ -3,8 +3,7 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* Connecteur MCP (26/10/2026) : une IA d'Astratra se branche sur un serveur MCP distant (transport « Streamable HTTP »)
|
|
5
5
|
* et en reçoit les outils comme ses outils natifs ({ name, description, parameters, kind, run }), prêts pour
|
|
6
|
-
* runToolLoop / createToolCaller.
|
|
7
|
-
* serveur MCP (GitHub, documentation…) se branche de la même façon.
|
|
6
|
+
* runToolLoop / createToolCaller. Tout serveur MCP (GitHub, documentation…) se branche de la même façon.
|
|
8
7
|
*
|
|
9
8
|
* Règles :
|
|
10
9
|
* - ce que rend un serveur MCP est une DONNÉE NON FIABLE : chaque outil est marqué `external: true`, pour que les gardes
|
|
@@ -48,7 +47,7 @@ async function chargerSdk() {
|
|
|
48
47
|
* @param {object} options
|
|
49
48
|
* @param {string} options.url adresse du serveur MCP (https://…/mcp)
|
|
50
49
|
* @param {Record<string,string>} [options.headers] en-têtes envoyés à chaque requête (par exemple Authorization: Bearer …)
|
|
51
|
-
* @param {string} [options.prefix] préfixe des noms d'outils (par exemple «
|
|
50
|
+
* @param {string} [options.prefix] préfixe des noms d'outils (par exemple « salon_ »)
|
|
52
51
|
* @param {string[]} [options.allow] noms MCP des seuls outils à exposer
|
|
53
52
|
* @param {Record<string,{kind?:string,risk?:string}|string>} [options.kinds] genre et risque par nom MCP (défaut read)
|
|
54
53
|
* @param {number} [options.timeoutMs] délai d'un appel d'outil (défaut 20 s)
|
package/src/webSearch.js
CHANGED
|
@@ -5,15 +5,21 @@
|
|
|
5
5
|
* seulement, un titre obligatoire, au plus `num`, et un filtre de l'appelant
|
|
6
6
|
* (un site hostile, une source refusée) appliqué AVANT que le modèle ne lise.
|
|
7
7
|
* La clé part dans l'en-tête et n'apparaît dans aucune erreur.
|
|
8
|
+
*
|
|
9
|
+
* C'est aussi l'adaptateur Serper de @astratra/web-search, qui le réutilise
|
|
10
|
+
* (fusion de plusieurs moteurs, lecture des pages) au lieu d'en écrire un autre.
|
|
8
11
|
*/
|
|
9
12
|
|
|
10
13
|
const DEFAULT_ENDPOINT = 'https://google.serper.dev/search';
|
|
11
14
|
const DEFAULT_NUM = 8;
|
|
12
15
|
const DEFAULT_TIMEOUT_MS = 10_000;
|
|
16
|
+
/** La période de Google (`tbs=qdr:…`) : dernière heure, jour, semaine, mois, an. */
|
|
17
|
+
const PERIODS = Object.freeze({ hour: 'qdr:h', day: 'qdr:d', week: 'qdr:w', month: 'qdr:m', year: 'qdr:y' });
|
|
13
18
|
|
|
14
|
-
function failure(code, message) {
|
|
19
|
+
function failure(code, message, status) {
|
|
15
20
|
const error = new Error(message);
|
|
16
21
|
error.code = code;
|
|
22
|
+
if (status !== undefined) error.status = status;
|
|
17
23
|
return error;
|
|
18
24
|
}
|
|
19
25
|
|
|
@@ -22,6 +28,8 @@ function failure(code, message) {
|
|
|
22
28
|
* @param {string} search.query
|
|
23
29
|
* @param {string[]} [search.sites] la recherche restreinte à ces sites (site:a OR site:b).
|
|
24
30
|
* @param {string} [search.hl] la langue de l'interface de recherche.
|
|
31
|
+
* @param {string} [search.gl] le pays des résultats (code à deux lettres).
|
|
32
|
+
* @param {string} [search.period] 'hour' | 'day' | 'week' | 'month' | 'year' : seulement les résultats récents.
|
|
25
33
|
* @param {number} [search.num] Défaut 8.
|
|
26
34
|
* @param {object} io
|
|
27
35
|
* @param {string} io.key
|
|
@@ -30,25 +38,36 @@ function failure(code, message) {
|
|
|
30
38
|
* @param {number} [io.timeoutMs] Défaut 10 s.
|
|
31
39
|
* @param {string} [io.endpoint]
|
|
32
40
|
* @returns {Promise<{ title: string, url: string, snippet: string, date: string|null }[]>}
|
|
33
|
-
* @throws {Error} code 'WEB_SEARCH_NO_KEY' sans clé (rien n'est demandé), 'WEB_SEARCH_FAILED' sinon
|
|
41
|
+
* @throws {Error} code 'WEB_SEARCH_NO_KEY' sans clé (rien n'est demandé), 'WEB_SEARCH_FAILED' sinon,
|
|
42
|
+
* avec `status` quand Serper a répondu (429, 5xx…) : de quoi décider d'un repli.
|
|
34
43
|
*/
|
|
35
44
|
async function searchSerper(search = {}, io = {}) {
|
|
36
45
|
if (!io.key) throw failure('WEB_SEARCH_NO_KEY', 'no key');
|
|
37
46
|
if (typeof io.fetch !== 'function') throw new Error('searchSerper requires io.fetch.');
|
|
38
47
|
const num = search.num || DEFAULT_NUM;
|
|
39
48
|
const scope = (search.sites || []).map((site) => `site:${site}`).join(' OR ');
|
|
49
|
+
if (search.period !== undefined && !PERIODS[search.period]) throw new Error(`searchSerper: unknown period ${search.period}.`);
|
|
50
|
+
const extra = {
|
|
51
|
+
...(search.hl ? { hl: search.hl } : {}),
|
|
52
|
+
...(search.gl ? { gl: String(search.gl).toLowerCase() } : {}),
|
|
53
|
+
...(search.period ? { tbs: PERIODS[search.period] } : {})
|
|
54
|
+
};
|
|
40
55
|
let answer;
|
|
56
|
+
let status;
|
|
41
57
|
try {
|
|
42
58
|
const response = await io.fetch(io.endpoint || DEFAULT_ENDPOINT, {
|
|
43
59
|
method: 'POST',
|
|
44
60
|
headers: { 'X-API-KEY': io.key, 'content-type': 'application/json' },
|
|
45
|
-
body: JSON.stringify({ q: scope ? `${search.query} ${scope}` : search.query, num, ...
|
|
61
|
+
body: JSON.stringify({ q: scope ? `${search.query} ${scope}` : search.query, num, ...extra }),
|
|
46
62
|
signal: globalThis.AbortSignal.timeout(io.timeoutMs || DEFAULT_TIMEOUT_MS)
|
|
47
63
|
});
|
|
48
|
-
if (!response.ok)
|
|
64
|
+
if (!response.ok) {
|
|
65
|
+
status = response.status;
|
|
66
|
+
throw new Error(`Serper answered ${response.status}`);
|
|
67
|
+
}
|
|
49
68
|
answer = await response.json();
|
|
50
69
|
} catch (error) {
|
|
51
|
-
throw failure('WEB_SEARCH_FAILED', error.message);
|
|
70
|
+
throw failure('WEB_SEARCH_FAILED', error.message, status);
|
|
52
71
|
}
|
|
53
72
|
const accept = typeof io.accept === 'function' ? io.accept : () => true;
|
|
54
73
|
return (Array.isArray(answer?.organic) ? answer.organic : [])
|
|
@@ -68,4 +87,4 @@ async function searchSerper(search = {}, io = {}) {
|
|
|
68
87
|
.slice(0, num);
|
|
69
88
|
}
|
|
70
89
|
|
|
71
|
-
module.exports = { searchSerper };
|
|
90
|
+
module.exports = { searchSerper, SERPER_PERIODS: PERIODS };
|