@astratra/ai 1.3.0 → 1.4.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
@@ -103,6 +103,139 @@ Fonctionnalité non triviale dont une boucle d'agent de production a besoin,
103
103
  mais dont le portage fidèle reste jugé trop ambitieux pour ce package. À
104
104
  construire dans votre propre boucle, ou à couvrir dans un futur spec.
105
105
 
106
+ ## Un disjoncteur par fournisseur, jamais un pour tous
107
+
108
+ Un seul disjoncteur partagé par toutes les dépendances extérieures a l'air
109
+ propre et c'est un piège : un reclasseur lent l'ouvrait, et le détecteur de
110
+ noms derrière le masquage s'éteignait avec lui pendant une minute. Ce qui
111
+ tombe doit être seul à s'arrêter.
112
+
113
+ Le paquet n'a pas de disjoncteur à lui : celui de `@astratra/resilience` (une
114
+ seule sonde en demi-ouverture) s'injecte.
115
+
116
+ ```js
117
+ const { createCircuitBreaker } = require('@astratra/resilience');
118
+ const { createProviderRouter, isProviderOutage } = require('@astratra/ai');
119
+
120
+ const router = createProviderRouter({
121
+ providers,
122
+ breakers: (id) => createCircuitBreaker({ name: id, failureThreshold: 3, recoveryMs: 60_000, isFailure: isProviderOutage })
123
+ });
124
+ router.getStats()['groq:llama'].circuit; // 'closed' | 'open' | 'half-open'
125
+ ```
126
+
127
+ `isProviderOutage` : délais, erreurs réseau, 408 et 5xx sont des pannes ; un
128
+ 429 ne l'est pas (le refroidissement du routeur s'en charge), ni un 400/401/404
129
+ (c'est la requête ou la clé, pas le fournisseur). Un appel refusé par le
130
+ disjoncteur ne consomme aucun quota et ne compte pas comme échec du modèle.
131
+ `createBreakerPool` sert pour tout le reste (routes d'un service local de
132
+ modèles…) et **refuse une fabrique qui rendrait le même disjoncteur pour deux
133
+ clés** — c'est exactement le disjoncteur partagé.
134
+
135
+ ## Masquer ce qui sort, démasquer ce qui revient
136
+
137
+ La question était masquée ; la recherche web ne l'était pas. Le modèle écrivait
138
+ la requête à partir de la question masquée, la boucle démasquait les paramètres
139
+ pour les outils qui ont besoin des vrais noms — et le nom de l'enfant partait
140
+ en clair chez le moteur de recherche. La règle porte donc sur la **direction** :
141
+ ce qui quitte la machine est masqué au moment où il la quitte.
142
+
143
+ ```js
144
+ const { createReversibleMasker } = require('@astratra/ai');
145
+
146
+ const masker = createReversibleMasker({
147
+ names: registreDeLEcole, // sensible à la casse
148
+ patterns: [{ type: 'EMAIL', pattern: /[\w.+-]+@[\w-]+\.[\w.]+/g }],
149
+ detect: (texte) => serviceLocal.entites(texte), // NER local, jamais distant
150
+ });
151
+
152
+ // Routeur : un fournisseur externe reçoit le texte masqué, la réponse revient démasquée
153
+ // (y compris en flux). Un fournisseur `external: false` (sur la machine) reçoit le clair.
154
+ await router.ask(question, { complexity: 'simple' }, { masker });
155
+
156
+ // Boucle d'agent : un outil `external: true` reçoit des paramètres MASQUÉS.
157
+ registry.register({ name: 'web_search', external: true, /* … */ });
158
+ await runAgentLoop({ prompt, registry, router, userRole, masker });
159
+ ```
160
+
161
+ Un masqueur par conversation ; il **apprend** : un nom trouvé une fois est
162
+ masqué partout ensuite, avec le même jeton. Le registre est comparé en
163
+ respectant la casse et sur des mots entiers (« Grace » masqué, « grâce à »
164
+ intact), un nom de moins de trois lettres n'est jamais masqué, un nom absent du
165
+ texte ne crée aucun jeton, les détections sous 0,6 sont ignorées et le
166
+ détecteur ne reçoit que 1 500 caractères coupés sur un blanc. Au démasquage, un
167
+ modèle qui a perdu le `#` du jeton récupère quand même le nom, et
168
+ `#PERSON_0001` ne mange jamais le début de `#PERSON_00012`.
169
+
170
+ ## Des passages dans une autre langue
171
+
172
+ Une question en anglais peut trouver sa meilleure réponse dans un texte qui
173
+ n'existe qu'en français. Chaque passage dit sa langue (`[fr]`) et une consigne
174
+ — la tienne, par langue — demande de traduire ce qui sert **en gardant la
175
+ référence d'origine**.
176
+
177
+ ```js
178
+ const lignes = buildPassagesContext({
179
+ passages, // null = la recherche a échoué : on ne dit rien de la bibliothèque
180
+ lang: 'en',
181
+ texts: { header, footer, empty, foreign: 'A passage marked {languages} … keep its original reference.' }
182
+ });
183
+ ```
184
+
185
+ `fr-FR` et `fr` sont la même langue (sous-étiquette principale). Un passage
186
+ étranger sans consigne est refusé plutôt que laissé à deviner au modèle.
187
+
188
+ ## Les sources : lues, utilisées, contredites
189
+
190
+ - `createSourceLedger()` collecte les sources rendues par les outils ; un outil
191
+ qui en rend plusieurs ne rattache pas toute sa sortie à chacune.
192
+ - `usedSources(réponse, sources, preuves, options)` ne garde que celles sur
193
+ lesquelles la réponse s'appuie (son lien, une référence nommée des deux
194
+ côtés, assez de mots distinctifs communs). Rien n'est jamais ajouté.
195
+ - `findContradiction(réponse, extraits, { compare })` confronte chaque phrase
196
+ factuelle à l'extrait le plus proche via un modèle d'inférence local ; seule
197
+ une contradiction franche compte, un doute, une panne ou un délai dépassé ne
198
+ disent rien (`null`).
199
+ - `rerankResults(question, trouvés, { score })` range les résultats par
200
+ pertinence et les sources suivent ; sans score, l'ordre du moteur reste.
201
+
202
+ ## Le texte de la réponse
203
+
204
+ `tidyMarkdown` ramène la réponse au Markdown qu'un téléphone dessine,
205
+ `plainText` l'enlève pour une voix, et `verifyQuotations(texte, { findReferences,
206
+ resolve })` remplace une citation infidèle suivie de sa référence par le vrai
207
+ texte — ce qu'est une référence et où vit son texte t'appartient.
208
+
209
+ ## La langue de la réponse, la cadence, les points compatibles OpenAI
210
+
211
+ - `createLanguageDetector({ words, identify })` : les petits mots d'abord (un
212
+ « merci » ne se devine pas autrement), puis un identifiant injecté, cru
213
+ seulement au-dessus d'un seuil — bien plus haut pour deux mots.
214
+ - `createAskLimit({ max, windowMs, code })` : fenêtre glissante par personne ;
215
+ le refus porte un code et l'attente, jamais une phrase ; les comptes qui
216
+ n'écrivent plus sont oubliés.
217
+ - `createOpenAICompatibleProvider({ id, url, getKey, models, fetch })` : un
218
+ fournisseur pour le routeur. La clé est relue à chaque appel, une erreur porte
219
+ le statut HTTP (429 → refroidissement) et jamais la clé, des arguments d'outil
220
+ mal formés sont signalés (`invalid: true`) au lieu de faire tomber le tour, les
221
+ balises de réflexion ne sont jamais montrées.
222
+
223
+ ## La boucle d'agent : outils en panne, budget de temps, dernier tour
224
+
225
+ ```js
226
+ await runAgentLoop({
227
+ prompt, registry, router, userRole,
228
+ reportToolErrors: true, // un outil qui lève devient { error: 'tool_failed' } pour le modèle
229
+ toolTimeoutMs: 20_000, // … ou { error: 'tool_timeout' }
230
+ maxMs: 60_000, // budget total
231
+ finalInstruction: 'Réponds maintenant avec ce que tu as lu, sans outil.'
232
+ });
233
+ ```
234
+
235
+ Le modèle lit un code, jamais le message d'erreur. À court de tours ou de
236
+ temps, un dernier tour sans outils répond avec ce qui a été lu, plutôt qu'une
237
+ erreur.
238
+
106
239
  ## Tests
107
240
 
108
241
  ```bash
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astratra/ai",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Generic AI provider routing, tool registry, and agent loop utilities for Astratra.",
5
5
  "engines": {
6
6
  "node": ">=20"
@@ -40,6 +40,7 @@
40
40
  }
41
41
  },
42
42
  "devDependencies": {
43
+ "@astratra/resilience": "^0.2.0",
43
44
  "jest": "30.4.2",
44
45
  "redis": "^4.7.0"
45
46
  }
package/src/agentLoop.js CHANGED
@@ -11,25 +11,49 @@ async function runAgentLoop({
11
11
  userRole,
12
12
  maxSteps = DEFAULT_MAX_STEPS,
13
13
  onChunk,
14
- confirmTool
14
+ confirmTool,
15
+ masker,
16
+ reportToolErrors = false,
17
+ toolTimeoutMs,
18
+ maxMs,
19
+ finalInstruction,
20
+ now = Date.now
15
21
  }) {
16
22
  if (!registry) throw new AppError('agentLoop requires a registry', 500);
17
23
  if (!router || typeof router.ask !== 'function') throw new AppError('agentLoop requires a router', 500);
24
+ if (masker && (typeof masker.mask !== 'function' || typeof masker.unmask !== 'function')) {
25
+ throw new AppError('agentLoop requires masker from createReversibleMasker()', 500);
26
+ }
18
27
 
19
28
  const messages = Array.isArray(history) ? [...history] : [];
20
29
  messages.push({ role: 'user', content: prompt });
30
+ const started = now();
31
+
32
+ /* The question is read by the entity detector once, so every name in it is
33
+ known before the first byte leaves; afterwards the prompt is masked with
34
+ what the masker has learnt. Inside the loop everything stays in clear —
35
+ masking happens at the door, on the way out. */
36
+ if (masker && typeof masker.maskAsync === 'function') await masker.maskAsync(String(prompt || ''));
21
37
 
22
- for (let step = 0; step < maxSteps; step += 1) {
23
- const modelPrompt = buildPrompt(registry, userRole, messages);
38
+ async function askModel(modelPrompt) {
39
+ const outbound = masker ? masker.mask(modelPrompt) : modelPrompt;
40
+ const raw = await router.ask(outbound, {
41
+ complexity: 'agent',
42
+ intent: 'agent_loop',
43
+ estimatedTokens: estimateTokens(outbound)
44
+ }, ctx);
45
+ const readable = masker ? unmaskAnswer(masker, raw) : raw;
24
46
  // onChunk, when provided, is called with each chunk AS IT ARRIVES if
25
47
  // router.ask() returns a stream — real token-by-token streaming to the
26
48
  // caller. The loop itself still needs the fully-assembled text to
27
49
  // detect a <tool_call>, so it accumulates in parallel regardless.
28
- const response = await stringifyModelResponse(await router.ask(modelPrompt, {
29
- complexity: 'agent',
30
- intent: 'agent_loop',
31
- estimatedTokens: estimateTokens(modelPrompt)
32
- }, ctx), onChunk);
50
+ return stringifyModelResponse(readable, onChunk);
51
+ }
52
+
53
+ const outOfTime = () => Number.isFinite(maxMs) && now() - started >= maxMs;
54
+
55
+ for (let step = 0; step < maxSteps && !outOfTime(); step += 1) {
56
+ const response = await askModel(buildPrompt(registry, userRole, messages));
33
57
  const toolCall = parseToolCall(response);
34
58
 
35
59
  if (!toolCall) {
@@ -61,19 +85,70 @@ async function runAgentLoop({
61
85
  }
62
86
  }
63
87
 
64
- const result = await tool.handler(toolCall.params, ctx);
88
+ /* A tool that reaches OUTSIDE (a web search, a third-party API) gets its
89
+ parameters masked: the model wrote them from a masked prompt, the loop
90
+ read them in clear, and they must not leave in clear. */
91
+ const params = masker && tool.external === true ? masker.maskDeep(toolCall.params) : toolCall.params;
92
+ let result;
93
+ try {
94
+ result = await runTool(tool, params, ctx, toolTimeoutMs);
95
+ } catch (error) {
96
+ if (!reportToolErrors) throw error;
97
+ /* The model reads a code, never the error message: it may quote
98
+ internals, and it is not the model's business. */
99
+ result = { error: error && error.code === 'TOOL_TIMEOUT' ? 'tool_timeout' : 'tool_failed' };
100
+ }
101
+ if (masker && tool.external === true) result = masker.unmaskDeep(result);
102
+ const serialized = JSON.stringify(result);
103
+ /* Your own data (a class list, a file) carries names the register may not
104
+ know: the detector reads the result before it can reach the prompt. */
105
+ if (masker && tool.external !== true && typeof masker.maskAsync === 'function') await masker.maskAsync(String(serialized));
65
106
  messages.push({ role: 'assistant', content: response });
66
107
  messages.push({
67
108
  role: 'tool',
68
- content: `<tool_result name="${tool.name}">${JSON.stringify(result)}</tool_result>`
109
+ content: `<tool_result name="${tool.name}">${serialized}</tool_result>`
69
110
  });
70
111
  }
71
112
 
113
+ /* Out of steps or time: one last turn without tools, when the caller says
114
+ how to ask for it — an answer with what was read beats an error. */
115
+ if (typeof finalInstruction === 'string' && finalInstruction.trim()) {
116
+ const last = await askModel(`${buildPrompt(null, userRole, messages)}\n\n${finalInstruction}`);
117
+ const stray = parseToolCallSafely(last);
118
+ return stray ? last.replace(TOOL_CALL_PATTERN, '').trim() : last;
119
+ }
120
+
72
121
  throw new AppError(`agentLoop reached maxSteps (${maxSteps}) before a final answer`, 500);
73
122
  }
74
123
 
124
+ async function runTool(tool, params, ctx, timeoutMs) {
125
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return tool.handler(params, ctx);
126
+ let timer;
127
+ const timeout = new Promise((_resolve, reject) => {
128
+ timer = setTimeout(() => reject(Object.assign(new Error(`Tool "${tool.name}" timed out`), { code: 'TOOL_TIMEOUT' })), timeoutMs);
129
+ });
130
+ try {
131
+ return await Promise.race([Promise.resolve().then(() => tool.handler(params, ctx)), timeout]);
132
+ } finally {
133
+ clearTimeout(timer);
134
+ }
135
+ }
136
+
137
+ function unmaskAnswer(masker, raw) {
138
+ if (isAsyncIterable(raw) && typeof masker.unmaskStream === 'function') return masker.unmaskStream(raw);
139
+ return typeof raw === 'string' ? masker.unmask(raw) : raw;
140
+ }
141
+
142
+ function parseToolCallSafely(text) {
143
+ try {
144
+ return parseToolCall(text);
145
+ } catch (_error) {
146
+ return { name: 'invalid', params: {} };
147
+ }
148
+ }
149
+
75
150
  function buildPrompt(registry, userRole, messages) {
76
- const tools = registry.formatToolsForPrompt(userRole);
151
+ const tools = registry ? registry.formatToolsForPrompt(userRole) : '';
77
152
  const renderedHistory = messages.map(message => {
78
153
  if (typeof message === 'string') return message;
79
154
  return `${message.role || 'message'}: ${message.content || ''}`;
@@ -85,6 +160,8 @@ function buildPrompt(registry, userRole, messages) {
85
160
  ].filter(Boolean).join('\n\n');
86
161
  }
87
162
 
163
+ const TOOL_CALL_PATTERN = /<tool_call\s+name="([^"]+)">\s*([\s\S]*?)\s*<\/tool_call>/gi;
164
+
88
165
  function parseToolCall(text) {
89
166
  const match = String(text || '').match(/<tool_call\s+name="([^"]+)">\s*([\s\S]*?)\s*<\/tool_call>/i);
90
167
  if (!match) return null;
@@ -0,0 +1,117 @@
1
+ /**
2
+ * The last look at an answer before a screen draws it, or a voice reads it.
3
+ *
4
+ * A mobile Markdown renderer draws a small subset — **bold**, "- " and "1. "
5
+ * lists, "### " headings, "> " quotes — and shows everything else as raw
6
+ * symbols. tidyMarkdown brings the answer back to that subset; plainText
7
+ * strips it for a voice or a notification.
8
+ *
9
+ * verifyQuotations checks every quotation that cites a reference against the
10
+ * text you hold. A model quotes from memory, or from another edition, despite
11
+ * its instructions; an unfaithful quotation is replaced by the true text. What
12
+ * a "reference" is and where its text lives is yours (verses, articles of law,
13
+ * clauses of a contract): both are injected.
14
+ */
15
+
16
+ /** Markdown and stray asterisks out, the words kept: what is read aloud. */
17
+ function plainText(text) {
18
+ return String(text === null || text === undefined ? '' : text)
19
+ .replace(/^#{1,6}\s+/gm, '')
20
+ .replace(/^>\s?/gm, '')
21
+ .replace(/^\s*[-*•]\s+/gm, '')
22
+ .replace(/\*\*([^*]+)\*\*/g, '$1')
23
+ .replace(/__([^_]+)__/g, '$1')
24
+ .replace(/\*([^*\s][^*]*)\*/g, '$1')
25
+ .replace(/`([^`]+)`/g, '$1')
26
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')
27
+ .replace(/ ?\*+ ?/g, ' ')
28
+ .replace(/\n{3,}/g, '\n\n')
29
+ .trim();
30
+ }
31
+
32
+ /**
33
+ * @param {string} text
34
+ * @param {object} [options]
35
+ * @param {boolean} [options.removeEmoji] drop emoji — for an app that draws its own symbols. Default false.
36
+ */
37
+ function tidyMarkdown(text, options = {}) {
38
+ let out = String(text === null || text === undefined ? '' : text)
39
+ .replace(/```\w*\n?/g, '')
40
+ /* A rule drawn across ("---", "***") is only a pause: a blank line. */
41
+ .replace(/^[ \t]*([-*_])(?:[ \t]*\1){2,}[ \t]*$/gm, '')
42
+ /* Tables: the separator row goes, each row becomes "a · b · c". */
43
+ .replace(/^[ \t]*\|[ \t:|-]+\|[ \t]*(\n|$)/gm, '')
44
+ .replace(/^[ \t]*\|(.*)\|[ \t]*$/gm, (_row, cells) => cells.split('|').map((cell) => cell.trim()).filter(Boolean).join(' · '))
45
+ .replace(/^#{1,6}\s+(.+)$/gm, '### $1')
46
+ .replace(/^(\s*)[*•]\s+/gm, '$1- ')
47
+ .replace(/__([^_\n]+)__/g, '**$1**')
48
+ .replace(/(^|[^*])\*(?!\*)([^*\n]+?)\*(?!\*)/g, '$1$2')
49
+ .replace(/(^|[^*])\*(?!\*)/g, '$1')
50
+ .replace(/`([^`]+)`/g, '$1')
51
+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1');
52
+ if (options.removeEmoji) {
53
+ out = out.replace(/[\p{Extended_Pictographic}\p{Emoji_Modifier}\u{FE0F}\u{200D}]/gu, '');
54
+ }
55
+ return out
56
+ .replace(/(\S)[ \t]{2,}/g, '$1 ')
57
+ .replace(/[ \t]+$/gm, '')
58
+ .replace(/\n{3,}/g, '\n\n')
59
+ .trim();
60
+ }
61
+
62
+ /* A quotation between guillemets, curly quotes or straight quotes. */
63
+ const QUOTATION = /(«\s*)([^«»]+?)(\s*»)|(“)([^“”]+)(”)|(")([^"\n]+)(")/g;
64
+ /* What may stand between a quotation and the reference saying where it comes from. */
65
+ const BETWEEN = /^\s*\(?\s*$/;
66
+ const ELLIPSIS = /…|\.\.\./;
67
+
68
+ /* Words only: no punctuation, no accents, no case. */
69
+ const foldWords = (text) => ` ${String(text).normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().replace(/[^\p{L}\d]+/gu, ' ').trim()} `;
70
+
71
+ /** Faithful when each piece of the quotation (cut by an ellipsis) is in the source. */
72
+ function isFaithfulQuotation(quoted, source) {
73
+ const haystack = foldWords(source);
74
+ return String(quoted).split(ELLIPSIS).map(foldWords).filter((piece) => piece.trim()).every((piece) => haystack.includes(piece));
75
+ }
76
+
77
+ /**
78
+ * @param {string} text
79
+ * @param {object} options
80
+ * @param {Function} options.findReferences (text) => [{ start, end, refs }] — places cited, with offsets.
81
+ * @param {Function} options.resolve async (refs) => the true text of those places, or null.
82
+ * @returns {Promise<string>} the text, each unfaithful quotation followed by a
83
+ * reference replaced by the true text. When references cannot be read, unchanged.
84
+ */
85
+ async function verifyQuotations(text, options = {}) {
86
+ const source = String(text === null || text === undefined ? '' : text);
87
+ if (typeof options.findReferences !== 'function' || typeof options.resolve !== 'function') {
88
+ throw new Error('verifyQuotations requires options.findReferences and options.resolve.');
89
+ }
90
+ let references;
91
+ try {
92
+ references = (await options.findReferences(source)) || [];
93
+ } catch (_error) {
94
+ return source;
95
+ }
96
+ const replacements = [];
97
+ for (const match of source.matchAll(QUOTATION)) {
98
+ const groups = match.slice(1);
99
+ const triple = [groups.slice(0, 3), groups.slice(3, 6), groups.slice(6, 9)].find((group) => group[1] !== undefined);
100
+ const end = match.index + match[0].length;
101
+ const reference = references.find((found) => found.start >= end && BETWEEN.test(source.slice(end, found.start)));
102
+ if (!reference) continue;
103
+ let truth = null;
104
+ try {
105
+ truth = await options.resolve(reference.refs);
106
+ } catch (_error) {
107
+ truth = null;
108
+ }
109
+ if (!truth || isFaithfulQuotation(triple[1], truth)) continue;
110
+ replacements.push({ start: match.index, end, value: `${triple[0]}${truth}${triple[2]}` });
111
+ }
112
+ let out = source;
113
+ for (const { start, end, value } of replacements.reverse()) out = out.slice(0, start) + value + out.slice(end);
114
+ return out;
115
+ }
116
+
117
+ module.exports = { plainText, tidyMarkdown, verifyQuotations, isFaithfulQuotation };
@@ -0,0 +1,69 @@
1
+ /**
2
+ * How often one account may ask the AI: a sliding window per person, in
3
+ * memory — one process. For several instances, put the counter in Redis (the
4
+ * provider router already does for provider quotas).
5
+ *
6
+ * Each area (chat, image, voice) keeps its own limiter with its own code. The
7
+ * refusal carries a code and the wait, never a sentence: the client translates.
8
+ *
9
+ * Accounts that stop asking are forgotten: a map that only grows is a slow
10
+ * memory leak on a server that runs for months.
11
+ */
12
+ const { AppError } = require('@astratra/core');
13
+
14
+ /**
15
+ * @param {object} options
16
+ * @param {number} options.max asks allowed in the window.
17
+ * @param {number} options.windowMs
18
+ * @param {string} [options.code] Default 'AI_RATE_LIMITED'.
19
+ * @param {number} [options.sweepEvery] asks between two clean-ups. Default 500.
20
+ */
21
+ function createAskLimit(options = {}) {
22
+ const { max, windowMs } = options;
23
+ if (!Number.isInteger(max) || max < 1) throw new Error('createAskLimit requires an integer options.max >= 1.');
24
+ if (!Number.isFinite(windowMs) || windowMs <= 0) throw new Error('createAskLimit requires options.windowMs > 0.');
25
+ const code = options.code || 'AI_RATE_LIMITED';
26
+ const sweepEvery = options.sweepEvery || 500;
27
+ const asks = new Map();
28
+ let sinceSweep = 0;
29
+
30
+ function sweep(now) {
31
+ for (const [id, times] of asks) {
32
+ const recent = times.filter((at) => now - at < windowMs);
33
+ if (recent.length) asks.set(id, recent);
34
+ else asks.delete(id);
35
+ }
36
+ }
37
+
38
+ /** What `take` would answer, without counting an ask. */
39
+ function peek(subject, now = Date.now()) {
40
+ const recent = (asks.get(String(subject)) || []).filter((at) => now - at < windowMs);
41
+ if (recent.length < max) return { allowed: true, remaining: max - recent.length, retryInMs: 0 };
42
+ return { allowed: false, remaining: 0, retryInMs: Math.max(0, recent[0] + windowMs - now) };
43
+ }
44
+
45
+ /** Count one ask; throws a 429 AppError carrying `code` and `retryInMs` past the limit. */
46
+ function take(subject, now = Date.now()) {
47
+ const id = String(subject);
48
+ sinceSweep += 1;
49
+ if (sinceSweep >= sweepEvery) {
50
+ sinceSweep = 0;
51
+ sweep(now);
52
+ }
53
+ const verdict = peek(id, now);
54
+ if (!verdict.allowed) {
55
+ const error = new AppError(code, 429);
56
+ error.code = code;
57
+ error.retryInMs = verdict.retryInMs;
58
+ throw error;
59
+ }
60
+ const recent = (asks.get(id) || []).filter((at) => now - at < windowMs);
61
+ recent.push(now);
62
+ asks.set(id, recent);
63
+ return { allowed: true, remaining: max - recent.length, retryInMs: 0 };
64
+ }
65
+
66
+ return { take, peek, reset: (subject) => (subject === undefined ? asks.clear() : asks.delete(String(subject))), size: () => asks.size, sweep };
67
+ }
68
+
69
+ module.exports = { createAskLimit };
@@ -0,0 +1,97 @@
1
+ /**
2
+ * One circuit per provider — never one for all.
3
+ *
4
+ * A single breaker shared by every outside dependency looks tidy and is a
5
+ * trap: a slow reranker opened it, and the name detector behind the privacy
6
+ * mask went dark with it for a full minute. The failing thing must be the only
7
+ * thing that stops.
8
+ *
9
+ * This package ships no breaker of its own. `@astratra/resilience` has one,
10
+ * with a single half-open probe; inject its factory:
11
+ *
12
+ * const { createCircuitBreaker } = require('@astratra/resilience');
13
+ * const breakers = createBreakerPool({
14
+ * create: (id) => createCircuitBreaker({ name: id, isFailure: isProviderOutage })
15
+ * });
16
+ *
17
+ * Any object with `call(fn)` fits; `status()` and `reset()` are used when
18
+ * present.
19
+ */
20
+
21
+ /**
22
+ * Is this error the provider being DOWN, rather than refusing this request?
23
+ *
24
+ * A 429 is the provider saying "slow down" — the router's cooldown handles it.
25
+ * A 400, 401, 403 or 404 is about the request or the key: opening the circuit
26
+ * on it would take a healthy provider away from every other request. Timeouts,
27
+ * network failures and 5xx are outages.
28
+ */
29
+ function isProviderOutage(error) {
30
+ if (!error) return false;
31
+ const status = [error.statusCode, error.status, Number(error.code)].find((value) => Number.isInteger(value) && value >= 100 && value < 600);
32
+ if (status === undefined) return true;
33
+ if (status === 408) return true;
34
+ return status >= 500;
35
+ }
36
+
37
+ /**
38
+ * @param {object} options
39
+ * @param {Function} options.create (key) => breaker. Called once per key.
40
+ */
41
+ function createBreakerPool(options = {}) {
42
+ const create = options.create;
43
+ if (typeof create !== 'function') {
44
+ throw new Error('createBreakerPool requires options.create: (key) => breaker.');
45
+ }
46
+ const pool = new Map();
47
+ const owners = new Map();
48
+
49
+ function get(key) {
50
+ const name = String(key);
51
+ if (pool.has(name)) return pool.get(name);
52
+ const breaker = create(name);
53
+ if (!breaker || typeof breaker.call !== 'function') {
54
+ throw new Error(`createBreakerPool: create("${name}") must return an object with call(fn).`);
55
+ }
56
+ /* The mistake this module exists to prevent: a factory that hands back the
57
+ same breaker for every key re-creates the shared circuit. */
58
+ if (owners.has(breaker)) {
59
+ throw new Error(`createBreakerPool: "${name}" received the breaker of "${owners.get(breaker)}" — one breaker per key.`);
60
+ }
61
+ owners.set(breaker, name);
62
+ pool.set(name, breaker);
63
+ return breaker;
64
+ }
65
+
66
+ /** Run `fn` under the breaker of `key`. */
67
+ const run = (key, fn) => get(key).call(fn);
68
+
69
+ function status() {
70
+ const out = {};
71
+ for (const [name, breaker] of pool) {
72
+ out[name] = typeof breaker.status === 'function' ? breaker.status() : { name };
73
+ }
74
+ return out;
75
+ }
76
+
77
+ function stateOf(key) {
78
+ const breaker = pool.get(String(key));
79
+ if (!breaker || typeof breaker.status !== 'function') return null;
80
+ const current = breaker.status();
81
+ return current && current.state ? current.state : null;
82
+ }
83
+
84
+ function reset(key) {
85
+ const targets = key === undefined ? [...pool.values()] : [pool.get(String(key))].filter(Boolean);
86
+ for (const breaker of targets) if (typeof breaker.reset === 'function') breaker.reset();
87
+ }
88
+
89
+ return { get, run, status, stateOf, reset, keys: () => [...pool.keys()] };
90
+ }
91
+
92
+ /** An error thrown by a breaker that refused to call — not a provider failure. */
93
+ function isCircuitOpen(error) {
94
+ return Boolean(error && (error.code === 'CIRCUIT_OPEN' || error.name === 'CircuitOpenError'));
95
+ }
96
+
97
+ module.exports = { createBreakerPool, isProviderOutage, isCircuitOpen };