@astratra/ai 1.5.0 → 1.6.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
@@ -177,6 +177,7 @@ registry.register({
177
177
  name: 'get_patient_record',
178
178
  description: "Récupère le dossier d'un patient par son id",
179
179
  type: 'read',
180
+ risk: 'LOW', // LOW, MEDIUM ou HIGH ; absent = UNKNOWN
180
181
  roles: ['doctor', 'admin'],
181
182
  params: { patientId: 'string' },
182
183
  handler: async ({ patientId }, ctx) => patientStore.findById(patientId)
@@ -222,6 +223,43 @@ comme résultat d'outil) et continue, il peut réagir (expliquer, proposer
222
223
  autre chose, s'arrêter). Omis, chaque outil autorisé s'exécute automatiquement,
223
224
  comme avant.
224
225
 
226
+ ### Garde-fous de la boucle, résultats volumineux et risque
227
+
228
+ Les appels répétés avec le même nom et les mêmes paramètres JSON (l'ordre des
229
+ clés d'objet ne compte pas) reçoivent un rappel aux répétitions 3 et 5, puis
230
+ la boucle s'arrête à 8. Ces seuils se règlent avec `loopGuard`; `onEvent`
231
+ reçoit `tool_loop_warning` ou `tool_loop_stopped`. Le nombre d'étapes par
232
+ défaut reste 5 : l'arrêt à 8 ne joue que si `maxSteps` est réglé à 8 ou plus.
233
+
234
+ ```js
235
+ await runAgentLoop({
236
+ prompt, registry, router, userRole: 'doctor',
237
+ loopGuard: { reminder: 3, firmReminder: 5, stop: 8 },
238
+ spill: { threshold: 12_000 },
239
+ confirmationPolicy: { threshold: 'HIGH' },
240
+ riskAnalyzers: [async (call, ctx, tool) => classifier(call, ctx, tool)],
241
+ pendingActions
242
+ });
243
+ ```
244
+
245
+ Au-dessus du seuil (`spill.threshold`, 12 000 caractères par défaut), le
246
+ résultat complet est écrit dans `spill.store` (stockage mémoire par défaut).
247
+ Le modèle reçoit un extrait et un identifiant, puis peut appeler
248
+ `read_spilled_result` avec `{ id, start, length }` pour lire une tranche. Si
249
+ l'écriture échoue, le contenu est supprimé de la réponse et le modèle reçoit
250
+ `result_storage_failed`. Un stockage injecté expose `set(id, value)` et
251
+ `get(id)`.
252
+
253
+ Les risques possibles sont `LOW`, `MEDIUM`, `HIGH` et `UNKNOWN` (valeur des
254
+ outils sans déclaration). La politique de confirmation est inactive par
255
+ défaut, pour préserver l'exécution existante. Elle accepte `'always'`,
256
+ `'never'` ou `{ threshold: 'MEDIUM' }`; dans ce dernier cas, les risques au
257
+ moins aussi élevés que le seuil, dont `UNKNOWN`, demandent une confirmation.
258
+ Les `riskAnalyzers` reçoivent l'appel, le contexte et l'outil ; le niveau le
259
+ plus élevé entre l'outil et les analyseurs l'emporte. Les appels à confirmer
260
+ sont enregistrés par `pendingActions.propose()` et attendent l'approbation
261
+ via le cycle de vie déjà fourni par `createPendingActions`.
262
+
225
263
  **Périmètre V0 — toujours volontairement exclu :** gestion d'images/vision.
226
264
  Fonctionnalité non triviale dont une boucle d'agent de production a besoin,
227
265
  mais dont le portage fidèle reste jugé trop ambitieux pour ce package. À
@@ -363,6 +401,77 @@ Le modèle lit un code, jamais le message d'erreur. À court de tours ou de
363
401
  temps, un dernier tour sans outils répond avec ce qui a été lu, plutôt qu'une
364
402
  erreur.
365
403
 
404
+ ## llama.cpp : un modèle sur CPU, sur ton VPS
405
+
406
+ Fournisseur « **llama.cpp server** » : un modèle qui tourne sur **CPU** (un VPS
407
+ sans GPU) derrière l'API compatible OpenAI de `llama-server`. Aucune dépendance
408
+ (`src/llamaCpp.js`). C'est un client ; il ne lance rien. Le serveur se lance avec
409
+ le `docker-compose` de `deploy/llama-cpp/`. Ce n'est pas un doublon de
410
+ `createOpenAICompatibleProvider` : celui-ci branche un modèle dans le routeur et
411
+ rend `{ status }` pour une erreur HTTP, alors qu'un serveur hébergé par toi a
412
+ besoin de sa santé, du chargement du modèle (503) et d'erreurs typées.
413
+
414
+ ### Client
415
+
416
+ ```js
417
+ const { createLlamaCppProvider } = require('@astratra/ai');
418
+
419
+ const llm = createLlamaCppProvider({
420
+ baseUrl: 'http://127.0.0.1:8080', // avec ou sans /v1
421
+ apiKey: process.env.LLAMA_API_KEY,
422
+ model: 'local', // l'alias donné au serveur (facultatif)
423
+ timeoutMs: 120_000,
424
+ });
425
+
426
+ await llm.waitUntilReady({ timeoutMs: 120_000 }); // le chargement du modèle prend du temps
427
+ console.log(await llm.health()); // { ok, status: 'ok'|'loading'|'unauthorized'|'error'|'unreachable'|'timeout', latencyMs }
428
+ console.log(await llm.listModels()); // [{ id: 'local', ownedBy: 'llamacpp' }]
429
+
430
+ const { text, usage } = await llm.chat([{ role: 'user', content: 'Bonjour' }], { temperature: 0.2 });
431
+ for await (const piece of llm.chatStream([{ role: 'user', content: 'Raconte-moi une histoire' }])) process.stdout.write(piece);
432
+
433
+ llm.toOpenAICompatible(); // { baseURL: '…/v1', apiKey, model } pour tout autre client compatible OpenAI
434
+ ```
435
+
436
+ `health()` ne lance jamais d'exception (c'est une sonde). Les autres appels
437
+ lancent `LocalLlmError` avec `code` : `UNREACHABLE`, `TIMEOUT`, `UNAUTHORIZED`,
438
+ `LOADING` (503, modèle pas chargé), `HTTP_ERROR` (avec `status`), `INVALID_RESPONSE`.
439
+
440
+ ### Lancer `llama-server` sur un VPS CPU
441
+
442
+ Image officielle : `ghcr.io/ggml-org/llama.cpp:server` (CPU ; épingle un tag
443
+ `server-b<numéro>` en production).
444
+
445
+ ```bash
446
+ cd packages/ai/deploy/llama-cpp
447
+ cp .env.example .env # remplis LLAMA_API_KEY (longue valeur aléatoire) et LLAMA_MODEL_FILE
448
+ mkdir -p models # y déposer le fichier .gguf (quantisation Q4_K_M : bon compromis)
449
+ docker compose up -d
450
+ docker compose logs -f llama # attendre « server is listening »
451
+ curl -H "Authorization: Bearer $LLAMA_API_KEY" http://127.0.0.1:8080/v1/models
452
+ ```
453
+
454
+ Points à régler :
455
+
456
+ - **`LLAMA_THREADS`** : cœurs *physiques*, pas vCPU. Trop de fils ralentit.
457
+ - **`LLAMA_PARALLEL`** : requêtes simultanées. Le contexte (`LLAMA_CTX`) est
458
+ **partagé** : chacune dispose de `LLAMA_CTX / LLAMA_PARALLEL` jetons.
459
+ - **Mémoire** : prévoir la taille du fichier .gguf + ~1 à 2 Go pour le contexte ;
460
+ `LLAMA_MEMORY_LIMIT` plafonne le conteneur.
461
+ - **Débit** : sur CPU, un modèle de 3 à 4 milliards de paramètres en Q4 donne de
462
+ l'ordre de quelques à une dizaine de jetons par seconde selon le VPS ; à
463
+ mesurer sur le tien avant de promettre quoi que ce soit.
464
+ - Le port n'est publié que sur `127.0.0.1` : l'ouverture au public passe par un
465
+ proxy avec TLS, et la clé API reste obligatoire.
466
+ - La clé est lue dans l'environnement (`LLAMA_API_KEY`), jamais en argument.
467
+
468
+ ### Limites
469
+
470
+ Pas de répartition de charge ni de repli intégrés au client : pour router ce
471
+ serveur avec les autres fournisseurs, donne `toOpenAICompatible()` (adresse et clé)
472
+ à `createOpenAICompatibleProvider`. Testé avec un faux
473
+ serveur HTTP ; le vrai `llama-server` n'a pas été lancé dans ce dépôt.
474
+
366
475
  ## Tests
367
476
 
368
477
  ```bash
@@ -0,0 +1,10 @@
1
+ # Copie en .env (jamais commité) puis remplis.
2
+ LLAMA_API_KEY=remplace-par-une-longue-valeur-aleatoire
3
+ LLAMA_MODEL_FILE=nom-du-modele-Q4_K_M.gguf
4
+ LLAMA_ALIAS=local
5
+ LLAMA_CTX=8192
6
+ LLAMA_THREADS=4
7
+ LLAMA_PARALLEL=2
8
+ LLAMA_MEMORY_LIMIT=6g
9
+ LLAMA_MODELS_DIR=./models
10
+ LLAMA_PORT=8080
@@ -0,0 +1,47 @@
1
+ # llama.cpp en inférence CPU sur un VPS — API compatible OpenAI sur le port 8080.
2
+ # NE démarre rien tout seul : `docker compose up -d` après avoir lu le README du paquet.
3
+ #
4
+ # Image officielle : ghcr.io/ggml-org/llama.cpp:server (CPU). Épingle un tag
5
+ # `server-b<numéro>` en production plutôt que le tag flottant.
6
+ services:
7
+ llama:
8
+ image: ${LLAMA_IMAGE:-ghcr.io/ggml-org/llama.cpp:server}
9
+ restart: unless-stopped
10
+ # Écoute en local seulement : la sortie publique passe par un proxy avec TLS (nginx, Caddy).
11
+ ports:
12
+ - "127.0.0.1:${LLAMA_PORT:-8080}:8080"
13
+ volumes:
14
+ # Les fichiers .gguf, à télécharger une fois (voir README).
15
+ - ${LLAMA_MODELS_DIR:-./models}:/models:ro
16
+ environment:
17
+ # La clé est lue dans l'environnement, jamais passée en argument (visible dans `ps`).
18
+ LLAMA_API_KEY: ${LLAMA_API_KEY:?définis LLAMA_API_KEY dans .env}
19
+ command:
20
+ - --host
21
+ - 0.0.0.0
22
+ - --port
23
+ - "8080"
24
+ - --model
25
+ - /models/${LLAMA_MODEL_FILE:?définis LLAMA_MODEL_FILE dans .env}
26
+ - --alias
27
+ - ${LLAMA_ALIAS:-local}
28
+ - --ctx-size
29
+ - "${LLAMA_CTX:-8192}"
30
+ # Fils de calcul : le nombre de cœurs PHYSIQUES, pas de vCPU.
31
+ - --threads
32
+ - "${LLAMA_THREADS:-4}"
33
+ # Requêtes simultanées ; le contexte est partagé entre elles (ctx-size / parallel chacune).
34
+ - --parallel
35
+ - "${LLAMA_PARALLEL:-2}"
36
+ - --metrics
37
+ healthcheck:
38
+ test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
39
+ interval: 30s
40
+ timeout: 5s
41
+ retries: 5
42
+ # Le chargement d'un modèle de plusieurs Go prend du temps.
43
+ start_period: 120s
44
+ deploy:
45
+ resources:
46
+ limits:
47
+ memory: ${LLAMA_MEMORY_LIMIT:-6g}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/ai",
3
- "version": "1.5.0",
3
+ "version": "1.6.0",
4
4
  "description": "Generic AI provider routing, tool registry, and agent loop utilities for Astratra.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -9,7 +9,8 @@
9
9
  "types": "src/index.d.ts",
10
10
  "type": "commonjs",
11
11
  "files": [
12
- "src"
12
+ "src",
13
+ "deploy"
13
14
  ],
14
15
  "scripts": {
15
16
  "test": "jest"
@@ -22,7 +23,9 @@
22
23
  "keywords": [
23
24
  "astratra",
24
25
  "ai",
25
- "agents"
26
+ "agents",
27
+ "llama.cpp",
28
+ "cpu-inference"
26
29
  ],
27
30
  "license": "MIT",
28
31
  "publishConfig": {
@@ -40,7 +43,7 @@
40
43
  }
41
44
  },
42
45
  "devDependencies": {
43
- "@astratra/resilience": "^0.2.0",
46
+ "@astratra/resilience": "^1.0.0",
44
47
  "jest": "30.4.2",
45
48
  "redis": "^4.7.0"
46
49
  }
package/src/agentLoop.js CHANGED
@@ -1,6 +1,9 @@
1
1
  const { AppError } = require('@astratra/core');
2
2
 
3
3
  const DEFAULT_MAX_STEPS = 5;
4
+ const DEFAULT_LOOP_THRESHOLDS = Object.freeze({ reminder: 3, firmReminder: 5, stop: 8 });
5
+ const DEFAULT_SPILL_THRESHOLD = 12_000;
6
+ const SPILL_TOOL_NAME = 'read_spilled_result';
4
7
 
5
8
  async function runAgentLoop({
6
9
  prompt,
@@ -17,6 +20,12 @@ async function runAgentLoop({
17
20
  toolTimeoutMs,
18
21
  maxMs,
19
22
  finalInstruction,
23
+ loopGuard = {},
24
+ spill = {},
25
+ confirmationPolicy,
26
+ riskAnalyzers = [],
27
+ pendingActions,
28
+ onEvent,
20
29
  now = Date.now
21
30
  }) {
22
31
  if (!registry) throw new AppError('agentLoop requires a registry', 500);
@@ -26,6 +35,12 @@ async function runAgentLoop({
26
35
  }
27
36
 
28
37
  const messages = Array.isArray(history) ? [...history] : [];
38
+ const loopCounts = new Map();
39
+ const spillStore = spill.store || createMemorySpillStore();
40
+ const spillThreshold = Number.isFinite(spill.threshold) && spill.threshold >= 0 ? spill.threshold : DEFAULT_SPILL_THRESHOLD;
41
+ const thresholds = { ...DEFAULT_LOOP_THRESHOLDS, ...loopGuard };
42
+ const spills = new Map();
43
+ if (typeof spillStore.set !== 'function' || typeof spillStore.get !== 'function') throw new AppError('spill.store requires set() and get()', 500);
29
44
  messages.push({ role: 'user', content: prompt });
30
45
  const started = now();
31
46
 
@@ -53,13 +68,28 @@ async function runAgentLoop({
53
68
  const outOfTime = () => Number.isFinite(maxMs) && now() - started >= maxMs;
54
69
 
55
70
  for (let step = 0; step < maxSteps && !outOfTime(); step += 1) {
56
- const response = await askModel(buildPrompt(registry, userRole, messages));
71
+ const spillInstruction = spills.size ? `\n### Lire un résultat mis de côté\nAppelle <tool_call name="${SPILL_TOOL_NAME}">{"id":"référence","start":0,"length":4000}</tool_call> pour relire une tranche.` : '';
72
+ const response = await askModel(buildPrompt(registry, userRole, messages) + spillInstruction);
57
73
  const toolCall = parseToolCall(response);
58
74
 
59
75
  if (!toolCall) {
60
76
  return response;
61
77
  }
62
78
 
79
+ if (toolCall.name === SPILL_TOOL_NAME) {
80
+ const id = String(toolCall.params.id || '');
81
+ const stored = spills.get(id);
82
+ let result;
83
+ if (!stored) result = { error: 'spill_not_found' };
84
+ else {
85
+ const start = Math.max(0, Math.floor(Number(toolCall.params.start) || 0));
86
+ const length = Math.min(12_000, Math.max(0, Math.floor(Number(toolCall.params.length) || 4000)));
87
+ const value = await spillStore.get(id);
88
+ result = typeof value === 'string' ? { id, start, totalLength: value.length, text: value.slice(start, start + length) } : { error: 'spill_not_found' };
89
+ }
90
+ messages.push({ role: 'assistant', content: response }, { role: 'tool', content: `<tool_result name="${SPILL_TOOL_NAME}">${JSON.stringify(result)}</tool_result>` });
91
+ continue;
92
+ }
63
93
  const tool = registry.getToolByName(toolCall.name);
64
94
  if (!tool) {
65
95
  throw new AppError(`Tool "${toolCall.name}" is not registered`, 400);
@@ -73,8 +103,41 @@ async function runAgentLoop({
73
103
  // runs. Denying doesn't crash the loop: the model gets told and can
74
104
  // adjust course (ask something else, explain, stop), same as it would
75
105
  // handle any other tool result.
76
- if (typeof confirmTool === 'function') {
77
- const approved = await confirmTool(toolCall, ctx);
106
+ const normalizedCall = `${tool.name}:${stableStringify(toolCall.params)}`;
107
+ const repetitions = (loopCounts.get(normalizedCall) || 0) + 1;
108
+ loopCounts.set(normalizedCall, repetitions);
109
+ if (repetitions >= thresholds.stop) {
110
+ const reason = `Boucle arrêtée : l'appel ${tool.name} a été répété ${repetitions} fois.`;
111
+ const event = { type: 'tool_loop_stopped', name: tool.name, repetitions, reason };
112
+ if (typeof onEvent === 'function') onEvent(event);
113
+ return reason;
114
+ }
115
+ if (repetitions === thresholds.reminder || repetitions === thresholds.firmReminder) {
116
+ const reminder = repetitions === thresholds.reminder
117
+ ? `Rappel : cet appel identique a déjà été effectué ${repetitions} fois. Change de stratégie si le résultat ne suffit pas.`
118
+ : `Rappel ferme : cet appel identique a déjà été effectué ${repetitions} fois. Ne le répète plus sans modifier les arguments.`;
119
+ messages.push({ role: 'system', content: reminder });
120
+ if (typeof onEvent === 'function') onEvent({ type: 'tool_loop_warning', name: tool.name, repetitions, message: reminder });
121
+ }
122
+
123
+ let requiresConfirmation = typeof confirmTool === 'function';
124
+ if (confirmationPolicy !== undefined) {
125
+ let risk = tool.risk || 'UNKNOWN';
126
+ for (const analyze of riskAnalyzers) {
127
+ const analyzed = await analyze(toolCall, ctx, tool);
128
+ if (analyzed !== undefined && riskValue(analyzed) > riskValue(risk)) risk = String(analyzed).toUpperCase();
129
+ }
130
+ requiresConfirmation = shouldConfirm(confirmationPolicy, risk);
131
+ }
132
+ if (requiresConfirmation) {
133
+ let approved;
134
+ if (typeof confirmTool === 'function') approved = await confirmTool(toolCall, ctx);
135
+ else if (pendingActions && typeof pendingActions.propose === 'function') {
136
+ const proposed = await pendingActions.propose({ action: tool.name, payload: toolCall.params, description: `Appel ${tool.name} (${tool.risk || 'UNKNOWN'})`, proposedBy: ctx.userId, tenant: ctx.tenantId });
137
+ approved = false;
138
+ messages.push({ role: 'assistant', content: response }, { role: 'tool', content: `<tool_result name="${tool.name}">${JSON.stringify({ pending: true, actionId: proposed.action.id })}</tool_result>` });
139
+ continue;
140
+ } else approved = false;
78
141
  if (!approved) {
79
142
  messages.push({ role: 'assistant', content: response });
80
143
  messages.push({
@@ -100,13 +163,25 @@ async function runAgentLoop({
100
163
  }
101
164
  if (masker && tool.external === true) result = masker.unmaskDeep(result);
102
165
  const serialized = JSON.stringify(result);
166
+ const modelSerialized = masker ? masker.mask(serialized) : serialized;
103
167
  /* Your own data (a class list, a file) carries names the register may not
104
168
  know: the detector reads the result before it can reach the prompt. */
105
169
  if (masker && tool.external !== true && typeof masker.maskAsync === 'function') await masker.maskAsync(String(serialized));
106
170
  messages.push({ role: 'assistant', content: response });
171
+ let modelResult = serialized;
172
+ if (serialized.length > spillThreshold) {
173
+ const id = createSpillId();
174
+ try {
175
+ await spillStore.set(id, serialized);
176
+ spills.set(id, true);
177
+ modelResult = JSON.stringify({ spilled: true, id, totalLength: serialized.length, excerpt: modelSerialized.slice(0, 1500), readTool: SPILL_TOOL_NAME });
178
+ } catch (_error) {
179
+ modelResult = JSON.stringify({ error: 'result_storage_failed' });
180
+ }
181
+ }
107
182
  messages.push({
108
183
  role: 'tool',
109
- content: `<tool_result name="${tool.name}">${serialized}</tool_result>`
184
+ content: `<tool_result name="${tool.name}">${modelResult}</tool_result>`
110
185
  });
111
186
  }
112
187
 
@@ -121,6 +196,24 @@ async function runAgentLoop({
121
196
  throw new AppError(`agentLoop reached maxSteps (${maxSteps}) before a final answer`, 500);
122
197
  }
123
198
 
199
+ function stableStringify(value) {
200
+ if (value === null || typeof value !== 'object') return JSON.stringify(value);
201
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;
202
+ return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${stableStringify(value[key])}`).join(',')}}`;
203
+ }
204
+ function riskValue(risk) { return ({ LOW: 0, MEDIUM: 1, HIGH: 2, UNKNOWN: 3 })[String(risk).toUpperCase()] ?? 3; }
205
+ function shouldConfirm(policy, risk) {
206
+ if (policy === 'always') return true;
207
+ if (policy === 'never') return false;
208
+ const threshold = typeof policy === 'object' && policy ? policy.threshold : policy;
209
+ return risk === 'UNKNOWN' || riskValue(risk) >= riskValue(threshold);
210
+ }
211
+ function createMemorySpillStore() {
212
+ const values = new Map();
213
+ return { async set(id, value) { values.set(id, value); }, async get(id) { return values.get(id); } };
214
+ }
215
+ function createSpillId() { return `spill_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`; }
216
+
124
217
  async function runTool(tool, params, ctx, timeoutMs) {
125
218
  if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return tool.handler(params, ctx);
126
219
  let timer;
@@ -200,5 +293,8 @@ function estimateTokens(text) {
200
293
  }
201
294
 
202
295
  module.exports = {
203
- runAgentLoop
296
+ runAgentLoop,
297
+ createMemorySpillStore,
298
+ DEFAULT_LOOP_THRESHOLDS,
299
+ DEFAULT_SPILL_THRESHOLD
204
300
  };
package/src/index.d.ts CHANGED
@@ -118,12 +118,19 @@ export interface ToolDefinition<TParams = Record<string, unknown>, TResult = unk
118
118
  roles: string[];
119
119
  /** Reaches outside (web search, third-party API): its parameters are masked. */
120
120
  external?: boolean;
121
+ /** Niveau de risque déclaré ; absent, le registre utilise UNKNOWN. */
122
+ risk?: DeclaredToolRisk;
121
123
  params?: Record<string, unknown>;
122
124
  handler(params: TParams, ctx: Record<string, unknown>): Awaitable<TResult>;
123
125
  }
124
126
 
125
- export interface RegisteredTool<TParams = Record<string, unknown>, TResult = unknown> extends ToolDefinition<TParams, TResult> {
127
+ export type ToolRisk = 'LOW' | 'MEDIUM' | 'HIGH' | 'UNKNOWN';
128
+ export type DeclaredToolRisk = Exclude<ToolRisk, 'UNKNOWN'>;
129
+ export const TOOL_RISKS: Readonly<Record<ToolRisk, number>>;
130
+
131
+ export interface RegisteredTool<TParams = Record<string, unknown>, TResult = unknown> extends Omit<ToolDefinition<TParams, TResult>, 'risk'> {
126
132
  params: Record<string, unknown>;
133
+ risk: ToolRisk;
127
134
  }
128
135
 
129
136
  export interface ToolRegistry {
@@ -183,9 +190,28 @@ export interface AgentLoopOptions {
183
190
  maxMs?: number;
184
191
  /** When steps or time run out: one last turn without tools, with this instruction. */
185
192
  finalInstruction?: string;
193
+ /** Seuils d'appels strictement identiques (défauts : 3, 5 et 8). */
194
+ loopGuard?: { reminder?: number; firmReminder?: number; stop?: number };
195
+ /** Mise de côté au-delà du seuil en caractères (défaut : 12 000). */
196
+ spill?: { threshold?: number; store?: SpillStore };
197
+ /** Politique active uniquement lorsqu'elle est fournie : always, never ou seuil de risque. */
198
+ confirmationPolicy?: 'always' | 'never' | { threshold: ToolRisk };
199
+ /** Analyseurs supplémentaires ; le risque le plus élevé prévaut. */
200
+ riskAnalyzers?: Array<(toolCall: ToolCall, ctx: Record<string, unknown>, tool: RegisteredTool) => Awaitable<ToolRisk>>;
201
+ /** Adaptateur de createPendingActions ; les actions créées attendent leur approbation. */
202
+ pendingActions?: Pick<PendingActions, 'propose'>;
203
+ onEvent?: (event: { type: 'tool_loop_warning' | 'tool_loop_stopped'; name: string; repetitions: number; message?: string; reason?: string }) => void;
186
204
  now?: () => number;
187
205
  }
188
206
 
207
+ export interface SpillStore {
208
+ set(id: string, value: string): Awaitable<void>;
209
+ get(id: string): Awaitable<string | undefined>;
210
+ }
211
+ export function createMemorySpillStore(): SpillStore;
212
+ export const DEFAULT_LOOP_THRESHOLDS: Readonly<{ reminder: number; firmReminder: number; stop: number }>;
213
+ export const DEFAULT_SPILL_THRESHOLD: number;
214
+
189
215
  export function runAgentLoop(options: AgentLoopOptions): Promise<string>;
190
216
 
191
217
  export type ActionStatus = 'proposed' | 'approved' | 'rejected' | 'executing' | 'executed' | 'failed';
@@ -734,3 +760,60 @@ export function searchSerper(
734
760
  search: { query: string; sites?: string[]; hl?: string; num?: number },
735
761
  io: { key: string | null | undefined; fetch: FetchLike; accept?: (result: WebResult, url: URL) => boolean; timeoutMs?: number; endpoint?: string }
736
762
  ): Promise<WebResult[]>;
763
+
764
+ // Serveur llama.cpp (inférence CPU) : src/llamaCpp.js
765
+ export const DEFAULT_LLAMA_CPP_URL: string;
766
+ export function normalizeLlamaCppUrl(value: string): string;
767
+
768
+ export interface LlamaCppConfigInput {
769
+ /** Base du serveur, avec ou sans `/v1` (défaut http://127.0.0.1:8080). */
770
+ baseUrl?: string;
771
+ apiKey?: string | null;
772
+ model?: string | null;
773
+ timeoutMs?: number;
774
+ healthTimeoutMs?: number;
775
+ }
776
+ export interface LlamaCppConfig {
777
+ readonly id: 'llama.cpp';
778
+ readonly baseUrl: string;
779
+ readonly apiKey: string | null;
780
+ readonly model: string | null;
781
+ readonly timeoutMs: number;
782
+ readonly healthTimeoutMs: number;
783
+ }
784
+ export function createLlamaCppConfig(input?: LlamaCppConfigInput): LlamaCppConfig;
785
+
786
+ export type LocalLlmErrorCode = 'UNREACHABLE' | 'TIMEOUT' | 'UNAUTHORIZED' | 'LOADING' | 'HTTP_ERROR' | 'INVALID_RESPONSE';
787
+ export class LocalLlmError extends Error {
788
+ code: LocalLlmErrorCode;
789
+ status: number | null;
790
+ }
791
+
792
+ export interface LlamaCppChatMessage { role: 'system' | 'user' | 'assistant' | 'tool'; content: string; [key: string]: unknown }
793
+ export interface LlamaCppChatOptions { model?: string; temperature?: number; max_tokens?: number; [key: string]: unknown }
794
+ export interface LlamaCppChatResult {
795
+ text: string;
796
+ finishReason: string | null;
797
+ usage: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number } | null;
798
+ model: string | null;
799
+ }
800
+ export interface LlamaCppHealthState {
801
+ ok: boolean;
802
+ status: 'ok' | 'loading' | 'unauthorized' | 'error' | 'unreachable' | 'timeout';
803
+ latencyMs: number;
804
+ httpStatus?: number;
805
+ message?: string;
806
+ }
807
+ export interface LlamaCppProvider {
808
+ config: LlamaCppConfig;
809
+ health(): Promise<LlamaCppHealthState>;
810
+ waitUntilReady(options?: { timeoutMs?: number; intervalMs?: number }): Promise<LlamaCppHealthState>;
811
+ listModels(): Promise<Array<{ id: string; ownedBy: string | null }>>;
812
+ chat(messages: LlamaCppChatMessage[], options?: LlamaCppChatOptions): Promise<LlamaCppChatResult>;
813
+ chatStream(messages: LlamaCppChatMessage[], options?: LlamaCppChatOptions): AsyncGenerator<string, void, undefined>;
814
+ toOpenAICompatible(): { baseURL: string; apiKey: string; model: string | null };
815
+ }
816
+ export function createLlamaCppProvider(options?: LlamaCppConfigInput & {
817
+ fetch?: (url: string, init: object) => Awaitable<Response>;
818
+ sleep?: (ms: number) => Promise<void>;
819
+ }): LlamaCppProvider;
package/src/index.js CHANGED
@@ -14,6 +14,7 @@ module.exports = {
14
14
  ...require('./language'),
15
15
  ...require('./askLimit'),
16
16
  ...require('./openaiCompatible'),
17
+ ...require('./llamaCpp'),
17
18
  ...require('./gemini'),
18
19
  ...require('./nativeTools'),
19
20
  ...require('./eventStream'),
@@ -0,0 +1,192 @@
1
+ 'use strict';
2
+
3
+ /* global AbortController, TextDecoder */
4
+
5
+ /*
6
+ * Fournisseur d'un `llama-server` (llama.cpp), inférence sur CPU, API compatible
7
+ * OpenAI. Ce n'est pas un doublon de openaiCompatible.js : celui-ci branche un
8
+ * modèle dans le routeur et avale les erreurs HTTP (il rend `{ status }`), alors
9
+ * qu'un serveur qu'on héberge soi-même a besoin de sa santé (/health), du
10
+ * chargement du modèle (503), de la liste de ses modèles et d'erreurs typées.
11
+ * Pour router ce serveur, `toOpenAICompatible()` donne l'adresse et la clé à
12
+ * `createOpenAICompatibleProvider`.
13
+ */
14
+
15
+ const DEFAULT_LLAMA_CPP_URL = 'http://127.0.0.1:8080';
16
+
17
+ /**
18
+ * `llama-server` expose l'API OpenAI sous /v1 et sa santé sous /health (hors
19
+ * /v1). On garde donc une base nue et on ajoute les chemins nous-mêmes : que
20
+ * l'utilisateur écrive `http://hote:8080` ou `http://hote:8080/v1`, c'est pareil.
21
+ */
22
+ function normalizeLlamaCppUrl(value) {
23
+ let url;
24
+ try {
25
+ url = new URL(value);
26
+ } catch {
27
+ throw new TypeError('INVALID_BASE_URL');
28
+ }
29
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') throw new TypeError('INVALID_BASE_URL');
30
+ return url.toString().replace(/\/+$/, '').replace(/\/v1$/, '');
31
+ }
32
+
33
+ function createLlamaCppConfig({ baseUrl = DEFAULT_LLAMA_CPP_URL, apiKey = null, model = null, timeoutMs = 120_000, healthTimeoutMs = 5_000 } = {}) {
34
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) throw new RangeError('INVALID_TIMEOUT');
35
+ if (!Number.isFinite(healthTimeoutMs) || healthTimeoutMs <= 0) throw new RangeError('INVALID_TIMEOUT');
36
+ return Object.freeze({
37
+ id: 'llama.cpp',
38
+ baseUrl: normalizeLlamaCppUrl(baseUrl),
39
+ apiKey: apiKey || null,
40
+ model: model || null,
41
+ timeoutMs,
42
+ healthTimeoutMs
43
+ });
44
+ }
45
+
46
+
47
+ /** Erreur du fournisseur local ; `code` : UNREACHABLE, TIMEOUT, UNAUTHORIZED, LOADING, HTTP_ERROR, INVALID_RESPONSE. */
48
+ class LocalLlmError extends Error {
49
+ constructor(code, message, { status = null, cause } = {}) {
50
+ super(message, cause ? { cause } : undefined);
51
+ this.name = 'LocalLlmError';
52
+ this.code = code;
53
+ this.status = status;
54
+ }
55
+ }
56
+
57
+
58
+ const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
59
+
60
+ /**
61
+ * Client d'un `llama-server` (llama.cpp) : API compatible OpenAI, inférence sur
62
+ * CPU. Aucune dépendance : `fetch` est injectable pour les tests.
63
+ */
64
+ function createLlamaCppProvider(options = {}) {
65
+ const config = createLlamaCppConfig(options);
66
+ const fetchImpl = options.fetch || globalThis.fetch;
67
+ const sleep = options.sleep || wait;
68
+ if (typeof fetchImpl !== 'function') throw new TypeError('FETCH_REQUIRED');
69
+
70
+ function headers(extra) {
71
+ return { ...(config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}), ...extra };
72
+ }
73
+
74
+ async function request(path, { method = 'GET', body, timeoutMs = config.timeoutMs } = {}) {
75
+ const controller = new AbortController();
76
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
77
+ try {
78
+ return await fetchImpl(`${config.baseUrl}${path}`, {
79
+ method,
80
+ headers: headers(body ? { 'Content-Type': 'application/json' } : {}),
81
+ body: body ? JSON.stringify(body) : undefined,
82
+ signal: controller.signal
83
+ });
84
+ } catch (error) {
85
+ if (controller.signal.aborted) throw new LocalLlmError('TIMEOUT', `Pas de réponse en ${timeoutMs} ms`, { cause: error });
86
+ throw new LocalLlmError('UNREACHABLE', `Serveur injoignable (${config.baseUrl})`, { cause: error });
87
+ } finally {
88
+ clearTimeout(timer);
89
+ }
90
+ }
91
+
92
+ async function failure(response) {
93
+ let detail = '';
94
+ try { detail = (await response.json())?.error?.message || ''; } catch { /* corps non JSON */ }
95
+ if (response.status === 401 || response.status === 403) return new LocalLlmError('UNAUTHORIZED', 'Clé API refusée', { status: response.status });
96
+ if (response.status === 503) return new LocalLlmError('LOADING', detail || 'Modèle en cours de chargement', { status: 503 });
97
+ return new LocalLlmError('HTTP_ERROR', detail || `Réponse HTTP ${response.status}`, { status: response.status });
98
+ }
99
+
100
+ async function json(response) {
101
+ try {
102
+ return await response.json();
103
+ } catch (error) {
104
+ throw new LocalLlmError('INVALID_RESPONSE', 'Réponse non JSON', { cause: error });
105
+ }
106
+ }
107
+
108
+ /** `{ ok, status }` — status : ok | loading | unauthorized | error | unreachable | timeout. Ne lance jamais. */
109
+ async function health() {
110
+ const started = Date.now();
111
+ try {
112
+ const response = await request('/health', { timeoutMs: config.healthTimeoutMs });
113
+ const latencyMs = Date.now() - started;
114
+ if (response.ok) return { ok: true, status: 'ok', latencyMs };
115
+ const error = await failure(response);
116
+ return { ok: false, status: error.code === 'LOADING' ? 'loading' : error.code === 'UNAUTHORIZED' ? 'unauthorized' : 'error', httpStatus: response.status, latencyMs, message: error.message };
117
+ } catch (error) {
118
+ return { ok: false, status: error.code === 'TIMEOUT' ? 'timeout' : 'unreachable', latencyMs: Date.now() - started, message: error.message };
119
+ }
120
+ }
121
+
122
+ /** Attend que le modèle soit chargé (le premier démarrage peut prendre une minute). */
123
+ async function waitUntilReady({ timeoutMs = 120_000, intervalMs = 2_000 } = {}) {
124
+ const deadline = Date.now() + timeoutMs;
125
+ for (;;) {
126
+ const state = await health();
127
+ if (state.ok) return state;
128
+ if (state.status === 'unauthorized') throw new LocalLlmError('UNAUTHORIZED', state.message, { status: state.httpStatus });
129
+ if (Date.now() + intervalMs > deadline) throw new LocalLlmError('TIMEOUT', `Serveur pas prêt après ${timeoutMs} ms (${state.status})`);
130
+ await sleep(intervalMs);
131
+ }
132
+ }
133
+
134
+ /** Modèles servis, au format OpenAI : `[{ id, ownedBy }]`. */
135
+ async function listModels() {
136
+ const response = await request('/v1/models');
137
+ if (!response.ok) throw await failure(response);
138
+ const payload = await json(response);
139
+ if (!Array.isArray(payload?.data)) throw new LocalLlmError('INVALID_RESPONSE', 'Liste de modèles absente');
140
+ return payload.data.map((item) => ({ id: item.id, ownedBy: item.owned_by ?? null }));
141
+ }
142
+
143
+ function chatBody(messages, { model, stream = false, ...rest } = {}) {
144
+ if (!Array.isArray(messages) || messages.length === 0) throw new TypeError('MESSAGES_REQUIRED');
145
+ // llama-server ne sert qu'un modèle : le champ « model » est facultatif chez lui, on le passe s'il est connu.
146
+ const name = model || config.model;
147
+ return { ...(name ? { model: name } : {}), messages, stream, ...rest };
148
+ }
149
+
150
+ async function chat(messages, options = {}) {
151
+ const response = await request('/v1/chat/completions', { method: 'POST', body: chatBody(messages, { ...options, stream: false }) });
152
+ if (!response.ok) throw await failure(response);
153
+ const payload = await json(response);
154
+ const choice = payload?.choices?.[0];
155
+ if (!choice?.message) throw new LocalLlmError('INVALID_RESPONSE', 'Réponse sans choix');
156
+ return { text: choice.message.content ?? '', finishReason: choice.finish_reason ?? null, usage: payload.usage ?? null, model: payload.model ?? null };
157
+ }
158
+
159
+ /** Itère sur les fragments de texte (SSE `data: {...}` jusqu'à `[DONE]`). */
160
+ async function* chatStream(messages, options = {}) {
161
+ const response = await request('/v1/chat/completions', { method: 'POST', body: chatBody(messages, { ...options, stream: true }) });
162
+ if (!response.ok) throw await failure(response);
163
+ const decoder = new TextDecoder();
164
+ let buffer = '';
165
+ for await (const chunk of response.body) {
166
+ buffer += decoder.decode(chunk, { stream: true });
167
+ const lines = buffer.split('\n');
168
+ buffer = lines.pop();
169
+ for (const line of lines) {
170
+ if (!line.startsWith('data:')) continue;
171
+ const data = line.slice(5).trim();
172
+ if (data === '[DONE]') return;
173
+ let parsed;
174
+ try { parsed = JSON.parse(data); } catch (error) { throw new LocalLlmError('INVALID_RESPONSE', 'Fragment SSE illisible', { cause: error }); }
175
+ const delta = parsed?.choices?.[0]?.delta?.content;
176
+ if (delta) yield delta;
177
+ }
178
+ }
179
+ }
180
+
181
+ /** Configuration à donner à tout client « compatible OpenAI » (SDK, LiteLLM, autre paquet). */
182
+ function toOpenAICompatible() {
183
+ return { baseURL: `${config.baseUrl}/v1`, apiKey: config.apiKey || 'sans-cle', model: config.model };
184
+ }
185
+
186
+ return { config, health, waitUntilReady, listModels, chat, chatStream, toOpenAICompatible };
187
+ }
188
+
189
+
190
+ module.exports = {
191
+ DEFAULT_LLAMA_CPP_URL, normalizeLlamaCppUrl, createLlamaCppConfig, createLlamaCppProvider, LocalLlmError
192
+ };
@@ -1,9 +1,12 @@
1
+ const TOOL_RISKS = Object.freeze({ LOW: 0, MEDIUM: 1, HIGH: 2, UNKNOWN: 3 });
2
+
1
3
  function createToolRegistry() {
2
4
  const tools = [];
3
5
 
4
6
  function register(tool) {
5
7
  validateTool(tool);
6
- tools.push({ ...tool, roles: [...tool.roles], params: tool.params || {} });
8
+ const risk = normalizeRisk(tool.risk);
9
+ tools.push({ ...tool, risk, roles: [...tool.roles], params: tool.params || {} });
7
10
  return tool;
8
11
  }
9
12
 
@@ -40,8 +43,16 @@ function validateTool(tool) {
40
43
  if (!tool.type) throw new Error('tool.type is required');
41
44
  if (!Array.isArray(tool.roles)) throw new Error('tool.roles must be an array');
42
45
  if (typeof tool.handler !== 'function') throw new Error('tool.handler must be a function');
46
+ if (tool.risk !== undefined && !['LOW', 'MEDIUM', 'HIGH'].includes(String(tool.risk).toUpperCase())) {
47
+ throw new Error('tool.risk must be LOW, MEDIUM or HIGH');
48
+ }
49
+ }
50
+
51
+ function normalizeRisk(risk) {
52
+ return risk === undefined ? 'UNKNOWN' : String(risk).toUpperCase();
43
53
  }
44
54
 
45
55
  module.exports = {
46
- createToolRegistry
56
+ createToolRegistry,
57
+ TOOL_RISKS
47
58
  };