adaptive-memory-multi-model-router 2.14.16 → 2.14.18

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.
Files changed (69) hide show
  1. package/.a3m-vault.json +23 -0
  2. package/.github/workflows/ci.yml +253 -5
  3. package/.publish-tick +1 -1
  4. package/AGENT_COUNCIL_FINDINGS.md +142 -0
  5. package/LAUNCH_CHECKLIST.md +141 -0
  6. package/README.md +15 -17
  7. package/README.md.bak +836 -0
  8. package/articles/CHINESE_SUBMISSIONS_READY.md +322 -0
  9. package/articles/DEVTO_READY.md +255 -0
  10. package/articles/HN_POST_READY.md +137 -0
  11. package/articles/INDIEHACKERS_READY.md +120 -0
  12. package/articles/NEWSLETTER_SEND_NOW.md +259 -0
  13. package/articles/PRODUCTHUNT_READY.md +106 -0
  14. package/articles/REDDIT_SUBMISSION_READY.md +348 -0
  15. package/articles/TWEET_STORM_READY.md +165 -0
  16. package/benchmark-results.json +45 -43
  17. package/council-votes/architecture-vote.md +121 -0
  18. package/council-votes/coverage-vote.md +93 -0
  19. package/dist/cost/costTracker.d.ts +109 -44
  20. package/dist/cost/costTracker.js +321 -98
  21. package/dist/cost/costTracker.js.map +1 -1
  22. package/dist/ensemble.d.ts +21 -0
  23. package/dist/ensemble.js +85 -0
  24. package/dist/index.d.ts +9 -5
  25. package/dist/index.js +12 -4
  26. package/dist/routing/advancedRouter.d.ts +38 -43
  27. package/dist/routing/advancedRouter.js +394 -408
  28. package/dist/routing/advancedRouter.js.map +1 -1
  29. package/dist/routing/providers/providerConfig.d.ts +49 -0
  30. package/dist/routing/providers/providerConfig.js +883 -0
  31. package/dist/routing/routing/advancedRouter.d.ts +62 -0
  32. package/dist/routing/routing/advancedRouter.js +447 -0
  33. package/dist/routing/utils/tokenUtils.d.ts +52 -0
  34. package/dist/routing/utils/tokenUtils.js +129 -0
  35. package/dist/server/proxyServer.d.ts +1 -1
  36. package/dist/tui/dashboard.js +66 -2
  37. package/dist/tui/dashboard.js.map +1 -1
  38. package/dist/utils/tokenUtils.d.ts +48 -1
  39. package/dist/utils/tokenUtils.js +117 -4
  40. package/dist/utils/tokenUtils.js.map +1 -1
  41. package/docs/CITATIONS.md +2 -2
  42. package/docs/GEO_STATUS.md +43 -157
  43. package/docs/ai-plugin.json +4 -4
  44. package/docs/llms.txt +21 -27
  45. package/docs/sitemap.xml +14 -20
  46. package/package.json +2 -2
  47. package/research-log.md +49 -0
  48. package/sitemap.xml +57 -0
  49. package/src/cost/costTracker.ts +576 -0
  50. package/src/ensemble.ts +103 -0
  51. package/src/index.ts +13 -3
  52. package/src/routing/advancedRouter.ts +536 -0
  53. package/src/tui/dashboard.ts +76 -3
  54. package/src/utils/tokenUtils.ts +142 -4
  55. package/test-council/1-structure-tests.test.js +353 -0
  56. package/test-council/1-structure-tests.test.ts +353 -0
  57. package/test-council/2-edge-case-tests.test.ts +361 -0
  58. package/test-council/3-performance-tests.test.ts +669 -0
  59. package/test-council/4-integration-tests.test.ts +391 -0
  60. package/test-council/5-agent-council-eval.test.ts +413 -0
  61. package/test-council/AGENT_COUNCIL_ARCHITECTURE.md +349 -0
  62. package/test-council/TEST_COUNCIL_REPORT.md +201 -0
  63. package/test-council/agents/edge-case-agent.ts +363 -0
  64. package/test-council/agents/performance-agent.ts +426 -0
  65. package/test-council/agents/structure-agent.ts +227 -0
  66. package/test-council/council.md +183 -0
  67. package/tests/security/guardrailEngine.test.ts +700 -0
  68. package/docs/.well-known/ai-plugin.json +0 -16
  69. package/research/PUBLISH_LOG.md +0 -3
package/src/index.ts CHANGED
@@ -74,7 +74,6 @@ export type { MemoryChunk, TreeNode } from './memory/memoryTree';
74
74
  // UTILITIES
75
75
  // ============================================================
76
76
  export { countTokens, estimateTokens } from './utils/tokenUtils';
77
- export { MODEL_COSTS } from './utils/tokenUtils';
78
77
 
79
78
  // ============================================================
80
79
  // v2.0.0 FEATURES
@@ -100,6 +99,11 @@ export {
100
99
  } from './observability';
101
100
  export type { Span, Metric, RouteTrace, ObservabilityEvent } from './observability';
102
101
 
102
+ // ============================================================
103
+ // ENSEMBLE ORCHESTRATION
104
+ // ============================================================
105
+ export { EnsembleOrchestrator, EnsembleStrategy, EnsembleResponse } from './ensemble';
106
+
103
107
  // ============================================================
104
108
  // CONVENIENCE: Create a router instance
105
109
  // ============================================================
@@ -107,6 +111,7 @@ import { routeQuery, routeBatch, recommendForTask } from './routing/advancedRout
107
111
  import { getAvailableProviders, healthCheck } from './providers/providerConfig';
108
112
  import { CostTracker } from './cost/costTracker';
109
113
  import { MemoryTree } from './memory/memoryTree';
114
+ import { EnsembleOrchestrator } from './ensemble';
110
115
 
111
116
  export interface A3MRouterOptions {
112
117
  defaultProvider?: string;
@@ -118,8 +123,7 @@ export interface A3MRouterOptions {
118
123
  export function createA3MRouter(options?: A3MRouterOptions) {
119
124
  const costTracker = new CostTracker();
120
125
  const memoryTree = new MemoryTree();
121
-
122
- return {
126
+ const router = {
123
127
  route: routeQuery,
124
128
  routeBatch,
125
129
  recommendForTask,
@@ -127,8 +131,14 @@ export function createA3MRouter(options?: A3MRouterOptions) {
127
131
  healthCheck,
128
132
  costTracker,
129
133
  memoryTree,
134
+ ensemble: new EnsembleOrchestrator(null as any), // Lazy initialization or pass router instance
130
135
  options: options || {},
131
136
  };
137
+
138
+ // Properly link the orchestrator back to the router methods
139
+ (router.ensemble as any).router = router;
140
+
141
+ return router;
132
142
  }
133
143
 
134
144
  // Default export
@@ -0,0 +1,536 @@
1
+ /**
2
+ * A3M Router - Generic Adaptive Routing (RouteLLM Style)
3
+ *
4
+ * Routes queries to the best available LLM based on:
5
+ * - Query features (code, math, creative, etc.)
6
+ * - Provider availability (checks API keys)
7
+ * - Cost optimization
8
+ * - Quality vs speed tradeoff
9
+ *
10
+ * All provider references are dynamically loaded from providerConfig.
11
+ * Users can add/remove providers via environment variables or config files.
12
+ */
13
+
14
+ import { getAvailableProviders } from "../providers/providerConfig";
15
+ import { estimateCost } from "../utils/tokenUtils";
16
+
17
+ // ============================================================
18
+ // CACHE FOR MODEL PROFILES (avoids O(n*m) rebuild on every routeQuery)
19
+ // ============================================================
20
+
21
+ interface ModelProfile {
22
+ name: string;
23
+ provider: string;
24
+ providerName: string;
25
+ cost_per_1k_input: number;
26
+ cost_per_1k_output: number;
27
+ latency_ms: number;
28
+ quality_score: number;
29
+ strengths: string[];
30
+ context_window: number;
31
+ type: string;
32
+ priority: number;
33
+ }
34
+
35
+ let cachedProfiles: Record<string, ModelProfile> | null = null;
36
+ let cacheTimestamp = 0;
37
+ const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
38
+
39
+ function buildModelProfiles(): Record<string, ModelProfile> {
40
+ const profiles: Record<string, ModelProfile> = {};
41
+ const available = getAvailableProviders();
42
+
43
+ for (const [providerId, provider] of Object.entries(available)) {
44
+ for (const model of provider.models) {
45
+ const modelKey = model.includes('/') ? model : providerId + '/' + model;
46
+ const costPerKInput = provider.costPerK ? provider.costPerK.input : 0;
47
+ const costPerKOutput = provider.costPerK ? provider.costPerK.output : 0;
48
+
49
+ // Assign strengths based on model characteristics
50
+ const strengths: string[] = [];
51
+ if (provider.type === 'cli') {
52
+ strengths.push('free', 'local');
53
+ }
54
+ if (costPerKInput < 0.3) {
55
+ strengths.push('budget', 'fast');
56
+ } else if (costPerKInput > 2) {
57
+ strengths.push('premium', 'reasoning');
58
+ }
59
+ if (provider.name === 'Mistral' || provider.name === 'Groq' || provider.name === 'Cerebras') {
60
+ strengths.push('fast', 'coding');
61
+ }
62
+ if (provider.name === 'CommandCode') {
63
+ strengths.push('code-aware', 'context-rich');
64
+ }
65
+ if (provider.name === 'OpenCode') {
66
+ strengths.push('free', 'multi-model');
67
+ }
68
+ if (provider.name === 'Google') {
69
+ strengths.push('multilingual', 'long-context');
70
+ }
71
+ if (provider.name === 'OpenAI') {
72
+ strengths.push('reasoning', 'coding', 'analysis');
73
+ }
74
+ if (provider.name === 'Anthropic') {
75
+ strengths.push('reasoning', 'creative', 'analysis');
76
+ }
77
+
78
+ profiles[modelKey] = {
79
+ name: modelKey,
80
+ provider: providerId,
81
+ providerName: provider.name,
82
+ cost_per_1k_input: costPerKInput,
83
+ cost_per_1k_output: costPerKOutput,
84
+ latency_ms: provider.type === 'cli' ? 5000 : (provider.priority * 200 + 300),
85
+ quality_score: strengths.includes('premium') ? 0.95 :
86
+ strengths.includes('reasoning') ? 0.90 :
87
+ strengths.includes('fast') ? 0.82 : 0.80,
88
+ strengths,
89
+ context_window: provider.maxTokens || 8192,
90
+ type: provider.type,
91
+ priority: provider.priority,
92
+ };
93
+ }
94
+ }
95
+
96
+ return profiles;
97
+ }
98
+
99
+ // Lazy cache with TTL - replaces refreshModelProfiles()
100
+ function getModelProfiles(): Record<string, ModelProfile> {
101
+ const now = Date.now();
102
+ if (!cachedProfiles || (now - cacheTimestamp) > CACHE_TTL_MS) {
103
+ cachedProfiles = buildModelProfiles();
104
+ cacheTimestamp = now;
105
+ }
106
+ return cachedProfiles;
107
+ }
108
+
109
+ // Manual cache invalidation (call if provider config changes)
110
+ function invalidateProfileCache(): void {
111
+ cachedProfiles = null;
112
+ cacheTimestamp = 0;
113
+ }
114
+
115
+ export let MODEL_PROFILES: Record<string, ModelProfile> = {};
116
+ try {
117
+ MODEL_PROFILES = buildModelProfiles();
118
+ } catch (e) {
119
+ // Circular dependency at module load — will retry on first use
120
+ MODEL_PROFILES = {};
121
+ }
122
+
123
+ // ============================================================
124
+ // FEATURE EXTRACTION (v3 — multi-signal complexity scorer)
125
+ // ============================================================
126
+
127
+ export interface QueryFeatures {
128
+ length: number;
129
+ wordCount: number;
130
+ complexity: number;
131
+ has_code: boolean;
132
+ requires_reasoning: boolean;
133
+ is_multilingual: boolean;
134
+ is_translation: boolean;
135
+ domain: string | null;
136
+ intent: string;
137
+ detected_language: string | null;
138
+ }
139
+
140
+ export function extractQueryFeatures(prompt: string): QueryFeatures {
141
+ const lower = prompt.toLowerCase();
142
+ const words = prompt.split(/\s+/);
143
+ const wordCount = words.length;
144
+
145
+ // === SIGNAL 1: Domain Detection ===
146
+ const domainSignals: Record<string, { keywords: string[]; weight: number }> = {
147
+ legal: {
148
+ keywords: ['legal', 'law', 'contract', 'liability', 'litigation', 'patent', 'copyright',
149
+ 'regulation', 'compliance', 'constitutional', 'statute', 'jurisdiction',
150
+ 'court', 'ruling', 'precedent', 'attorney', 'amicus', 'sec ', 'fda ',
151
+ 'gdpr', 'ccpa', 'cfpr', 'due diligence', 'merger', 'acquisition',
152
+ '10-k', 'sec filing', 'forensic', 'embezzlement', 'infringement'],
153
+ weight: 0.35
154
+ },
155
+ medical: {
156
+ keywords: ['clinical', 'medical', 'pharmaceutical', 'oncology', 'drug', 'trial protocol',
157
+ 'diagnosis', 'treatment', 'epidemiolog', 'genome', 'cohort study',
158
+ 'biomarker', 'efficacy', 'pharmacoeconomic', 'biologic', 'vaccine',
159
+ 'sepsis', 'ehr ', 'surgical', 'patient safety', 'fda approval'],
160
+ weight: 0.35
161
+ },
162
+ finance: {
163
+ keywords: ['financial model', 'valuation', 'revenue', 'portfolio', 'derivative',
164
+ 'hedge fund', 'series a', 'series b', 'startup valuation', 'sensitivity analysis',
165
+ 'investment thesis', 'earnings', 'tax optimization', 'forensic accounting',
166
+ 'multinational', 'jurisdiction', 'risk assessment', 'monte carlo',
167
+ 'black-scholes', 'options pricing', 'credit risk'],
168
+ weight: 0.30
169
+ },
170
+ security: {
171
+ keywords: ['security audit', 'penetration', 'vulnerability', 'exploit', 'zero-trust',
172
+ 'threat model', 'incident response', 'malware', 'ransomware',
173
+ 'authentication flow', 'cryptograph', 'encryption', 'timing attack',
174
+ 'supply chain attack', 'owasp', 'compliance', 'risk assessment',
175
+ 'mfa', 'zero-day', 'firewall', 'intrusion'],
176
+ weight: 0.30
177
+ },
178
+ architecture: {
179
+ keywords: ['system design', 'microservice', 'distributed system', 'fault-tolerant',
180
+ 'event-sourced', 'cqrs', 'consensus algorithm', 'real-time pipeline',
181
+ 'high availability', 'multi-region', 'latency sla', 'kafka',
182
+ 'event-driven', 'data warehouse', 'etl', 'streaming', '1m events',
183
+ 'million events', 'scalab', 'infrastruct', 'deploy'],
184
+ weight: 0.25
185
+ },
186
+ data_science: {
187
+ keywords: ['machine learning', 'deep learning', 'neural network', 'transformer',
188
+ 'training data', 'model accuracy', 'hyperparameter', 'cross-validation',
189
+ 'feature engineering', 'data pipeline', 'pandas', 'numpy', 'scikit',
190
+ 'tensorflow', 'pytorch', 'regression', 'classification', 'clustering'],
191
+ weight: 0.30
192
+ },
193
+ };
194
+
195
+ let detectedDomain: string | null = null;
196
+ let maxDomainScore = 0;
197
+ for (const [domain, signal] of Object.entries(domainSignals)) {
198
+ let domainScore = 0;
199
+ for (const kw of signal.keywords) {
200
+ if (lower.includes(kw)) {
201
+ domainScore += signal.weight;
202
+ }
203
+ }
204
+ if (domainScore > maxDomainScore) {
205
+ maxDomainScore = domainScore;
206
+ detectedDomain = domain;
207
+ }
208
+ }
209
+
210
+ // === SIGNAL 2: Code Detection ===
211
+ const codeSignals = [
212
+ 'function ', 'def ', 'class ', 'import ', 'from ', 'const ', 'let ', 'var ',
213
+ '=>', '->', 'async ', 'await ', 'return ', 'if (', 'for (', 'while (',
214
+ 'public ', 'private ', 'protected ', 'static ', 'void ', 'int ', 'string ',
215
+ '#include', 'std::', 'cout', 'cin', 'printf(', 'println!',
216
+ 'fn ', 'impl ', 'pub ', 'mut ', 'struct ', 'enum ',
217
+ '```', 'code', 'python', 'javascript', 'typescript', 'java', 'cpp', 'ruby',
218
+ 'write a', 'create a', 'implement', 'algorithm'
219
+ ];
220
+ const hasCode = codeSignals.some(sig => lower.includes(sig));
221
+
222
+ // === SIGNAL 3: Reasoning Detection ===
223
+ const reasoningSignals = [
224
+ 'why', 'how', 'explain', 'analyze', 'compare', 'contrast', 'evaluate',
225
+ 'think about', 'reason', 'logic', 'proof', 'derive', '证明', '分析',
226
+ 'reasoning', 'step by step', 'thinking', 'thought process'
227
+ ];
228
+ const requiresReasoning = reasoningSignals.some(sig => lower.includes(sig));
229
+
230
+ // === SIGNAL 4: Language Detection ===
231
+ const languagePatterns: [RegExp, string][] = [
232
+ [/[\u4e00-\u9fff]/, 'zh'],
233
+ [/[\u0900-\u097f]/, 'hi'],
234
+ [/[\u0600-\u06ff]/, 'ar'],
235
+ [/[\u0400-\u04ff]/, 'ru'],
236
+ [/[\u0900-\u097f]/, 'hi-latn'],
237
+ [/বাংলা|করুন|হিন্দি|ভারত|ভারতীয়/, 'bn'],
238
+ ];
239
+
240
+ let detectedLanguage: string | null = null;
241
+ for (const [pattern, lang] of languagePatterns) {
242
+ if (pattern.test(prompt)) {
243
+ detectedLanguage = lang;
244
+ break;
245
+ }
246
+ }
247
+
248
+ // Translation detection
249
+ const translationSignals = ['translate', 'translation', 'into english', 'to english',
250
+ 'traducir', 'traduction', 'traduzione', 'übersetzen'];
251
+ const isTranslation = translationSignals.some(sig => lower.includes(sig)) ||
252
+ /to (english|french|german|spanish|chinese|japanese|korean)/i.test(prompt);
253
+
254
+ const isMultilingual = detectedLanguage !== null || isTranslation;
255
+
256
+ // === SIGNAL 5: Intent Classification ===
257
+ let intent = 'general';
258
+ if (hasCode) intent = 'code';
259
+ else if (isTranslation) intent = 'translation';
260
+ else if (lower.includes('write') || lower.includes('create') || lower.includes('generate')) {
261
+ intent = 'creative';
262
+ } else if (lower.includes('explain') || lower.includes('what is') || lower.includes('how does')) {
263
+ intent = 'explanation';
264
+ } else if (lower.includes('calculate') || lower.includes('compute') || lower.includes('integral')) {
265
+ intent = 'math';
266
+ }
267
+
268
+ // === COMPLEXITY SCORING ===
269
+ // Base complexity from length
270
+ let complexity = Math.min(wordCount / 100, 1.0);
271
+
272
+ // Domain加成
273
+ if (detectedDomain) complexity += 0.2;
274
+
275
+ // Code加成
276
+ if (hasCode) complexity += 0.15;
277
+
278
+ // Reasoning加成
279
+ if (requiresReasoning) complexity += 0.15;
280
+
281
+ // Multilingual加成
282
+ if (isMultilingual) complexity += 0.1;
283
+
284
+ // Cap at 1.0
285
+ complexity = Math.min(complexity, 1.0);
286
+
287
+ return {
288
+ length: prompt.length,
289
+ wordCount,
290
+ complexity,
291
+ has_code: hasCode,
292
+ requires_reasoning: requiresReasoning,
293
+ is_multilingual: isMultilingual,
294
+ is_translation: isTranslation,
295
+ domain: detectedDomain,
296
+ intent,
297
+ detected_language: detectedLanguage,
298
+ };
299
+ }
300
+
301
+ function scoreModelFit(model: ModelProfile, features: QueryFeatures): number {
302
+ let score = model.quality_score * 0.6;
303
+
304
+ // Domain match
305
+ if (features.domain) {
306
+ const domainBonus: Record<string, string[]> = {
307
+ code: ['code-aware', 'coding', 'fast'],
308
+ medical: ['reasoning', 'analysis'],
309
+ legal: ['reasoning', 'analysis', 'context-rich'],
310
+ finance: ['analysis', 'reasoning'],
311
+ security: ['reasoning', 'analysis'],
312
+ architecture: ['context-rich', 'long-context'],
313
+ data_science: ['coding', 'fast', 'reasoning'],
314
+ };
315
+ const bonuses = domainBonus[features.domain] || [];
316
+ if (bonuses.some(b => model.strengths.includes(b))) {
317
+ score += 0.2;
318
+ }
319
+ }
320
+
321
+ // Code bonus
322
+ if (features.has_code && model.strengths.includes('coding')) {
323
+ score += 0.15;
324
+ }
325
+
326
+ // Multilingual bonus
327
+ if (features.is_multilingual && model.strengths.includes('multilingual')) {
328
+ score += 0.15;
329
+ }
330
+
331
+ // Free tier preference for simple queries
332
+ if (features.complexity < 0.5 && model.strengths.includes('free')) {
333
+ score += 0.2;
334
+ }
335
+
336
+ // Fast provider for simple queries
337
+ if (features.complexity < 0.4 && model.strengths.includes('fast')) {
338
+ score += 0.15;
339
+ }
340
+
341
+ // Premium for complex queries
342
+ if (features.complexity > 0.6 && model.strengths.includes('premium')) {
343
+ score += 0.15;
344
+ }
345
+
346
+ return Math.min(score, 1.0);
347
+ }
348
+
349
+ function costEfficiency(model: ModelProfile, features: QueryFeatures): number {
350
+ const avg_cost = (model.cost_per_1k_input + model.cost_per_1k_output) / 2;
351
+ if (features.complexity < 0.5) {
352
+ return (1 - Math.min(avg_cost / 10, 1)) * 0.6;
353
+ }
354
+ return (1 - Math.min(avg_cost / 10, 1)) * 0.2;
355
+ }
356
+
357
+ // ============================================================
358
+ // ROUTING
359
+ // ============================================================
360
+
361
+ export interface RouteDecision {
362
+ primary_model: string | null;
363
+ fallback_models: string[];
364
+ confidence: number;
365
+ reasoning: string;
366
+ estimated_cost: number;
367
+ estimated_latency_ms: number;
368
+ features?: QueryFeatures;
369
+ provider_type?: string;
370
+ }
371
+
372
+ export function routeQuery(prompt: string, available_models?: string[], budget_multiplier: number = 1.0): RouteDecision {
373
+ // Use cached profiles instead of rebuilding every time (5-10ms savings)
374
+ const profiles = getModelProfiles();
375
+
376
+ const features = extractQueryFeatures(prompt);
377
+ const candidate_names = available_models || Object.keys(profiles);
378
+
379
+ // Filter to available models
380
+ const candidates = candidate_names
381
+ .filter(name => profiles[name])
382
+ .map(name => {
383
+ const profile = profiles[name];
384
+ const quality = scoreModelFit(profile, features);
385
+ const cost = costEfficiency(profile, features);
386
+ return {
387
+ name,
388
+ profile,
389
+ quality_score: quality,
390
+ cost_score: cost,
391
+ total_score: quality + cost
392
+ };
393
+ });
394
+
395
+ if (candidates.length === 0) {
396
+ return {
397
+ primary_model: null,
398
+ fallback_models: [],
399
+ confidence: 0,
400
+ reasoning: "No providers available - configure API keys in ~/.config/a3m-router/providers.json",
401
+ estimated_cost: 0,
402
+ estimated_latency_ms: 0,
403
+ };
404
+ }
405
+
406
+ // Sort by total score (quality vs cost tradeoff based on complexity)
407
+ const complexity_bias = features.complexity > 0.6 ? 0.7 : 0.3;
408
+ candidates.sort((a, b) => {
409
+ const score_a = a.quality_score * complexity_bias + a.cost_score * (1 - complexity_bias);
410
+ const score_b = b.quality_score * complexity_bias + b.cost_score * (1 - complexity_bias);
411
+ return score_b - score_a;
412
+ });
413
+
414
+ const primary = candidates[0];
415
+ const secondary = candidates.slice(1, 3);
416
+
417
+ // Calculate confidence based on score gap
418
+ let confidence = 0.5;
419
+ if (candidates.length > 1) {
420
+ const gap = primary.total_score - candidates[1].total_score;
421
+ confidence = Math.min(0.95, 0.5 + gap * 2);
422
+ }
423
+
424
+ // Build reasoning
425
+ const reasons: string[] = [];
426
+ if (features.has_code) reasons.push("code detected");
427
+ if (features.requires_reasoning) reasons.push("reasoning needed");
428
+ if (features.complexity > 0.6) reasons.push("high complexity");
429
+ if (features.is_multilingual) reasons.push("multilingual");
430
+ if (features.is_translation) reasons.push("translation");
431
+ if (primary.profile.strengths.includes("free")) reasons.push("free tier");
432
+
433
+ const estimated_tokens = features.length * 1.5;
434
+ const estimated_cost = estimateCost(features.length, estimated_tokens, primary.name);
435
+
436
+ return {
437
+ primary_model: primary.name,
438
+ fallback_models: secondary.map(c => c.name),
439
+ confidence,
440
+ reasoning: `Selected ${primary.profile.providerName || primary.profile.provider}/${primary.name} for ${reasons.join(", ") || "general query"}`,
441
+ estimated_cost: estimated_cost * budget_multiplier,
442
+ estimated_latency_ms: primary.profile.latency_ms,
443
+ features,
444
+ provider_type: primary.profile.type,
445
+ };
446
+ }
447
+
448
+ // ============================================================
449
+ // BATCH ROUTING
450
+ // ============================================================
451
+
452
+ export function routeBatch(prompts: string[], options: {
453
+ same_model?: boolean;
454
+ max_cost_per_prompt?: number;
455
+ } = {}): RouteDecision[] {
456
+ const decisions = prompts.map(p => routeQuery(p));
457
+
458
+ if (options.same_model && decisions.length > 0) {
459
+ const primary_model = decisions[0].primary_model;
460
+ decisions.forEach(d => {
461
+ d.primary_model = primary_model;
462
+ d.fallback_models = decisions[0].fallback_models;
463
+ });
464
+ }
465
+
466
+ if (options.max_cost_per_prompt !== undefined) {
467
+ const profiles = getModelProfiles();
468
+ decisions.forEach(d => {
469
+ if (d.estimated_cost > options.max_cost_per_prompt!) {
470
+ const cheap = Object.entries(profiles)
471
+ .find(([name, p]) => p.cost_per_1k_input < 0.5);
472
+ if (cheap) {
473
+ d.primary_model = cheap[0];
474
+ d.reasoning = `Budget-limited routing to ${cheap[1].providerName || cheap[1].provider}`;
475
+ }
476
+ }
477
+ });
478
+ }
479
+
480
+ return decisions;
481
+ }
482
+
483
+ // ============================================================
484
+ // TASK RECOMMENDATIONS
485
+ // ============================================================
486
+
487
+ export function recommendForTask(task: string) {
488
+ const features = extractQueryFeatures(task);
489
+ const decision = routeQuery(task);
490
+ return {
491
+ primary: decision.primary_model,
492
+ fallbacks: decision.fallback_models,
493
+ reason: decision.reasoning,
494
+ features,
495
+ };
496
+ }
497
+
498
+ // ============================================================
499
+ // ONLINE LEARNING - Update model profiles from feedback
500
+ // ============================================================
501
+
502
+ export function updateModelProfile(model_name: string, actual_latency_ms: number, actual_cost: number, quality_rating: number): void {
503
+ const profiles = getModelProfiles();
504
+ const profile = profiles[model_name];
505
+ if (!profile) return;
506
+
507
+ const alpha = 0.2; // Learning rate
508
+ profile.latency_ms = profile.latency_ms * (1 - alpha) + actual_latency_ms * alpha;
509
+ profile.quality_score = profile.quality_score * (1 - alpha) + quality_rating * alpha;
510
+ }
511
+
512
+ // ============================================================
513
+ // PROVIDER HEALTH CHECK
514
+ // ============================================================
515
+
516
+ export async function getProviderHealth() {
517
+ const { checkAllProviders } = require("../providers/providerConfig");
518
+ return checkAllProviders();
519
+ }
520
+
521
+ // ============================================================
522
+ // Default export
523
+ // ============================================================
524
+
525
+ module.exports = {
526
+ extractQueryFeatures,
527
+ routeQuery,
528
+ routeBatch,
529
+ recommendForTask,
530
+ updateModelProfile,
531
+ getProviderHealth,
532
+ MODEL_PROFILES,
533
+ invalidateProfileCache,
534
+ };
535
+
536
+ module.exports.default = module.exports;