@astratra/ai 1.11.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
@@ -182,6 +182,20 @@ appel — et n'est jamais une réponse à montrer. Des arguments illisibles gard
182
182
  l'appel, marqué `invalid` avec `invalidReason` (`not_json`, `not_object`), et
183
183
  repartent en `{}` au tour suivant.
184
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
+
185
199
  ### La réponse petit à petit (`onText`)
186
200
 
187
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.11.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(''));
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
  );