@astratra/ai 1.9.0 → 1.11.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,22 @@ 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
+ ### La réponse petit à petit (`onText`)
186
+
187
+ Passé dans le contexte de `route()` (`router.route(requete, options, { onText })`) ou dans `io` d'`askChatModel` /
188
+ `askGeminiModel`, `onText` demande la réponse en flux (`stream: true` au format OpenAI, `streamGenerateContent` chez
189
+ Gemini) et reçoit le texte montrable **entier** à chaque avancée :
190
+
191
+ - jamais la réflexion (balises think, parties `thought` de Gemini), jamais une balise coupée en deux ;
192
+ - rien quand le modèle écrit un appel d'outil dans son texte ou commence par du JSON ;
193
+ - au modèle suivant du routeur, le texte repart de zéro et remplace le précédent ;
194
+ - la valeur rendue (texte, appels d'outils, `cut`, sources) est la même que sans flux ;
195
+ - jamais passé à un fournisseur masqué : un texte masqué ne se montre pas en cours de route.
196
+
197
+ ```js
198
+ await router.route(requete, { accepts }, { onText: (texte) => ecrireBrouillon(texte) });
199
+ ```
200
+
180
201
  ### La recherche Google intégrée de Gemini
181
202
 
182
203
  `googleSearch` sur une requête active l'outil de recherche de Gemini
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/ai",
3
- "version": "1.9.0",
3
+ "version": "1.11.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
@@ -21,6 +21,7 @@ const { readRetryAfter } = require('./providerLimits');
21
21
  */
22
22
 
23
23
  const { providerResult, readWrittenAnswer, withoutThinking } = require('./modelAnswers');
24
+ const { readServerEvents, textReporter } = require('./streamedAnswer');
24
25
 
25
26
  const DEFAULT_ENDPOINT = 'https://generativelanguage.googleapis.com/v1beta/models';
26
27
  const DEFAULT_TIMEOUT_MS = 45_000;
@@ -162,7 +163,10 @@ async function askGeminiModel(model, request, io = {}) {
162
163
  const hasFunctions = Boolean(request.tools && request.tools.length);
163
164
  const timeout = globalThis.AbortSignal.timeout(io.timeoutMs || DEFAULT_TIMEOUT_MS);
164
165
  const signal = io.signal ? globalThis.AbortSignal.any([io.signal, timeout]) : timeout;
165
- const send = (dropFunctions) => io.fetch(`${io.endpoint || DEFAULT_ENDPOINT}/${model}:generateContent`, {
166
+ /* `onText` : la réponse en flux (streamGenerateContent), le texte montrable entier à chaque avancée. */
167
+ const report = textReporter(io.onText);
168
+ const method = report ? 'streamGenerateContent?alt=sse' : 'generateContent';
169
+ const send = (dropFunctions) => io.fetch(`${io.endpoint || DEFAULT_ENDPOINT}/${model}:${method}`, {
166
170
  method: 'POST',
167
171
  headers: { 'content-type': 'application/json', 'x-goog-api-key': io.key },
168
172
  body: JSON.stringify({ ...requestBody(model, request, io.noSystemInstruction || noSystemInstructionByDefault, search, dropFunctions), ...(io.extra || {}) }),
@@ -179,7 +183,8 @@ async function askGeminiModel(model, request, io = {}) {
179
183
  const retryAfterMs = readRetryAfter(response);
180
184
  return { status: response.status, ...(retryAfterMs === null ? {} : { retryAfterMs }) };
181
185
  }
182
- const answer = await response.json();
186
+ const contentType = (response.headers && typeof response.headers.get === 'function' && response.headers.get('content-type')) || '';
187
+ const answer = report && contentType.includes('text/event-stream') ? await readGeminiStream(response, report) : await response.json();
183
188
  const candidate = (answer && answer.candidates && answer.candidates[0]) || {};
184
189
  const grounding = search ? { grounding: { ...readGeminiGrounding(candidate), functionsDropped } } : {};
185
190
  const parts = (candidate.content && candidate.content.parts) || [];
@@ -195,6 +200,28 @@ async function askGeminiModel(model, request, io = {}) {
195
200
  return { status: response.status, text, cut: candidate.finishReason === 'MAX_TOKENS', ...grounding };
196
201
  }
197
202
 
203
+ /* Une réponse en flux, rassemblée en un seul candidat : ses parties (texte, réflexion, appels), sa fin, ses sources. */
204
+ async function readGeminiStream(response, report) {
205
+ const parts = [];
206
+ let finishReason;
207
+ let groundingMetadata;
208
+ let shown = '';
209
+ await readServerEvents(response, (event) => {
210
+ const candidate = event && Array.isArray(event.candidates) ? event.candidates[0] : null;
211
+ if (!candidate) return;
212
+ if (candidate.finishReason) finishReason = candidate.finishReason;
213
+ if (candidate.groundingMetadata) groundingMetadata = candidate.groundingMetadata;
214
+ for (const part of (candidate.content && candidate.content.parts) || []) {
215
+ parts.push(part);
216
+ if (!part.thought && !part.functionCall && typeof part.text === 'string') {
217
+ shown += part.text;
218
+ report(shown);
219
+ }
220
+ }
221
+ });
222
+ return { candidates: [{ content: { parts }, ...(finishReason ? { finishReason } : {}), ...(groundingMetadata ? { groundingMetadata } : {}) }] };
223
+ }
224
+
198
225
  /**
199
226
  * Un fournisseur Gemini pour createProviderRouter : mêmes options que
200
227
  * createOpenAICompatibleProvider, sans adresse (le point d'accès de Google,
@@ -240,6 +267,7 @@ function createGeminiProvider(options = {}) {
240
267
  timeoutMs: ctx.timeoutMs || options.timeoutMs,
241
268
  endpoint: options.endpoint,
242
269
  noSystemInstruction: options.noSystemInstruction,
270
+ onText: ctx.onText,
243
271
  extra: { ...(options.extra || {}), ...(model.extra || {}) }
244
272
  });
245
273
  return providerResult(id, answer, options.detailed);
@@ -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
@@ -605,9 +605,23 @@ export type FetchLike = (url: string, init: { method: string; headers: Record<st
605
605
  export function askChatModel(
606
606
  target: { url: string; key: string; model: string; extra?: Record<string, unknown> },
607
607
  request: { system?: string; messages: ChatMessage[]; tools?: Array<Record<string, unknown>>; maxTokens?: number; temperature?: number },
608
- io: { fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number }
608
+ io: { fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; onText?: (shown: string) => void }
609
609
  ): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean; retryAfterMs?: number }>;
610
610
 
611
+ /* ─────────────────── Réponse en flux ─────────────────── */
612
+
613
+ /**
614
+ * `onText` (sur `io`, ou sur le contexte de `route()` : `{ onText }`) demande la réponse en flux et reçoit
615
+ * le texte montrable ENTIER à chaque avancée : sans réflexion (think), sans balise coupée, et vide quand le
616
+ * modèle écrit un appel d'outil dans son texte. Au modèle suivant du routeur, il repart de zéro. La valeur
617
+ * rendue est la même que sans flux. Jamais passé à un fournisseur masqué (le texte serait masqué).
618
+ */
619
+ export function visibleSoFar(raw: string): string;
620
+ /** Les événements `data:` d'un corps text/event-stream, un objet JSON chacun. */
621
+ export function readServerEvents(response: { body?: unknown; text?: () => Promise<string> }, onEvent: (event: any) => void): Promise<void>;
622
+ /** Un onText qui ne prévient que quand le texte montré change, et ne lève jamais. */
623
+ export function textReporter(onText?: (shown: string) => void): ((raw: string) => void) | null;
624
+
611
625
  export function readToolArguments(raw: unknown): { args: Record<string, unknown> | null; invalid: boolean; reason?: 'not_json' | 'not_object'; detail?: string };
612
626
 
613
627
  /** Les appels d'outil écrits dans un texte (<function=…>, <tool_call>{…}</tool_call>), relus. */
@@ -685,7 +699,7 @@ export function createOpenAICompatibleProvider(options: ChatProviderOptions & {
685
699
  export function askGeminiModel(
686
700
  model: string,
687
701
  request: ChatRequest,
688
- io: { key: string; fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; endpoint?: string; noSystemInstruction?: (model: string) => boolean; extra?: Record<string, unknown> }
702
+ io: { key: string; fetch: FetchLike; signal?: AbortSignal; timeoutMs?: number; endpoint?: string; noSystemInstruction?: (model: string) => boolean; extra?: Record<string, unknown>; onText?: (shown: string) => void }
689
703
  ): Promise<{ status: number; text?: string | null; toolCalls?: ChatToolCall[]; cut?: boolean; retryAfterMs?: number; grounding?: GeminiGrounding & { functionsDropped: boolean } }>;
690
704
 
691
705
  /** Les sources d'une réponse generateContent (ou d'un de ses candidats), nettoyées et bornées. Ne lève jamais. */
package/src/index.js CHANGED
@@ -16,6 +16,7 @@ module.exports = {
16
16
  ...require('./openaiCompatible'),
17
17
  ...require('./llamaCpp'),
18
18
  ...require('./gemini'),
19
+ ...require('./streamedAnswer'),
19
20
  ...require('./nativeTools'),
20
21
  ...require('./eventStream'),
21
22
  ...require('./webSearch'),
@@ -15,6 +15,7 @@ const { readRetryAfter } = require('./providerLimits');
15
15
  */
16
16
 
17
17
  const { providerResult, readToolArguments, readWrittenAnswer, readWrittenToolCalls, toolCallOf, withoutThinking } = require('./modelAnswers');
18
+ const { readServerEvents, textReporter } = require('./streamedAnswer');
18
19
 
19
20
  function toTranscript(messages) {
20
21
  return (Array.isArray(messages) ? messages : []).map((message) => {
@@ -55,7 +56,9 @@ function toTranscript(messages) {
55
56
  * Ask one model.
56
57
  * @param {{ url: string, key: string, model: string, extra?: object }} target
57
58
  * @param {{ system?: string, messages: object[], tools?: object[], maxTokens?: number, temperature?: number }} request
58
- * @param {{ fetch: Function, signal?: AbortSignal, timeoutMs?: number }} io
59
+ * @param {{ fetch: Function, signal?: AbortSignal, timeoutMs?: number, onText?: Function }} io
60
+ * `onText` : la réponse est demandée en flux (`stream`) et `onText(texte)` reçoit le texte montrable
61
+ * entier à chaque avancée ; la valeur rendue est la même que sans flux.
59
62
  * @returns {Promise<{ status: number, text?: string|null, toolCalls?: object[], cut?: boolean }>}
60
63
  * A non-2xx answer resolves `{ status }` — nothing is thrown for it.
61
64
  */
@@ -66,6 +69,7 @@ async function askChatModel(target, request, io = {}) {
66
69
  const Signal = globalThis.AbortSignal;
67
70
  const timeout = Signal.timeout(timeoutMs);
68
71
  const signal = io.signal && typeof Signal.any === 'function' ? Signal.any([io.signal, timeout]) : (io.signal || timeout);
72
+ const report = textReporter(io.onText);
69
73
  const messages = [
70
74
  ...(request.system ? [{ role: 'system', content: request.system }] : []),
71
75
  ...toTranscript(request.messages)
@@ -79,7 +83,8 @@ async function askChatModel(target, request, io = {}) {
79
83
  temperature: request.temperature === undefined ? 0.4 : request.temperature,
80
84
  max_tokens: request.maxTokens || 1200,
81
85
  ...(request.tools && request.tools.length ? { tools: request.tools.map((tool) => ({ type: 'function', function: tool })) } : {}),
82
- ...extra
86
+ ...extra,
87
+ ...(report ? { stream: true } : {})
83
88
  }),
84
89
  signal
85
90
  });
@@ -87,7 +92,8 @@ async function askChatModel(target, request, io = {}) {
87
92
  const retryAfterMs = readRetryAfter(response);
88
93
  return { status: response.status, ...(retryAfterMs === null ? {} : { retryAfterMs }) };
89
94
  }
90
- const answer = await response.json();
95
+ const contentType = (response.headers && typeof response.headers.get === 'function' && response.headers.get('content-type')) || '';
96
+ const answer = report && contentType.includes('text/event-stream') ? await readChatStream(response, report) : await response.json();
91
97
  const choice = (answer && answer.choices && answer.choices[0]) || {};
92
98
  const message = choice.message || {};
93
99
  if (Array.isArray(message.tool_calls) && message.tool_calls.length) {
@@ -103,6 +109,32 @@ async function askChatModel(target, request, io = {}) {
103
109
  return { status: response.status, text, cut: choice.finish_reason === 'length' };
104
110
  }
105
111
 
112
+ /* Une réponse en flux, rassemblée dans la forme d'une réponse entière (message, appels d'outils, fin). */
113
+ async function readChatStream(response, report) {
114
+ let content = '';
115
+ let finish = null;
116
+ const calls = [];
117
+ await readServerEvents(response, (event) => {
118
+ const choice = event && Array.isArray(event.choices) ? event.choices[0] : null;
119
+ if (!choice) return;
120
+ if (choice.finish_reason) finish = choice.finish_reason;
121
+ const delta = choice.delta || {};
122
+ if (typeof delta.content === 'string' && delta.content) {
123
+ content += delta.content;
124
+ report(content);
125
+ }
126
+ for (const part of Array.isArray(delta.tool_calls) ? delta.tool_calls : []) {
127
+ const index = Number.isInteger(part.index) ? part.index : calls.length;
128
+ const call = calls[index] || (calls[index] = { id: '', function: { name: '', arguments: '' } });
129
+ if (part.id) call.id = part.id;
130
+ if (part.function && part.function.name) call.function.name += part.function.name;
131
+ if (part.function && typeof part.function.arguments === 'string') call.function.arguments += part.function.arguments;
132
+ }
133
+ });
134
+ const toolCalls = calls.filter(Boolean).map((call, index) => ({ ...call, id: call.id || `call_${index}` }));
135
+ return { choices: [{ message: { content, ...(toolCalls.length ? { tool_calls: toolCalls } : {}) }, finish_reason: finish }] };
136
+ }
137
+
106
138
  /**
107
139
  * A provider for createProviderRouter, over an OpenAI-compatible endpoint.
108
140
  *
@@ -152,7 +184,7 @@ function createOpenAICompatibleProvider(options = {}) {
152
184
  const answer = await askChatModel(
153
185
  { url, key, model: model.id, extra: { ...(options.extra || {}), ...(model.extra || {}) } },
154
186
  { maxTokens: model.maxTokens, ...toRequest(prompt, ctx) },
155
- { fetch: typeof ctx.fetch === 'function' ? ctx.fetch : options.fetch, signal: ctx.signal, timeoutMs: ctx.timeoutMs || options.timeoutMs }
187
+ { fetch: typeof ctx.fetch === 'function' ? ctx.fetch : options.fetch, signal: ctx.signal, timeoutMs: ctx.timeoutMs || options.timeoutMs, onText: ctx.onText }
156
188
  );
157
189
  return providerResult(options.id, answer, options.detailed);
158
190
  }
@@ -114,7 +114,9 @@ function createProviderRouter(config = {}) {
114
114
  /* Masked at the moment it leaves: a provider that runs on this machine
115
115
  (`external: false`) gets the text as it is. */
116
116
  const outbound = masker && provider.external !== false;
117
- const send = async () => provider.call(outbound ? await masker.maskAsync(prompt) : prompt, providerCtx, model);
117
+ /* Un texte masqué ne se montre pas en cours de route : `onText` ne part qu'aux fournisseurs non masqués. */
118
+ const callCtx = outbound && providerCtx.onText ? { ...providerCtx, onText: undefined } : providerCtx;
119
+ const send = async () => provider.call(outbound ? await masker.maskAsync(prompt) : prompt, callCtx, model);
118
120
 
119
121
  let raw;
120
122
  try {
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Une réponse qui arrive petit à petit (`stream`) : le texte est montré pendant qu'il s'écrit.
3
+ *
4
+ * - readServerEvents lit les événements d'un corps `text/event-stream` (lignes `data:`), un objet JSON chacun ;
5
+ * - visibleSoFar dit ce qu'on peut montrer du texte reçu jusqu'ici : jamais la réflexion entre balises think
6
+ * (même pas encore fermée), jamais une balise coupée en deux, et rien du tout quand le modèle écrit un appel
7
+ * d'outil dans son texte (<tool_call>, <function=…>) ou commence par du JSON.
8
+ *
9
+ * `onText` reçoit toujours le texte ENTIER montré jusqu'ici (pas un morceau) : quand le routeur passe au modèle
10
+ * suivant, le texte repart de zéro et remplace le précédent, sans rien à recoller.
11
+ */
12
+
13
+ const { withoutThinking } = require('./modelAnswers');
14
+
15
+ const WRITTEN_CALL = /<tool_call>|<function=/;
16
+
17
+ async function readServerEvents(response, onEvent) {
18
+ const body = response && response.body;
19
+ if (!body || typeof body.getReader !== 'function') {
20
+ /* Un corps sans flux (un double de test, un relais qui a tout gardé) : lu d'un coup. */
21
+ const text = typeof response.text === 'function' ? await response.text() : '';
22
+ for (const line of text.split(/\r?\n/)) readLine(line, onEvent);
23
+ return;
24
+ }
25
+ const reader = body.getReader();
26
+ const decoder = new globalThis.TextDecoder();
27
+ let pending = '';
28
+ for (;;) {
29
+ const { value, done } = await reader.read();
30
+ if (done) break;
31
+ pending += decoder.decode(value, { stream: true });
32
+ let end;
33
+ while ((end = pending.indexOf('\n')) >= 0) {
34
+ readLine(pending.slice(0, end), onEvent);
35
+ pending = pending.slice(end + 1);
36
+ }
37
+ }
38
+ pending += decoder.decode();
39
+ if (pending) readLine(pending, onEvent);
40
+ }
41
+
42
+ function readLine(raw, onEvent) {
43
+ const line = raw.replace(/\r$/, '');
44
+ if (!line.startsWith('data:')) return;
45
+ const data = line.slice(5).trim();
46
+ if (!data || data === '[DONE]') return;
47
+ let event;
48
+ try {
49
+ event = JSON.parse(data);
50
+ } catch (_error) {
51
+ return;
52
+ }
53
+ onEvent(event);
54
+ }
55
+
56
+ function visibleSoFar(raw) {
57
+ const text = String(raw || '');
58
+ if (WRITTEN_CALL.test(text)) return '';
59
+ let shown = withoutThinking(text);
60
+ /* Une balise pas encore fermée en fin de texte (« <thi », « <tool_c ») : attendue avant d'être montrée. */
61
+ const open = shown.lastIndexOf('<');
62
+ if (open >= 0 && !shown.includes('>', open)) shown = shown.slice(0, open).trimEnd();
63
+ if (/^[[{]/.test(shown)) return '';
64
+ return shown;
65
+ }
66
+
67
+ /** Un `onText` qui ne prévient que quand le texte montré change, et qui ne lève jamais chez l'appelant. */
68
+ function textReporter(onText) {
69
+ if (typeof onText !== 'function') return null;
70
+ let last = '';
71
+ return (raw) => {
72
+ const shown = visibleSoFar(raw);
73
+ if (shown === last) return;
74
+ last = shown;
75
+ try {
76
+ onText(shown);
77
+ } catch (_error) {
78
+ /* L'affichage d'un morceau n'arrête jamais la réponse. */
79
+ }
80
+ };
81
+ }
82
+
83
+ module.exports = { readServerEvents, visibleSoFar, textReporter };