@astratra/ai 1.10.0 → 1.12.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 CHANGED
@@ -39,7 +39,7 @@ const reply = await guards.output(modelAnswer, run); // démasqué, pui
39
39
 
40
40
  | Garde | Ce qu'elle fait |
41
41
  |---|---|
42
- | `input(text, run)` | masque les noms (détecteur d'entités + `names` du registre) et les données structurées (e-mail, IBAN, carte, téléphone) ; le texte revient démasqué dans `output`. Rend `text: null` si elle bloque. |
42
+ | `input(text, run)` | masque les noms (détecteur d'entités + `names` du registre) et les données structurées (e-mail, IBAN, carte, téléphone) ainsi que les secrets (clés d'API, jetons JWT, clés privées, adresses IP) ; le texte revient démasqué dans `output`. Rend `text: null` si elle bloque. |
43
43
  | `toolResult(result, run, { tool, external })` | pour un résultat **externe** (ou marqué `{ untrusted: true, content }`) : détection d'injection (texte long lu par fenêtres, jamais passé sans contrôle), contenu encadré par des marqueurs à nonce comme *données non fiables*. Injection suspectée : `run.requiresConfirmation = true` pour tout le reste de l'exécution. |
44
44
  | `output(text, run)` | démasque ; **ancrage** (chaque phrase contre les sources lues, NLI, via `verifySources` de rag) avec `groundingScore` et la liste `unsupported` ; **fuite** de données personnelles que la personne n'a pas données (`onLeak`: `block`, `redact`, `flag`) ; **modération**. |
45
45
  | `beforeAction(action, run, { humanConfirmed })` | refuse toute action tant qu'une injection est suspectée et qu'aucun humain n'a confirmé (`humanConfirmed: true` vient de votre interface, jamais du modèle). |
@@ -61,7 +61,12 @@ vraies gardes sur ce client, avec un enregistreur d'événements) et
61
61
  `createEventRecorder`.
62
62
 
63
63
  Limites : les gardes réduisent le risque, elles ne le suppriment pas. Les
64
- règles de fuite ne couvrent que les données structurées ; l'ancrage compte
64
+ règles de fuite ne couvrent que les données structurées et les secrets à forme
65
+ connue (`findPersonalData` : `email`, `iban`, `card`, `phone`, `apiKey` —
66
+ OpenAI, Anthropic, Google, GitHub, Stripe, AWS, Slack, Groq, Hugging Face —,
67
+ `jwt`, `privateKey`, `ip`) ; une clé sans préfixe reconnaissable passe. Une
68
+ clé ou une adresse IP n'est jamais lue à moitié comme un téléphone ou une
69
+ carte. L'ancrage compte
65
70
  aussi comme « non soutenues » des phrases de liaison ; la détection d'injection
66
71
  lit un texte isolé.
67
72
 
@@ -177,6 +182,20 @@ appel — et n'est jamais une réponse à montrer. Des arguments illisibles gard
177
182
  l'appel, marqué `invalid` avec `invalidReason` (`not_json`, `not_object`), et
178
183
  repartent en `{}` au tour suivant.
179
184
 
185
+ **Signatures de pensée (Gemini 3, 1.12.0)** : chaque appel d'outil de Gemini 3
186
+ porte une signature, à rendre telle quelle au tour suivant, sinon Gemini répond
187
+ 400. Elle arrive dans `toolCalls[i].signature` (directement chez Gemini, par
188
+ l'API compatible OpenAI de Google, ou par la passerelle Centrale) : **gardez
189
+ l'appel tel quel** dans le message `assistant` de l'historique, elle repart
190
+ avec lui (`thoughtSignature` chez Gemini, `extra_content.google.thought_signature`
191
+ au format OpenAI). Au format OpenAI, elle n'est envoyée qu'à `*.googleapis.com`,
192
+ ou à une cible qui le demande : `thoughtSignatures: true` (dans la cible
193
+ d'`askChatModel` ou les options de `createOpenAICompatibleProvider` ;
194
+ `modeleDiscussion()` de `@astratra/centrale` 1.7.0 le donne) ; jamais à un
195
+ autre fournisseur, qui pourrait refuser le champ. Un premier appel sans
196
+ signature (venu d'un autre fournisseur) part chez Gemini avec la valeur de
197
+ contournement de Google (`skip_thought_signature_validator`), sauf pour Gemma.
198
+
180
199
  ### La réponse petit à petit (`onText`)
181
200
 
182
201
  Passé dans le contexte de `route()` (`router.route(requete, options, { onText })`) ou dans `io` d'`askChatModel` /
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/ai",
3
- "version": "1.10.0",
3
+ "version": "1.12.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
@@ -30,13 +30,22 @@ const noSystemInstructionByDefault = (model) => String(model).startsWith('gemma-
30
30
  /* Des arguments illisibles (null) repartent en objet vide : Gemini refuse autre chose. */
31
31
  const argsOf = (args) => (args && typeof args === 'object' && !Array.isArray(args) ? args : {});
32
32
 
33
- function contentsOf(messages) {
33
+ /* Gemini 3 vérifie la signature de pensée du premier appel de chaque étape (les appels parallèles suivants n'en ont pas).
34
+ Un appel sans signature (venu d'un autre fournisseur, ou d'un historique d'avant) reçoit la valeur de contournement
35
+ documentée par Google plutôt qu'un 400 ; Gemma n'a pas de signatures. */
36
+ const BYPASS_SIGNATURE = 'skip_thought_signature_validator';
37
+
38
+ function contentsOf(messages, model = '') {
39
+ const bypass = !String(model).startsWith('gemma-');
34
40
  return (Array.isArray(messages) ? messages : []).map((message) => {
35
41
  if (message.role === 'assistant') {
36
42
  const parts = [];
37
43
  const text = message.text === undefined ? message.content : message.text;
38
44
  if (text) parts.push({ text });
39
- for (const call of message.toolCalls || []) parts.push({ functionCall: { name: call.name, args: argsOf(call.args) } });
45
+ (message.toolCalls || []).forEach((call, index) => {
46
+ const signature = call.signature || (index === 0 && bypass ? BYPASS_SIGNATURE : null);
47
+ parts.push({ functionCall: { name: call.name, args: argsOf(call.args) }, ...(signature ? { thoughtSignature: signature } : {}) });
48
+ });
40
49
  return { role: 'model', parts };
41
50
  }
42
51
  if (message.role === 'tool') {
@@ -123,7 +132,7 @@ function readGeminiGrounding(answer) {
123
132
 
124
133
  /** Le corps de la requête pour un modèle. */
125
134
  function requestBody(model, request, noSystemInstruction, search = null, dropFunctions = false) {
126
- const contents = contentsOf(request.messages);
135
+ const contents = contentsOf(request.messages, model);
127
136
  const generationConfig = {
128
137
  temperature: request.temperature === undefined ? 0.4 : request.temperature,
129
138
  maxOutputTokens: request.maxTokens || 1200
@@ -191,7 +200,8 @@ async function askGeminiModel(model, request, io = {}) {
191
200
  const toolCalls = functionsDropped ? [] : parts.filter((part) => part.functionCall).map((part, index) => ({
192
201
  id: part.functionCall.id || `call_${index}`,
193
202
  name: part.functionCall.name,
194
- args: argsOf(part.functionCall.args)
203
+ args: argsOf(part.functionCall.args),
204
+ ...(typeof part.thoughtSignature === 'string' && part.thoughtSignature ? { signature: part.thoughtSignature } : {})
195
205
  }));
196
206
  if (toolCalls.length) return { status: response.status, text: null, toolCalls, ...grounding };
197
207
  const text = withoutThinking(parts.filter((part) => !part.thought && !part.functionCall).map((part) => part.text || '').join(''));
@@ -72,7 +72,7 @@ export interface CreateGuardsOptions {
72
72
  moderation?: boolean;
73
73
  /** Share of supported claims under which the reply is `unsupported`. Default 0.5. */
74
74
  minSupport?: number;
75
- leakTypes?: Array<'email' | 'iban' | 'card' | 'phone'>;
75
+ leakTypes?: Array<PersonalDataType>;
76
76
  allowLeak?: (item: { type: string; key: string }, run: GuardRun) => boolean;
77
77
  };
78
78
  /** `verifySources` of @astratra/rag; default: the installed @astratra/rag. */
@@ -143,7 +143,9 @@ export function createGuards(options?: CreateGuardsOptions): Guards;
143
143
  /** Every check on, failClosed for actions, 0.3 injection threshold before an action, leaks and unsafe replies blocked. */
144
144
  export function recommendedGuards(options?: CreateGuardsOptions & { readOnly?: boolean }): Guards;
145
145
  export function frameUntrusted(content: string, options?: { source?: string; nonce?: string }): string;
146
- export function findPersonalData(text: string, types?: string[]): Array<{ type: string; value: string; key: string; start: number; end: number }>;
146
+ /** Personal data and secrets recognised without a model. */
147
+ export type PersonalDataType = 'email' | 'iban' | 'card' | 'phone' | 'apiKey' | 'jwt' | 'privateKey' | 'ip';
148
+ export function findPersonalData(text: string, types?: PersonalDataType[]): Array<{ type: PersonalDataType; value: string; key: string; start: number; end: number }>;
147
149
  export const UNTRUSTED_NOTICE: string;
148
150
  export const GUARD_DECISIONS: readonly GuardDecision[];
149
151
  export const FAIL_CLOSED: 'failClosed';
@@ -1,7 +1,9 @@
1
1
  'use strict';
2
2
 
3
- /* Personal data a reply must not carry unless the person gave it in this run.
4
- Small on purpose: structured data that can be recognised without a model. */
3
+ /* Personal data and secrets a reply must not carry unless the person gave it in this run.
4
+ Small on purpose: structured data that can be recognised without a model. Secrets
5
+ (API keys, tokens, private keys) and IP addresses are found first: a key or an address
6
+ is never half-read as a phone number or a card. */
5
7
 
6
8
  function luhnValid(digits) {
7
9
  if (digits.length < 13 || digits.length > 19) return false;
@@ -30,7 +32,31 @@ function ibanValid(value) {
30
32
 
31
33
  const DATE_LIKE = /^\d{4}-\d{2}-\d{2}/;
32
34
 
35
+ /* Keys whose shape is published by their provider. A prefix and a long random tail: no
36
+ ordinary word looks like this. */
37
+ const API_KEY = new RegExp([
38
+ 'sk-ant-[A-Za-z0-9_-]{20,}', // Anthropic
39
+ 'sk-(?:proj-|svcacct-)?[A-Za-z0-9_-]{20,}', // OpenAI
40
+ 'AIza[0-9A-Za-z_-]{35}', // Google
41
+ 'gh[pousr]_[A-Za-z0-9]{36,}', // GitHub
42
+ 'github_pat_[A-Za-z0-9_]{22,}', // GitHub, fine-grained
43
+ '(?:sk|rk|pk)_(?:live|test)_[A-Za-z0-9]{16,}', // Stripe
44
+ 'whsec_[A-Za-z0-9]{24,}', // Stripe webhooks
45
+ 'AKIA[0-9A-Z]{16}', // AWS
46
+ 'xox[baprs]-[A-Za-z0-9-]{10,}', // Slack
47
+ 'gsk_[A-Za-z0-9]{20,}', // Groq
48
+ 'hf_[A-Za-z0-9]{30,}' // Hugging Face
49
+ ].map((p) => `(?<![A-Za-z0-9_-])${p}`).join('|'), 'g');
50
+
51
+ function ipv4Valid(value) {
52
+ return value.split('.').every((part) => Number(part) <= 255 && !(part.length > 1 && part.startsWith('0')));
53
+ }
54
+
33
55
  const DETECTORS = [
56
+ { type: 'privateKey', pattern: () => /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, valid: () => true },
57
+ { type: 'jwt', pattern: () => /(?<![A-Za-z0-9_-])eyJ[A-Za-z0-9_-]{8,}\.eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, valid: () => true },
58
+ { type: 'apiKey', pattern: () => new RegExp(API_KEY.source, 'g'), valid: () => true },
59
+ { type: 'ip', pattern: () => /(?<![\w.:])(?:\d{1,3}\.){3}\d{1,3}(?![\w.])|(?<![\w:])(?:[0-9a-f]{1,4}:){7}[0-9a-f]{1,4}(?![\w:])|(?<![\w:])(?:[0-9a-f]{1,4}:){1,6}:(?:[0-9a-f]{1,4}(?::[0-9a-f]{1,4}){0,5})?(?![\w:])/gi, valid: (value) => (value.includes('.') ? ipv4Valid(value) : (value.match(/:/g) || []).length >= 2) },
34
60
  { type: 'email', pattern: () => /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g, valid: () => true },
35
61
  { type: 'iban', pattern: () => /\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{2,5}){3,8}\b/g, valid: ibanValid },
36
62
  { type: 'card', pattern: () => /\b(?:\d[ -]?){13,19}\b/g, valid: (value) => luhnValid(value.replace(/\D/g, '')) },
@@ -44,7 +70,12 @@ const DETECTORS = [
44
70
  }
45
71
  ];
46
72
 
47
- const normal = (type, value) => (type === 'email' ? value.toLowerCase() : value.replace(/[\s.()-]/g, '').toUpperCase());
73
+ const SECRET_TYPES = new Set(['privateKey', 'jwt', 'apiKey']);
74
+ const normal = (type, value) => {
75
+ if (type === 'email' || type === 'ip') return value.toLowerCase();
76
+ if (SECRET_TYPES.has(type)) return value.replace(/\s+/g, '');
77
+ return value.replace(/[\s.()-]/g, '').toUpperCase();
78
+ };
48
79
 
49
80
  /** Structured personal data in a text: [{ type, value, start, end }] (values stay in memory, never in events). */
50
81
  function findPersonalData(text, types) {
package/src/index.d.ts CHANGED
@@ -583,7 +583,7 @@ export interface ChatMessage {
583
583
  text?: string;
584
584
  content?: string;
585
585
  images?: Array<{ mimeType: string; data: string }>;
586
- toolCalls?: Array<{ id: string; name: string; args: unknown }>;
586
+ toolCalls?: Array<{ id: string; name: string; args: unknown; signature?: string }>;
587
587
  toolCallId?: string;
588
588
  result?: unknown;
589
589
  }
@@ -598,12 +598,15 @@ export interface ChatToolCall {
598
598
  invalidReason?: 'not_json' | 'not_object';
599
599
  /** L'erreur de lecture, pour 'not_json'. */
600
600
  invalidDetail?: string;
601
+ /** La signature de pensée de Gemini 3 : gardez l'appel tel quel dans l'historique, elle repart avec lui (sinon Gemini répond 400). */
602
+ signature?: string;
601
603
  }
602
604
 
603
605
  export type FetchLike = (url: string, init: { method: string; headers: Record<string, string>; body: string; signal?: AbortSignal }) => Promise<{ ok: boolean; status: number; json(): Promise<any> }>;
604
606
 
605
607
  export function askChatModel(
606
- target: { url: string; key: string; model: string; extra?: Record<string, unknown> },
608
+ /** `thoughtSignatures` : renvoyer les signatures de pensée de Gemini 3 (par défaut : seulement vers *.googleapis.com ; true pour la passerelle Centrale). */
609
+ target: { url: string; key: string; model: string; extra?: Record<string, unknown>; thoughtSignatures?: boolean },
607
610
  request: { system?: string; messages: ChatMessage[]; tools?: Array<Record<string, unknown>>; maxTokens?: number; temperature?: number },
608
611
  io: { fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; onText?: (shown: string) => void }
609
612
  ): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean; retryAfterMs?: number }>;
@@ -692,6 +695,8 @@ export function createOpenAICompatibleProvider(options: ChatProviderOptions & {
692
695
  url: string | ((ctx: Record<string, unknown>) => string | null | undefined);
693
696
  external?: boolean;
694
697
  extra?: Record<string, unknown>;
698
+ /** Renvoyer les signatures de pensée de Gemini 3 (par défaut : seulement vers *.googleapis.com ; true pour la passerelle Centrale). */
699
+ thoughtSignatures?: boolean;
695
700
  }): Provider;
696
701
 
697
702
  /* ─────────────────── Gemini ─────────────────── */
@@ -750,6 +755,8 @@ export interface NativeToolCall {
750
755
  invalid?: boolean;
751
756
  invalidReason?: 'not_json' | 'not_object';
752
757
  invalidDetail?: string;
758
+ /** La signature de pensée de Gemini 3, rendue avec l'appel au tour suivant. */
759
+ signature?: string;
753
760
  }
754
761
 
755
762
  export interface ToolMessage {
@@ -88,13 +88,15 @@ function readToolArguments(raw) {
88
88
  }
89
89
 
90
90
  /** Un appel d'outil lu : ses arguments, et quand ils sont illisibles, pourquoi. */
91
- function toolCallOf(id, name, rawArguments) {
91
+ function toolCallOf(id, name, rawArguments, signature) {
92
92
  const { args, invalid, reason, detail } = readToolArguments(rawArguments);
93
93
  return {
94
94
  id,
95
95
  name,
96
96
  args,
97
- ...(invalid ? { invalid: true, invalidReason: reason, ...(detail ? { invalidDetail: detail } : {}) } : {})
97
+ ...(invalid ? { invalid: true, invalidReason: reason, ...(detail ? { invalidDetail: detail } : {}) } : {}),
98
+ /* La « signature de pensée » de Gemini 3 : à rendre telle quelle avec l'appel au tour suivant, sinon Gemini répond 400. */
99
+ ...(typeof signature === 'string' && signature ? { signature } : {})
98
100
  };
99
101
  }
100
102
 
@@ -17,7 +17,18 @@ const { readRetryAfter } = require('./providerLimits');
17
17
  const { providerResult, readToolArguments, readWrittenAnswer, readWrittenToolCalls, toolCallOf, withoutThinking } = require('./modelAnswers');
18
18
  const { readServerEvents, textReporter } = require('./streamedAnswer');
19
19
 
20
- function toTranscript(messages) {
20
+ /* Les signatures de pensée de Gemini 3 voyagent dans `extra_content.google.thought_signature`, une extension de Google :
21
+ envoyées à Google, ou à une cible qui les demande (`thoughtSignatures: true`, la passerelle Centrale), jamais ailleurs. */
22
+ const signatureOf = (call) => {
23
+ const signature = call && call.extra_content && call.extra_content.google && call.extra_content.google.thought_signature;
24
+ return typeof signature === 'string' && signature ? signature : undefined;
25
+ };
26
+ function sendsSignatures(target) {
27
+ if (typeof target.thoughtSignatures === 'boolean') return target.thoughtSignatures;
28
+ try { return new URL(target.url).hostname.endsWith('.googleapis.com'); } catch (_error) { return false; }
29
+ }
30
+
31
+ function toTranscript(messages, signatures = false) {
21
32
  return (Array.isArray(messages) ? messages : []).map((message) => {
22
33
  if (message.role === 'assistant') {
23
34
  return {
@@ -28,7 +39,8 @@ function toTranscript(messages) {
28
39
  id: call.id,
29
40
  type: 'function',
30
41
  /* Des arguments illisibles (null) repartent en objet vide : le fournisseur refuserait « null ». */
31
- function: { name: call.name, arguments: JSON.stringify(call.args && typeof call.args === 'object' ? call.args : {}) }
42
+ function: { name: call.name, arguments: JSON.stringify(call.args && typeof call.args === 'object' ? call.args : {}) },
43
+ ...(signatures && call.signature ? { extra_content: { google: { thought_signature: call.signature } } } : {})
32
44
  }))
33
45
  } : {})
34
46
  };
@@ -72,7 +84,7 @@ async function askChatModel(target, request, io = {}) {
72
84
  const report = textReporter(io.onText);
73
85
  const messages = [
74
86
  ...(request.system ? [{ role: 'system', content: request.system }] : []),
75
- ...toTranscript(request.messages)
87
+ ...toTranscript(request.messages, sendsSignatures(target || {}))
76
88
  ];
77
89
  const response = await io.fetch(url, {
78
90
  method: 'POST',
@@ -100,7 +112,7 @@ async function askChatModel(target, request, io = {}) {
100
112
  return {
101
113
  status: response.status,
102
114
  text: null,
103
- toolCalls: message.tool_calls.map((call) => toolCallOf(call.id, call.function && call.function.name, call.function && call.function.arguments))
115
+ toolCalls: message.tool_calls.map((call) => toolCallOf(call.id, call.function && call.function.name, call.function && call.function.arguments, signatureOf(call)))
104
116
  };
105
117
  }
106
118
  const text = withoutThinking(message.content);
@@ -129,6 +141,7 @@ async function readChatStream(response, report) {
129
141
  if (part.id) call.id = part.id;
130
142
  if (part.function && part.function.name) call.function.name += part.function.name;
131
143
  if (part.function && typeof part.function.arguments === 'string') call.function.arguments += part.function.arguments;
144
+ if (signatureOf(part)) call.extra_content = part.extra_content;
132
145
  }
133
146
  });
134
147
  const toolCalls = calls.filter(Boolean).map((call, index) => ({ ...call, id: call.id || `call_${index}` }));
@@ -153,6 +166,8 @@ async function readChatStream(response, report) {
153
166
  * @param {boolean} [options.detailed] true: the call resolves { text, toolCalls, cut } (an empty text
154
167
  * included, for the router's `accepts` to judge) instead of the text alone.
155
168
  * @param {Function} [options.toRequest] (prompt, ctx) => { system?, messages, tools?, maxTokens? }. Default: the prompt as one user message.
169
+ * @param {boolean} [options.thoughtSignatures] send the thought signatures of Gemini 3 back (default: only to *.googleapis.com);
170
+ * true for a gateway that relays them (Centrale).
156
171
  */
157
172
  function createOpenAICompatibleProvider(options = {}) {
158
173
  if (typeof options.id !== 'string' || !options.id) throw new Error('createOpenAICompatibleProvider requires options.id.');
@@ -182,7 +197,8 @@ function createOpenAICompatibleProvider(options = {}) {
182
197
  throw missing;
183
198
  }
184
199
  const answer = await askChatModel(
185
- { url, key, model: model.id, extra: { ...(options.extra || {}), ...(model.extra || {}) } },
200
+ { url, key, model: model.id, extra: { ...(options.extra || {}), ...(model.extra || {}) },
201
+ ...(typeof options.thoughtSignatures === 'boolean' ? { thoughtSignatures: options.thoughtSignatures } : {}) },
186
202
  { maxTokens: model.maxTokens, ...toRequest(prompt, ctx) },
187
203
  { fetch: typeof ctx.fetch === 'function' ? ctx.fetch : options.fetch, signal: ctx.signal, timeoutMs: ctx.timeoutMs || options.timeoutMs, onText: ctx.onText }
188
204
  );