@astratra/ai 1.12.0 → 1.13.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 +32 -1
- package/package.json +1 -1
- package/src/gemini.js +19 -1
- package/src/guards/createGuards.js +14 -2
- package/src/guards/index.d.ts +2 -0
package/README.md
CHANGED
|
@@ -49,6 +49,28 @@ défaut (bloquer et signaler). `failOpen` laisse passer en signalant
|
|
|
49
49
|
`degraded` ; `recommendedGuards({ readOnly: true })` l'applique à un agent qui
|
|
50
50
|
ne fait que lire. Le mode d'une exécution est `newRun({ mode: 'action' | 'read' })`.
|
|
51
51
|
|
|
52
|
+
**Textes courts (1.13.0)** : un texte de moins de `injection.minWords` mots (3 par
|
|
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é sur Examen d'État le 20/10/2026 : « oui » 0,96,
|
|
55
|
+
« Salut » 0,72, alors que toutes les vraies attaques dépassaient 0,993 dès trois
|
|
56
|
+
mots). Le résultat porte `score: null` et la raison `too_short_to_scan`.
|
|
57
|
+
|
|
58
|
+
**Où passent les messages de la personne** : par `input()`, jamais par
|
|
59
|
+
`toolResult(…, { external: true })`. `toolResult` sert à ce qui vient de
|
|
60
|
+
l'extérieur (page web, fichier, réponse d'un service) ; un message de la
|
|
61
|
+
personne passé par là peut marquer toute l'exécution `requiresConfirmation`, et
|
|
62
|
+
un agent qui revérifie tout l'historique à chaque tour reste alors bloqué.
|
|
63
|
+
|
|
64
|
+
**À savoir avec `recommendedGuards`** :
|
|
65
|
+
- sans `readOnly`, la politique est `failClosed` partout : si le modèle
|
|
66
|
+
d'entités ne répond plus (par exemple son disjoncteur ouvert après des délais
|
|
67
|
+
dépassés quand un tour vérifie beaucoup de messages en parallèle), `input`
|
|
68
|
+
bloque et l'agent entier s'arrête. Pour un agent qui ne fait que lire,
|
|
69
|
+
`readOnly: true` ; sinon, limiter ce qui est revérifié à chaque tour ;
|
|
70
|
+
- l'ancrage (`output.grounding`, NLI phrase par phrase) coûte de l'ordre de 3 s
|
|
71
|
+
par réponse sur un processeur ; c'est un signal, `output: { grounding: false }`
|
|
72
|
+
le coupe quand la latence compte plus.
|
|
73
|
+
|
|
52
74
|
**Événements** : chaque décision appelle `onEvent({ type: 'guard', guard, decision,
|
|
53
75
|
reasons, degraded, metrics, runId, mode, at })`. Ils ne contiennent jamais le
|
|
54
76
|
texte (ni saisie, ni résultat d'outil, ni réponse) : des nombres, des codes et
|
|
@@ -78,7 +100,10 @@ suspected, forbids every action without a human for the rest of the run
|
|
|
78
100
|
(`beforeAction`), `output` unmasks the reply and checks grounding against the
|
|
79
101
|
sources, personal-data leaks and moderation. Failure policy is `failClosed` for
|
|
80
102
|
actions by default, `failOpen` possible for read-only runs. Events never carry
|
|
81
|
-
the text. Mocks for tests: `@astratra/ai/guards/testing`.
|
|
103
|
+
the text. Mocks for tests: `@astratra/ai/guards/testing`. Since 1.13.0, texts
|
|
104
|
+
under `injection.minWords` words (default 3) are not sent to the injection
|
|
105
|
+
model, which scores one or two words at random; the person's own messages go
|
|
106
|
+
through `input()`, never `toolResult(…, { external: true })`.
|
|
82
107
|
|
|
83
108
|
## Routeur de providers
|
|
84
109
|
|
|
@@ -182,6 +207,12 @@ appel — et n'est jamais une réponse à montrer. Des arguments illisibles gard
|
|
|
182
207
|
l'appel, marqué `invalid` avec `invalidReason` (`not_json`, `not_object`), et
|
|
183
208
|
repartent en `{}` au tour suivant.
|
|
184
209
|
|
|
210
|
+
**Schémas d'outils chez Gemini (1.13.0)** : l'API Gemini native refuse
|
|
211
|
+
`additionalProperties`, `$schema` et `$id` dans les paramètres d'une fonction
|
|
212
|
+
(400 « Unknown name "additionalProperties" »). Ils sont retirés à toute
|
|
213
|
+
profondeur avant l'envoi (une *propriété* qui porte un de ces noms reste) ; les
|
|
214
|
+
schémas stricts produits par `toolSpecs` passent donc tels quels.
|
|
215
|
+
|
|
185
216
|
**Signatures de pensée (Gemini 3, 1.12.0)** : chaque appel d'outil de Gemini 3
|
|
186
217
|
porte une signature, à rendre telle quelle au tour suivant, sinon Gemini répond
|
|
187
218
|
400. Elle arrive dans `toolCalls[i].signature` (directement chez Gemini, par
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astratra/ai",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.13.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
|
@@ -130,6 +130,24 @@ function readGeminiGrounding(answer) {
|
|
|
130
130
|
return { searched: queries.length > 0 || sources.length > 0, queries, sources, searchSuggestionsHtml: entry };
|
|
131
131
|
}
|
|
132
132
|
|
|
133
|
+
/* L'API Gemini native refuse ces mots de JSON Schema dans `parameters` (400 « Unknown name "additionalProperties" »),
|
|
134
|
+
alors que les schémas stricts en portent souvent (`additionalProperties: false`). Ils sont retirés à toute profondeur,
|
|
135
|
+
sans toucher à une propriété qui porte un de ces noms (les clés de `properties` sont des noms, pas des mots du schéma). */
|
|
136
|
+
const GEMINI_UNSUPPORTED = new Set(['additionalProperties', '$schema', '$id']);
|
|
137
|
+
function geminiSchema(value) {
|
|
138
|
+
if (Array.isArray(value)) return value.map(geminiSchema);
|
|
139
|
+
if (!value || typeof value !== 'object') return value;
|
|
140
|
+
const out = {};
|
|
141
|
+
for (const [key, child] of Object.entries(value)) {
|
|
142
|
+
if (GEMINI_UNSUPPORTED.has(key)) continue;
|
|
143
|
+
out[key] = key === 'properties' && child && typeof child === 'object' && !Array.isArray(child)
|
|
144
|
+
? Object.fromEntries(Object.entries(child).map(([name, schema]) => [name, geminiSchema(schema)]))
|
|
145
|
+
: geminiSchema(child);
|
|
146
|
+
}
|
|
147
|
+
return out;
|
|
148
|
+
}
|
|
149
|
+
const geminiDeclaration = (tool) => (tool && tool.parameters ? { ...tool, parameters: geminiSchema(tool.parameters) } : tool);
|
|
150
|
+
|
|
133
151
|
/** Le corps de la requête pour un modèle. */
|
|
134
152
|
function requestBody(model, request, noSystemInstruction, search = null, dropFunctions = false) {
|
|
135
153
|
const contents = contentsOf(request.messages, model);
|
|
@@ -138,7 +156,7 @@ function requestBody(model, request, noSystemInstruction, search = null, dropFun
|
|
|
138
156
|
maxOutputTokens: request.maxTokens || 1200
|
|
139
157
|
};
|
|
140
158
|
const toolList = [];
|
|
141
|
-
if (request.tools && request.tools.length && !dropFunctions) toolList.push({ functionDeclarations: request.tools });
|
|
159
|
+
if (request.tools && request.tools.length && !dropFunctions) toolList.push({ functionDeclarations: request.tools.map(geminiDeclaration) });
|
|
142
160
|
if (search) toolList.push({ google_search: {} });
|
|
143
161
|
const functions = toolList.length ? { tools: toolList } : {};
|
|
144
162
|
const system = request.system || '';
|
|
@@ -27,6 +27,9 @@ const FAIL_OPEN = 'failOpen';
|
|
|
27
27
|
const DECISIONS = Object.freeze(['allow', 'flag', 'block']);
|
|
28
28
|
const SEVERITY = { allow: 0, flag: 1, block: 2 };
|
|
29
29
|
const DEFAULT_MAX_SCAN_CHARS = 100000;
|
|
30
|
+
const DEFAULT_MIN_WORDS = 3;
|
|
31
|
+
/* Words that carry letters or digits: emoji and punctuation alone are not words. */
|
|
32
|
+
const wordCount = (text) => String(text).split(/\s+/).filter((word) => /[\p{L}\p{N}]/u.test(word)).length;
|
|
30
33
|
const WITHHELD = '[content withheld by a guard]';
|
|
31
34
|
|
|
32
35
|
const keyHash = (key) => crypto.createHash('sha256').update(String(key)).digest('hex');
|
|
@@ -77,7 +80,8 @@ function lazyVerifySources() {
|
|
|
77
80
|
* @param {Function} [options.onEvent]
|
|
78
81
|
* @param {string[]} [options.names] register names always masked.
|
|
79
82
|
* @param {string[]} [options.entityLabels] default ['person'].
|
|
80
|
-
* @param {object} [options.injection] { threshold = 0.5, actionThreshold = threshold, maxScanChars, chunkChars, overlapChars
|
|
83
|
+
* @param {object} [options.injection] { threshold = 0.5, actionThreshold = threshold, maxScanChars, chunkChars, overlapChars,
|
|
84
|
+
* minWords = 3 (shorter texts are not sent to the injection model; 0 sends everything) }.
|
|
81
85
|
* @param {object} [options.output] { grounding = true, leak = true, moderation = true, minSupport = 0.5, leakTypes }.
|
|
82
86
|
* @param {Function} [options.verifySources] (answer, sources, { nli }) => report; default: @astratra/rag if installed.
|
|
83
87
|
* @param {'action'|'read'} [options.defaultMode] mode of a run that does not name one. Default 'action'.
|
|
@@ -101,6 +105,8 @@ function createGuards(options = {}) {
|
|
|
101
105
|
const maxScanChars = injectionOptions.maxScanChars || DEFAULT_MAX_SCAN_CHARS;
|
|
102
106
|
const chunkChars = injectionOptions.chunkChars || 6000;
|
|
103
107
|
const overlapChars = injectionOptions.overlapChars === undefined ? 300 : injectionOptions.overlapChars;
|
|
108
|
+
const minWords = injectionOptions.minWords === undefined ? DEFAULT_MIN_WORDS : injectionOptions.minWords;
|
|
109
|
+
if (!Number.isInteger(minWords) || minWords < 0) throw new TypeError('injection.minWords must be an integer >= 0.');
|
|
104
110
|
const outputOptions = { grounding: true, leak: true, moderation: true, minSupport: 0.5, ...(options.output || {}) };
|
|
105
111
|
const verifySources = options.verifySources || (outputOptions.grounding ? lazyVerifySources() : null);
|
|
106
112
|
|
|
@@ -233,6 +239,9 @@ function createGuards(options = {}) {
|
|
|
233
239
|
/* ---- toolResult --------------------------------------------------------- */
|
|
234
240
|
|
|
235
241
|
async function scanForInjection(content, threshold) {
|
|
242
|
+
/* One or two words carry no instruction, and the injection model scores them at random (« oui » 0.96,
|
|
243
|
+
« Salut » 0.72 on Examen d'État, 20/10/2026, where every real attack scored ≥ 0.993 from three words up). */
|
|
244
|
+
if (wordCount(content) < minWords) return { score: null, suspected: false, chunks: 0, short: true };
|
|
236
245
|
const pieces = windowsOf(content, chunkChars, overlapChars);
|
|
237
246
|
let max = 0;
|
|
238
247
|
for (let i = 0; i < pieces.length; i += 8) {
|
|
@@ -271,7 +280,10 @@ function createGuards(options = {}) {
|
|
|
271
280
|
} else {
|
|
272
281
|
const scan = await scanForInjection(content, run.mode === 'action' ? actionThreshold : injectionThreshold);
|
|
273
282
|
if (scan.failed) degraded.push('injection');
|
|
274
|
-
else
|
|
283
|
+
else {
|
|
284
|
+
({ score, suspected, chunks } = scan);
|
|
285
|
+
if (scan.short) reasons.push('too_short_to_scan');
|
|
286
|
+
}
|
|
275
287
|
}
|
|
276
288
|
if (degraded.length) {
|
|
277
289
|
reasons.push('injection_check_unavailable');
|
package/src/guards/index.d.ts
CHANGED
|
@@ -65,6 +65,8 @@ export interface CreateGuardsOptions {
|
|
|
65
65
|
maxScanChars?: number;
|
|
66
66
|
chunkChars?: number;
|
|
67
67
|
overlapChars?: number;
|
|
68
|
+
/** Texts with fewer words are not sent to the injection model (it scores one or two words at random). Default 3; 0 sends everything. */
|
|
69
|
+
minWords?: number;
|
|
68
70
|
};
|
|
69
71
|
output?: {
|
|
70
72
|
grounding?: boolean;
|