1package agent
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8 "strings"
9 "time"
10
11 "github.com/patriceckhart/zot/packages/provider"
12)
13
14// ModelCachePath returns the on-disk location of the merged model cache.
15func ModelCachePath() string {
16 return filepath.Join(ZotHome(), "models-cache.json")
17}
18
19// UserModelsPath returns the path to the user's models.json override.
20func UserModelsPath() string {
21 return filepath.Join(ZotHome(), "models.json")
22}
23
24// LoadCachedModels loads the cache file and applies it to the provider
25// package so FindModel / ModelsForProvider see live ids immediately.
26// Safe to call before any credentials are known.
27func LoadCachedModels() {
28 c, err := provider.LoadCache(ModelCachePath())
29 if err != nil {
30 return
31 }
32 if len(c.Models) > 0 {
33 provider.SetLiveModels(c.Models)
34 }
35}
36
37// LoadUserModels reads $ZOT_HOME/models.json and merges any user-defined
38// models into the active catalog. User models take highest precedence.
39// Any validation issues (bad provider id, empty model id, malformed
40// JSON, negative widths) are surfaced as one warning per line on stderr;
41// the well-formed entries from the rest of the file are still loaded.
42func LoadUserModels() {
43 models, warnings := provider.LoadUserModelsWithWarnings(UserModelsPath())
44 for _, w := range warnings {
45 fmt.Fprintln(os.Stderr, "zot:", w)
46 }
47 provider.SetUserModels(models)
48}
49
50// isGatewayProvider returns true for providers whose OpenAI-compatible
51// endpoint can accept routed model IDs that are not present in zot's local
52// catalog. Vercel AI Gateway is intentionally not listed here: zot currently
53// talks to it through the Anthropic-compatible client, which still requires
54// catalog metadata for request shaping.
55func isGatewayProvider(prov string) bool {
56 switch prov {
57 case "openrouter", "cloudflare-ai-gateway":
58 return true
59 default:
60 return false
61 }
62}
63
64// isGatewayRoutedModelID reports whether a model looks like the routed IDs
65// used by gateway providers, for example "deepseek/deepseek-v4-flash".
66// Non-routed typos like "deepseek-v4-flashh" should still be repaired to a
67// known default instead of being silently accepted.
68func isGatewayRoutedModelID(model string) bool {
69 return strings.Contains(strings.TrimSpace(model), "/")
70}
71
72// ValidateAndRepairConfig checks the persisted config.json's
73// (Provider, Model) pair against the active catalog and repairs any
74// mismatch in-place (and on disk) before any UI renders. Three failure
75// modes are handled:
76//
77// - cfg.Provider is empty or unknown -> reset to "anthropic".
78// - cfg.Model is empty -> set to the provider's default.
79// - cfg.Model belongs to a different provider than cfg.Provider
80// (e.g. provider=anthropic + model=kimi-for-coding from a stale
81// half-applied switch) -> reset model to the provider's default.
82//
83// Gateway providers are exempt from the cross-provider model check for routed
84// model IDs because those IDs can be valid even when absent from zot's catalog.
85//
86// Silent on success; one stderr line per repair. Errors loading or
87// saving the file are non-fatal — the caller continues with defaults.
88func ValidateAndRepairConfig() {
89 cfg, err := LoadConfig()
90 if err != nil {
91 fmt.Fprintf(os.Stderr, "zot: config.json: %v (using defaults)\n", err)
92 return
93 }
94 changed := false
95
96 if cfg.Provider != "" && !isKnownProvider(cfg.Provider) {
97 fmt.Fprintf(os.Stderr, "zot: config.json: unknown provider %q reset to \"anthropic\"\n", cfg.Provider)
98 cfg.Provider = "anthropic"
99 cfg.Model = ""
100 changed = true
101 }
102
103 if cfg.Provider != "" && cfg.Model != "" {
104 if _, err := provider.FindModel(cfg.Provider, cfg.Model); err != nil {
105 // Gateway providers can serve routed model ids like
106 // "deepseek/deepseek-v4-flash" even when the local catalog does not
107 // know them. Preserve only routed ids; plain typos are still repaired.
108 if isGatewayProvider(cfg.Provider) && isGatewayRoutedModelID(cfg.Model) {
109 // Provider is a router and the id is route-qualified; preserve it.
110 } else if m, err := provider.FindModel("", cfg.Model); err == nil {
111 fix := defaultModelForProvider(cfg.Provider)
112 fmt.Fprintf(os.Stderr,
113 "zot: config.json: model %q belongs to provider %q (config has provider=%q); switched model to %q\n",
114 cfg.Model, m.Provider, cfg.Provider, fix)
115 cfg.Model = fix
116 changed = true
117 } else if cfg.Provider != "ollama" && cfg.Provider != provider.LlamaCPPProviderID {
118 // Model id not in any catalog. Reset to provider's default.
119 fix := defaultModelForProvider(cfg.Provider)
120 fmt.Fprintf(os.Stderr,
121 "zot: config.json: model %q not found in the active catalog; switched to %q\n",
122 cfg.Model, fix)
123 cfg.Model = fix
124 changed = true
125 }
126 }
127 }
128
129 if changed {
130 if err := SaveConfig(cfg); err != nil {
131 fmt.Fprintf(os.Stderr, "zot: config.json: failed to persist repair: %v\n", err)
132 }
133 }
134}
135
136// RefreshModelsAsync kicks a background discovery for every provider
137// we have credentials for. Refreshed results are merged into the
138// active catalog and persisted to the on-disk cache.
139//
140// Silent on error: discovery is a nice-to-have. Callers can still use
141// the baked-in catalog if this fails.
142func RefreshModelsAsync() {
143 go refreshModels()
144 go func() {
145 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
146 defer cancel()
147 _ = refreshLlamaCPPModels(ctx, apiKeyCommandSkip)
148 }()
149}
150
151// RefreshLlamaCPPModels adds the router's currently loaded models to the
152// active catalog. Unloaded models remain in the management UI and cannot be
153// selected for inference until they are loaded.
154func RefreshLlamaCPPModels(ctx context.Context) error {
155 return refreshLlamaCPPModels(ctx, apiKeyCommandExecute)
156}
157
158func refreshLlamaCPPModels(ctx context.Context, commandMode apiKeyCommandMode) error {
159 baseURL, apiKey, err := resolveLlamaCPPConfig(ctx, commandMode)
160 if err != nil || baseURL == "" {
161 return err
162 }
163 client, err := provider.NewLlamaCPPClient(baseURL, apiKey)
164 if err != nil {
165 return err
166 }
167 models, err := client.List(ctx, false)
168 if err != nil {
169 return err
170 }
171 provider.SetManagedModels(provider.LlamaCPPModels(models, client.ServerURL))
172 return nil
173}
174
175func refreshModels() {
176 cached, _ := provider.LoadCache(ModelCachePath())
177 cacheFresh := cached.IsFresh()
178
179 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
180 defer cancel()
181
182 var all []provider.Model
183 var openrouterCred string
184 var haveOpenRouter bool
185 if cred, _, err := resolveCredentialForBackground(ctx, "openrouter"); err == nil {
186 openrouterCred = cred
187 haveOpenRouter = true
188 }
189
190 if cacheFresh {
191 all = append(all, cached.Models...)
192 } else {
193 if cred, method, err := resolveCredentialForBackground(ctx, "anthropic"); err == nil && method == "apikey" {
194 // /v1/models on Anthropic is API-key only; OAuth tokens can
195 // also list models via the bearer header, but we skip OAuth
196 // here to avoid surprise rate-limit hits on subscription keys.
197 if live, err := provider.DiscoverAnthropic(ctx, cred, ""); err == nil {
198 all = append(all, live...)
199 }
200 }
201 if cred, method, err := resolveCredentialForBackground(ctx, "openai"); err == nil && method == "apikey" {
202 if live, err := provider.DiscoverOpenAI(ctx, cred, ""); err == nil {
203 all = append(all, live...)
204 }
205 }
206 if cred, method, err := resolveCredentialForBackground(ctx, "kimi"); err == nil && method == "apikey" {
207 if live, err := provider.DiscoverOpenAI(ctx, cred, "https://api.kimi.com/coding/v1"); err == nil {
208 for i := range live {
209 live[i].Provider = "kimi"
210 live[i].Source = "live"
211 }
212 all = append(all, live...)
213 }
214 }
215 if cred, method, err := resolveCredentialForBackground(ctx, "google"); err == nil && method == "apikey" {
216 if live, err := provider.DiscoverGoogle(ctx, cred, ""); err == nil {
217 all = append(all, live...)
218 }
219 }
220 if haveOpenRouter {
221 // /models is public; gate on a credential so the picker only
222 // fills with OpenRouter's hundreds of routes for users who use it.
223 if live, err := provider.DiscoverOpenRouter(ctx, ""); err == nil {
224 all = append(all, live...)
225 }
226 }
227 if _, _, err := resolveCredentialForBackground(ctx, "gondola"); err == nil {
228 // Gondola's catalog is also public. Gate discovery on a credential so
229 // its text models only fill the picker for users of the provider.
230 if live, err := provider.DiscoverGondola(ctx, ""); err == nil {
231 all = append(all, live...)
232 }
233 }
234 }
235
236 // Presets are per-account and require auth. Fetch them even when the
237 // public /models cache is still fresh so @preset/{slug} shows up in
238 // the picker without waiting out CacheTTL.
239 if haveOpenRouter {
240 if presets, err := provider.DiscoverOpenRouterPresets(ctx, openrouterCred, ""); err == nil {
241 all = mergeOpenRouterPresets(all, presets)
242 }
243 }
244
245 if len(all) == 0 {
246 return
247 }
248 provider.SetLiveModels(all)
249 _ = provider.SaveCache(ModelCachePath(), provider.ModelCache{
250 FetchedAt: modelCacheFetchedAt(cached, !cacheFresh, time.Now().UTC()),
251 Models: all,
252 })
253}
254
255func modelCacheFetchedAt(cached provider.ModelCache, catalogRefreshed bool, now time.Time) time.Time {
256 if catalogRefreshed {
257 return now
258 }
259 return cached.FetchedAt
260}
261
262// mergeOpenRouterPresets replaces any previously cached OpenRouter preset
263// models with the freshly listed set, keeping every non-preset entry.
264func mergeOpenRouterPresets(existing, presets []provider.Model) []provider.Model {
265 out := make([]provider.Model, 0, len(existing)+len(presets))
266 for _, m := range existing {
267 if m.Provider == "openrouter" && strings.HasPrefix(m.ID, "@preset/") {
268 continue
269 }
270 out = append(out, m)
271 }
272 return append(out, presets...)
273}