File size: 64,034 Bytes
cd8bd0a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
/**
 * T-07 config-hook backward-compat shim tests.
 *
 * Covers `createOmniRouteConfigHook(opts, deps)`:
 *   - happy path: valid auth.json β†’ mutates input.provider[id] with the
 *     stripped per-model shape (mirroring `@omniroute/opencode-provider`).
 *   - no-op paths: missing auth.json, malformed JSON, missing apiKey,
 *     missing baseURL, existing input.provider[id] (manual override).
 *   - fail-open: /v1/models error β†’ stub `models: {}`; /api/combos error β†’
 *     models-only static catalog.
 *   - baseURL resolution: opts.baseURL β†’ auth.json.baseURL fallback.
 *   - multi-instance: two plugins with different providerIds publish to
 *     their own keys without collision.
 *   - cache sharing: provider hook + config hook on the same Map dedupe
 *     fetcher invocations.
 *   - sibling-shape parity: emitted entries carry only
 *     `{name, attachment?, reasoning?, temperature?, tool_call?, limit?}`
 *     β€” never the rich ModelV2 nested capabilities tree.
 *
 * Mocking strategy mirrors `provider.test.ts` and `combos.test.ts`: every
 * dependency (`readAuthJson`, `fetcher`, `combosFetcher`, `now`, `cache`,
 * `logger`) is dependency-injected at hook construction. No global
 * `fs/promises` or `fetch` monkey-patch needed.
 */

import test from "node:test";
import assert from "node:assert/strict";
import type { Config } from "@opencode-ai/plugin";

import {
  buildStaticProviderEntry,
  createOmniRouteConfigHook,
  createOmniRouteProviderHook,
  OmniRoutePlugin,
  resolveOmniRoutePluginOptions,
  type OmniRouteCombosFetcher,
  type OmniRouteEnrichmentEntry,
  type OmniRouteEnrichmentFetcher,
  type OmniRouteEnrichmentMap,
  type OmniRouteFetchCache,
  type OmniRouteModelsFetcher,
  type OmniRouteProviderConnection,
  type OmniRouteProvidersFetcher,
  type OmniRouteRawCombo,
  type OmniRouteRawModelEntry,
  type OmniRouteReadAuthJson,
  type OmniRouteStaticProviderEntry,
} from "../src/index.js";

// ────────────────────────────────────────────────────────────────────────────
// Fixtures
// ────────────────────────────────────────────────────────────────────────────

const MODEL_CLAUDE: OmniRouteRawModelEntry = {
  id: "claude-sonnet-4-6",
  capabilities: {
    tool_calling: true,
    reasoning: true,
    vision: true,
    thinking: false,
    temperature: true,
  },
  context_length: 200_000,
  max_output_tokens: 64_000,
  max_input_tokens: 180_000,
  input_modalities: ["text", "image"],
  output_modalities: ["text"],
};

const MODEL_GEMINI: OmniRouteRawModelEntry = {
  id: "gemini-3-flash",
  capabilities: { tool_calling: true, reasoning: false, vision: true, thinking: false },
  context_length: 1_000_000,
  max_output_tokens: 8_192,
  input_modalities: ["text", "image"],
  output_modalities: ["text"],
};

const COMBO_CLAUDE_TIER: OmniRouteRawCombo = {
  id: "combo-claude-tier",
  name: "Claude Tier",
  models: [
    { id: "s1", kind: "model", model: "claude-sonnet-4-6", weight: 100 },
    { id: "s2", kind: "model", model: "gemini-3-flash", weight: 50 },
  ],
};

// ────────────────────────────────────────────────────────────────────────────
// Helpers (DI stubs β€” mirrors patterns in provider.test.ts / combos.test.ts)
// ────────────────────────────────────────────────────────────────────────────

function stubReadAuthJson(
  value: Record<string, unknown> | undefined | null
): OmniRouteReadAuthJson & { callCount: () => number } {
  let n = 0;
  const f: OmniRouteReadAuthJson = async () => {
    n++;
    return value as never;
  };
  return Object.assign(f, { callCount: () => n });
}

function throwingReadAuthJson(): OmniRouteReadAuthJson & { callCount: () => number } {
  let n = 0;
  const f: OmniRouteReadAuthJson = async () => {
    n++;
    throw new Error("EACCES");
  };
  return Object.assign(f, { callCount: () => n });
}

function stubModelsFetcher(
  payload: OmniRouteRawModelEntry[]
): OmniRouteModelsFetcher & { callCount: () => number; callsBy: () => Array<[string, string]> } {
  let n = 0;
  const calls: Array<[string, string]> = [];
  const f: OmniRouteModelsFetcher = async (baseURL, apiKey) => {
    n++;
    calls.push([baseURL, apiKey]);
    return payload;
  };
  return Object.assign(f, { callCount: () => n, callsBy: () => calls });
}

function stubCombosFetcher(
  payload: OmniRouteRawCombo[]
): OmniRouteCombosFetcher & { callCount: () => number; callsBy: () => Array<[string, string]> } {
  let n = 0;
  const calls: Array<[string, string]> = [];
  const f: OmniRouteCombosFetcher = async (baseURL, apiKey) => {
    n++;
    calls.push([baseURL, apiKey]);
    return payload;
  };
  return Object.assign(f, { callCount: () => n, callsBy: () => calls });
}

function throwingModelsFetcher(): OmniRouteModelsFetcher & { callCount: () => number } {
  let n = 0;
  const f: OmniRouteModelsFetcher = async () => {
    n++;
    throw new Error("ECONNREFUSED");
  };
  return Object.assign(f, { callCount: () => n });
}

function throwingCombosFetcher(): OmniRouteCombosFetcher & { callCount: () => number } {
  let n = 0;
  const f: OmniRouteCombosFetcher = async () => {
    n++;
    throw new Error("403 Forbidden");
  };
  return Object.assign(f, { callCount: () => n });
}

function stubEnrichmentFetcher(payload: OmniRouteEnrichmentMap): OmniRouteEnrichmentFetcher & {
  callCount: () => number;
  callsBy: () => Array<[string, string]>;
} {
  let n = 0;
  const calls: Array<[string, string]> = [];
  const f: OmniRouteEnrichmentFetcher = async (baseURL, apiKey) => {
    n++;
    calls.push([baseURL, apiKey]);
    return payload;
  };
  return Object.assign(f, { callCount: () => n, callsBy: () => calls });
}

function throwingEnrichmentFetcher(): OmniRouteEnrichmentFetcher & { callCount: () => number } {
  let n = 0;
  const f: OmniRouteEnrichmentFetcher = async () => {
    n++;
    throw new Error("ETIMEDOUT");
  };
  return Object.assign(f, { callCount: () => n });
}

interface WarnCapture {
  warn: (...args: unknown[]) => void;
  entries: unknown[][];
}

function captureWarn(): WarnCapture {
  const entries: unknown[][] = [];
  return {
    warn: (...args: unknown[]) => {
      entries.push(args);
    },
    entries,
  };
}

function makeInput(initialProvider: Record<string, unknown> = {}): Config {
  // Config = Omit<SDKConfig, "plugin"> & {plugin?: ...}. We only touch the
  // `provider` slot, so a partial cast is acceptable for these tests.
  return { provider: initialProvider } as unknown as Config;
}

// ────────────────────────────────────────────────────────────────────────────
// 1. Happy path β€” valid auth.json + apiKey + baseURL β†’ mutates input.provider
// ────────────────────────────────────────────────────────────────────────────

test("config: with valid auth.json + apiKey + baseURL β†’ mutates input.provider[id] with stripped models block", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test-1", baseURL: "https://or.example.com/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE, MODEL_GEMINI]);
  const combosFetcher = stubCombosFetcher([COMBO_CLAUDE_TIER]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const provider = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider;
  const entry = provider["opencode-omniroute"];
  assert.ok(entry, "input.provider['opencode-omniroute'] set");
  assert.equal(entry.npm, "@ai-sdk/openai-compatible");
  assert.equal(entry.name, "OmniRoute");
  assert.equal(entry.options.baseURL, "https://or.example.com/v1");
  assert.equal(entry.options.apiKey, "sk-test-1");

  // Stripped per-model shape: name + cap flags + modalities + (optional)
  // cost. OC's SDK static schema accepts only `limit.{context,output}` β€”
  // `limit.input` is NOT in the SDK shape and gets dropped silently.
  const claude = entry.models["opencode-omniroute/claude-sonnet-4-6"];
  assert.ok(claude, "claude model surfaced");
  assert.equal(claude.name, "claude-sonnet-4-6");
  assert.equal(claude.attachment, true);
  assert.equal(claude.reasoning, true);
  assert.equal(claude.temperature, true);
  assert.equal(claude.tool_call, true);
  assert.equal(claude.limit?.context, 200_000);
  assert.equal(claude.limit?.output, 64_000);
  assert.equal(
    (claude.limit as Record<string, unknown>).input,
    undefined,
    "limit.input is NOT in OC's SDK schema β€” must not emit"
  );
  // Modalities β€” without this field OC defaults `input.image: false`
  // even when `attachment: true`, blocking clipboard paste in the TUI.
  assert.deepEqual(claude.modalities?.input, ["text", "image"]);
  assert.deepEqual(claude.modalities?.output, ["text"]);

  // Combo surfaces under bare key + LCD'd
  // (gemini's reasoning=false β†’ combo reasoning=false).
  const combo = entry.models["opencode-omniroute/claude-tier"];
  assert.ok(combo, "combo surfaced under bare key");
  assert.equal(combo.name, "Claude Tier");
  assert.equal(combo.reasoning, false, "LCD: any member reasoning=false β†’ combo reasoning=false");
  assert.equal(combo.tool_call, true);
  assert.equal(combo.limit?.context, 200_000, "LCD: min(200_000, 1_000_000)");
});

// ────────────────────────────────────────────────────────────────────────────
// 1b. Dual-key fallback (#5027) β€” auth.json stored under the BARE providerId
//     (pre-auto-prefix login) must still resolve when the active providerId is
//     prefixed (`opencode-omniroute`). Without the fallback the lookup misses
//     the stored key and the user is forced to re-auth.
// ────────────────────────────────────────────────────────────────────────────

test("config: auth.json under bare key (pre-prefix login) resolves via dual-key fallback", async () => {
  // Stored under bare `omniroute` (the key OC wrote before the auto-prefix fix),
  // but the resolved providerId is now `opencode-omniroute`.
  const readAuthJson = stubReadAuthJson({
    omniroute: { type: "api", key: "sk-bare-1", baseURL: "https://or.example.com/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" }, // resolves to opencode-omniroute internally
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const provider = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider;
  const entry = provider["opencode-omniroute"];
  assert.ok(entry, "provider entry published from bare-key apiKey");
  assert.equal(entry.options.apiKey, "sk-bare-1", "apiKey resolved from the bare auth.json key");
  assert.equal(entry.options.baseURL, "https://or.example.com/v1");
});

test("config: prefixed key wins over bare key when both present (dual-key precedence)", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-prefixed", baseURL: "https://pref.example/v1" },
    omniroute: { type: "api", key: "sk-bare", baseURL: "https://bare.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry);
  assert.equal(
    entry.options.apiKey,
    "sk-prefixed",
    "prefixed key takes precedence (looked up first)"
  );
  assert.equal(entry.options.baseURL, "https://pref.example/v1");
});

// ────────────────────────────────────────────────────────────────────────────
// 2. Missing auth.json β†’ no-op, no throw, no mutation
// ────────────────────────────────────────────────────────────────────────────

test("config: missing auth.json file β†’ no-op, no throw, no input mutation", async () => {
  const readAuthJson = stubReadAuthJson(undefined);
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  assert.deepEqual((input as { provider: Record<string, unknown> }).provider, {});
  assert.equal(fetcher.callCount(), 0, "no fetch on missing auth.json");
  assert.equal(combosFetcher.callCount(), 0, "no combos fetch on missing auth.json");
  // One breadcrumb β€” the missing-apiKey path.
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("no apiKey")),
    "breadcrumb emitted"
  );
});

// ────────────────────────────────────────────────────────────────────────────
// 3. Malformed auth.json β†’ no-op + warn once
// ────────────────────────────────────────────────────────────────────────────

test("config: malformed auth.json β†’ no-op + warn once", async () => {
  // stubReadAuthJson returns `null` to signal malformed JSON (matches
  // defaultReadAuthJson's contract).
  const readAuthJson = stubReadAuthJson(null);
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  assert.deepEqual((input as { provider: Record<string, unknown> }).provider, {});
  assert.equal(fetcher.callCount(), 0);
  // First warn = "failed to parse"; second warn = "no apiKey".
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("failed to parse")),
    "parse-failure breadcrumb emitted"
  );
});

// ────────────────────────────────────────────────────────────────────────────
// 4. Existing input.provider[id] β†’ no overwrite (respect manual override)
// ────────────────────────────────────────────────────────────────────────────

test("config: existing input.provider[id] β†’ no overwrite (respect manual override)", async () => {
  const manual = {
    npm: "@ai-sdk/openai-compatible",
    name: "Manual OmniRoute",
    options: { baseURL: "http://manual/v1", apiKey: "manual-key" },
    models: { "manual-model": { name: "manual-model" } },
  };
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput({ "opencode-omniroute": manual });
  await hook(input);

  const provider = (input as { provider: Record<string, unknown> }).provider;
  assert.equal(provider["opencode-omniroute"], manual, "manual override preserved by reference");
  assert.equal(fetcher.callCount(), 0, "no fetch β€” short-circuited before I/O");
  assert.equal(readAuthJson.callCount(), 0, "no auth.json read either");
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("already set")),
    "override breadcrumb emitted"
  );
});

// ────────────────────────────────────────────────────────────────────────────
// 5. fetchers throw β†’ warn + emit stub entry with `models: {}`
// ────────────────────────────────────────────────────────────────────────────

test("config: fetchers throw β†’ warn + emit stub entry with models: {}", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = throwingModelsFetcher();
  const combosFetcher = throwingCombosFetcher();
  const logger = captureWarn();

  // Opt-out of disk-cache fallback for this test β€” we want to assert the
  // pure stub path, not the disk-cache-recovery path (covered by its own
  // test below).
  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", features: { diskCache: false } },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry, "stub provider entry published even when fetchers fail");
  assert.equal(entry.npm, "@ai-sdk/openai-compatible");
  assert.deepEqual(entry.models, {}, "models stub is empty object");
  assert.equal(entry.options.baseURL, "https://or.example/v1");
  assert.equal(entry.options.apiKey, "sk-test");
  // Both warns fired.
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("/v1/models fetch failed")),
    "models-fetch breadcrumb emitted"
  );
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("/api/combos fetch failed")),
    "combos-fetch breadcrumb emitted"
  );
});

// ────────────────────────────────────────────────────────────────────────────
// 6. Combos fetcher throws β†’ models-only catalog (no combos in models block)
// ────────────────────────────────────────────────────────────────────────────

test("config: combos fetcher throws β†’ emit models-only catalog (no combos in models block)", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE, MODEL_GEMINI]);
  const combosFetcher = throwingCombosFetcher();
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry);
  const ids = Object.keys(entry.models).sort();
  assert.deepEqual(ids, [
    "opencode-omniroute/claude-sonnet-4-6",
    "opencode-omniroute/gemini-3-flash",
  ]);
  assert.equal(entry.models["opencode-omniroute/claude-tier"], undefined, "no combo entry");
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("/api/combos fetch failed")),
    "combos-fetch breadcrumb emitted"
  );
});

// ────────────────────────────────────────────────────────────────────────────
// 7. baseURL from auth.json takes precedence when opts.baseURL absent
// ────────────────────────────────────────────────────────────────────────────

test("config: baseURL from auth.json takes precedence when opts.baseURL absent", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://creds.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" }, // NO opts.baseURL
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  assert.equal(fetcher.callsBy()[0][0], "https://creds.example/v1");
  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.equal(entry.options.baseURL, "https://creds.example/v1");
});

test("config: opts.baseURL wins over auth.json's stored baseURL", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://creds.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://opts.example/v1" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  assert.equal(fetcher.callsBy()[0][0], "https://opts.example/v1");
  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.equal(entry.options.baseURL, "https://opts.example/v1");
});

test("config: no baseURL resolvable (no opts, no auth.json baseURL) β†’ no-op", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test" }, // NO baseURL on the credential
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" }, // NO opts.baseURL
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  assert.deepEqual((input as { provider: Record<string, unknown> }).provider, {});
  assert.equal(fetcher.callCount(), 0);
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("no baseURL")),
    "no-baseURL breadcrumb emitted"
  );
});

// ────────────────────────────────────────────────────────────────────────────
// 8. Multi-instance: two plugins with different providerIds publish to
//    their own keys without collision.
// ────────────────────────────────────────────────────────────────────────────

test("config: multi-instance β€” two plugins with different providerIds publish to their own keys without collision", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute-prod": {
      type: "api",
      key: "sk-prod",
      baseURL: "https://prod.example/v1",
    },
    "opencode-omniroute-preprod": {
      type: "api",
      key: "sk-preprod",
      baseURL: "https://preprod.example/v1",
    },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hookA = createOmniRouteConfigHook(
    { providerId: "omniroute-prod" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const hookB = createOmniRouteConfigHook(
    { providerId: "omniroute-preprod" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );

  const input = makeInput();
  await hookA(input);
  await hookB(input);

  const provider = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider;
  assert.ok(provider["opencode-omniroute-prod"], "prod block present");
  assert.ok(provider["opencode-omniroute-preprod"], "preprod block present");
  assert.equal(provider["opencode-omniroute-prod"].options.apiKey, "sk-prod");
  assert.equal(provider["opencode-omniroute-preprod"].options.apiKey, "sk-preprod");
  assert.equal(provider["opencode-omniroute-prod"].options.baseURL, "https://prod.example/v1");
  assert.equal(
    provider["opencode-omniroute-preprod"].options.baseURL,
    "https://preprod.example/v1"
  );
  assert.notEqual(
    provider["opencode-omniroute-prod"],
    provider["opencode-omniroute-preprod"],
    "blocks are distinct references"
  );
});

// ────────────────────────────────────────────────────────────────────────────
// 9. Cache sharing: provider hook + config hook on the same Map dedupe
//    fetcher invocations.
// ────────────────────────────────────────────────────────────────────────────

test("config + provider share cache: second call uses cached fetch result (single fetch per TTL)", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-shared", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([COMBO_CLAUDE_TIER]);
  const sharedCache: OmniRouteFetchCache = new Map();
  const logger = captureWarn();

  const configHook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1", modelCacheTtl: 60_000 },
    { readAuthJson, fetcher, combosFetcher, cache: sharedCache, logger }
  );
  const providerHook = createOmniRouteProviderHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1", modelCacheTtl: 60_000 },
    { fetcher, combosFetcher, cache: sharedCache }
  );

  // Simulate OC β‰₯1.14.49 cold start: config fires first, populates cache,
  // then provider.models() reuses the cached raw results.
  const input = makeInput();
  await configHook(input);
  assert.equal(fetcher.callCount(), 1, "config fired the only models fetch");
  assert.equal(combosFetcher.callCount(), 1, "config fired the only combos fetch");

  // provider hook then runs β€” should hit the shared cache, NOT refetch.
  const apiAuth = { type: "api", key: "sk-shared" };
  await providerHook.models!({} as never, { auth: apiAuth as never });
  assert.equal(fetcher.callCount(), 1, "provider reused cached models");
  assert.equal(combosFetcher.callCount(), 1, "provider reused cached combos");
});

test("provider β†’ config order also dedupes (cache populated by provider, consumed by config)", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-reverse", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const sharedCache: OmniRouteFetchCache = new Map();
  const logger = captureWarn();

  const configHook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1", modelCacheTtl: 60_000 },
    { readAuthJson, fetcher, combosFetcher, cache: sharedCache, logger }
  );
  const providerHook = createOmniRouteProviderHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1", modelCacheTtl: 60_000 },
    { fetcher, combosFetcher, cache: sharedCache }
  );

  await providerHook.models!({} as never, {
    auth: { type: "api", key: "sk-reverse" } as never,
  });
  assert.equal(fetcher.callCount(), 1);

  const input = makeInput();
  await configHook(input);
  assert.equal(fetcher.callCount(), 1, "config reused cached models");
});

// ────────────────────────────────────────────────────────────────────────────
// 10. Stripped models shape matches sibling provider spec
//     (`{name, attachment, reasoning, tool_call, temperature, limit?}`).
// ────────────────────────────────────────────────────────────────────────────

test("buildStaticProviderEntry: stripped per-model shape matches sibling @omniroute/opencode-provider", () => {
  const resolved = resolveOmniRoutePluginOptions({
    providerId: "omniroute",
    displayName: "OmniRoute",
  });
  const block = buildStaticProviderEntry(
    [MODEL_CLAUDE, MODEL_GEMINI],
    [],
    resolved,
    "https://or.example/v1",
    "sk-test"
  );

  // Top-level provider entry shape β€” ONLY these four keys.
  assert.deepEqual(Object.keys(block).sort(), ["models", "name", "npm", "options"]);
  assert.equal(block.npm, "@ai-sdk/openai-compatible");
  assert.equal(block.name, "OmniRoute");
  assert.deepEqual(Object.keys(block.options).sort(), ["apiKey", "baseURL"]);

  // Per-model entry shape β€” the keys OC's SDK static schema accepts
  // (see @opencode-ai/sdk types.gen.d.ts). NO nested capabilities tree,
  // NO providerID/api fields from ModelV2 (those belong on the dynamic
  // hook path).
  const allowedKeys = new Set([
    "name",
    "release_date",
    "attachment",
    "reasoning",
    "temperature",
    "tool_call",
    "cost",
    "limit",
    "modalities",
    "providerID",
  ]);
  for (const [id, entry] of Object.entries(block.models)) {
    for (const key of Object.keys(entry)) {
      assert.ok(allowedKeys.has(key), `${id}.${key} is not in the SDK static shape`);
    }
    // capabilities (ModelV2-only) must NOT leak β€” that's the dynamic-
    // hook nested shape, not the static SDK schema.
    assert.equal(
      (entry as Record<string, unknown>).capabilities,
      undefined,
      `${id} must not carry nested capabilities tree`
    );
  }

  // Sanity: claude entry has all expected stripped fields.
  const claude = block.models["opencode-omniroute/claude-sonnet-4-6"];
  assert.equal(typeof claude.name, "string");
  assert.equal(typeof claude.attachment, "boolean");
  assert.equal(typeof claude.reasoning, "boolean");
  assert.equal(typeof claude.temperature, "boolean");
  assert.equal(typeof claude.tool_call, "boolean");
  assert.equal(typeof claude.limit?.context, "number");
});

test("buildStaticProviderEntry: empty fetch results β†’ stub block with models: {}", () => {
  const resolved = resolveOmniRoutePluginOptions({ providerId: "omniroute" });
  const block = buildStaticProviderEntry([], [], resolved, "https://or.example/v1", "sk-test");
  assert.deepEqual(block.models, {});
  assert.equal(block.options.apiKey, "sk-test");
});

test("buildStaticProviderEntry: hidden combos are excluded", () => {
  const resolved = resolveOmniRoutePluginOptions({ providerId: "omniroute" });
  const block = buildStaticProviderEntry(
    [MODEL_CLAUDE],
    [{ ...COMBO_CLAUDE_TIER, isHidden: true }],
    resolved,
    "https://or.example/v1",
    "sk-test"
  );
  assert.equal(block.models["opencode-omniroute/claude-tier"], undefined);
  assert.ok(block.models["opencode-omniroute/claude-sonnet-4-6"]);
});

// ────────────────────────────────────────────────────────────────────────────
// Schema parity (modalities / cost / release_date / limit cleanup)
// ────────────────────────────────────────────────────────────────────────────

test("buildStaticProviderEntry: emits modalities.input from raw.input_modalities", () => {
  const resolved = resolveOmniRoutePluginOptions({ providerId: "omniroute" });
  const block = buildStaticProviderEntry(
    [MODEL_CLAUDE, MODEL_GEMINI],
    [],
    resolved,
    "https://or.example/v1",
    "sk-test"
  );
  const claude = block.models["opencode-omniroute/claude-sonnet-4-6"];
  assert.deepEqual(claude.modalities?.input, ["text", "image"]);
  assert.deepEqual(claude.modalities?.output, ["text"]);
});

test("buildStaticProviderEntry: never emits limit.input (OC SDK rejects it)", () => {
  const resolved = resolveOmniRoutePluginOptions({ providerId: "omniroute" });
  const block = buildStaticProviderEntry(
    [MODEL_CLAUDE],
    [],
    resolved,
    "https://or.example/v1",
    "sk-test"
  );
  const claude = block.models["opencode-omniroute/claude-sonnet-4-6"];
  assert.equal((claude.limit as Record<string, unknown>).input, undefined);
  assert.equal(typeof claude.limit?.context, "number");
  assert.equal(typeof claude.limit?.output, "number");
});

test("buildStaticProviderEntry: emits cost when enrichment carries pricing", () => {
  const resolved = resolveOmniRoutePluginOptions({ providerId: "omniroute" });
  const enrichment = new Map([
    [
      "claude-sonnet-4-6",
      {
        name: "Claude Sonnet 4.6",
        providerAlias: "cc",
        providerCanonical: "claude",
        providerDisplayName: "Claude",
        pricing: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
      },
    ],
  ]);
  const block = buildStaticProviderEntry(
    [MODEL_CLAUDE],
    [],
    resolved,
    "https://or.example/v1",
    "sk-test",
    enrichment
  );
  const claude = block.models["opencode-omniroute/claude-sonnet-4-6"];
  assert.equal(claude.cost?.input, 3);
  assert.equal(claude.cost?.output, 15);
  assert.equal(claude.cost?.cache_read, 0.3);
  assert.equal(claude.cost?.cache_write, 3.75);
});

test("buildStaticProviderEntry: emits release_date when raw carries it; omits when null", () => {
  const resolved = resolveOmniRoutePluginOptions({ providerId: "omniroute" });
  const withDate: OmniRouteRawModelEntry = {
    ...MODEL_CLAUDE,
    id: "claude-with-date",
    release_date: "2026-02-19",
  };
  const block = buildStaticProviderEntry(
    [withDate, MODEL_GEMINI],
    [],
    resolved,
    "https://or.example/v1",
    "sk-test"
  );
  assert.equal(block.models["opencode-omniroute/claude-with-date"].release_date, "2026-02-19");
  assert.equal(block.models["opencode-omniroute/gemini-3-flash"].release_date, undefined);
});

test("buildStaticProviderEntry: combo modalities = intersection of members (LCD)", () => {
  const resolved = resolveOmniRoutePluginOptions({ providerId: "omniroute" });
  const TEXT_ONLY: OmniRouteRawModelEntry = {
    id: "text-only",
    capabilities: { tool_calling: true, reasoning: false, vision: false, thinking: false },
    context_length: 100_000,
    max_output_tokens: 4_096,
    input_modalities: ["text"],
    output_modalities: ["text"],
  };
  const block = buildStaticProviderEntry(
    [MODEL_CLAUDE, TEXT_ONLY],
    [
      {
        id: "combo-mixed",
        name: "Mixed Tier",
        models: [
          { id: "s1", kind: "model", model: "claude-sonnet-4-6", weight: 100 },
          { id: "s2", kind: "model", model: "text-only", weight: 50 },
        ],
      },
    ],
    resolved,
    "https://or.example/v1",
    "sk-test"
  );
  const combo = block.models["opencode-omniroute/mixed-tier"];
  assert.ok(combo, "combo emitted under slug key");
  // claude has text+image, text-only has text β†’ intersection drops image.
  assert.deepEqual(combo.modalities?.input, ["text"]);
  assert.deepEqual(combo.modalities?.output, ["text"]);
});

// ────────────────────────────────────────────────────────────────────────────
// Integration: OmniRoutePlugin factory now exposes config hook
// ────────────────────────────────────────────────────────────────────────────

test("OmniRoutePlugin factory exposes config hook alongside auth + provider", async () => {
  const hooks = await OmniRoutePlugin({} as never, { providerId: "omniroute" });
  assert.equal(typeof hooks.config, "function", "config hook present");
  assert.ok(hooks.auth, "auth hook present");
  assert.ok(hooks.provider, "provider hook present");
});

// ────────────────────────────────────────────────────────────────────────────
// Edge cases / robustness
// ────────────────────────────────────────────────────────────────────────────

test("config: auth.json entry of wrong type (oauth) β†’ no-op", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "oauth", refresh: "r", access: "a", expires: 0 },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  assert.deepEqual((input as { provider: Record<string, unknown> }).provider, {});
  assert.equal(fetcher.callCount(), 0);
});

test("config: readAuthJson throws β†’ treat as missing file (silent fallback)", async () => {
  const readAuthJson = throwingReadAuthJson();
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  assert.deepEqual((input as { provider: Record<string, unknown> }).provider, {});
  assert.equal(readAuthJson.callCount(), 1);
  assert.equal(fetcher.callCount(), 0);
});

test("config: initialises input.provider when undefined", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, logger }
  );
  // input with NO provider field at all
  const input = {} as Config;
  await hook(input);
  const provider = (input as { provider?: Record<string, unknown> }).provider;
  assert.ok(provider, "provider bag initialised");
  assert.ok(provider!["opencode-omniroute"]);
});

// ────────────────────────────────────────────────────────────────────────────
// Enrichment overlay β€” eager fetch on config-hook so OC ≀1.15.5 TUI sees
// human display names instead of raw provider/model ids.
// ────────────────────────────────────────────────────────────────────────────

test("config: enrichment fetched + name overlaid on raw-model entries", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE, MODEL_GEMINI]);
  const combosFetcher = stubCombosFetcher([COMBO_CLAUDE_TIER]);
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["claude-sonnet-4-6", { name: "Claude Sonnet 4.6" }],
      ["gemini-3-flash", { name: "Gemini 3 Flash" }],
    ])
  );
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry);
  assert.equal(entry.models["opencode-omniroute/claude-sonnet-4-6"].name, "Claude Sonnet 4.6");
  assert.equal(entry.models["opencode-omniroute/gemini-3-flash"].name, "Gemini 3 Flash");
  // Combo names still come from /api/combos β€” enrichment overlay does NOT touch combos.
  assert.equal(entry.models["opencode-omniroute/claude-tier"].name, "Claude Tier");
  assert.equal(enrichmentFetcher.callCount(), 1);
});

test("config: features.enrichment=false skips enrichment fetch + keeps raw-id names", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["claude-sonnet-4-6", { name: "Claude Sonnet 4.6" }],
    ])
  );
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", features: { enrichment: false } },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry);
  assert.equal(enrichmentFetcher.callCount(), 0, "enrichment fetch suppressed by feature flag");
  assert.equal(
    entry.models["opencode-omniroute/claude-sonnet-4-6"].name,
    "claude-sonnet-4-6",
    "raw id retained"
  );
});

test("config: enrichment fetcher throws β†’ soft-fail (warn + raw-id static catalog)", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const enrichmentFetcher = throwingEnrichmentFetcher();
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry, "static block still published on enrichment failure");
  assert.equal(
    entry.models["opencode-omniroute/claude-sonnet-4-6"].name,
    "claude-sonnet-4-6",
    "raw id retained"
  );
  assert.equal(enrichmentFetcher.callCount(), 1);
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("/api/pricing/models fetch failed")),
    "enrichment-fetch breadcrumb emitted"
  );
});

function stubProvidersFetcher(payload: OmniRouteProviderConnection[]): OmniRouteProvidersFetcher & {
  callCount: () => number;
} {
  let n = 0;
  const f: OmniRouteProvidersFetcher = async () => {
    n++;
    return payload;
  };
  return Object.assign(f, { callCount: () => n });
}

function throwingProvidersFetcher(): OmniRouteProvidersFetcher & { callCount: () => number } {
  let n = 0;
  const f: OmniRouteProvidersFetcher = async () => {
    n++;
    throw new Error("ETIMEDOUT");
  };
  return Object.assign(f, { callCount: () => n });
}

const MODEL_CC_OPUS: OmniRouteRawModelEntry = {
  id: "cc/claude-opus-4-7",
  capabilities: { tool_calling: true, reasoning: true, temperature: true },
  context_length: 200_000,
};
const MODEL_NV_LLAMA: OmniRouteRawModelEntry = {
  id: "nvidia/llama-3-70b",
  capabilities: { tool_calling: true, temperature: true },
  context_length: 128_000,
};

test("config: usableOnly=false β†’ no filter (existing behavior)", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CC_OPUS, MODEL_NV_LLAMA]);
  const combosFetcher = stubCombosFetcher([]);
  const providersFetcher = stubProvidersFetcher([
    { id: "c1", provider: "claude", isActive: true, testStatus: "active" },
  ]);
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["cc/claude-opus-4-7", { name: "Claude Opus 4.7" }],
      ["nvidia/llama-3-70b", { name: "Llama 3 70B" }],
    ])
  );

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1" },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, providersFetcher }
  );

  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry.models["cc/claude-opus-4-7"], "claude kept");
  assert.ok(entry.models["nvidia/llama-3-70b"], "nvidia kept (filter off)");
  assert.equal(providersFetcher.callCount(), 0, "providers fetch not called when feature off");
});

test("config: usableOnly=true β†’ drops models for non-usable providers, keeps usable + unknown", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([
    MODEL_CC_OPUS,
    MODEL_NV_LLAMA,
    // Unknown prefix not in pricing-models nor connections β€” must pass through.
    {
      id: "agentrouter/synthetic-1",
      capabilities: { temperature: true },
      context_length: 100_000,
    },
  ]);
  const combosFetcher = stubCombosFetcher([]);
  const providersFetcher = stubProvidersFetcher([
    // Claude is usable.
    { id: "c1", provider: "claude", isActive: true, testStatus: "active" },
    // Nvidia provisioned but errored β†’ not usable.
    { id: "c2", provider: "nvidia", isActive: true, testStatus: "error" },
  ]);
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      [
        "cc/claude-opus-4-7",
        { name: "Claude Opus 4.7", providerAlias: "cc", providerCanonical: "claude" },
      ],
      [
        "nvidia/llama-3-70b",
        { name: "Llama 3 70B", providerAlias: "nvidia", providerCanonical: "nvidia" },
      ],
    ])
  );

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1", features: { usableOnly: true } },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, providersFetcher }
  );

  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry.models["cc/claude-opus-4-7"], "claude kept (active)");
  assert.equal(entry.models["nvidia/llama-3-70b"], undefined, "nvidia dropped (error status)");
  assert.ok(entry.models["agentrouter/synthetic-1"], "unknown prefix kept (subtract-filter)");
  assert.equal(providersFetcher.callCount(), 1);
});

test("config: usableOnly=true + providers fetch fails β†’ soft-fail keeps everything", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CC_OPUS, MODEL_NV_LLAMA]);
  const combosFetcher = stubCombosFetcher([]);
  const providersFetcher = throwingProvidersFetcher();
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["cc/claude-opus-4-7", { name: "Claude Opus 4.7" }],
      ["nvidia/llama-3-70b", { name: "Llama 3 70B" }],
    ])
  );
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1", features: { usableOnly: true } },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, providersFetcher, logger }
  );

  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry.models["cc/claude-opus-4-7"]);
  assert.ok(entry.models["nvidia/llama-3-70b"], "soft-fail keeps both");
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("/api/providers fetch failed")),
    "providers-fetch breadcrumb emitted"
  );
});

test("config: diskCache hydrates stale snapshot when /v1/models throws", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = throwingModelsFetcher();
  const combosFetcher = stubCombosFetcher([]);
  const logger = captureWarn();

  // Disk reader returns a stale snapshot β€” emulates the last-known-good
  // catalog written on a healthy refresh.
  const diskSnapshotReader: typeof import("../src/index.js").defaultDiskSnapshotReader =
    async () => ({
      rawModels: [MODEL_CLAUDE],
      rawCombos: [],
      rawEnrichment: new Map([["claude-sonnet-4-6", { name: "Claude Sonnet 4.6 (cached)" }]]),
      rawCompressionCombos: [],
      rawConnections: [],
    });
  let writes = 0;
  const diskSnapshotWriter: typeof import("../src/index.js").defaultDiskSnapshotWriter =
    async () => {
      writes++;
    };

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", features: { diskCache: true } },
    {
      readAuthJson,
      fetcher,
      combosFetcher,
      diskSnapshotReader,
      diskSnapshotWriter,
      logger,
    }
  );

  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(
    entry.models["opencode-omniroute/claude-sonnet-4-6"],
    "stale snapshot hydrated into static block"
  );
  assert.equal(
    entry.models["opencode-omniroute/claude-sonnet-4-6"].name,
    "Claude Sonnet 4.6 (cached)",
    "stale enrichment also reused"
  );
  assert.equal(writes, 0, "disk write skipped when live fetch failed");
  assert.ok(
    logger.entries.some((e) => String(e[0]).includes("using stale disk cache")),
    "disk-cache hydration breadcrumb emitted"
  );
});

test("config: cached rawEnrichment from earlier provider hook is reused (no refetch)", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-shared", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["claude-sonnet-4-6", { name: "Claude Sonnet 4.6" }],
    ])
  );
  const sharedCache: OmniRouteFetchCache = new Map();
  const logger = captureWarn();

  const providerHook = createOmniRouteProviderHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1", modelCacheTtl: 60_000 },
    { fetcher, combosFetcher, enrichmentFetcher, cache: sharedCache }
  );
  const configHook = createOmniRouteConfigHook(
    { providerId: "omniroute", baseURL: "https://or.example/v1", modelCacheTtl: 60_000 },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, cache: sharedCache, logger }
  );

  // Provider hook fires first (e.g. eager cache warm-up), populates rawEnrichment.
  await providerHook.models!({} as never, {
    auth: { type: "api", key: "sk-shared" } as never,
  });
  assert.equal(enrichmentFetcher.callCount(), 1);

  // Config hook then fires β€” must reuse cached enrichment, not refetch.
  const input = makeInput();
  await configHook(input);
  assert.equal(enrichmentFetcher.callCount(), 1, "config reused cached enrichment");

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.equal(entry.models["opencode-omniroute/claude-sonnet-4-6"].name, "Claude Sonnet 4.6");
});

// ─────────────────────────────────────────────────────────────────────
// Provider-tag suffix (Option E) β€” append upstream provider label to
// enriched model names so the picker can differentiate `cc/claude-opus-4-7`
// (Anthropic) from `kr/claude-opus-4-7` (Kiro) etc.
// ─────────────────────────────────────────────────────────────────────

test("config: providerTag (default-on) prepends '<provider> - ' to enriched raw-model names", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE, MODEL_GEMINI]);
  const combosFetcher = stubCombosFetcher([COMBO_CLAUDE_TIER]);
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      [
        "claude-sonnet-4-6",
        {
          name: "Claude Sonnet 4.6",
          providerAlias: "cc",
          providerCanonical: "claude",
          providerDisplayName: "Claude",
        },
      ],
      [
        "gemini-3-flash",
        {
          name: "Gemini 3 Flash",
          providerAlias: "gemini-cli",
          providerCanonical: "gemini-cli",
          providerDisplayName: "Gemini-cli",
        },
      ],
    ])
  );
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.ok(entry);
  assert.equal(
    entry.models["opencode-omniroute/claude-sonnet-4-6"].name,
    "Claude - Claude Sonnet 4.6"
  );
  assert.equal(
    entry.models["opencode-omniroute/gemini-3-flash"].name,
    "Gemini-cli - Gemini 3 Flash"
  );
  // Combos stay untouched β€” `Combo: ` prefix already conveys multi-upstream.
  assert.equal(entry.models["opencode-omniroute/claude-tier"].name, "Claude Tier");
});

test("config: providerTag=false suppresses the suffix", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["claude-sonnet-4-6", { name: "Claude Sonnet 4.6", providerDisplayName: "Claude" }],
    ])
  );
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", features: { providerTag: false } },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.equal(
    entry.models["opencode-omniroute/claude-sonnet-4-6"].name,
    "Claude Sonnet 4.6",
    "enriched name kept, provider tag suppressed"
  );
});

test("config: providerTag falls back to UPPER(alias) when providerDisplayName missing", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  // Enrichment has the friendly name but NO providerDisplayName β€” e.g.
  // a slot OmniRoute hasn't curated a human label for yet. We still
  // have the alias though, so the prefix uses UPPER(alias) = "CC".
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["claude-sonnet-4-6", { name: "Claude Sonnet 4.6", providerAlias: "cc" }],
    ])
  );
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.equal(entry.models["opencode-omniroute/claude-sonnet-4-6"].name, "CC - Claude Sonnet 4.6");
});

test("config: providerTag skipped entirely when neither providerDisplayName nor providerAlias set", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  // No metadata at all β€” defensive case, e.g. legacy enrichment payload.
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["claude-sonnet-4-6", { name: "Claude Sonnet 4.6" }],
    ])
  );
  const logger = captureWarn();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute" },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, logger }
  );
  const input = makeInput();
  await hook(input);

  const entry = (input as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.equal(entry.models["opencode-omniroute/claude-sonnet-4-6"].name, "Claude Sonnet 4.6");
});

test("config: providerTag is idempotent β€” second hook call doesn't double-suffix", async () => {
  const readAuthJson = stubReadAuthJson({
    "opencode-omniroute": { type: "api", key: "sk-test", baseURL: "https://or.example/v1" },
  });
  const fetcher = stubModelsFetcher([MODEL_CLAUDE]);
  const combosFetcher = stubCombosFetcher([]);
  const enrichmentFetcher = stubEnrichmentFetcher(
    new Map<string, OmniRouteEnrichmentEntry>([
      ["claude-sonnet-4-6", { name: "Claude Sonnet 4.6", providerDisplayName: "Claude" }],
    ])
  );
  const logger = captureWarn();
  const sharedCache = new Map();

  const hook = createOmniRouteConfigHook(
    { providerId: "omniroute", modelCacheTtl: 60_000 },
    { readAuthJson, fetcher, combosFetcher, enrichmentFetcher, cache: sharedCache, logger }
  );

  const inputA = makeInput();
  await hook(inputA);
  const entryA = (inputA as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.equal(
    entryA.models["opencode-omniroute/claude-sonnet-4-6"].name,
    "Claude - Claude Sonnet 4.6"
  );

  // Second invocation (cache hit) β€” name must still be single-suffixed.
  const inputB = makeInput();
  await hook(inputB);
  const entryB = (inputB as { provider: Record<string, OmniRouteStaticProviderEntry> }).provider[
    "opencode-omniroute"
  ];
  assert.equal(
    entryB.models["opencode-omniroute/claude-sonnet-4-6"].name,
    "Claude - Claude Sonnet 4.6"
  );
});

// ────────────────────────────────────────────────────────────────────────────
// T-NN: nested combo-ref resolution in the static catalog
// (mirrors the dynamic-catalog fix in combos.test.ts)
// ────────────────────────────────────────────────────────────────────────────

test("buildStaticProviderEntry: nested combo-ref context is the bottleneck across the graph", () => {
  const resolved = resolveOmniRoutePluginOptions({ providerId: "omniroute" });
  const rawModels: OmniRouteRawModelEntry[] = [
    {
      id: "raw-big",
      context_length: 200_000,
      max_output_tokens: 64_000,
      capabilities: { tool_calling: true, reasoning: true, vision: false, temperature: true },
      input_modalities: ["text"],
      output_modalities: ["text"],
    },
    {
      id: "raw-tiny",
      context_length: 8_000,
      max_output_tokens: 4_000,
      capabilities: { tool_calling: false, reasoning: false, vision: false, temperature: true },
      input_modalities: ["text"],
      output_modalities: ["text"],
    },
  ];
  const rawCombos: OmniRouteRawCombo[] = [
    {
      id: "tiny-combo",
      name: "TinyCombo",
      models: [{ id: "m1", kind: "model", model: "raw-tiny", weight: 100 }],
    },
    {
      id: "parent",
      name: "Parent",
      models: [
        { id: "p1", kind: "model", model: "raw-big", weight: 50 },
        { id: "p2", kind: "combo-ref", comboName: "TinyCombo", weight: 50 },
      ],
    },
  ];
  const block = buildStaticProviderEntry(
    rawModels,
    rawCombos,
    resolved,
    "https://or.example/v1",
    "sk-test"
  );
  // Pre-fix: Parent would advertise 200_000 (only raw-big counted).
  // Post-fix: Parent should advertise 8_000 (TinyCombo bottleneck).
  const parent = block.models["opencode-omniroute/parent"];
  assert.ok(parent, "Parent combo must be in the static catalog");
  assert.equal(parent.limit?.context, 8_000);
});