Spaces:
Sleeping

File size: 36,522 Bytes
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ec3c9b
 
 
9713441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { db, AUDIO_CACHE_DIR, UPLOADS_DIR } from '../db/database.js';
import {
  encryptSecret,
  decryptSecret,
  maskSecret,
  isMaskedOrEmptySecret,
} from '../db/crypto.js';
import type {
  AIProviderProfile,
  AIModelRecord,
  AIRoleRoutingEntry,
  AIRoleKey,
  AIConnectionTestResult,
  AIProviderProtocol,
  AIModelCapability,
} from '@olokaflow/shared';

export function normalizeBaseUrl(baseUrl: string, protocol?: AIProviderProtocol): string {
  let clean = String(baseUrl || '').trim();
  if (!clean) return '';

  try {
    const parsed = new URL(clean);
    parsed.hash = '';
    parsed.search = '';
    clean = parsed.toString();
  } catch {
    // keep raw string if partial
  }

  clean = clean.replace(/\/+$/, '');
  const suffixes = [
    '/chat/completions',
    '/completions',
    '/responses',
    '/embeddings',
    '/models',
    '/messages',
    '/audio/speech',
    '/audio/transcriptions',
    '/images/generations',
  ];

  const lower = clean.toLowerCase();
  for (const suffix of suffixes) {
    if (lower.endsWith(suffix)) {
      clean = clean.slice(0, -suffix.length).replace(/\/+$/, '');
      break;
    }
  }

  try {
    const parsed = new URL(clean);
    if (
      (protocol === 'gemini' || parsed.hostname === 'generativelanguage.googleapis.com') &&
      !parsed.pathname.includes('/openai')
    ) {
      clean = 'https://generativelanguage.googleapis.com/v1beta/openai';
    }
  } catch {
    // ignore
  }

  return clean;
}

function rowToProfile(row: any, includePlainKey = false): AIProviderProfile {
  const plainKey = decryptSecret(row.encrypted_api_key || '');
  let customHeaders: Record<string, string> = {};
  let models: AIModelRecord[] = [];
  try {
    customHeaders = JSON.parse(row.custom_headers_json || '{}');
  } catch {}
  try {
    models = JSON.parse(row.models_json || '[]');
  } catch {}

  return {
    id: row.id,
    name: row.name,
    protocol: row.protocol as AIProviderProtocol,
    baseUrl: row.base_url,
    apiKey: includePlainKey ? plainKey : '',
    hasApiKey: Boolean(plainKey),
    maskedApiKey: maskSecret(row.encrypted_api_key || ''),
    customHeaders,
    timeoutMs: Number(row.timeout_ms || 180000),
    maxConcurrency: Number(row.max_concurrency || 4),
    enabled: Boolean(row.enabled),
    notes: row.notes || '',
    healthStatus: row.health_status || 'untested',
    lastTestedAt: row.last_tested_at || null,
    lastLatencyMs: row.last_latency_ms ?? null,
    lastTestMessage: row.last_test_message || '',
    models,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  };
}

export function listAIProfiles(includePlainKey = false): AIProviderProfile[] {
  const rows = db.prepare('SELECT * FROM ai_provider_profiles ORDER BY created_at ASC').all();
  return rows.map((r) => rowToProfile(r, includePlainKey));
}

export function getAIProfileById(id: string, includePlainKey = false): AIProviderProfile | null {
  const row = db.prepare('SELECT * FROM ai_provider_profiles WHERE id = ?').get(id);
  if (!row) return null;
  return rowToProfile(row, includePlainKey);
}

export function saveAIProfile(input: Partial<AIProviderProfile> & { name: string; baseUrl: string; protocol: AIProviderProtocol }): AIProviderProfile {
  const now = new Date().toISOString();
  const existingRow = input.id
    ? (db.prepare('SELECT * FROM ai_provider_profiles WHERE id = ?').get(input.id) as any)
    : null;

  const id = existingRow ? existingRow.id : input.id || `prof-${crypto.randomUUID().slice(0, 8)}`;
  const cleanUrl = normalizeBaseUrl(input.baseUrl, input.protocol);

  let encryptedKey = existingRow ? existingRow.encrypted_api_key : '';
  if (input.apiKey !== undefined && !isMaskedOrEmptySecret(input.apiKey)) {
    encryptedKey = encryptSecret(input.apiKey.trim());
  } else if (input.apiKey === '' && !existingRow) {
    encryptedKey = '';
  }

  const customHeaders = input.customHeaders ?? (existingRow ? JSON.parse(existingRow.custom_headers_json || '{}') : {});
  const models = input.models ?? (existingRow ? JSON.parse(existingRow.models_json || '[]') : []);

  if (existingRow) {
    db.prepare(`
      UPDATE ai_provider_profiles SET
        name = ?,
        protocol = ?,
        base_url = ?,
        encrypted_api_key = ?,
        custom_headers_json = ?,
        timeout_ms = ?,
        max_concurrency = ?,
        enabled = ?,
        notes = ?,
        models_json = ?,
        updated_at = ?
      WHERE id = ?
    `).run(
      input.name,
      input.protocol,
      cleanUrl,
      encryptedKey,
      JSON.stringify(customHeaders),
      input.timeoutMs ?? existingRow.timeout_ms ?? 180000,
      input.maxConcurrency ?? existingRow.max_concurrency ?? 4,
      input.enabled === undefined ? existingRow.enabled : input.enabled ? 1 : 0,
      input.notes ?? existingRow.notes ?? '',
      JSON.stringify(models),
      now,
      id
    );
  } else {
    db.prepare(`
      INSERT INTO ai_provider_profiles (
        id, name, protocol, base_url, encrypted_api_key, custom_headers_json,
        timeout_ms, max_concurrency, enabled, notes, health_status,
        last_tested_at, last_latency_ms, last_test_message, models_json,
        created_at, updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `).run(
      id,
      input.name,
      input.protocol,
      cleanUrl,
      encryptedKey,
      JSON.stringify(customHeaders),
      input.timeoutMs ?? 180000,
      input.maxConcurrency ?? 4,
      input.enabled === false ? 0 : 1,
      input.notes ?? '',
      'untested',
      null,
      null,
      'Chưa kiểm tra kết nối',
      JSON.stringify(models),
      now,
      now
    );
  }

  return getAIProfileById(id, false)!;
}

export function deleteAIProfile(id: string): boolean {
  const res = db.prepare('DELETE FROM ai_provider_profiles WHERE id = ?').run(id);
  return res.changes > 0;
}

export function duplicateAIProfile(id: string): AIProviderProfile | null {
  const source = getAIProfileById(id, true);
  if (!source) return null;
  return saveAIProfile({
    ...source,
    id: `prof-${crypto.randomUUID().slice(0, 8)}`,
    name: `${source.name} (Bản sao)`,
  });
}

function inferModelCapabilities(modelId: string, raw: any): AIModelCapability[] {
  const lower = modelId.toLowerCase();
  const caps = new Set<AIModelCapability>();

  if (lower.includes('embed') || lower.includes('bge')) {
    caps.add('embedding');
    return Array.from(caps);
  }
  if (lower.includes('tts') || lower.includes('speech') || lower.includes('omnivoice')) {
    caps.add('tts');
    return Array.from(caps);
  }
  if (lower.includes('whisper') || lower.includes('asr') || lower.includes('transcribe')) {
    caps.add('asr');
    return Array.from(caps);
  }
  if (lower.includes('flux') || lower.includes('dall-e') || lower.includes('sdxl') || lower.includes('imagen')) {
    caps.add('image_gen');
    return Array.from(caps);
  }

  caps.add('chat');
  caps.add('coding');
  caps.add('json_mode');

  if (
    lower.includes('vl') ||
    lower.includes('vision') ||
    lower.includes('4o') ||
    lower.includes('gemini') ||
    lower.includes('claude-3') ||
    lower.includes('omni') ||
    lower.includes('pixtral')
  ) {
    caps.add('vision');
  }
  if (
    lower.includes('r1') ||
    lower.includes('reasoner') ||
    lower.includes('o1') ||
    lower.includes('o3') ||
    lower.includes('thinking') ||
    lower.includes('gemini-2.5') ||
    raw?.reasoning === true
  ) {
    caps.add('reasoning');
  }

  return Array.from(caps);
}

function getFallbackProviderCatalog(baseUrl: string, protocol: AIProviderProtocol): AIModelRecord[] {
  const lowerUrl = baseUrl.toLowerCase();
  const createRec = (modelId: string, name: string, caps: AIModelCapability[], thinking = false): AIModelRecord => ({
    id: `mdl-${modelId.replace(/[^a-zA-Z0-9_-]/g, '-')}`,
    modelId,
    name,
    ownedBy: protocol,
    capabilities: caps,
    supportsThinking: thinking,
    reasoningEffort: thinking ? 'medium' : 'none',
    maxTokens: 8192,
    healthStatus: 'untested',
    lastTestedAt: null,
    ttftMs: null,
    durationMs: null,
    lastTestMessage: '',
  });

  if (protocol === 'gemini' || lowerUrl.includes('googleapis.com')) {
    return [
      createRec('gemini-2.5-flash', 'Gemini 2.5 Flash (Vision + Fast Code)', ['chat', 'coding', 'vision', 'reasoning', 'json_mode'], true),
      createRec('gemini-2.5-pro', 'Gemini 2.5 Pro (Director + Deep Code)', ['chat', 'coding', 'vision', 'reasoning', 'json_mode'], true),
      createRec('gemini-2.0-flash', 'Gemini 2.0 Flash', ['chat', 'coding', 'vision', 'json_mode'], false),
    ];
  }
  if (protocol === 'anthropic' || lowerUrl.includes('anthropic.com')) {
    return [
      createRec('claude-3-7-sonnet-20250219', 'Claude 3.7 Sonnet (Motion & Code)', ['chat', 'coding', 'vision', 'reasoning', 'json_mode'], true),
      createRec('claude-3-5-sonnet-20241022', 'Claude 3.5 Sonnet', ['chat', 'coding', 'vision', 'json_mode'], false),
      createRec('claude-3-5-haiku-20241022', 'Claude 3.5 Haiku (Fast Edit)', ['chat', 'coding', 'json_mode'], false),
    ];
  }
  if (lowerUrl.includes('xiaomimimo.com')) {
    return [
      createRec('mimo-v2.5-pro', 'MiMo-V2.5-Pro', ['chat', 'coding', 'reasoning', 'json_mode'], true),
      createRec('mimo-v2.5-pro-ultraspeed', 'MiMo-V2.5-Pro-UltraSpeed', ['chat', 'coding', 'reasoning', 'json_mode'], true),
      createRec('mimo-v2-omni', 'MiMo-V2-Omni (Vision)', ['chat', 'coding', 'vision', 'json_mode'], true),
    ];
  }
  if (lowerUrl.includes('deepseek.com')) {
    return [
      createRec('deepseek-chat', 'DeepSeek V3 Chat', ['chat', 'coding', 'json_mode'], false),
      createRec('deepseek-reasoner', 'DeepSeek R1 Reasoner', ['chat', 'coding', 'reasoning', 'json_mode'], true),
    ];
  }
  if (protocol === 'huggingface') {
    return [
      createRec('black-forest-labs/FLUX.1-schnell', 'FLUX.1 Schnell (Fast Image Gen)', ['image_gen'], false),
      createRec('black-forest-labs/FLUX.1-dev', 'FLUX.1 Dev (HD Image Gen)', ['image_gen'], false),
    ];
  }
  if (protocol === 'openai-voice') {
    return [
      createRec('tts-1-hd', 'OpenAI TTS-1-HD', ['tts'], false),
      createRec('tts-1', 'OpenAI TTS-1 Standard', ['tts'], false),
      createRec('whisper-1', 'Whisper-1 Word Timestamps', ['asr'], false),
    ];
  }

  return [];
}

/**
 * Fetches available models from an endpoint (`/models`) or merges with known catalog fallback.
 */
export async function fetchModelsFromEndpoint(params: {
  profileId?: string;
  baseUrl?: string;
  apiKey?: string;
  protocol?: AIProviderProtocol;
  customHeaders?: Record<string, string>;
}): Promise<{
  success: boolean;
  models: AIModelRecord[];
  source: 'endpoint' | 'fallback';
  message: string;
}> {
  const existing = params.profileId ? getAIProfileById(params.profileId, true) : null;
  const protocol = params.protocol || existing?.protocol || 'openai-compatible';
  const baseUrl = normalizeBaseUrl(params.baseUrl || existing?.baseUrl || '', protocol);
  const apiKey =
    params.apiKey && !isMaskedOrEmptySecret(params.apiKey)
      ? params.apiKey.trim()
      : existing?.apiKey || '';
  const customHeaders = params.customHeaders || existing?.customHeaders || {};

  if (!baseUrl) {
    throw new Error('Chưa nhập API Base URL.');
  }

  const candidateUrls = [`${baseUrl}/models`];
  try {
    const u = new URL(baseUrl);
    if (!u.pathname.match(/\/v\d+/)) {
      candidateUrls.push(`${u.origin}/v1/models`);
    }
  } catch {}

  const errors: string[] = [];
  for (const url of candidateUrls) {
    try {
      const headers: Record<string, string> = {
        Accept: 'application/json',
        ...customHeaders,
      };
      if (apiKey) {
        if (protocol === 'anthropic' || url.includes('anthropic.com')) {
          headers['x-api-key'] = apiKey;
          headers['anthropic-version'] = '2023-06-01';
        } else {
          headers['Authorization'] = `Bearer ${apiKey}`;
        }
      }

      const resp = await fetch(url, {
        method: 'GET',
        headers,
        signal: AbortSignal.timeout(10000),
      });

      if (!resp.ok) {
        errors.push(`${url} -> HTTP ${resp.status}`);
        continue;
      }

      const payload = (await resp.json()) as any;
      const rawList = Array.isArray(payload?.data)
        ? payload.data
        : Array.isArray(payload?.models)
          ? payload.models
          : Array.isArray(payload)
            ? payload
            : [];

      if (rawList.length > 0) {
        const models: AIModelRecord[] = rawList
          .map((item: any) => {
            const modelId = typeof item === 'string' ? item : item.id || item.name || item.model || '';
            if (!modelId) return null;
            const caps = inferModelCapabilities(modelId, item);
            const supportsThinking = caps.includes('reasoning');
            return {
              id: `mdl-${modelId.replace(/[^a-zA-Z0-9_-]/g, '-')}`,
              modelId,
              name: item.display_name || item.name || modelId,
              ownedBy: item.owned_by || item.provider || protocol,
              capabilities: caps,
              supportsThinking,
              reasoningEffort: supportsThinking ? 'medium' : 'none',
              maxTokens: Number(item.context_length || item.max_tokens || 8192),
              healthStatus: 'untested',
              lastTestedAt: null,
              ttftMs: null,
              durationMs: null,
              lastTestMessage: '',
            } as AIModelRecord;
          })
          .filter(Boolean) as AIModelRecord[];

        if (existing) {
          saveAIProfile({ ...existing, models });
        }

        return {
          success: true,
          models,
          source: 'endpoint',
          message: `Đã quét thành công ${models.length} model trực tiếp từ ${url}.`,
        };
      }
    } catch (err: any) {
      errors.push(`${url}: ${err.message}`);
    }
  }

  const fallbackModels = getFallbackProviderCatalog(baseUrl, protocol);
  if (fallbackModels.length > 0) {
    if (existing) {
      saveAIProfile({ ...existing, models: fallbackModels });
    }
    return {
      success: true,
      models: fallbackModels,
      source: 'fallback',
      message: `Endpoint không mở /models (${errors.join('; ')}); đã nạp ${fallbackModels.length} model chuẩn cho ${protocol}.`,
    };
  }

  throw new Error(`Không thể lấy danh sách model từ ${baseUrl}. Chi tiết: ${errors.join(' | ')}`);
}

/**
 * TEST 1: Ping & Authentication Connection Test
 */
export async function testProfileConnection(params: {
  profileId?: string;
  baseUrl?: string;
  apiKey?: string;
  protocol?: AIProviderProtocol;
  modelId?: string;
  customHeaders?: Record<string, string>;
}): Promise<AIConnectionTestResult> {
  const existing = params.profileId ? getAIProfileById(params.profileId, true) : null;
  const protocol = params.protocol || existing?.protocol || 'openai-compatible';
  const baseUrl = normalizeBaseUrl(params.baseUrl || existing?.baseUrl || '', protocol);
  const apiKey =
    params.apiKey && !isMaskedOrEmptySecret(params.apiKey)
      ? params.apiKey.trim()
      : existing?.apiKey || '';
  const customHeaders = params.customHeaders || existing?.customHeaders || {};
  const testedAt = new Date().toISOString();
  const startTime = Date.now();

  if (!baseUrl) {
    return {
      success: false,
      testType: 'connection',
      durationMs: 0,
      message: 'Chưa nhập API Base URL.',
      error: 'Missing baseUrl',
      testedAt,
    };
  }

  try {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      ...customHeaders,
    };
    if (apiKey) {
      if (protocol === 'anthropic') {
        headers['x-api-key'] = apiKey;
        headers['anthropic-version'] = '2023-06-01';
      } else {
        headers['Authorization'] = `Bearer ${apiKey}`;
      }
    }

    let testUrl = `${baseUrl}/models`;
    let method = 'GET';
    let body: string | undefined;

    if (protocol === 'modal-render') {
      testUrl = `${baseUrl.replace(/\/api\/render$/i, '')}/health`;
      method = 'GET';
    } else if (protocol === 'huggingface' || baseUrl.includes('huggingface.co')) {
      testUrl = 'https://huggingface.co/api/whoami-v2';
      method = 'GET';
    } else if (baseUrl.includes('tts.oloka.net')) {
      testUrl = `${baseUrl.replace(/\/v1$/i, '')}/v1/voices`;
      method = 'GET';
    } else if (protocol === 'anthropic') {
      testUrl = `${baseUrl}/messages`;
      method = 'POST';
      body = JSON.stringify({
        model: params.modelId || existing?.models?.[0]?.modelId || 'claude-3-5-haiku-20241022',
        messages: [{ role: 'user', content: 'ping' }],
        max_tokens: 8,
      });
    }

    let resp = await fetch(testUrl, {
      method,
      headers,
      body,
      signal: AbortSignal.timeout(10000),
    });

    // If GET /models is 404 on a custom OpenAI gateway, fallback to POST /chat/completions ping
    if (!resp.ok && resp.status === 404 && protocol === 'openai-compatible') {
      const modelToPing = params.modelId || existing?.models?.[0]?.modelId || 'gpt-4o';
      resp = await fetch(`${baseUrl}/chat/completions`, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          model: modelToPing,
          messages: [{ role: 'user', content: 'ping' }],
          max_tokens: 5,
        }),
        signal: AbortSignal.timeout(10000),
      });
    }

    const durationMs = Date.now() - startTime;
    const text = await resp.text();

    if (text.trim().startsWith('<!DOCTYPE html') || text.trim().startsWith('<html')) {
      throw new Error('Server trả về trang HTML (có thể bị chặn bởi Cloudflare hoặc sai đường dẫn API).');
    }

    if (!resp.ok) {
      let errMsg = `HTTP ${resp.status}`;
      try {
        const json = JSON.parse(text);
        errMsg = json.error?.message || json.message || errMsg;
      } catch {}
      throw new Error(errMsg);
    }

    const message = `Kết nối thành công tới ${baseUrl} (${durationMs}ms, HTTP ${resp.status}).`;
    if (existing) {
      db.prepare(`
        UPDATE ai_provider_profiles
        SET health_status = 'healthy', last_tested_at = ?, last_latency_ms = ?, last_test_message = ?
        WHERE id = ?
      `).run(testedAt, durationMs, message, existing.id);
    }

    return {
      success: true,
      testType: 'connection',
      profileId: existing?.id,
      protocol,
      statusCode: resp.status,
      durationMs,
      message,
      testedAt,
    };
  } catch (err: any) {
    const durationMs = Date.now() - startTime;
    const errMsg = `Kết nối thất bại: ${err.message}`;
    if (existing) {
      db.prepare(`
        UPDATE ai_provider_profiles
        SET health_status = 'failed', last_tested_at = ?, last_latency_ms = ?, last_test_message = ?
        WHERE id = ?
      `).run(testedAt, durationMs, errMsg, existing.id);
    }
    return {
      success: false,
      testType: 'connection',
      profileId: existing?.id,
      protocol,
      durationMs,
      message: errMsg,
      error: err.message,
      testedAt,
    };
  }
}

/**
 * TEST 2: Deep Model Preflight Benchmark (TTFT ms, SSE Stream, JSON Validation, Sample Output)
 */
export async function testModelPreflight(params: {
  profileId?: string;
  baseUrl?: string;
  apiKey?: string;
  protocol?: AIProviderProtocol;
  modelId: string;
  reasoningEffort?: string;
  customHeaders?: Record<string, string>;
}): Promise<AIConnectionTestResult> {
  const existing = params.profileId ? getAIProfileById(params.profileId, true) : null;
  const protocol = params.protocol || existing?.protocol || 'openai-compatible';
  const baseUrl = normalizeBaseUrl(params.baseUrl || existing?.baseUrl || '', protocol);
  const apiKey =
    params.apiKey && !isMaskedOrEmptySecret(params.apiKey)
      ? params.apiKey.trim()
      : existing?.apiKey || '';
  const customHeaders = params.customHeaders || existing?.customHeaders || {};
  const modelId = (params.modelId || '').trim();
  const testedAt = new Date().toISOString();

  if (!baseUrl || !modelId) {
    return {
      success: false,
      testType: 'model_preflight',
      durationMs: 0,
      message: 'Thiếu Base URL hoặc Model ID cần kiểm tra.',
      testedAt,
    };
  }

  const startTime = Date.now();
  let ttftMs: number | null = null;
  let streamMode = 'non-stream';

  try {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      ...customHeaders,
    };
    if (apiKey) {
      if (protocol === 'anthropic') {
        headers['x-api-key'] = apiKey;
        headers['anthropic-version'] = '2023-06-01';
      } else {
        headers['Authorization'] = `Bearer ${apiKey}`;
      }
    }

    const targetUrl =
      protocol === 'anthropic' ? `${baseUrl}/messages` : `${baseUrl}/chat/completions`;

    const messages = [
      {
        role: 'system',
        content:
          'You are OlokaFlow HyperFrames preflight checker. Reply ONLY with a valid JSON object: {"ready": true, "engine": "hyperframes", "model": "<your_model>", "greeting_vi": "Sẵn sàng dựng video chuyên nghiệp!"}',
      },
      {
        role: 'user',
        content: 'Run preflight JSON & responsiveness check.',
      },
    ];

    const bodyObj: Record<string, any> = {
      model: modelId,
      messages,
      max_tokens: 160,
      stream: protocol !== 'anthropic',
    };

    if (params.reasoningEffort && params.reasoningEffort !== 'none') {
      bodyObj.reasoning_effort = params.reasoningEffort;
    }

    const resp = await fetch(targetUrl, {
      method: 'POST',
      headers,
      body: JSON.stringify(bodyObj),
      signal: AbortSignal.timeout(25000),
    });

    if (!resp.ok) {
      const errText = await resp.text();
      throw new Error(`HTTP ${resp.status}: ${errText.slice(0, 240)}`);
    }

    const contentType = resp.headers.get('content-type') || '';
    let fullContent = '';

    if (contentType.includes('text/event-stream') && resp.body) {
      streamMode = 'sse-stream';
      const reader = resp.body.getReader();
      const decoder = new TextDecoder();
      let buffer = '';

      while (true) {
        const { value, done } = await reader.read();
        if (done) break;
        if (ttftMs === null) {
          ttftMs = Date.now() - startTime;
        }
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';
        for (const line of lines) {
          const trimmed = line.trim();
          if (!trimmed.startsWith('data:')) continue;
          const dataStr = trimmed.slice(5).trim();
          if (dataStr === '[DONE]') continue;
          try {
            const parsed = JSON.parse(dataStr);
            const delta = parsed.choices?.[0]?.delta?.content || '';
            fullContent += delta;
          } catch {}
        }
      }
    } else {
      const json = (await resp.json()) as any;
      ttftMs = Date.now() - startTime;
      fullContent =
        json.choices?.[0]?.message?.content ||
        json.content?.[0]?.text ||
        JSON.stringify(json);
    }

    const durationMs = Date.now() - startTime;
    let isJson = false;
    try {
      const cleaned = fullContent
        .trim()
        .replace(/^```(?:json)?\s*/i, '')
        .replace(/\s*```$/, '')
        .trim();
      JSON.parse(cleaned);
      isJson = true;
    } catch {}

    const msg = `Model "${modelId}" hoạt động tốt! TTFT: ${ttftMs || durationMs}ms | Tổng: ${(durationMs / 1000).toFixed(2)}s | Chế độ: ${streamMode} | Output: ${isJson ? 'JSON Chuẩn ✓' : 'Text'}`;

    if (existing) {
      const updatedModels = existing.models.map((m) =>
        m.modelId === modelId
          ? {
              ...m,
              healthStatus: (durationMs < 12000 ? 'healthy' : 'degraded') as any,
              lastTestedAt: testedAt,
              ttftMs: ttftMs || durationMs,
              durationMs,
              lastTestMessage: msg,
            }
          : m
      );
      saveAIProfile({
        ...existing,
        healthStatus: 'healthy',
        lastTestedAt: testedAt,
        lastLatencyMs: ttftMs || durationMs,
        lastTestMessage: msg,
        models: updatedModels,
      });
    }

    return {
      success: true,
      testType: 'model_preflight',
      profileId: existing?.id,
      modelId,
      protocol,
      durationMs,
      ttftMs: ttftMs || durationMs,
      streamMode,
      isJson,
      sampleOutput: fullContent.slice(0, 300),
      message: msg,
      testedAt,
    };
  } catch (err: any) {
    const durationMs = Date.now() - startTime;
    const errMsg = `Lỗi test model "${modelId}": ${err.message}`;

    if (existing) {
      const updatedModels = existing.models.map((m) =>
        m.modelId === modelId
          ? {
              ...m,
              healthStatus: 'failed' as const,
              lastTestedAt: testedAt,
              durationMs,
              lastTestMessage: errMsg,
            }
          : m
      );
      saveAIProfile({ ...existing, models: updatedModels });
    }

    return {
      success: false,
      testType: 'model_preflight',
      profileId: existing?.id,
      modelId,
      protocol,
      durationMs,
      message: errMsg,
      error: err.message,
      testedAt,
    };
  }
}

/**
 * TEST 3: Vision Capability Test (Base64 PNG inspection)
 */
export async function testModelVision(params: {
  profileId?: string;
  baseUrl?: string;
  apiKey?: string;
  protocol?: AIProviderProtocol;
  modelId: string;
}): Promise<AIConnectionTestResult> {
  const existing = params.profileId ? getAIProfileById(params.profileId, true) : null;
  const protocol = params.protocol || existing?.protocol || 'openai-compatible';
  const baseUrl = normalizeBaseUrl(params.baseUrl || existing?.baseUrl || '', protocol);
  const apiKey =
    params.apiKey && !isMaskedOrEmptySecret(params.apiKey)
      ? params.apiKey.trim()
      : existing?.apiKey || '';
  const testedAt = new Date().toISOString();
  const startTime = Date.now();

  // 1x1 cobalt blue PNG in base64
  const samplePngDataUri =
    'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPj/HwADBwIAMCbHYQAAAABJRU5ErkJggg==';

  try {
    const resp = await fetch(`${baseUrl}/chat/completions`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
        ...(existing?.customHeaders || {}),
      },
      body: JSON.stringify({
        model: params.modelId,
        messages: [
          {
            role: 'user',
            content: [
              { type: 'text', text: 'Describe this image briefly in 5 words.' },
              { type: 'image_url', image_url: { url: samplePngDataUri } },
            ],
          },
        ],
        max_tokens: 60,
      }),
      signal: AbortSignal.timeout(20000),
    });

    const durationMs = Date.now() - startTime;
    if (!resp.ok) {
      const errText = await resp.text();
      throw new Error(`HTTP ${resp.status}: ${errText.slice(0, 200)}`);
    }
    const json = (await resp.json()) as any;
    const reply = json.choices?.[0]?.message?.content || '';

    return {
      success: true,
      testType: 'vision',
      profileId: existing?.id,
      modelId: params.modelId,
      durationMs,
      sampleOutput: reply.slice(0, 200),
      message: `Model "${params.modelId}" đọc ảnh Vision thành công trong ${durationMs}ms! Phản hồi: "${reply.slice(0, 80)}"`,
      testedAt,
    };
  } catch (err: any) {
    return {
      success: false,
      testType: 'vision',
      profileId: existing?.id,
      modelId: params.modelId,
      durationMs: Date.now() - startTime,
      message: `Model "${params.modelId}" không hỗ trợ Vision hoặc lỗi: ${err.message}`,
      error: err.message,
      testedAt,
    };
  }
}

/**
 * TEST 4: Voice TTS / Image Gen / Modal Render Live Test
 */
export async function testVoiceOrMediaEndpoint(params: {
  profileId?: string;
  testKind: 'voice' | 'image_gen' | 'modal_render';
  modelId?: string;
  voiceId?: string;
}): Promise<AIConnectionTestResult> {
  const existing = params.profileId ? getAIProfileById(params.profileId, true) : null;
  if (!existing) {
    throw new Error('Không tìm thấy Profile cần kiểm tra.');
  }

  const testedAt = new Date().toISOString();
  const startTime = Date.now();
  const baseUrl = normalizeBaseUrl(existing.baseUrl, existing.protocol);
  const apiKey = existing.apiKey;

  try {
    if (params.testKind === 'voice') {
      const isOloka = baseUrl.includes('tts.oloka.net');
      const ttsModel =
        params.modelId ||
        existing.models[0]?.modelId ||
        (isOloka ? 'olokatts-v3-turbo' : 'tts-1');
      const voice = params.voiceId || (isOloka ? 'Hải Đăng' : 'alloy');
      const speechUrl = isOloka
        ? `${baseUrl.replace(/\/v1$/i, '')}/v1/audio/speech`
        : `${baseUrl}/audio/speech`;

      const resp = await fetch(speechUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
          ...(isOloka ? { Accept: 'audio/wav' } : {}),
          ...existing.customHeaders,
        },
        body: JSON.stringify(
          isOloka
            ? {
                model: ttsModel,
                voice,
                input: 'Xin chào, hệ thống giọng nói OlokaFlow đã kết nối thành công!',
                speed: 1.0,
              }
            : {
                model: ttsModel,
                voice,
                input: 'Xin chào, hệ thống giọng nói OlokaFlow đã kết nối thành công!',
                response_format: 'mp3',
              }
        ),
        signal: AbortSignal.timeout(40000),
      });

      if (!resp.ok) {
        const errText = await resp.text();
        throw new Error(`TTS HTTP ${resp.status}: ${errText.slice(0, 200)}`);
      }

      const buf = Buffer.from(await resp.arrayBuffer());
      const ext = isOloka ? 'wav' : 'mp3';
      const fileName = `test-voice-${Date.now()}.${ext}`;
      const filePath = path.join(AUDIO_CACHE_DIR, fileName);
      fs.writeFileSync(filePath, buf);
      const durationMs = Date.now() - startTime;

      return {
        success: true,
        testType: 'voice',
        profileId: existing.id,
        modelId: ttsModel,
        durationMs,
        audioPreviewUrl: `/media/audio_cache/${fileName}`,
        message: `Sinh giọng nói TTS thành công (${(buf.length / 1024).toFixed(1)} KB trong ${durationMs}ms). Bấm Play để nghe thử!`,
        testedAt,
      };
    }

    if (params.testKind === 'image_gen') {
      const imgModel = params.modelId || existing.models[0]?.modelId || 'black-forest-labs/FLUX.1-schnell';
      let imgBuffer: Buffer;

      if (existing.protocol === 'huggingface' || baseUrl.includes('huggingface.co')) {
        const hfUrl = baseUrl.endsWith(imgModel) ? baseUrl : `${baseUrl}/${imgModel}`;
        const resp = await fetch(hfUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
          },
          body: JSON.stringify({
            inputs: 'Futuristic neon studio camera icon, minimal 3d render, dark obsidian background',
          }),
          signal: AbortSignal.timeout(30000),
        });
        if (!resp.ok) {
          throw new Error(`HF Image API HTTP ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
        }
        imgBuffer = Buffer.from(await resp.arrayBuffer());
      } else {
        const resp = await fetch(`${baseUrl}/images/generations`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
          },
          body: JSON.stringify({
            model: imgModel,
            prompt: 'Minimal 3d studio camera icon on dark background',
            n: 1,
            size: '1024x1024',
          }),
          signal: AbortSignal.timeout(30000),
        });
        if (!resp.ok) {
          throw new Error(`OpenAI Image API HTTP ${resp.status}: ${(await resp.text()).slice(0, 200)}`);
        }
        const data = (await resp.json()) as any;
        const b64 = data.data?.[0]?.b64_json;
        const url = data.data?.[0]?.url;
        if (b64) {
          imgBuffer = Buffer.from(b64, 'base64');
        } else if (url) {
          const r2 = await fetch(url);
          imgBuffer = Buffer.from(await r2.arrayBuffer());
        } else {
          throw new Error('API không trả về url hoặc b64_json.');
        }
      }

      const fileName = `test-img-${Date.now()}.png`;
      fs.writeFileSync(path.join(UPLOADS_DIR, fileName), imgBuffer);
      const durationMs = Date.now() - startTime;

      return {
        success: true,
        testType: 'image_gen',
        profileId: existing.id,
        modelId: imgModel,
        durationMs,
        imagePreviewUrl: `/media/uploads/${fileName}`,
        message: `Tạo ảnh thử nghiệm thành công bằng "${imgModel}" trong ${(durationMs / 1000).toFixed(1)}s!`,
        testedAt,
      };
    }

    // Modal Render endpoint test
    return await testProfileConnection({ profileId: existing.id });
  } catch (err: any) {
    return {
      success: false,
      testType: params.testKind,
      profileId: existing.id,
      durationMs: Date.now() - startTime,
      message: `Lỗi kiểm tra ${params.testKind}: ${err.message}`,
      error: err.message,
      testedAt,
    };
  }
}

// ============================================================================
// ROLE ROUTING MATRIX & ENDPOINT RESOLUTION WITH AUTO-FAILOVER
// ============================================================================

export function getRoleRoutings(): AIRoleRoutingEntry[] {
  const rows = db.prepare('SELECT * FROM ai_role_routings ORDER BY role ASC').all() as any[];
  return rows.map((r) => ({
    role: r.role as AIRoleKey,
    label: r.label,
    description: r.description,
    primaryProfileId: r.primary_profile_id || '',
    primaryModelId: r.primary_model_id || '',
    fallbackProfileId: r.fallback_profile_id || '',
    fallbackModelId: r.fallback_model_id || '',
  }));
}

export function saveRoleRoutings(entries: AIRoleRoutingEntry[]): AIRoleRoutingEntry[] {
  const now = new Date().toISOString();
  const stmt = db.prepare(`
    UPDATE ai_role_routings
    SET primary_profile_id = ?, primary_model_id = ?, fallback_profile_id = ?, fallback_model_id = ?, updated_at = ?
    WHERE role = ?
  `);
  for (const e of entries) {
    stmt.run(
      e.primaryProfileId || '',
      e.primaryModelId || '',
      e.fallbackProfileId || '',
      e.fallbackModelId || '',
      now,
      e.role
    );
  }
  return getRoleRoutings();
}

export interface ResolvedModelTarget {
  profile: AIProviderProfile;
  modelId: string;
  isFallback: boolean;
}

export function resolveTargetsForRole(
  role: AIRoleKey,
  overrideProfileId?: string,
  overrideModelId?: string
): ResolvedModelTarget[] {
  const allProfiles = listAIProfiles(true).filter((p) => p.enabled);
  const targets: ResolvedModelTarget[] = [];

  if (overrideProfileId) {
    const p = allProfiles.find((x) => x.id === overrideProfileId);
    if (p) {
      targets.push({
        profile: p,
        modelId: overrideModelId || p.models[0]?.modelId || 'gpt-4o',
        isFallback: false,
      });
    }
  }

  const routing = getRoleRoutings().find((r) => r.role === role);
  if (routing) {
    const primaryProf = allProfiles.find((x) => x.id === routing.primaryProfileId);
    if (primaryProf) {
      targets.push({
        profile: primaryProf,
        modelId: routing.primaryModelId || primaryProf.models[0]?.modelId || 'gpt-4o',
        isFallback: false,
      });
    }
    const fallbackProf = allProfiles.find((x) => x.id === routing.fallbackProfileId);
    if (fallbackProf) {
      targets.push({
        profile: fallbackProf,
        modelId: routing.fallbackModelId || fallbackProf.models[0]?.modelId || 'gpt-4o',
        isFallback: true,
      });
    }
  }

  return targets;
}