-
Notifications
You must be signed in to change notification settings - Fork 508
Expand file tree
/
Copy pathmodel-discovery.service.spec.ts
More file actions
2084 lines (1758 loc) · 70.1 KB
/
Copy pathmodel-discovery.service.spec.ts
File metadata and controls
2084 lines (1758 loc) · 70.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ModelDiscoveryService } from './model-discovery.service';
import { ProviderModelFetcherService } from './provider-model-fetcher.service';
import { ProviderModelRegistryService } from './provider-model-registry.service';
import { UserProvider } from '../entities/user-provider.entity';
import { CustomProvider } from '../entities/custom-provider.entity';
import { DiscoveredModel } from './model-fetcher';
import { buildSubscriptionFallbackModels, supplementWithKnownModels } from './model-fallback';
jest.mock('../common/utils/crypto.util', () => ({
decrypt: jest.fn(),
getEncryptionSecret: jest.fn(),
}));
jest.mock('../database/quality-score.util', () => ({
computeQualityScore: jest.fn().mockReturnValue(3),
}));
import { decrypt, getEncryptionSecret } from '../common/utils/crypto.util';
import { computeQualityScore } from '../database/quality-score.util';
const mockDecrypt = decrypt as jest.MockedFunction<typeof decrypt>;
const mockGetSecret = getEncryptionSecret as jest.MockedFunction<typeof getEncryptionSecret>;
const mockComputeScore = computeQualityScore as jest.MockedFunction<typeof computeQualityScore>;
function makeModel(overrides: Partial<DiscoveredModel> = {}): DiscoveredModel {
return {
id: 'test-model',
displayName: 'Test Model',
provider: 'openai',
contextWindow: 128000,
inputPricePerToken: null,
outputPricePerToken: null,
capabilityReasoning: false,
capabilityCode: false,
qualityScore: 3,
...overrides,
};
}
function makeProvider(overrides: Partial<UserProvider> = {}): UserProvider {
return {
id: 'prov-1',
user_id: 'user-1',
agent_id: 'agent-1',
provider: 'openai',
api_key_encrypted: 'encrypted-key',
key_prefix: 'sk-',
auth_type: 'api_key',
is_active: true,
connected_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
cached_models: null,
models_fetched_at: null,
...overrides,
} as UserProvider;
}
function makeCustomProvider(overrides: Partial<CustomProvider> = {}): CustomProvider {
return {
id: 'cp-1',
agent_id: 'agent-1',
user_id: 'user-1',
name: 'My Custom',
base_url: 'http://localhost:8000',
models: [
{
model_name: 'custom-llm',
input_price_per_million_tokens: 1.5,
output_price_per_million_tokens: 3.0,
context_window: 32000,
},
],
created_at: new Date().toISOString(),
...overrides,
} as CustomProvider;
}
function makeMockRepo() {
return {
find: jest.fn().mockResolvedValue([]),
findOne: jest.fn().mockResolvedValue(null),
save: jest.fn().mockImplementation((e: unknown) => Promise.resolve(e)),
};
}
describe('ModelDiscoveryService', () => {
let service: ModelDiscoveryService;
let providerRepo: ReturnType<typeof makeMockRepo>;
let customProviderRepo: ReturnType<typeof makeMockRepo>;
let fetcher: { fetch: jest.Mock };
let mockPricingSync: { lookupPricing: jest.Mock; getAll: jest.Mock };
let mockModelRegistry: {
registerModels: jest.Mock;
getConfirmedModels: jest.Mock;
};
let mockModelsDevSync: { lookupModel: jest.Mock; getModelsForProvider: jest.Mock };
let mockCopilotTokenService: { getCopilotToken: jest.Mock };
beforeEach(() => {
providerRepo = makeMockRepo();
customProviderRepo = makeMockRepo();
fetcher = { fetch: jest.fn().mockResolvedValue([]) };
mockPricingSync = {
lookupPricing: jest.fn().mockReturnValue(null),
getAll: jest.fn().mockReturnValue(new Map()),
};
mockModelsDevSync = {
lookupModel: jest.fn().mockReturnValue(null),
getModelsForProvider: jest.fn().mockReturnValue([]),
};
mockModelRegistry = {
registerModels: jest.fn(),
getConfirmedModels: jest.fn().mockReturnValue(null),
};
mockCopilotTokenService = {
getCopilotToken: jest.fn().mockResolvedValue('tid=exchanged-copilot-token'),
};
mockDecrypt.mockReturnValue('decrypted-key');
mockGetSecret.mockReturnValue('secret-32-chars-long-xxxxxxxxxx');
mockComputeScore.mockReturnValue(3);
service = new ModelDiscoveryService(
providerRepo as never,
customProviderRepo as never,
fetcher as unknown as ProviderModelFetcherService,
mockPricingSync as never,
mockModelsDevSync as never,
mockModelRegistry as unknown as ProviderModelRegistryService,
mockCopilotTokenService as never,
);
});
afterEach(() => {
jest.clearAllMocks();
});
/* ── discoverModels ── */
describe('discoverModels', () => {
it('should decrypt key, fetch, enrich, and cache models', async () => {
const models = [makeModel({ id: 'gpt-4' })];
fetcher.fetch.mockResolvedValue(models);
const provider = makeProvider();
const result = await service.discoverModels(provider);
expect(mockGetSecret).toHaveBeenCalled();
expect(mockDecrypt).toHaveBeenCalledWith('encrypted-key', expect.any(String));
expect(fetcher.fetch).toHaveBeenCalledWith('openai', 'decrypted-key', 'api_key', undefined);
expect(result).toHaveLength(1);
expect(provider.cached_models).toEqual(result);
expect(provider.models_fetched_at).toBeDefined();
expect(providerRepo.save).toHaveBeenCalledWith(provider);
});
it('should return [] when decrypt fails', async () => {
mockDecrypt.mockImplementation(() => {
throw new Error('bad key');
});
const result = await service.discoverModels(makeProvider());
expect(result).toEqual([]);
expect(fetcher.fetch).not.toHaveBeenCalled();
});
it('should pass empty string as key when no encrypted key', async () => {
const provider = makeProvider({ api_key_encrypted: null });
fetcher.fetch.mockResolvedValue([]);
await service.discoverModels(provider);
expect(mockDecrypt).not.toHaveBeenCalled();
expect(fetcher.fetch).toHaveBeenCalledWith('openai', '', 'api_key', undefined);
});
it('should enrich models with openRouter pricing when available', async () => {
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'openai/gpt-4') {
return {
input: 0.00003,
output: 0.00006,
contextWindow: 200000,
displayName: 'GPT-4 via OR',
};
}
return null;
});
const models = [makeModel({ id: 'gpt-4' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('openai/gpt-4');
expect(result[0].inputPricePerToken).toBe(0.00003);
expect(result[0].outputPricePerToken).toBe(0.00006);
expect(result[0].contextWindow).toBe(200000);
expect(result[0].displayName).toBe('GPT-4 via OR');
});
it('should use model contextWindow when openRouter has no contextWindow', async () => {
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'openai/gpt-4') {
return { input: 0.00003, output: 0.00006 };
}
return null;
});
const models = [makeModel({ id: 'gpt-4', contextWindow: 8192 })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(result[0].contextWindow).toBe(8192);
});
it('should keep model displayName when openRouter displayName is empty', async () => {
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'openai/gpt-4') {
return { input: 0.00003, output: 0.00006, displayName: '' };
}
return null;
});
const models = [makeModel({ id: 'gpt-4', displayName: 'GPT-4' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(result[0].displayName).toBe('GPT-4');
});
it('should keep null pricing when pricingSync lookup returns null', async () => {
const models = [makeModel({ id: 'unknown-model' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(result[0].inputPricePerToken).toBeNull();
expect(result[0].outputPricePerToken).toBeNull();
});
it('should keep null pricing when pricingSync is null', async () => {
const serviceNoPricing = new ModelDiscoveryService(
providerRepo as never,
customProviderRepo as never,
fetcher as unknown as ProviderModelFetcherService,
null,
null,
null,
null,
);
const models = [makeModel({ id: 'some-model' })];
fetcher.fetch.mockResolvedValue(models);
const result = await serviceNoPricing.discoverModels(makeProvider());
expect(result[0].inputPricePerToken).toBeNull();
});
it('should keep null pricing when no pricing source available', async () => {
const models = [makeModel({ id: 'unknown-model' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(result[0].inputPricePerToken).toBeNull();
expect(result[0].outputPricePerToken).toBeNull();
});
it('should skip enrichment when fetcher already provided pricing', async () => {
const models = [
makeModel({
id: 'priced-model',
inputPricePerToken: 0.001,
outputPricePerToken: 0.002,
}),
];
fetcher.fetch.mockResolvedValue(models);
await service.discoverModels(makeProvider());
expect(mockPricingSync.lookupPricing).not.toHaveBeenCalled();
});
it('should call computeQualityScore for enriched models', async () => {
mockComputeScore.mockReturnValue(5);
const models = [makeModel({ id: 'gpt-4' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(mockComputeScore).toHaveBeenCalledWith(
expect.objectContaining({ model_name: 'gpt-4' }),
);
expect(result[0].qualityScore).toBe(5);
});
it('should register models in registry after successful native fetch', async () => {
const models = [makeModel({ id: 'gpt-4o' }), makeModel({ id: 'gpt-4-turbo' })];
fetcher.fetch.mockResolvedValue(models);
await service.discoverModels(makeProvider());
expect(mockModelRegistry.registerModels).toHaveBeenCalledWith('openai', [
'gpt-4o',
'gpt-4-turbo',
]);
});
it('should not register models when native fetch returns empty', async () => {
fetcher.fetch.mockResolvedValue([]);
await service.discoverModels(makeProvider());
expect(mockModelRegistry.registerModels).not.toHaveBeenCalled();
});
it('should pass confirmed models to buildFallbackModels when native fetch fails', async () => {
fetcher.fetch.mockResolvedValue([]);
const confirmed = new Set(['gpt-4o']);
mockModelRegistry.getConfirmedModels.mockReturnValue(confirmed);
// Set up OpenRouter cache with matching models
const orMap = new Map([
['openai/gpt-4o', { input: 0.01, output: 0.02, displayName: 'GPT-4o' }],
['openai/phantom', { input: 0.01, output: 0.02, displayName: 'Phantom' }],
]);
mockPricingSync.getAll.mockReturnValue(orMap);
const result = await service.discoverModels(makeProvider());
expect(mockModelRegistry.getConfirmedModels).toHaveBeenCalledWith('openai');
// Only confirmed model should be in fallback
expect(result).toHaveLength(1);
expect(result[0].id).toBe('gpt-4o');
});
it('should not call registry when modelRegistry is null', async () => {
const serviceNoRegistry = new ModelDiscoveryService(
providerRepo as never,
customProviderRepo as never,
fetcher as unknown as ProviderModelFetcherService,
mockPricingSync as never,
mockModelsDevSync as never,
null,
null,
);
const models = [makeModel({ id: 'gpt-4o' })];
fetcher.fetch.mockResolvedValue(models);
await serviceNoRegistry.discoverModels(makeProvider());
expect(mockModelRegistry.registerModels).not.toHaveBeenCalled();
});
});
/* ── discoverAllForAgent ── */
describe('discoverAllForAgent', () => {
it('should discover models for all active non-custom providers', async () => {
const providers = [
makeProvider({ id: 'p1', provider: 'openai' }),
makeProvider({ id: 'p2', provider: 'anthropic' }),
];
providerRepo.find.mockResolvedValue(providers);
fetcher.fetch.mockResolvedValue([]);
await service.discoverAllForAgent('agent-1');
expect(providerRepo.find).toHaveBeenCalledWith({
where: { agent_id: 'agent-1', is_active: true },
});
expect(fetcher.fetch).toHaveBeenCalledTimes(2);
});
it('should skip custom providers', async () => {
const providers = [
makeProvider({ id: 'p1', provider: 'openai' }),
makeProvider({ id: 'p2', provider: 'custom:my-provider' }),
];
providerRepo.find.mockResolvedValue(providers);
fetcher.fetch.mockResolvedValue([]);
await service.discoverAllForAgent('agent-1');
expect(fetcher.fetch).toHaveBeenCalledTimes(1);
});
it('should not throw when individual discovery fails', async () => {
const providers = [
makeProvider({ id: 'p1', provider: 'openai' }),
makeProvider({ id: 'p2', provider: 'anthropic' }),
];
providerRepo.find.mockResolvedValue(providers);
fetcher.fetch.mockResolvedValue([]);
// Make providerRepo.save throw on first call to trigger .catch handler
providerRepo.save
.mockRejectedValueOnce(new Error('DB write failed'))
.mockResolvedValueOnce({});
await expect(service.discoverAllForAgent('agent-1')).resolves.not.toThrow();
});
});
/* ── getModelsForAgent ── */
describe('getModelsForAgent', () => {
it('should merge cached models from providers and custom providers', async () => {
const cachedModels = [makeModel({ id: 'gpt-4', provider: 'openai' })];
const providers = [makeProvider({ cached_models: cachedModels })];
providerRepo.find.mockResolvedValue(providers);
const customProviders = [makeCustomProvider()];
customProviderRepo.find.mockResolvedValue(customProviders);
const result = await service.getModelsForAgent('agent-1');
expect(result).toHaveLength(2);
expect(result[0].id).toBe('gpt-4');
expect(result[1].id).toBe('custom:cp-1/custom-llm');
expect(result[1].provider).toBe('custom:cp-1');
expect(result[1].displayName).toBe('custom-llm');
});
it('should deduplicate models by id', async () => {
const providers = [
makeProvider({
id: 'p1',
provider: 'openai',
cached_models: [makeModel({ id: 'gpt-4' })],
}),
makeProvider({
id: 'p2',
provider: 'deepseek',
cached_models: [makeModel({ id: 'gpt-4' })],
}),
];
providerRepo.find.mockResolvedValue(providers);
customProviderRepo.find.mockResolvedValue([]);
const result = await service.getModelsForAgent('agent-1');
expect(result).toHaveLength(1);
});
it('should skip providers with no cached_models', async () => {
const providers = [makeProvider({ cached_models: null })];
providerRepo.find.mockResolvedValue(providers);
customProviderRepo.find.mockResolvedValue([]);
const result = await service.getModelsForAgent('agent-1');
expect(result).toEqual([]);
});
it('should skip custom: prefixed providers from main loop', async () => {
const providers = [
makeProvider({
provider: 'custom:provider-x',
cached_models: [makeModel({ id: 'custom-model' })],
}),
];
providerRepo.find.mockResolvedValue(providers);
customProviderRepo.find.mockResolvedValue([]);
const result = await service.getModelsForAgent('agent-1');
expect(result).toEqual([]);
});
it('should handle custom provider with no models array', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([makeCustomProvider({ models: null as never })]);
const result = await service.getModelsForAgent('agent-1');
expect(result).toEqual([]);
});
it('should handle custom provider with null pricing', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([
makeCustomProvider({
models: [
{
model_name: 'free-model',
input_price_per_million_tokens: undefined,
output_price_per_million_tokens: undefined,
},
],
}),
]);
const result = await service.getModelsForAgent('agent-1');
expect(result).toHaveLength(1);
expect(result[0].inputPricePerToken).toBeNull();
expect(result[0].outputPricePerToken).toBeNull();
});
it('should compute per-token prices from per-million-token prices', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([makeCustomProvider()]);
const result = await service.getModelsForAgent('agent-1');
expect(result[0].inputPricePerToken).toBeCloseTo(1.5 / 1_000_000);
expect(result[0].outputPricePerToken).toBeCloseTo(3.0 / 1_000_000);
});
it('should default custom model context window to 128000', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([
makeCustomProvider({
models: [{ model_name: 'no-ctx' }],
}),
]);
const result = await service.getModelsForAgent('agent-1');
expect(result[0].contextWindow).toBe(128000);
});
it('should deduplicate custom provider models by composite key', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([
makeCustomProvider({
id: 'cp-1',
models: [{ model_name: 'dup-model' }, { model_name: 'dup-model' }],
}),
]);
const result = await service.getModelsForAgent('agent-1');
expect(result).toHaveLength(1);
});
it('should read capability_reasoning from custom provider model data', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([
makeCustomProvider({
models: [
{
model_name: 'reasoning-model',
capability_reasoning: true,
capability_code: false,
},
],
}),
]);
const result = await service.getModelsForAgent('agent-1');
expect(result[0].capabilityReasoning).toBe(true);
expect(result[0].capabilityCode).toBe(false);
});
it('should read capability_code from custom provider model data', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([
makeCustomProvider({
models: [
{
model_name: 'code-model',
capability_reasoning: false,
capability_code: true,
},
],
}),
]);
const result = await service.getModelsForAgent('agent-1');
expect(result[0].capabilityReasoning).toBe(false);
expect(result[0].capabilityCode).toBe(true);
});
it('should default capabilities to false for legacy custom provider models', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([
makeCustomProvider({
models: [{ model_name: 'legacy-model' }],
}),
]);
const result = await service.getModelsForAgent('agent-1');
expect(result[0].capabilityReasoning).toBe(false);
expect(result[0].capabilityCode).toBe(false);
});
it('should compute quality score dynamically for custom provider models', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([
makeCustomProvider({
models: [
{
model_name: 'scored-model',
input_price_per_million_tokens: 15,
output_price_per_million_tokens: 75,
capability_reasoning: true,
capability_code: true,
},
],
}),
]);
const result = await service.getModelsForAgent('agent-1');
expect(mockComputeScore).toHaveBeenCalledWith({
model_name: 'custom:cp-1/scored-model',
input_price_per_token: 15 / 1_000_000,
output_price_per_token: 75 / 1_000_000,
capability_reasoning: true,
capability_code: true,
context_window: 128000,
});
expect(result[0].qualityScore).toBe(3); // mock returns 3
});
});
/* ── getModelForAgent ── */
describe('getModelForAgent', () => {
it('should return the matching model', async () => {
providerRepo.find.mockResolvedValue([
makeProvider({
cached_models: [makeModel({ id: 'gpt-4' }), makeModel({ id: 'gpt-3.5' })],
}),
]);
customProviderRepo.find.mockResolvedValue([]);
const result = await service.getModelForAgent('agent-1', 'gpt-4');
expect(result).toBeDefined();
expect(result!.id).toBe('gpt-4');
});
it('should return undefined for missing model', async () => {
providerRepo.find.mockResolvedValue([]);
customProviderRepo.find.mockResolvedValue([]);
const result = await service.getModelForAgent('agent-1', 'nonexistent');
expect(result).toBeUndefined();
});
});
/* ── enrichModel edge cases via discoverModels ── */
describe('enrichModel (via discoverModels)', () => {
it('should preserve zero pricing from fetcher (free/subscription models)', async () => {
// inputPricePerToken is 0 (free/subscription), enrichment should NOT override
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'openai/free-model') {
return { input: 0.001, output: 0.002 };
}
return null;
});
const models = [
makeModel({ id: 'free-model', inputPricePerToken: 0, outputPricePerToken: 0 }),
];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
// Price=0 means "free/included" — should not be overwritten
expect(result[0].inputPricePerToken).toBe(0);
expect(result[0].outputPricePerToken).toBe(0);
});
it('should apply capabilities from models.dev even when pricing is already set', async () => {
// Copilot/subscription model has price=0 but needs capability flags for scoring
mockModelsDevSync.lookupModel.mockImplementation((providerId: string, modelId: string) => {
if (modelId === 'copilot-model') {
return {
id: 'copilot-model',
name: 'Copilot Model',
inputPricePerToken: 0.000005, // pricing should NOT be applied
outputPricePerToken: 0.000025,
reasoning: true,
toolCall: true,
};
}
return null;
});
const models = [
makeModel({
id: 'copilot-model',
inputPricePerToken: 0,
outputPricePerToken: 0,
capabilityReasoning: false,
capabilityCode: false,
}),
];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
// Pricing preserved as 0 (not overwritten)
expect(result[0].inputPricePerToken).toBe(0);
expect(result[0].outputPricePerToken).toBe(0);
// Capabilities applied from models.dev
expect(result[0].capabilityReasoning).toBe(true);
expect(result[0].capabilityCode).toBe(true);
});
it('should fall back to exact model ID lookup when prefix lookup misses', async () => {
// Prefix lookup returns null, but exact model ID lookup returns pricing
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'openai/special-model') return null;
if (key === 'special-model') {
return { input: 0.0001, output: 0.0002, contextWindow: 64000, displayName: 'Special' };
}
return null;
});
const models = [makeModel({ id: 'special-model' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('openai/special-model');
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('special-model');
expect(result[0].inputPricePerToken).toBe(0.0001);
expect(result[0].outputPricePerToken).toBe(0.0002);
expect(result[0].contextWindow).toBe(64000);
expect(result[0].displayName).toBe('Special');
});
it('should resolve prefix via displayName when provider ID is not a prefix', async () => {
// 'Mistral' is the displayName for prefix 'mistralai' in OPENROUTER_PREFIX_TO_PROVIDER
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'mistralai/mistral-large') {
return { input: 0.00002, output: 0.00006 };
}
return null;
});
const models = [makeModel({ id: 'mistral-large' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider({ provider: 'Mistral' }));
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('mistralai/mistral-large');
expect(result[0].inputPricePerToken).toBe(0.00002);
expect(result[0].outputPricePerToken).toBe(0.00006);
});
it('should use models.dev pricing before OpenRouter when available', async () => {
mockModelsDevSync.lookupModel.mockImplementation((providerId: string, modelId: string) => {
if (providerId === 'openai' && modelId === 'gpt-4o') {
return {
id: 'gpt-4o',
name: 'GPT-4o',
inputPricePerToken: 0.0000025,
outputPricePerToken: 0.00001,
contextWindow: 128000,
reasoning: false,
};
}
return null;
});
// OpenRouter also has pricing but should NOT be used
mockPricingSync.lookupPricing.mockReturnValue({
input: 0.99,
output: 0.99,
displayName: 'Wrong',
});
const models = [makeModel({ id: 'gpt-4o' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(result[0].inputPricePerToken).toBe(0.0000025);
expect(result[0].outputPricePerToken).toBe(0.00001);
expect(result[0].displayName).toBe('GPT-4o');
});
it('should propagate capabilities from models.dev to quality scoring', async () => {
mockModelsDevSync.lookupModel.mockReturnValue({
id: 'claude-opus-4-6',
name: 'Claude Opus 4.6',
inputPricePerToken: 0.000005,
outputPricePerToken: 0.000025,
contextWindow: 1000000,
reasoning: true,
toolCall: true,
});
const models = [
makeModel({ id: 'claude-opus-4-6', capabilityReasoning: false, capabilityCode: false }),
];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider({ provider: 'anthropic' }));
expect(result[0].capabilityReasoning).toBe(true);
expect(result[0].capabilityCode).toBe(true);
});
it('should fall through to OpenRouter when models.dev has no match', async () => {
mockModelsDevSync.lookupModel.mockReturnValue(null);
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'openai/new-model') {
return { input: 0.001, output: 0.002, displayName: 'New Model' };
}
return null;
});
const models = [makeModel({ id: 'new-model' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(result[0].inputPricePerToken).toBe(0.001);
expect(result[0].displayName).toBe('New Model');
});
it('should skip prefix lookup when provider has no OpenRouter prefix', async () => {
// Use a provider that has no OpenRouter prefix mapping
const models = [makeModel({ id: 'unknown-model' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider({ provider: 'unknown-provider' }));
// lookupPricing should still be called for exact match (model.id)
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('unknown-model');
expect(result[0].inputPricePerToken).toBeNull();
});
it('should use model defaults when exact match has no contextWindow or displayName', async () => {
// No prefix found, exact match returns pricing without optional fields
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'bare-model') {
return { input: 0.0005, output: 0.001 };
}
return null;
});
const models = [makeModel({ id: 'bare-model', contextWindow: 4096, displayName: 'Bare' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider({ provider: 'unknown-provider' }));
expect(result[0].inputPricePerToken).toBe(0.0005);
expect(result[0].contextWindow).toBe(4096);
expect(result[0].displayName).toBe('Bare');
});
it('should call computeQualityScore with null pricing when no source available', async () => {
mockComputeScore.mockReturnValue(2);
const models = [makeModel({ id: 'unknown-model' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider());
expect(mockComputeScore).toHaveBeenCalledWith(
expect.objectContaining({
model_name: 'unknown-model',
input_price_per_token: null,
output_price_per_token: null,
}),
);
expect(result[0].qualityScore).toBe(2);
});
it('should call computeQualityScore even when no pricing is found', async () => {
const models = [makeModel({ id: 'no-pricing-model' })];
fetcher.fetch.mockResolvedValue(models);
await service.discoverModels(makeProvider());
expect(mockComputeScore).toHaveBeenCalledWith(
expect.objectContaining({
model_name: 'no-pricing-model',
input_price_per_token: null,
output_price_per_token: null,
}),
);
});
it('should resolve pricing via dash-to-dot normalization', async () => {
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'anthropic/claude-sonnet-4.6') {
return { input: 0.00003, output: 0.00015 };
}
return null;
});
const models = [makeModel({ id: 'claude-sonnet-4-6' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider({ provider: 'anthropic' }));
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('anthropic/claude-sonnet-4-6');
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('anthropic/claude-sonnet-4.6');
expect(result[0].inputPricePerToken).toBe(0.00003);
expect(result[0].outputPricePerToken).toBe(0.00015);
});
it('should resolve pricing via dot-to-dash normalization', async () => {
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'anthropic/claude-sonnet-4-6') {
return { input: 0.00003, output: 0.00015 };
}
return null;
});
const models = [makeModel({ id: 'claude-sonnet-4.6' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider({ provider: 'anthropic' }));
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('anthropic/claude-sonnet-4.6');
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('anthropic/claude-sonnet-4-6');
expect(result[0].inputPricePerToken).toBe(0.00003);
expect(result[0].outputPricePerToken).toBe(0.00015);
});
it('should resolve pricing by stripping date suffix', async () => {
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'anthropic/claude-sonnet-4-5') {
return { input: 0.00003, output: 0.00015 };
}
return null;
});
const models = [makeModel({ id: 'claude-sonnet-4-5-20250929' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider({ provider: 'anthropic' }));
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith(
'anthropic/claude-sonnet-4-5-20250929',
);
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('anthropic/claude-sonnet-4-5');
expect(result[0].inputPricePerToken).toBe(0.00003);
});
it('should resolve pricing by stripping date suffix then applying dot variant', async () => {
mockPricingSync.lookupPricing.mockImplementation((key: string) => {
if (key === 'anthropic/claude-sonnet-4.5') {
return { input: 0.00003, output: 0.00015 };
}
return null;
});
const models = [makeModel({ id: 'claude-sonnet-4-5-20250929' })];
fetcher.fetch.mockResolvedValue(models);
const result = await service.discoverModels(makeProvider({ provider: 'anthropic' }));
expect(mockPricingSync.lookupPricing).toHaveBeenCalledWith('anthropic/claude-sonnet-4.5');
expect(result[0].inputPricePerToken).toBe(0.00003);
});
it('should build fallback models from OpenRouter cache when native API returns empty', async () => {
fetcher.fetch.mockResolvedValue([]);
const orMap = new Map([
[
'anthropic/claude-opus-4.6',
{
input: 0.000015,
output: 0.000075,
contextWindow: 200000,
displayName: 'Claude Opus 4.6',
},
],
[
'anthropic/claude-sonnet-4.6',
{
input: 0.000003,
output: 0.000015,
contextWindow: 200000,
displayName: 'Claude Sonnet 4.6',
},
],
[
'openai/gpt-4o',
{
input: 0.0000025,
output: 0.00001,
contextWindow: 128000,
displayName: 'GPT-4o',
},
],
]);
mockPricingSync.getAll.mockReturnValue(orMap);
const result = await service.discoverModels(makeProvider({ provider: 'anthropic' }));
expect(result).toHaveLength(2);
expect(result[0].id).toBe('claude-opus-4-6');
expect(result[0].displayName).toBe('Claude Opus 4.6');
expect(result[0].inputPricePerToken).toBe(0.000015);
expect(result[0].provider).toBe('anthropic');
expect(result[1].id).toBe('claude-sonnet-4-6');
});
it('should unwrap OAuth blob for OpenAI subscription before fetching', async () => {
const blob = JSON.stringify({
t: 'access-token-123',
r: 'refresh-tok',
e: Date.now() + 60000,