@astratra/ai 1.3.0 → 1.5.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/src/masking.js ADDED
@@ -0,0 +1,279 @@
1
+ /**
2
+ * Masking what identifies people before a text leaves for an outside provider,
3
+ * and putting it back in the answer.
4
+ *
5
+ * The prompt was masked; the web search was not. The model wrote the search
6
+ * query from the masked question, the loop unmasked the tool parameters for
7
+ * the tools that need real names — and the child's name went to the search
8
+ * engine in clear. So the rule here is about DIRECTION, not about which tool:
9
+ * whatever leaves the machine is masked at the moment it leaves, and only what
10
+ * comes back is unmasked.
11
+ *
12
+ * One masker per conversation. It LEARNS: a name found once (in the school's
13
+ * register, by a pattern, by an entity detector) is masked everywhere after,
14
+ * with the same token, so the model can still tell two people apart.
15
+ *
16
+ * Choices kept from real use:
17
+ *
18
+ * - register names match CASE-SENSITIVELY and on whole words. "Grace",
19
+ * "Chance" and "Merveille" are real first names; "grâce à" and "la chance"
20
+ * must survive. A common word damaged costs less than a child's name in
21
+ * clear, but the case keeps most sentences intact;
22
+ * - a name shorter than three letters identifies no one and breaks sentences;
23
+ * - a register name absent from the text creates NO token — a register of a
24
+ * thousand names must not pollute the unmasking table;
25
+ * - models drop the leading "#" of a token; unmasking tolerates it;
26
+ * - tokens are replaced longest first, on token boundaries, so #PERSON_0001
27
+ * never eats the start of #PERSON_00012.
28
+ */
29
+
30
+ const DEFAULT_MIN_LENGTH = 3;
31
+ const DEFAULT_MIN_SCORE = 0.6;
32
+ const DEFAULT_DETECT_MAX_CHARS = 1500;
33
+
34
+ const ESCAPE = /[.*+?^${}()|[\]\\]/g;
35
+ const escape = (text) => String(text).replace(ESCAPE, '\\$&');
36
+ const LEXICAL = '\\p{L}\\p{N}\\p{M}_';
37
+
38
+ const defaultToken = (type, sequence) => `#${String(type || 'ENTITY').toUpperCase()}_${String(sequence).padStart(4, '0')}`;
39
+
40
+ /** At most `max` characters, cut on a blank: a name is never sliced in two. */
41
+ function headWithoutCuttingWords(text, max) {
42
+ if (text.length <= max) return text;
43
+ const cut = text.slice(0, max);
44
+ const blank = cut.search(/\s\S*$/);
45
+ return blank > 0 ? cut.slice(0, blank) : cut;
46
+ }
47
+
48
+ /**
49
+ * @param {object} [options]
50
+ * @param {string[]} [options.names] register names, masked case-sensitively.
51
+ * @param {Array<{type: string, pattern: RegExp}>} [options.patterns] global
52
+ * regexes for structured data (e-mail, phone…), masked as found.
53
+ * @param {Function} [options.detect] async (text) => [{ text, type, score }] — an
54
+ * entity detector (a local NER model). Its absence, or a null answer, leaves
55
+ * the register and the patterns alone.
56
+ * @param {string[]} [options.detectTypes] which detected types to mask. Default ['person'].
57
+ * @param {number} [options.minScore] detections under this are ignored. Default 0.6 —
58
+ * a false name masked damages the sentence sent to the model.
59
+ * @param {number} [options.detectMaxChars] text handed to the detector, cut on a blank. Default 1500.
60
+ * @param {number} [options.minLength] shortest value masked. Default 3.
61
+ * @param {Function} [options.token] (type, sequence) => string. Default "#TYPE_0001".
62
+ * @param {Function} [options.typeOf] (value) => type for register names. Default 'PERSON'.
63
+ * @param {Function} [options.keep] (value) => true to never mask it (a product name…).
64
+ */
65
+ function createReversibleMasker(options = {}) {
66
+ const minLength = options.minLength || DEFAULT_MIN_LENGTH;
67
+ const minScore = options.minScore === undefined ? DEFAULT_MIN_SCORE : options.minScore;
68
+ const detectMaxChars = options.detectMaxChars || DEFAULT_DETECT_MAX_CHARS;
69
+ const detect = typeof options.detect === 'function' ? options.detect : null;
70
+ const detectTypes = new Set(options.detectTypes || ['person']);
71
+ const tokenFor = options.token || defaultToken;
72
+ const typeOf = options.typeOf || (() => 'PERSON');
73
+ const keep = options.keep || (() => false);
74
+ const patterns = (options.patterns || []).map(({ type, pattern }) => {
75
+ if (!(pattern instanceof RegExp) || !pattern.global) {
76
+ throw new Error('createReversibleMasker: every pattern must be a global RegExp.');
77
+ }
78
+ return { type, pattern };
79
+ });
80
+
81
+ /* token -> real value ; real value -> token */
82
+ const byToken = new Map();
83
+ const byValue = new Map();
84
+ /* values matched case-insensitively (patterns: an e-mail is an e-mail in any case) */
85
+ const loose = new Set();
86
+ const register = new Set();
87
+ let sequence = 0;
88
+
89
+ const looksLikeToken = (value) => byToken.has(value) || byToken.has(`#${value}`);
90
+ const alreadyMasked = /#[A-Z]+_\d+/;
91
+
92
+ function tokenOf(value, type) {
93
+ if (byValue.has(value)) return byValue.get(value);
94
+ let token;
95
+ do {
96
+ sequence += 1;
97
+ token = tokenFor(type, sequence);
98
+ } while (byToken.has(token));
99
+ byToken.set(token, value);
100
+ byValue.set(value, token);
101
+ return token;
102
+ }
103
+
104
+ function acceptable(value) {
105
+ const text = String(value === null || value === undefined ? '' : value).trim();
106
+ if (text.length < minLength) return null;
107
+ if (alreadyMasked.test(text) || looksLikeToken(text)) return null;
108
+ if (keep(text)) return null;
109
+ return text;
110
+ }
111
+
112
+ function replaceWhole(text, value, token, caseSensitive) {
113
+ const regex = new RegExp(`(^|[^${LEXICAL}])(${escape(value)})(?=$|[^${LEXICAL}])`, caseSensitive ? 'gu' : 'giu');
114
+ return text.replace(regex, (_whole, prefix) => `${prefix}${token}`);
115
+ }
116
+
117
+ function learn(names, type) {
118
+ for (const raw of names || []) {
119
+ const value = acceptable(raw);
120
+ if (value) register.add(value);
121
+ if (value && type) typeOverride.set(value, type);
122
+ }
123
+ }
124
+ const typeOverride = new Map();
125
+ learn(options.names);
126
+
127
+ /** Mask a string with everything known so far, plus `names` for this call. */
128
+ function mask(text, { names } = {}) {
129
+ if (typeof text !== 'string' || !text) return text;
130
+ if (names) learn(names);
131
+ let out = text;
132
+
133
+ /* Structured data first, on the intact text. */
134
+ for (const { type, pattern } of patterns) {
135
+ pattern.lastIndex = 0;
136
+ for (const match of out.matchAll(pattern)) {
137
+ const value = acceptable(match[0]);
138
+ if (!value) continue;
139
+ tokenOf(value, type);
140
+ loose.add(value);
141
+ }
142
+ }
143
+
144
+ /* Longest first: "Marie Kabongo" before "Marie". Case-sensitive for the
145
+ register; a value absent from the text creates no token. */
146
+ const candidates = [...new Set([...register, ...byValue.keys()])].sort((a, b) => b.length - a.length);
147
+ for (const value of candidates) {
148
+ const caseSensitive = !loose.has(value);
149
+ const present = caseSensitive ? out.includes(value) : out.toLowerCase().includes(value.toLowerCase());
150
+ if (!present) continue;
151
+ const token = tokenOf(value, typeOverride.get(value) || typeOf(value));
152
+ out = replaceWhole(out, value, token, caseSensitive);
153
+ }
154
+ return out;
155
+ }
156
+
157
+ /**
158
+ * Names the detector finds, for the register — deduplicated, filtered by
159
+ * type, score and length; tokens already placed are not names.
160
+ */
161
+ async function detectNames(text) {
162
+ if (!detect || typeof text !== 'string' || !text.trim()) return [];
163
+ let found;
164
+ try {
165
+ found = await detect(headWithoutCuttingWords(text, detectMaxChars));
166
+ } catch (_error) {
167
+ return [];
168
+ }
169
+ if (!Array.isArray(found)) return [];
170
+ const names = found
171
+ .filter((entity) => entity && detectTypes.has(entity.type) && typeof entity.score === 'number' && entity.score >= minScore)
172
+ .map((entity) => acceptable(entity.text))
173
+ .filter(Boolean);
174
+ return [...new Set(names)];
175
+ }
176
+
177
+ /** Detect, learn, then mask. The detector sees the text in clear — keep it local. */
178
+ async function maskAsync(text, opts = {}) {
179
+ if (typeof text !== 'string' || !text) return text;
180
+ const detected = await detectNames(text);
181
+ return mask(text, { names: [...(opts.names || []), ...detected] });
182
+ }
183
+
184
+ /** Every string of a structure, masked. Keys are left alone. */
185
+ function maskDeep(value) {
186
+ if (typeof value === 'string') return mask(value);
187
+ if (Array.isArray(value)) return value.map(maskDeep);
188
+ if (value instanceof Date) return new Date(value.getTime());
189
+ if (value && typeof value === 'object') {
190
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, maskDeep(child)]));
191
+ }
192
+ return value;
193
+ }
194
+
195
+ function unmask(text) {
196
+ if (typeof text !== 'string' || !text || !byToken.size) return text;
197
+ let out = text;
198
+ const tokens = [...byToken.keys()].sort((a, b) => b.length - a.length);
199
+ for (const token of tokens) {
200
+ const value = byToken.get(token);
201
+ const variants = token.startsWith('#') ? [token, token.slice(1)] : [token];
202
+ for (const variant of variants) {
203
+ if (!out.includes(variant)) continue;
204
+ const regex = new RegExp(`(^|[^${LEXICAL}#])(${escape(variant)})(?![${LEXICAL}])`, 'gu');
205
+ out = out.replace(regex, (_whole, prefix) => `${prefix}${value}`);
206
+ }
207
+ }
208
+ return out;
209
+ }
210
+
211
+ function unmaskDeep(value) {
212
+ if (typeof value === 'string') return unmask(value);
213
+ if (Array.isArray(value)) return value.map(unmaskDeep);
214
+ if (value instanceof Date) return new Date(value.getTime());
215
+ if (value && typeof value === 'object') {
216
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, unmaskDeep(child)]));
217
+ }
218
+ return value;
219
+ }
220
+
221
+ /**
222
+ * Unmask a stream of chunks. A token can straddle two chunks ("#PERS" then
223
+ * "ON_0001"); the tail that could still be the start of a token is held
224
+ * back until the next chunk decides.
225
+ */
226
+ async function* unmaskStream(chunks) {
227
+ let carry = '';
228
+ const longest = () => Math.max(0, ...[...byToken.keys()].map((token) => token.length));
229
+ for await (const chunk of chunks) {
230
+ const text = carry + String(chunk);
231
+ const hold = holdBack(text, longest());
232
+ carry = text.slice(text.length - hold);
233
+ const ready = text.slice(0, text.length - hold);
234
+ if (ready) yield unmask(ready);
235
+ }
236
+ if (carry) yield unmask(carry);
237
+ }
238
+
239
+ function holdBack(text, maxLength) {
240
+ if (!maxLength) return 0;
241
+ const tokens = [...byToken.keys()].flatMap((token) => (token.startsWith('#') ? [token, token.slice(1)] : [token]));
242
+ for (let size = Math.min(maxLength, text.length); size > 0; size -= 1) {
243
+ const tail = text.slice(text.length - size);
244
+ /* A whole token at the very end may still be followed by a digit that
245
+ makes it another token: hold it too. */
246
+ if (tokens.some((token) => token.startsWith(tail))) return size;
247
+ }
248
+ return 0;
249
+ }
250
+
251
+ return {
252
+ mask,
253
+ maskAsync,
254
+ maskDeep,
255
+ unmask,
256
+ unmaskDeep,
257
+ unmaskStream,
258
+ detectNames,
259
+ /** How many values are masked so far — never the values. */
260
+ size: () => byToken.size
261
+ };
262
+ }
263
+
264
+ /**
265
+ * Wrap an outside call so its input is masked on the way out and its answer
266
+ * unmasked on the way back.
267
+ */
268
+ function withOutboundMasking(masker, call) {
269
+ if (!masker || typeof masker.maskAsync !== 'function' || typeof masker.unmaskDeep !== 'function') {
270
+ throw new Error('withOutboundMasking requires a masker from createReversibleMasker().');
271
+ }
272
+ if (typeof call !== 'function') throw new Error('withOutboundMasking requires a function to wrap.');
273
+ return async (input, ...rest) => {
274
+ const outbound = typeof input === 'string' ? await masker.maskAsync(input) : masker.maskDeep(input);
275
+ return masker.unmaskDeep(await call(outbound, ...rest));
276
+ };
277
+ }
278
+
279
+ module.exports = { createReversibleMasker, withOutboundMasking, headWithoutCuttingWords };
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Lire la réponse d'un modèle, quel que soit le fournisseur (format OpenAI,
3
+ * Gemini…) : son raisonnement retiré, ses appels d'outil lus — y compris ceux
4
+ * qu'il a écrits dans son texte au lieu de les demander —, et ce que le
5
+ * fournisseur rend au routeur. Module interne : les adaptateurs le partagent.
6
+ */
7
+
8
+ /**
9
+ * Le raisonnement d'un modèle écrit entre balises think n'est jamais montré.
10
+ * Un raisonnement resté ouvert (réponse coupée à sa longueur) part jusqu'à la
11
+ * fin ; une balise fermante sans ouvrante (un gabarit qui l'a ouverte lui-même)
12
+ * emporte tout ce qui la précède.
13
+ */
14
+ function withoutThinking(content) {
15
+ let text = String(content === null || content === undefined ? '' : content).replace(/<think>[\s\S]*?<\/think>/gi, '');
16
+ const closing = text.toLowerCase().lastIndexOf('</think>');
17
+ if (closing >= 0) text = text.slice(closing + '</think>'.length);
18
+ const opening = text.toLowerCase().indexOf('<think>');
19
+ if (opening >= 0) text = text.slice(0, opening);
20
+ return text.trim();
21
+ }
22
+
23
+ /* Un appel d'outil écrit dans le texte au lieu d'être demandé (façons de Qwen et de Hermes). */
24
+ const WRITTEN_CALL = /<tool_call>|<function=/;
25
+
26
+ /** Une valeur telle que le modèle l'a écrite : du JSON quand c'en est (un nombre, une liste), les mots sinon. */
27
+ function writtenValue(written) {
28
+ const text = written.trim();
29
+ try {
30
+ return JSON.parse(text);
31
+ } catch (_error) {
32
+ return text;
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Les appels d'outil écrits en texte, relus en vrais appels :
38
+ * <function=nom><parameter=clé>valeur</parameter></function>, ou un JSON
39
+ * {"name", "arguments"} entre balises <tool_call>. Ce qui ne se relit pas
40
+ * proprement est laissé de côté.
41
+ * @returns {{ id: string, name: string, args: object }[]}
42
+ */
43
+ function readWrittenToolCalls(text) {
44
+ const calls = [];
45
+ for (const [, name, body] of String(text || '').matchAll(/<function=([\w.-]+)>([\s\S]*?)<\/function>/g)) {
46
+ const args = Object.fromEntries([...body.matchAll(/<parameter=([\w.-]+)>([\s\S]*?)<\/parameter>/g)].map(([, key, value]) => [key, writtenValue(value)]));
47
+ calls.push({ name, args });
48
+ }
49
+ for (const [, body] of String(text || '').matchAll(/<tool_call>\s*(\{[\s\S]*?\})\s*<\/tool_call>/g)) {
50
+ try {
51
+ const { name, arguments: args } = JSON.parse(body);
52
+ const parsed = typeof args === 'string' ? JSON.parse(args) : args;
53
+ if (typeof name === 'string' && parsed && typeof parsed === 'object' && !Array.isArray(parsed)) calls.push({ name, args: parsed });
54
+ } catch (_error) {
55
+ /* Illisible : laissé de côté. */
56
+ }
57
+ }
58
+ return calls.map((call, index) => ({ id: `written-${index + 1}`, ...call }));
59
+ }
60
+
61
+ /**
62
+ * Une réponse en texte qui contient un appel écrit n'est JAMAIS une réponse à
63
+ * montrer : ses appels lisibles deviennent de vrais appels quand des outils
64
+ * étaient proposés, sinon il ne reste rien (le routeur passe au modèle suivant).
65
+ */
66
+ function readWrittenAnswer(text, toolsOffered) {
67
+ if (!WRITTEN_CALL.test(text || '')) return null;
68
+ return { text: null, toolCalls: toolsOffered ? readWrittenToolCalls(text) : [] };
69
+ }
70
+
71
+ /**
72
+ * Tool arguments as an object, or null with `invalid: true` for anything else.
73
+ * `reason` dit pourquoi ('not_json' : texte illisible, `detail` porte l'erreur
74
+ * de lecture ; 'not_object' : du JSON, mais pas un objet) — de quoi dire au
75
+ * modèle quoi corriger quand il redemande l'outil.
76
+ */
77
+ function readToolArguments(raw) {
78
+ if (raw === undefined || raw === null || (typeof raw === 'string' && !raw.trim())) return { args: {}, invalid: false };
79
+ if (typeof raw === 'object') {
80
+ return Array.isArray(raw) ? { args: null, invalid: true, reason: 'not_object' } : { args: raw, invalid: false };
81
+ }
82
+ try {
83
+ const parsed = JSON.parse(String(raw));
84
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? { args: parsed, invalid: false } : { args: null, invalid: true, reason: 'not_object' };
85
+ } catch (error) {
86
+ return { args: null, invalid: true, reason: 'not_json', detail: error.message };
87
+ }
88
+ }
89
+
90
+ /** Un appel d'outil lu : ses arguments, et quand ils sont illisibles, pourquoi. */
91
+ function toolCallOf(id, name, rawArguments) {
92
+ const { args, invalid, reason, detail } = readToolArguments(rawArguments);
93
+ return {
94
+ id,
95
+ name,
96
+ args,
97
+ ...(invalid ? { invalid: true, invalidReason: reason, ...(detail ? { invalidDetail: detail } : {}) } : {})
98
+ };
99
+ }
100
+
101
+ /** What a provider hands the router: a failure carries its status (never the key). */
102
+ function providerResult(id, answer, detailed) {
103
+ if (answer.status < 200 || answer.status >= 300) {
104
+ /* The status reaches the router (429 → cooldown); the key never does. */
105
+ const failure = new Error(`Provider "${id}" answered ${answer.status}.`);
106
+ failure.statusCode = answer.status;
107
+ throw failure;
108
+ }
109
+ if (detailed) return { text: answer.text === undefined ? null : answer.text, toolCalls: answer.toolCalls || [], cut: Boolean(answer.cut) };
110
+ if (answer.toolCalls && answer.toolCalls.length) return { toolCalls: answer.toolCalls };
111
+ if (!answer.text) {
112
+ const empty = new Error(`Provider "${id}" gave no text.`);
113
+ empty.statusCode = 502;
114
+ throw empty;
115
+ }
116
+ return answer.text;
117
+ }
118
+
119
+ module.exports = { withoutThinking, readWrittenToolCalls, readWrittenAnswer, readToolArguments, toolCallOf, providerResult };
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Des outils demandés par le modèle lui-même (function calling natif), et la
3
+ * boucle qui les fait tourner.
4
+ *
5
+ * `runAgentLoop` lit un protocole écrit dans le texte (<tool_call name="…">) ;
6
+ * ici le fournisseur rend des appels structurés, plusieurs à la fois, et la
7
+ * transcription garde des messages typés (assistant avec ses appels, un
8
+ * message `tool` par résultat). Ce que l'usage a appris :
9
+ *
10
+ * - un outil qui échoue ou tarde devient une erreur que le modèle LIT, jamais
11
+ * une boucle cassée — il peut redemander autrement ;
12
+ * - un outil inventé, ou des arguments illisibles, n'exécutent rien : le
13
+ * modèle lit pourquoi, et le plus souvent se corrige au tour suivant ;
14
+ * - ce qu'un outil rend au modèle est borné : une page entière noierait la
15
+ * conversation ;
16
+ * - un outil « à confirmer » n'écrit rien : il prépare, un humain dispose. Le
17
+ * modèle lit que rien n'est encore fait ;
18
+ * - la personne qui part arrête tout, outils compris ;
19
+ * - à court de tours ou de temps, un dernier tour sans outils répond avec ce
20
+ * qui a été lu, plutôt qu'une erreur.
21
+ *
22
+ * Un outil : { name, description, parameters (schéma JSON d'un objet), kind,
23
+ * summary?(args), run(args, ctx) }, avec perform(args, ctx) quand son genre est
24
+ * 'confirm' (l'écriture, une fois confirmée) et undo(annulation, ctx) quand il
25
+ * est 'write' (il écrit seul, on peut revenir dessus). `summary` donne les
26
+ * valeurs de la ligne d'étape que l'interface écrit elle-même : le serveur
27
+ * n'écrit aucune phrase que la personne lit.
28
+ */
29
+
30
+ const { AppError } = require('@astratra/core');
31
+
32
+ const KINDS = ['read', 'write', 'confirm'];
33
+ const NAME = /^[a-z][a-z0-9_]{0,63}$/;
34
+ const DEFAULT_PARAM_MAX = 120;
35
+ const DEFAULT_RESULT_MAX = 6000;
36
+ const DEFAULT_TOOL_MS = 20_000;
37
+
38
+ const MESSAGES = {
39
+ unknownTool: (name) => `There is no tool called ${name}.`,
40
+ timeout: () => 'This tool took too long to answer.',
41
+ invalidArguments: (call) => (call.invalidReason === 'not_object'
42
+ ? 'The arguments of this call must be a JSON object: call the tool again with one.'
43
+ : `The arguments of this call were not valid JSON${call.invalidDetail ? ` (${call.invalidDetail})` : ''}: call the tool again with a JSON object.`),
44
+ waiting: 'Nothing is written yet: the person must confirm it.'
45
+ };
46
+
47
+ const isValue = (value) => typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value));
48
+ const isPlain = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
49
+
50
+ /**
51
+ * Vérifie un catalogue d'outils. Un outil qui rompt le contrat arrête le
52
+ * serveur au démarrage, pas la personne au milieu d'une question.
53
+ *
54
+ * @param {object[]} tools
55
+ * @param {object} [options]
56
+ * @param {string[]} [options.kinds] Défaut read, write, confirm.
57
+ * @param {boolean} [options.requireSummary] chaque outil donne les valeurs de sa ligne d'étape. Défaut false.
58
+ * @returns {object[]} les mêmes outils
59
+ * @throws {Error} nommant le premier outil fautif, et pourquoi
60
+ */
61
+ function validateNativeTools(tools, options = {}) {
62
+ const kinds = options.kinds || KINDS;
63
+ const seen = new Set();
64
+ for (const tool of Array.isArray(tools) ? tools : []) {
65
+ const label = typeof tool?.name === 'string' && tool.name ? tool.name : JSON.stringify(tool?.name);
66
+ const refuse = (reason) => {
67
+ throw new Error(`The agent tool ${label} is not valid: ${reason}.`);
68
+ };
69
+ if (typeof tool?.name !== 'string' || !NAME.test(tool.name)) refuse('its name is not in snake_case');
70
+ if (seen.has(tool.name)) throw new Error(`The agent tool ${tool.name} is declared twice.`);
71
+ seen.add(tool.name);
72
+ if (typeof tool.description !== 'string' || !tool.description.trim()) refuse('it has no description');
73
+ if (tool.parameters?.type !== 'object') refuse('its parameters are not the schema of an object');
74
+ if (!kinds.includes(tool.kind)) refuse(`its kind is not one of ${kinds.join(', ')}`);
75
+ if (tool.summary !== undefined || options.requireSummary) {
76
+ if (typeof tool.summary !== 'function') refuse('its summary is not a function');
77
+ let values;
78
+ try {
79
+ values = tool.summary({});
80
+ } catch (_error) {
81
+ refuse('its summary fails without arguments');
82
+ }
83
+ if (!isPlain(values) || !Object.values(values).every(isValue)) refuse('its summary does not give an object of strings and numbers');
84
+ }
85
+ if (typeof tool.run !== 'function') refuse('its run is not a function');
86
+ if (tool.kind === 'confirm' && typeof tool.perform !== 'function') refuse('a tool to confirm needs perform');
87
+ if (tool.kind === 'write' && typeof tool.undo !== 'function') refuse('a tool that writes alone needs undo');
88
+ }
89
+ return tools;
90
+ }
91
+
92
+ /** Ce que le modèle voit de chaque outil : son nom, sa description, ses paramètres. */
93
+ const toolSpecs = (tools) => tools.map(({ name, description, parameters }) => ({ name, description, parameters }));
94
+
95
+ /**
96
+ * Les valeurs de la ligne d'étape d'un outil pour ces arguments : chaînes et
97
+ * nombres seulement, chacune coupée à `max` caractères ; {} quand le résumé échoue.
98
+ * @returns {Record<string, string | number>}
99
+ */
100
+ function stepParams(tool, args, { max = DEFAULT_PARAM_MAX } = {}) {
101
+ if (!tool || typeof tool.summary !== 'function') return {};
102
+ let values;
103
+ try {
104
+ values = tool.summary(args ?? {});
105
+ } catch (_error) {
106
+ return {};
107
+ }
108
+ if (!isPlain(values)) return {};
109
+ return Object.fromEntries(
110
+ Object.entries(values)
111
+ .filter(([, value]) => isValue(value))
112
+ .map(([key, value]) => [key, typeof value === 'string' && value.length > max ? `${value.slice(0, max - 1)}…` : value])
113
+ );
114
+ }
115
+
116
+ class ToolTimeout extends Error {}
117
+
118
+ /* Une promesse qui abandonne quand le signal s'interrompt, avec la raison du signal. */
119
+ function abortable(promise, signal) {
120
+ if (signal.aborted) return Promise.reject(signal.reason);
121
+ return new Promise((resolve, reject) => {
122
+ const stop = () => reject(signal.reason);
123
+ signal.addEventListener('abort', stop, { once: true });
124
+ promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', stop));
125
+ });
126
+ }
127
+
128
+ /**
129
+ * Le lanceur d'outils du modèle, partagé par tout ce qui fait appeler des
130
+ * outils (une conversation écrite, un appel vocal).
131
+ *
132
+ * @param {object} options
133
+ * @param {Map<string, object>|object[]} options.tools
134
+ * @param {object} [options.context] donné à chaque outil (run(args, { ...context, signal })).
135
+ * @param {AbortSignal} [options.signal] la personne est partie : l'appel lève sa raison.
136
+ * @param {number} [options.timeoutMs] par outil. Défaut 20 s.
137
+ * @param {Function} [options.now]
138
+ * @param {Function} [options.emit] (type, data) : 'step' { id, tool, params } puis 'step_done' { id, ok }.
139
+ * @param {Function} [options.keep] (sources, data) : ce qu'un outil a trouvé (createSourceLedger().keep).
140
+ * @param {Function} [options.record] async ({ tool, args, found }) : garder une action (à confirmer, à annuler).
141
+ * @param {Function} [options.onCall] ({ name, ms, ok }) : pour mesurer.
142
+ * @param {number} [options.resultMax] caractères de JSON rendus au modèle. Défaut 6000.
143
+ * @param {object} [options.messages] { unknownTool(name), timeout(), invalidArguments(call), waiting } — ce que lit le modèle.
144
+ * @returns {(call: { id: string, name: string, args: object|null, invalid?: boolean }) => Promise<{ role: 'tool', toolCallId: string, name: string, result: unknown }>}
145
+ */
146
+ function createToolCaller(options = {}) {
147
+ const tools = options.tools instanceof Map
148
+ ? options.tools
149
+ : new Map((options.tools || []).map((tool) => [tool.name, tool]));
150
+ const context = options.context || {};
151
+ const signal = options.signal || new globalThis.AbortController().signal;
152
+ const timeoutMs = options.timeoutMs || DEFAULT_TOOL_MS;
153
+ const now = options.now || Date.now;
154
+ const emit = options.emit || (() => {});
155
+ const keep = options.keep || (() => {});
156
+ const record = options.record || null;
157
+ const onCall = options.onCall || (() => {});
158
+ const resultMax = options.resultMax || DEFAULT_RESULT_MAX;
159
+ const messages = { ...MESSAGES, ...(options.messages || {}) };
160
+ let steps = 0;
161
+
162
+ function bounded(data) {
163
+ const json = JSON.stringify(data ?? null);
164
+ return json.length > resultMax ? `${json.slice(0, resultMax)}…` : data;
165
+ }
166
+
167
+ return async function call({ id, name, args, invalid, invalidReason, invalidDetail }) {
168
+ const tool = tools.get(name);
169
+ const step = `s${(steps += 1)}`;
170
+ /* Un outil inventé, ou un résumé qui échoue, montre quand même son étape, sans valeurs. */
171
+ emit('step', { id: step, tool: name, params: stepParams(tool, args) });
172
+ const begun = now();
173
+ const timeout = new globalThis.AbortController();
174
+ const timer = setTimeout(() => timeout.abort(new ToolTimeout(messages.timeout())), timeoutMs);
175
+ let result;
176
+ let ok = true;
177
+ try {
178
+ if (!tool) throw new Error(messages.unknownTool(name));
179
+ if (invalid) throw new Error(messages.invalidArguments({ name, invalidReason, invalidDetail }));
180
+ const toolSignal = globalThis.AbortSignal.any([signal, timeout.signal]);
181
+ const found = await abortable(Promise.resolve().then(() => tool.run(args, { ...context, signal: toolSignal })), toolSignal);
182
+ keep(found?.sources, found?.data);
183
+ if (record) await record({ tool, args, found: found ?? {} });
184
+ result = tool.kind === 'confirm' ? { data: bounded(found?.data), status: messages.waiting } : bounded(found?.data);
185
+ } catch (error) {
186
+ if (signal.aborted) throw signal.reason;
187
+ ok = false;
188
+ result = { error: error.message };
189
+ } finally {
190
+ clearTimeout(timer);
191
+ }
192
+ onCall({ name, ms: now() - begun, ok });
193
+ emit('step_done', { id: step, ok });
194
+ return { role: 'tool', toolCallId: id, name, result };
195
+ };
196
+ }
197
+
198
+ /**
199
+ * La boucle : le modèle lit la question avec la liste des outils, en demande,
200
+ * lit ce qu'ils rendent, et recommence jusqu'à répondre.
201
+ *
202
+ * @param {object} options
203
+ * @param {string} options.system
204
+ * @param {object[]} options.messages la transcription (modifiée en place : les tours s'y ajoutent).
205
+ * @param {object[]} [options.tools] ce que voit le modèle (toolSpecs).
206
+ * @param {Function} options.turn async ({ system, messages, tools }) => { text, toolCalls, model? }.
207
+ * @param {Function} options.callTool un appel => le message `tool` (createToolCaller).
208
+ * @param {number} [options.maxTurns] tours avec outils. Défaut 6.
209
+ * @param {number} [options.maxMs] budget de temps. Défaut 60 s.
210
+ * @param {string} [options.finalInstruction] ajoutée à la consigne du dernier tour, sans outils.
211
+ * @param {Function} [options.now]
212
+ * @param {AbortSignal} [options.signal]
213
+ * @returns {Promise<{ text: string, turns: number }>}
214
+ * @throws {AppError} code 'AI_NO_ANSWER' quand un tour ne donne ni texte ni outil
215
+ */
216
+ async function runToolLoop(options = {}) {
217
+ const { system, messages, turn, callTool } = options;
218
+ if (typeof turn !== 'function') throw new Error('runToolLoop requires options.turn.');
219
+ if (typeof callTool !== 'function') throw new Error('runToolLoop requires options.callTool.');
220
+ if (!Array.isArray(messages)) throw new Error('runToolLoop requires options.messages.');
221
+ const tools = options.tools || [];
222
+ const maxTurns = options.maxTurns === undefined ? 6 : options.maxTurns;
223
+ const maxMs = options.maxMs === undefined ? 60_000 : options.maxMs;
224
+ const now = options.now || Date.now;
225
+ const signal = options.signal;
226
+ const started = now();
227
+ let turns = 0;
228
+
229
+ const answerOf = (response) => {
230
+ if (!response || !response.text) {
231
+ const error = new AppError(`${(response && response.model) || 'The model'} gave no text.`, 503);
232
+ error.code = 'AI_NO_ANSWER';
233
+ throw error;
234
+ }
235
+ return { text: response.text, turns };
236
+ };
237
+
238
+ while (turns < maxTurns && now() - started < maxMs) {
239
+ if (signal && signal.aborted) throw signal.reason;
240
+ turns += 1;
241
+ const response = await turn({ system, messages, tools });
242
+ const calls = (response && response.toolCalls) || [];
243
+ if (!calls.length) return answerOf(response);
244
+ messages.push({ role: 'assistant', text: response.text ?? null, toolCalls: calls });
245
+ /* Les outils demandés ensemble tournent en même temps ; leurs résultats gardent l'ordre des appels. */
246
+ messages.push(...(await Promise.all(calls.map(callTool))));
247
+ }
248
+ if (signal && signal.aborted) throw signal.reason;
249
+ turns += 1;
250
+ const final = typeof options.finalInstruction === 'string' && options.finalInstruction.trim()
251
+ ? `${system}\n${options.finalInstruction}`
252
+ : system;
253
+ return answerOf(await turn({ system: final, messages, tools: [] }));
254
+ }
255
+
256
+ module.exports = { validateNativeTools, toolSpecs, stepParams, createToolCaller, runToolLoop, NATIVE_TOOL_KINDS: KINDS };