-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandlers.go
More file actions
executable file
·1469 lines (1381 loc) · 46.8 KB
/
Copy pathhandlers.go
File metadata and controls
executable file
·1469 lines (1381 loc) · 46.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package adminapi
import (
"context"
"fmt"
"net/http"
"net/url"
"os"
"sort"
"strings"
"time"
"telegram-agent/internal/config"
"telegram-agent/internal/llm"
)
// --- View data ---
type uiRole struct {
Name string // e.g. "default", "complex"
Current string // slot name the role currently points at
Provider string // provider type backing that slot ("openrouter", "gemini", ...)
ModelID string // live model id on that slot (from ConfigurableProvider)
HasPreset bool // true when a "Suggest" preset is defined for this role
AvailableSlots []uiSlotInfo // slots valid for this role (multimodal is Gemini+vision only)
}
type uiSlot struct {
Name string
ModelID string
}
type uiModel struct {
ID string
PromptPrice float64
CompletionPrice float64
ContextLength int
Vision bool
Tools bool
Reasoning bool
Free bool
Score float64 // AA Intelligence Index
CodingIndex float64 // AA Coding Index
AgenticIndex float64 // AA Agentic Index
SpeedTPS float64 // median output tokens/sec
TTFT float64 // median time-to-first-token, seconds
ThinkTime float64 // TTFA - TTFT — time spent thinking before answer starts (reasoners only)
AAPriceBlended float64 // AA's reference blended 3:1 input/output price (USD / 1M)
MarkupPct float64 // (OR blended - AA blended) / AA blended × 100 — positive means OR charges more
EffectivePrompt float64 // 0.9 × prompt + 0.1 × multimodal_slot.prompt for non-vision candidates under roles that route images elsewhere
ValuePerDollar float64 // quality / prompt price (role-specific in preset path; agent/$ in browse path)
Recommended bool
Source string
Policy string
Section string
OverrideNote string
Reasons []string
Warnings []string
Telemetry modelTelemetry
Market llm.OpenRouterMarketSignal
StatusLabel string
PolicyLabel string
PrimaryReason string
SecondaryReasons []string
}
type modelTelemetry struct {
Calls int `json:"calls"`
AvgLatencyMS int `json:"avg_latency_ms"`
ErrorRatePct float64 `json:"error_rate_pct"`
CostUSD float64 `json:"cost_usd"`
WindowDays int `json:"window_days"`
}
type uiSlotInfo struct {
Name string // slot key in config (e.g. "default-or", "simple-gemini")
Provider string // backend type: "openrouter", "gemini", "ollama", "claude-bridge", "local"
}
type uiRouting struct {
Roles []uiRole
AllSlots []uiSlotInfo // all provider keys with their backend type
}
type uiFilters struct {
Search string
Free bool
Vision bool
Tools bool
Reasoning bool
ActivePreset string // role name when a preset is applied; empty otherwise
PresetDescription string // human-readable summary for the banner
ValueLeaderID string // model id of the knee-point value leader (preset path only)
ValueLeaderHint string // e.g. "85% quality @ 30% price" (preset path only)
Sort string // active sort column: "prompt", "completion", "score", "context", "id"
SortDir string // "asc" or "desc"
View string // "cards" (default) or "table"
}
type uiModelSection struct {
Key string
Title string
Description string
Models []uiModel
}
type indexData struct {
ActiveTab string // "routing" or "analytics" — drives tab highlight in layout
Routing uiRouting
Slots []uiSlot // slots backing the currently-browsed provider (for per-model assign buttons)
Models []uiModel
ModelSections []uiModelSection
Filters uiFilters
CatalogProvider string // "openrouter" | "gemini" — which catalog is shown in the models browser
}
// --- Handlers ---
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
data := s.buildIndexData(r)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := render(w, viewIndex, data); err != nil {
s.logger.Error("render index", "err", err)
http.Error(w, "render error", http.StatusInternalServerError)
}
}
func (s *Server) handleAnalytics(w http.ResponseWriter, r *http.Request) {
// Analytics page is a thin frame — the usage section lazy-loads via /usage.
// Still needs ActiveTab so the tab bar highlights the right entry.
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := render(w, viewAnalytics, map[string]any{"ActiveTab": "analytics"}); err != nil {
s.logger.Error("render analytics", "err", err)
http.Error(w, "render error", http.StatusInternalServerError)
}
}
func (s *Server) handleModels(w http.ResponseWriter, r *http.Request) {
data := s.buildIndexData(r)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
view := viewModelsContent
if r.URL.Query().Get("full") == "1" {
view = viewModelsBrowser
}
if err := render(w, view, data); err != nil {
s.logger.Error("render models_content", "err", err)
http.Error(w, "render error", http.StatusInternalServerError)
}
}
func (s *Server) handleModelOverride(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if s.settings == nil {
http.Error(w, "settings store not available", http.StatusServiceUnavailable)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "parse form", http.StatusBadRequest)
return
}
provider := strings.TrimSpace(r.FormValue("provider"))
if provider == "" {
provider = "openrouter"
}
modelID := strings.TrimSpace(r.FormValue("model_id"))
if modelID == "" {
http.Error(w, "model_id required", http.StatusBadRequest)
return
}
state := strings.TrimSpace(r.FormValue("state"))
if state != "" && state != "allow" && state != "deny" {
http.Error(w, "invalid state", http.StatusBadRequest)
return
}
note := strings.TrimSpace(r.FormValue("note"))
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if err := saveModelOverride(ctx, s.settings, provider, modelID, state, note); err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
next := r.Clone(r.Context())
next.URL = cloneURL(r.URL)
next.URL.RawQuery = r.Form.Encode()
data := s.buildIndexData(next)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := render(w, viewModelsContent, data); err != nil {
s.logger.Error("render models after override", "err", err)
}
}
func cloneURL(u *url.URL) *url.URL {
v := *u
return &v
}
func (s *Server) handleRouting(w http.ResponseWriter, r *http.Request) {
data := s.buildRouting()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := render(w, viewRouting, data); err != nil {
s.logger.Error("render routing", "err", err)
http.Error(w, "render error", http.StatusInternalServerError)
}
}
// handleSlotAssign: POST /slots/{slot}/assign with body model_id=...
func (s *Server) handleSlotAssign(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
slot := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/slots/"), "/assign")
if slot == "" || strings.Contains(slot, "/") {
http.Error(w, "invalid slot", http.StatusBadRequest)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "parse form", http.StatusBadRequest)
return
}
modelID := r.FormValue("model_id")
if modelID == "" {
http.Error(w, "model_id required", http.StatusBadRequest)
return
}
// Provider type: prefer the form value (new UI — role/provider/model flow),
// fall back to the slot's config default for the legacy model-card path.
providerType := r.FormValue("provider")
if providerType == "" {
providerType = s.router.SlotProvider(slot)
}
if providerType == "" {
if mc, ok := s.cfgRef.Models[slot]; ok {
providerType = mc.Provider
}
}
caps := s.lookupCapsFor(r.Context(), providerType, modelID)
if err := s.router.SetProviderModel(slot, providerType, modelID, caps); err != nil {
s.logger.Warn("slot assign failed", "slot", slot, "model", modelID, "err", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.logger.Info("slot assigned", "slot", slot, "model", modelID)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := render(w, viewRouting, s.buildRouting()); err != nil {
s.logger.Error("render routing after assign", "err", err)
}
}
// handleRoleSet: POST /routing/{role}/set with body slot=...
func (s *Server) handleRoleSet(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
role := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/routing/"), "/set")
if role == "" || strings.Contains(role, "/") {
http.Error(w, "invalid role", http.StatusBadRequest)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, "parse form", http.StatusBadRequest)
return
}
slot := r.FormValue("slot")
if slot == "" {
http.Error(w, "slot required", http.StatusBadRequest)
return
}
if err := s.router.SetRole(role, slot); err != nil {
s.logger.Warn("role set failed", "role", role, "slot", slot, "err", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.logger.Info("role assigned", "role", role, "slot", slot)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := render(w, viewRouting, s.buildRouting()); err != nil {
s.logger.Error("render routing after role set", "err", err)
}
}
// handleRefresh triggers fresh catalog fetches for OpenRouter (+ AA scores)
// and Gemini, then re-caches caps. Which catalog the UI shows afterwards is
// controlled by the ?provider query param (default: openrouter).
func (s *Server) handleRefresh(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
apiKey := s.firstOpenRouterAPIKey()
if apiKey == "" {
http.Error(w, "no openrouter provider configured", http.StatusServiceUnavailable)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
caps, err := llm.FetchOpenRouterModels(ctx, apiKey)
if err != nil {
s.logger.Warn("refresh failed", "err", err)
http.Error(w, "upstream fetch failed: "+err.Error(), http.StatusBadGateway)
return
}
// Also refresh Gemini catalog (best effort — failures don't abort the OR path).
if geminiKey := s.firstGeminiAPIKey(); geminiKey != "" {
if gCaps, gErr := llm.FetchGeminiModels(ctx, geminiKey); gErr != nil {
s.logger.Warn("gemini refresh failed", "err", gErr)
} else if s.capStore != nil {
for id, c := range gCaps {
_ = s.capStore.PutCapabilities(ctx, "gemini", id, c)
}
s.logger.Info("gemini catalog refreshed", "count", len(gCaps))
}
}
// Overlay AA Intelligence Index scores if configured — always re-fetch on
// manual Refresh (bypass cache) and update the stored cache.
if aaKey := s.cfgRef.ArtificialAnalysisAPIKey; aaKey != "" {
if models, aaErr := llm.FetchArtificialAnalysisData(ctx, aaKey); aaErr != nil {
s.logger.Warn("AA data refresh failed", "err", aaErr)
} else {
llm.MergeAAScores(caps, models)
s.logger.Info("AA data refreshed", "models", len(models))
if s.settings != nil {
if storeErr := llm.StoreAACache(ctx, s.settings, models); storeErr != nil {
s.logger.Warn("AA cache store failed", "err", storeErr)
}
}
}
}
if s.settings != nil {
if market, marketErr := llm.FetchOpenRouterRankings(ctx); marketErr != nil {
s.logger.Warn("openrouter rankings refresh failed", "err", marketErr)
} else {
s.logger.Info("openrouter rankings refreshed", "models", len(market))
if storeErr := llm.StoreOpenRouterRankingsCache(ctx, s.settings, market); storeErr != nil {
s.logger.Warn("openrouter rankings cache store failed", "err", storeErr)
}
}
}
if s.capStore != nil {
for id, c := range caps {
_ = s.capStore.PutCapabilities(ctx, "openrouter", id, c)
}
}
s.logger.Info("openrouter catalog refreshed", "count", len(caps))
data := s.buildIndexData(r)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := render(w, viewModelsContent, data); err != nil {
s.logger.Error("render models after refresh", "err", err)
}
}
// --- Data builders ---
func (s *Server) buildIndexData(r *http.Request) indexData {
q := r.URL.Query()
preset := q.Get("preset")
catalogProv := q.Get("provider")
if catalogProv != "gemini" {
catalogProv = "openrouter"
}
viewMode := q.Get("view")
if viewMode != "table" {
viewMode = "cards"
}
ctx5, cancel5 := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel5()
var allCaps map[string]llm.Capabilities
if s.capStore != nil {
allCaps, _ = s.capStore.GetAllCapabilities(ctx5, catalogProv)
}
// Load AA cache for extra columns (coding, agentic, speed, ttft).
var aaModels map[string]llm.AAModelInfo
if s.settings != nil {
if cache, _ := llm.LoadAACache(ctx5, s.settings); cache != nil {
aaModels = cache.Models
}
}
marketSignals := s.loadMarketSignals(ctx5, catalogProv)
overrides := loadModelOverrides(ctx5, s.settings)
// Preset path — pre-filter + pre-sort via the role's preset. Checkbox
// filters are ignored on this path: the preset is a complete override.
if p, ok := rolePresets[preset]; ok {
// Find current multimodal slot's prompt price — passed to applyPreset
// so non-vision candidates for default/simple/complex get an effective
// price that accounts for image messages routing to multimodal.
var visionFallbackPrompt float64
cfg := s.router.GetConfig()
for _, sl := range s.openRouterSlots() {
if sl.Name == cfg.Multimodal {
if c, ok := allCaps[sl.ModelID]; ok {
visionFallbackPrompt = c.PromptPrice
}
break
}
}
models := applyPreset(allCaps, aaModels, preset, visionFallbackPrompt)
models = appendAllowedOverrideCandidates(models, allCaps, aaModels, catalogProv, preset, overrides)
models = filterModelOverrides(models, catalogProv, overrides, true)
attachMarketSignals(models, marketSignals)
attachModelTelemetry(models, s.loadModelTelemetry(ctx5, catalogProv))
decorateModelDisplay(models, preset)
sections := buildModelSections(models, true)
filters := uiFilters{
ActivePreset: preset,
PresetDescription: p.Description,
Tools: requiresTools(preset),
Vision: preset == "multimodal",
Reasoning: preset == "complex",
View: viewMode,
}
// Knee-point value leader: best quality/price among frontier models
// with quality ≥ 50% of top. Skipped when the top model is already
// the value leader.
axes := axesForPreset(preset, p, models)
if axes != nil {
if vl := valueLeader(models, axes, 0.5); vl != nil {
topQ, topP := axes(models[0])
vQ, vP := axes(*vl)
if topQ > 0 && topP > 0 {
filters.ValueLeaderID = vl.ID
filters.ValueLeaderHint = fmt.Sprintf("%.0f%% quality @ %.0f%% price",
100*vQ/topQ, 100*vP/topP)
}
}
}
return indexData{
ActiveTab: "routing",
Routing: s.buildRouting(),
Slots: s.allAssignableSlots(),
Models: models,
ModelSections: sections,
Filters: filters,
CatalogProvider: catalogProv,
}
}
// Manual filter path — Tools defaults ON on initial page load (empty
// query string), since the agentic loop requires tool calling. Once the
// user submits the filters form, whatever they send wins.
formSubmitted := len(q) > 0
sortCol := q.Get("sort")
if sortCol == "" {
sortCol = "prompt"
}
sortDir := q.Get("dir")
if sortDir != "asc" && sortDir != "desc" {
if sortCol == "score" || sortCol == "context" || sortCol == "market" {
sortDir = "desc"
} else {
sortDir = "asc"
}
}
f := uiFilters{
Search: strings.ToLower(strings.TrimSpace(q.Get("q"))),
Free: q.Get("free") != "",
Vision: q.Get("vision") != "",
Tools: q.Get("tools") != "" || !formSubmitted,
Reasoning: q.Get("reasoning") != "",
Sort: sortCol,
SortDir: sortDir,
View: viewMode,
}
models := make([]uiModel, 0, len(allCaps))
for id, c := range allCaps {
free := c.Free()
if f.Search != "" && !strings.Contains(strings.ToLower(id), f.Search) {
continue
}
if f.Free && !free {
continue
}
if f.Vision && !c.Vision {
continue
}
if f.Tools && !c.Tools {
continue
}
if f.Reasoning && !c.Reasoning {
continue
}
m := uiModel{
ID: id,
PromptPrice: c.PromptPrice,
CompletionPrice: c.CompletionPrice,
ContextLength: c.ContextLength,
Vision: c.Vision,
Tools: c.Tools,
Reasoning: c.Reasoning,
Free: free,
Score: c.Score,
}
if aaModels != nil {
if info := llm.LookupAAInfo(id, aaModels); info != nil {
enrichFromAA(&m, *info)
}
}
// Generic value metric for browse path: agentic index per $1/M prompt
// tokens, falling back to intelligence index when agentic is absent.
if m.PromptPrice > 0 {
q := m.AgenticIndex
if q == 0 {
q = m.Score
}
if q > 0 {
m.ValuePerDollar = q / m.PromptPrice
}
}
annotateModelForRole(&m, "", "catalog")
models = append(models, m)
}
models = filterModelOverrides(models, catalogProv, overrides, f.Search == "")
attachMarketSignals(models, marketSignals)
attachModelTelemetry(models, s.loadModelTelemetry(ctx5, catalogProv))
decorateModelDisplay(models, "")
asc := sortDir == "asc"
sort.Slice(models, func(i, j int) bool {
var less bool
switch sortCol {
case "completion":
less = models[i].CompletionPrice < models[j].CompletionPrice
case "score":
less = models[i].Score < models[j].Score
case "coding":
less = models[i].CodingIndex < models[j].CodingIndex
case "agentic":
less = models[i].AgenticIndex < models[j].AgenticIndex
case "speed":
less = models[i].SpeedTPS < models[j].SpeedTPS
case "ttft":
less = models[i].TTFT < models[j].TTFT
case "think":
less = models[i].ThinkTime < models[j].ThinkTime
case "markup":
less = models[i].MarkupPct < models[j].MarkupPct
case "effective":
less = effectiveOrNominal(models[i]) < effectiveOrNominal(models[j])
case "value":
less = models[i].ValuePerDollar < models[j].ValuePerDollar
case "market":
less = marketSortValue(models[i].Market) < marketSortValue(models[j].Market)
case "context":
less = models[i].ContextLength < models[j].ContextLength
case "id":
less = models[i].ID < models[j].ID
default: // "prompt"
if models[i].Free != models[j].Free {
return models[i].Free // free always first regardless of direction
}
less = models[i].PromptPrice < models[j].PromptPrice
}
if asc {
return less
}
return !less
})
return indexData{
Routing: s.buildRouting(),
Slots: s.allAssignableSlots(),
Models: models,
Filters: f,
CatalogProvider: catalogProv,
}
}
// orBlendedPrice mirrors AA's 3:1 input/output weighting so prices are
// directly comparable across sources.
func orBlendedPrice(promptPrice, completionPrice float64) float64 {
return (3*promptPrice + completionPrice) / 4
}
// effectiveOrNominal returns EffectivePrompt when set, otherwise PromptPrice.
// Used by the "effective" sort case so models without the adjustment still
// rank by their nominal price.
func effectiveOrNominal(m uiModel) float64 {
if m.EffectivePrompt > 0 {
return m.EffectivePrompt
}
return m.PromptPrice
}
func buildModelSections(models []uiModel, presetMode bool) []uiModelSection {
if !presetMode || len(models) == 0 {
return nil
}
order := []uiModelSection{
{Key: "recommended", Title: "Recommended", Description: "Stable, role-fit models backed by benchmark data."},
{Key: "interesting", Title: "Interesting", Description: "Plausible alternatives and non-obvious trade-offs worth reviewing."},
{Key: "untested", Title: "Untested", Description: "Capability-compatible models with missing quality data or local evidence."},
{Key: "blocked", Title: "Blocked", Description: "Filtered or manually denied models, shown only when present."},
}
byKey := make(map[string][]uiModel, len(order))
for _, m := range models {
key := modelSectionKey(m)
byKey[key] = append(byKey[key], m)
}
out := make([]uiModelSection, 0, len(order))
for _, section := range order {
section.Models = applySectionDiversity(byKey[section.Key], 3)
if len(section.Models) == 0 {
continue
}
out = append(out, section)
}
return out
}
func modelSectionKey(m uiModel) string {
switch {
case m.Policy == "manual_deny" || m.Policy == "free_blocked":
return "blocked"
case m.Section != "":
return m.Section
case m.Recommended:
return "recommended"
case m.Source == "untested" || m.Policy == "free_unverified":
return "untested"
case m.Source == "near_frontier" || m.Source == "manual" || m.Policy == "manual_allow":
return "interesting"
default:
return "interesting"
}
}
func applySectionDiversity(models []uiModel, perFamily int) []uiModel {
if perFamily <= 0 || len(models) == 0 {
return models
}
out := make([]uiModel, 0, len(models))
counts := map[string]int{}
for _, m := range models {
if m.Policy == "manual_allow" {
out = append(out, m)
counts[modelFamilyKey(m.ID)]++
continue
}
family := modelFamilyKey(m.ID)
if counts[family] >= perFamily {
continue
}
counts[family]++
out = append(out, m)
}
return out
}
func modelFamilyKey(id string) string {
provider, slug, ok := strings.Cut(id, "/")
if !ok {
return id
}
first := slug
if i := strings.IndexAny(slug, "-:"); i >= 0 {
first = slug[:i]
}
return provider + "/" + first
}
func (s *Server) loadModelTelemetry(ctx context.Context, provider string) map[string]modelTelemetry {
if s.usageStore == nil {
return nil
}
rows, err := s.usageStore.UsageByModel(ctx, time.Now().Add(-7*24*time.Hour), 1000)
if err != nil {
s.logger.Warn("model telemetry load failed", "err", err)
return nil
}
out := make(map[string]modelTelemetry, len(rows))
for _, row := range rows {
if row.Provider != provider || row.Calls <= 0 {
continue
}
out[row.ModelID] = modelTelemetry{
Calls: row.Calls,
AvgLatencyMS: int(row.AvgLatencyMS + 0.5),
ErrorRatePct: 100 * float64(row.ErrorCount) / float64(row.Calls),
CostUSD: row.CostUSD,
WindowDays: 7,
}
}
return out
}
func attachModelTelemetry(models []uiModel, telemetry map[string]modelTelemetry) {
if len(models) == 0 || len(telemetry) == 0 {
return
}
for i := range models {
if t, ok := telemetry[models[i].ID]; ok {
models[i].Telemetry = t
}
}
}
func (s *Server) loadMarketSignals(ctx context.Context, provider string) map[string]llm.OpenRouterMarketSignal {
if provider != "openrouter" || s.settings == nil {
return nil
}
cache, err := llm.LoadOpenRouterRankingsCache(ctx, s.settings)
if err != nil {
s.logger.Warn("openrouter rankings cache load failed", "err", err)
return nil
}
if cache == nil {
return nil
}
return cache.Models
}
func attachMarketSignals(models []uiModel, signals map[string]llm.OpenRouterMarketSignal) {
if len(models) == 0 || len(signals) == 0 {
return
}
for i := range models {
sig, ok := signals[models[i].ID]
if !ok {
continue
}
models[i].Market = sig
if label := marketSignalLabel(sig); label != "" {
models[i].Reasons = uniqueStrings(append(models[i].Reasons, label))
}
}
}
func marketSignalLabel(sig llm.OpenRouterMarketSignal) string {
if sig.Rank > 0 {
return fmt.Sprintf("OR market #%d", sig.Rank)
}
if sig.Share > 0 {
return fmt.Sprintf("OR market %.1f%%", sig.Share)
}
if sig.Score > 0 {
return "OR market signal"
}
return ""
}
func marketSortValue(sig llm.OpenRouterMarketSignal) float64 {
if sig.Rank > 0 {
return 1_000_000 - float64(sig.Rank)
}
if sig.Share > 0 {
return sig.Share
}
return sig.Score
}
// enrichFromAA populates the AA-derived fields on a uiModel from the matched
// AAModelInfo record. Used by both the preset path and the browse path so
// they share one formula for Think time and Markup %.
func enrichFromAA(m *uiModel, aa llm.AAModelInfo) {
if aa.Score > 0 {
m.Score = aa.Score
}
m.CodingIndex = aa.CodingIndex
m.AgenticIndex = aa.AgenticIndex
m.SpeedTPS = aa.SpeedTPS
m.TTFT = aa.TTFT
if aa.TTFA > 0 && aa.TTFT > 0 && aa.TTFA >= aa.TTFT {
m.ThinkTime = aa.TTFA - aa.TTFT
}
m.AAPriceBlended = aa.PriceBlended
if aa.PriceBlended > 0 && m.PromptPrice > 0 {
orBlended := orBlendedPrice(m.PromptPrice, m.CompletionPrice)
m.MarkupPct = (orBlended - aa.PriceBlended) / aa.PriceBlended * 100
}
}
// requiresTools returns true when the preset's filter requires tool-calling.
func requiresTools(preset string) bool {
switch preset {
case "simple", "default", "complex", "multimodal":
return true
}
return false
}
func (s *Server) buildRouting() uiRouting {
cfg := s.router.GetConfig()
allSlotNames := s.router.ProviderNames()
sort.Strings(allSlotNames)
// Build slot info with provider type from config.
allSlots := make([]uiSlotInfo, 0, len(allSlotNames))
for _, name := range allSlotNames {
prov := ""
if mc, ok := s.cfgRef.Models[name]; ok {
prov = mc.Provider
}
allSlots = append(allSlots, uiSlotInfo{Name: name, Provider: prov})
}
// Model id lookup across all reconfigurable providers — used to show
// "→ <model>" next to the current slot in the routing UI.
slotModelID := map[string]string{}
for _, sl := range s.allAssignableSlots() {
slotModelID[sl.Name] = sl.ModelID
}
// Multimodal role: by business rule, only Gemini slots whose current
// model supports vision are valid. Everything else would either fail or
// silently degrade.
multimodalAllowed := make([]uiSlotInfo, 0, len(allSlots))
for _, sl := range allSlots {
if sl.Provider != "gemini" {
continue
}
if s.visionCapsForSlot(sl.Name).Vision {
multimodalAllowed = append(multimodalAllowed, sl)
}
}
roleCur := map[string]string{
"simple": cfg.Simple,
"default": cfg.Default,
"complex": cfg.Complex,
"multimodal": cfg.Multimodal,
"fallback": cfg.Fallback,
"classifier": cfg.Classifier,
"compaction": cfg.Compaction,
}
order := []string{"simple", "default", "complex", "multimodal", "fallback", "classifier", "compaction"}
presets := presetRoles()
roles := make([]uiRole, 0, len(order))
for _, r := range order {
avail := allSlots
if r == "multimodal" {
avail = multimodalAllowed
}
cur := roleCur[r]
roles = append(roles, uiRole{
Name: r,
Current: cur,
Provider: s.router.SlotProvider(cur),
ModelID: slotModelID[cur],
HasPreset: presets[r],
AvailableSlots: avail,
})
}
return uiRouting{Roles: roles, AllSlots: allSlots}
}
// openRouterSlots returns the subset of configured models whose provider is
// "openrouter" — kept for preset path (vision fallback lookup).
func (s *Server) openRouterSlots() []uiSlot {
return s.slotsByProvider("openrouter")
}
// slotsByProvider returns all slots backed by the given provider type with
// their live model ids (reflecting runtime SetModel swaps).
func (s *Server) slotsByProvider(providerType string) []uiSlot {
var out []uiSlot
for name, mc := range s.cfgRef.Models {
if mc.Provider != providerType {
continue
}
modelID := mc.Model
if p, ok := s.providerFor(name); ok {
if cp, ok := p.(llm.ConfigurableProvider); ok {
if cur := cp.CurrentModel(); cur != "" {
modelID = cur
}
}
}
out = append(out, uiSlot{Name: name, ModelID: modelID})
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// allAssignableSlots returns every configured LLM slot (excluding embedding
// providers) with its LIVE model id — regardless of provider type. Used by
// the model-catalog assign buttons so users can retarget any slot to any
// backend via the cross-type swap flow.
func (s *Server) allAssignableSlots() []uiSlot {
var out []uiSlot
for name, mc := range s.cfgRef.Models {
if mc.Provider == "hf-tei" || mc.Provider == "openai" || mc.Provider == "" {
continue
}
modelID := mc.Model
if p, ok := s.providerFor(name); ok {
if cp, ok := p.(llm.ConfigurableProvider); ok {
if cur := cp.CurrentModel(); cur != "" {
modelID = cur
}
}
}
out = append(out, uiSlot{Name: name, ModelID: modelID})
}
sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
return out
}
// visionCapsForSlot returns the live capabilities of the slot's current model.
// Used by buildRouting to filter the multimodal dropdown.
func (s *Server) visionCapsForSlot(slot string) llm.Capabilities {
if p, ok := s.providerFor(slot); ok {
if vp, ok := p.(llm.VisionProvider); ok {
// VisionProvider only exposes a bool — we need full caps.
_ = vp
}
if cp, ok := p.(interface{ Capabilities() llm.Capabilities }); ok {
return cp.Capabilities()
}
}
return llm.Capabilities{}
}
func (s *Server) providerFor(name string) (llm.Provider, bool) {
return s.router.Provider(name)
}
func (s *Server) firstOpenRouterAPIKey() string {
for _, mc := range s.cfgRef.Models {
if mc.Provider == "openrouter" && mc.APIKey != "" {
return mc.APIKey
}
}
return ""
}
func (s *Server) firstGeminiAPIKey() string {
for _, mc := range s.cfgRef.Models {
if mc.Provider == "gemini" && mc.APIKey != "" {
return mc.APIKey
}
}
return ""
}
// --- MCP page ---
type uiMCPRow struct {
Name string
URL string
Headers string // JSON-serialised, one per line, for display/edit in a textarea
AllowTools string // comma-separated
DenyTools string // comma-separated
Type string
}
type uiMCPData struct {
ActiveTab string
Servers []uiMCPRow
BridgeExport string // MCP_BRIDGE_EXPORT_PATH if set, shown as a banner note
SavedName string // non-empty after a successful save — used by template to flash a success message
ReloadOK string // non-empty on successful live reload (e.g. "3 servers, 42 tools")
ReloadErr string // non-empty if the live reload failed after the DB save
}
// reloadMCPLive hot-reloads the bot's MCP client with the given config set.
// Uses a detached context with a 30 s timeout — the request's context is
// typically 5 s which isn't enough to reconnect several servers. Returns
// human-readable strings for the UI flash; empty strings if no reloader is
// wired.
func (s *Server) reloadMCPLive(servers map[string]config.MCPServerConfig) (okMsg, errMsg string) {
if s.reloader == nil {
return "", ""
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
toolCount, err := s.reloader.ReloadMCP(ctx, servers)
if err != nil {
s.logger.Warn("mcp live reload failed", "err", err)
return "", err.Error()
}
s.logger.Info("mcp live reload ok", "servers", len(servers), "tools", toolCount)
return fmt.Sprintf("%d servers, %d tools", len(servers), toolCount), ""
}
// loadMCPForUI returns the current MCP list flattened into UI rows. Prefers
// the DB list; falls back to the legacy mcp.json file so users landing on
// the page for the first time see their existing config instead of an
// empty table.
func (s *Server) loadMCPForUI(ctx context.Context) map[string]config.MCPServerConfig {
if servers, found, _ := LoadMCPServersFromSettings(ctx, s.settings); found {
return servers
}
// File fallback — best effort.
if servers, err := config.LoadMCPServers("config/mcp.json"); err == nil {
return servers